the validationlab.eu marketing site: 3 audience pages (en) + legal skeletons, i18n scaffold (25 locales, subdirectory scheme), structured frontmatter blocks, Zoho Flow lead forms with capability tagging + honeypot, sitemap/hreflang/JSON-LD/robots, cookie-gated analytics plumbing

This commit is contained in:
2026-11-21 09:25:06 +01:00
parent 95af7107d0
commit 477bf5114f
1076 changed files with 227743 additions and 110 deletions
+10 -3
View File
@@ -1,7 +1,14 @@
import { defineConfig } from "astro/config";
import sitemap from "@astrojs/sitemap";
// The canonical public origin (Caddy serves the pipeline's output at
// astro.<base> + the apex + www).
// The canonical public origin for SEO is the APEX domain (marketing at
// validationlab.eu root); Caddy serves the same build at the apex, www
// and the astro subdomain.
export default defineConfig({
site: "https://astro.validationlab.eu",
site: "https://validationlab.eu",
integrations: [
sitemap({
filter: (page) => !page.includes("/admin/") && !page.includes("/uploads/"),
}),
],
});
+1
View File
@@ -0,0 +1 @@
:root{--ink: #16213a;--muted: #5b6478;--accent: #3a55d9;--accent-soft: #eef1fd;--line: #e3e7f2;--bg: #fbfcfe}*{box-sizing:border-box}html{scrollbar-gutter:stable}body{margin:0;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;color:var(--ink);background:var(--bg);line-height:1.65}a{color:var(--accent);text-decoration-thickness:1px;text-underline-offset:2px}h1{font-size:2.3rem;line-height:1.15;margin:0 0 1rem;letter-spacing:-.02em}h2{font-size:1.45rem;margin:2.5rem 0 1rem;letter-spacing:-.01em}h3{font-size:1.12rem;margin:0 0 .5rem}p{margin:0 0 1rem}img{max-width:100%;height:auto;border-radius:.5rem}.site-header nav{display:flex;gap:1.25rem;align-items:center;flex-wrap:wrap;padding:.9rem 2rem;border-bottom:1px solid var(--line);background:#fff}.site-header .brand{font-weight:700;margin-inline-end:auto;color:var(--ink);text-decoration:none}.site-header nav a:not(.brand){color:var(--muted);text-decoration:none;font-size:.95rem}.site-header nav a:hover{color:var(--accent)}.switcher{display:flex;gap:.45rem;align-items:center;font-size:.85rem;color:var(--muted)}.switcher span{display:none}.switcher select{font:inherit;font-size:.85rem;padding:.3rem .4rem;border:1px solid var(--line);border-radius:.4rem;background:#fff;color:var(--ink)}main{max-width:46rem;margin:0 auto;padding:2.5rem 1.25rem 4rem}.hero{margin-inline:-1.25rem;margin-top:-2.5rem;padding:3.2rem 1.25rem 2.6rem;background:linear-gradient(180deg,var(--accent-soft),var(--bg))}.hero-sub{font-size:1.15rem;color:var(--muted);max-width:38rem}.cta-row{margin-top:1.6rem;display:flex;gap:.75rem;flex-wrap:wrap}.button{display:inline-block;background:var(--accent);color:#fff!important;border-radius:.5rem;padding:.6rem 1.1rem;text-decoration:none;font-weight:600;font-size:.95rem;border:1px solid transparent}.button:hover{filter:brightness(1.08)}.button-secondary{background:#fff;color:var(--accent)!important;border-color:var(--accent)}.cards{margin-top:2rem;display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(14rem,1fr))}.card{background:#fff;border:1px solid var(--line);border-radius:.7rem;padding:1.1rem 1.2rem;margin:0}.card p{color:var(--muted);font-size:.95rem;margin:0}.card h2,.card h3{margin:0 0 .5rem}.journey ol{padding:0;margin:0;list-style:none;counter-reset:none;display:grid;gap:.55rem}.journey li{padding:.55rem .9rem;background:#fff;border:1px solid var(--line);border-inline-start:3px solid var(--accent);border-radius:.45rem;color:var(--muted);font-size:.97rem}.journey li strong{color:var(--ink);margin-inline-end:.2rem}.note{margin-top:1.5rem;padding:.9rem 1.2rem;background:var(--accent-soft);border-radius:.5rem}.note p{margin:0}form.lead{margin-top:2.5rem;padding:1.5rem 1.6rem;background:#fff;border:1px solid var(--line);border-radius:.8rem}form.lead h2{margin-top:0}form.lead label{display:block;font-size:.9rem;margin-bottom:1rem}form.lead input[type=text],form.lead input[type=email],form.lead select,form.lead textarea{display:block;width:100%;margin-top:.3rem;font:inherit;padding:.55rem .65rem;border:1px solid var(--line);border-radius:.45rem;color:var(--ink);background:#fff}form.lead textarea{min-height:6rem;resize:vertical}form.lead label.consent{display:flex;gap:.5rem;align-items:start}form.lead .hp{position:absolute;inset-inline-start:-9999px}footer{border-top:1px solid var(--line);color:var(--muted);font-size:.85rem;padding:1.5rem 2rem 2rem;text-align:center}#cookie-consent{position:fixed;inset-inline:0;bottom:0;display:flex;gap:1rem;align-items:center;justify-content:center;flex-wrap:wrap;padding:.8rem 1.5rem;background:var(--ink);color:#fff;font-size:.85rem}#cookie-consent p{margin:0}#cookie-consent button{font:inherit;font-size:.85rem;border-radius:.4rem;border:1px solid rgba(255,255,255,.5);background:transparent;color:#fff;padding:.35rem .8rem;cursor:pointer}#cookie-consent button[data-answer=yes]{background:#fff;color:var(--ink);border-color:#fff}blockquote{margin:1.5rem 0;padding:.5rem 1.25rem;border-inline-start:3px solid var(--accent);color:var(--muted)}ul,ol{padding-inline-start:1.5rem}@media(prefers-reduced-motion:no-preference){.hero{transition:none}}
-9
View File
@@ -1,9 +0,0 @@
<!DOCTYPE html><html lang="en"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>About</title><style>:root{--ink: #1f2937;--muted: #6b7280;--accent: #4f46e5;--line: #e5e7eb}*{box-sizing:border-box}body{margin:0;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;color:var(--ink);line-height:1.65}nav{display:flex;gap:1.25rem;align-items:center;padding:.9rem 2rem;border-bottom:1px solid var(--line)}nav .brand{font-weight:700;margin-right:auto}nav a{color:var(--muted);text-decoration:none;font-size:.95rem}nav a:hover,nav a[aria-current=page]{color:var(--accent)}main{max-width:44rem;margin:0 auto;padding:2.5rem 1.25rem 4rem}main :is(h1,h2,h3){line-height:1.25}main h1{font-size:2.1rem;margin:0 0 1.25rem}main h2{font-size:1.45rem;margin-top:2.25rem}main img{max-width:100%;height:auto;border-radius:.5rem}main blockquote{margin:1.5rem 0;padding:.5rem 1.25rem;border-left:3px solid var(--accent);color:var(--muted)}main ul,main ol{padding-inline-start:1.5rem}footer{border-top:1px solid var(--line);color:var(--muted);font-size:.85rem;padding:1.25rem 2rem;text-align:center}
</style></head> <body> <nav> <span class="brand">About</span> <a href="/"> Home </a><a href="/about"> About </a> </nav> <main> <h1>About this site</h1>
<p>A static <a href="https://astro.build">Astro</a> site whose content is edited by a <a href="/admin/">browser-based visual editor</a>, with <strong>no git knowledge needed</strong>.</p>
<blockquote>
Behind every save is a normal git commit in an auditable repository on this server — editors never see that part.
</blockquote> </main> <footer>
This page is editable in the browser at
<a href="/admin/">/admin/</a> — no git knowledge required.
</footer> </body></html>
+46 -3
View File
@@ -29,17 +29,60 @@ collections:
label: Pages
label_singular: Page
folder: /src/pages
nested:
depth: 2
summary: "{{title}}"
extension: md
format: yaml-frontmatter
create: true # pages land in src/pages and appear in the nav (it is built from this folder)
create: true # pages land in src/pages/<locale>/ and appear in the nav (built from the folder)
delete: false # a page (the Home page above all) cannot be deleted from the CMS
slug: "{{slug}}"
identifier_field: title
summary: "{{title}}"
fields:
- { label: Title, name: title, widget: string }
- { label: Title (also the page <title> and h1), name: title, widget: string }
- { label: Meta description (search engines), name: description, widget: string, required: false }
- { label: Layout, name: layout, widget: hidden, default: ../layouts/Site.astro }
- { label: Hero headline, name: hero_headline, widget: string, required: false }
- { label: Hero subline, name: hero_sub, widget: text, required: false }
- label: Hero CTA to the founders page
name: cta_founders
widget: string
required: false
- label: Hero CTA to the hubs page
name: cta_hubs
widget: string
required: false
- label: Cards section (optional)
name: value_props
widget: list
required: false
fields:
- { label: Heading, name: heading, widget: string }
- { label: Text, name: text, widget: text }
- { label: Cards section heading, name: value_props_title, widget: string, required: false }
- label: Journey steps (optional)
name: journey
widget: list
required: false
fields:
- { label: Step title, name: title, widget: string }
- { label: Step text (optional), name: text, widget: string, required: false }
- { label: Journey heading, name: journey_title, widget: string, required: false }
- { label: Journey note, name: journey_note, widget: text, required: false }
- label: Capability blocks (hubs page, optional)
name: capabilities
widget: list
required: false
fields:
- { label: Key (lowercase_with_underscores), name: key, widget: string }
- { label: Heading, name: heading, widget: string }
- { label: Text, name: text, widget: text }
- { label: CTA label, name: cta, widget: string }
- { label: Capabilities heading, name: capabilities_title, widget: string, required: false }
- { label: Capabilities note, name: capabilities_note, widget: text, required: false }
- { label: Pricing note, name: pricing_note, widget: text, required: false }
- label: Body
name: body
widget: richtext
hint: The page content, edited visually. Everything here is published as the page's main content.
hint: The page's long-form content. Everything here is published as the page's main content.
+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html><html lang="en" dir="ltr"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Cookies</title><meta name="description" content="This site uses no cookies; the only local storage is your analytics choice, and analytics loads only after you opt in."><link rel="canonical" href="https://validationlab.eu/cookies/"><link rel="alternate" hreflang="en" href="https://validationlab.eu/cookies/"><link rel="alternate" hreflang="x-default" href="https://validationlab.eu/cookies/"><meta property="og:title" content="Cookies"><meta property="og:description" content="This site uses no cookies; the only local storage is your analytics choice, and analytics loads only after you opt in."><meta property="og:url" content="https://validationlab.eu/cookies/"><meta property="og:type" content="website"><meta property="og:locale" content="en"><meta name="twitter:card" content="summary"><script type="application/ld+json">{"@context":"https://schema.org","@type":"Service","serviceType":"Innovation hub programmes","provider":{"@type":"Organization","name":"Validation Lab","url":"https://validationlab.eu"},"areaServed":"EU","url":"https://validationlab.eu/cookies/","description":"This site uses no cookies; the only local storage is your analytics choice, and analytics loads only after you opt in."}</script><script>(() => {
// Cookie-gated analytics: nothing loads until the visitor opts in,
// and the choice is remembered in localStorage.
const banner = document.getElementById("cookie-consent");
if (!banner) return;
const KEY = "vl-consent";
const STATS_URL = "REPLACE_STATS_SCRIPT_URL";
const STATS_ID = "REPLACE_STATS_WEBSITE_ID";
const injectStats = () => {
if (STATS_URL.indexOf("REPLACE_") === 0 || document.getElementById("vl-stats")) return;
const s = document.createElement("script");
s.id = "vl-stats";
s.defer = true;
s.src = STATS_URL + "";
s.setAttribute("data-website-id", STATS_ID);
document.head.appendChild(s);
};
const decide = (allow) => {
try { localStorage.setItem(KEY, allow ? "granted" : "denied"); } catch {}
banner.remove();
if (allow) injectStats();
};
banner.addEventListener("click", (event) => {
const b = event.target.closest("button");
if (!b) return;
decide(b.dataset.answer === "yes");
});
let stored = null;
try { stored = localStorage.getItem(KEY); } catch {}
if (stored) {
banner.remove();
if (stored === "granted") injectStats();
}
})();</script><link rel="stylesheet" href="/_astro/cookies.a9D3y7n-.css"></head> <body> <header class="site-header"> <nav> <a class="brand" href="/">Validation Lab</a> <a href="/cookies/" aria-current="page">Cookies</a> <label class="switcher"> <span aria-hidden="true">Read this page in:</span> <select aria-label="Language" onchange="const u=new URL(this.value, location.origin); location.href = u.href;"> <option value="https://validationlab.eu/cookies/" selected> English </option> </select> </label> </nav> </header> <main> <p><strong>DRAFT — this notice needs review before launch.</strong></p>
<p>This website sets no cookies of any kind. The only thing stored in your
browser is a single local entry recording your answer to the analytics
banner (allow / decline) so we don’t ask you again.</p>
<p>The analytics itself is a self-hosted, privacy-first tool on our own
server. It is not loaded — not even its script — until you explicitly
allow it, and no third-party trackers or advertising networks run on this
site.</p> </main> <footer> <p>Guided validation for early-stage startups — from Business Model Canvas to validated learning.</p> <p> <a href="/privacy/">Privacy</a> ·
<a href="/cookies/">Cookies</a> ·
<a href="/admin/">This site is editable in the browser at /admin/ — no git knowledge required.</a> </p> <p>Hosted on EU infrastructure (Aruba, Italy).</p> </footer> <div id="cookie-consent" role="region" aria-label="We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in."> <p>We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in.</p> <button data-answer="yes">Allow analytics</button> <button data-answer="no">Decline</button> </div> </body></html>
+105
View File
@@ -0,0 +1,105 @@
<!DOCTYPE html><html lang="en" dir="ltr"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>For founders — validate before you build</title><meta name="description" content="Validation Lab guides founding teams from idea to depth interviews in fifteen structured stages, with an AI facilitator drafting the documents and the team keeping the decisions. Early access for founding teams."><link rel="canonical" href="https://validationlab.eu/for-founders/"><link rel="alternate" hreflang="en" href="https://validationlab.eu/for-founders/"><link rel="alternate" hreflang="x-default" href="https://validationlab.eu/for-founders/"><meta property="og:title" content="For founders — validate before you build"><meta property="og:description" content="Validation Lab guides founding teams from idea to depth interviews in fifteen structured stages, with an AI facilitator drafting the documents and the team keeping the decisions. Early access for founding teams."><meta property="og:url" content="https://validationlab.eu/for-founders/"><meta property="og:type" content="website"><meta property="og:locale" content="en"><meta name="twitter:card" content="summary"><script type="application/ld+json">{"@context":"https://schema.org","@type":"Service","serviceType":"Startup validation guidance","provider":{"@type":"Organization","name":"Validation Lab","url":"https://validationlab.eu"},"areaServed":"EU","url":"https://validationlab.eu/for-founders/","description":"Validation Lab guides founding teams from idea to depth interviews in fifteen structured stages, with an AI facilitator drafting the documents and the team keeping the decisions. Early access for founding teams."}</script><script>(() => {
// Cookie-gated analytics: nothing loads until the visitor opts in,
// and the choice is remembered in localStorage.
const banner = document.getElementById("cookie-consent");
if (!banner) return;
const KEY = "vl-consent";
const STATS_URL = "REPLACE_STATS_SCRIPT_URL";
const STATS_ID = "REPLACE_STATS_WEBSITE_ID";
const injectStats = () => {
if (STATS_URL.indexOf("REPLACE_") === 0 || document.getElementById("vl-stats")) return;
const s = document.createElement("script");
s.id = "vl-stats";
s.defer = true;
s.src = STATS_URL + "";
s.setAttribute("data-website-id", STATS_ID);
document.head.appendChild(s);
};
const decide = (allow) => {
try { localStorage.setItem(KEY, allow ? "granted" : "denied"); } catch {}
banner.remove();
if (allow) injectStats();
};
banner.addEventListener("click", (event) => {
const b = event.target.closest("button");
if (!b) return;
decide(b.dataset.answer === "yes");
});
let stored = null;
try { stored = localStorage.getItem(KEY); } catch {}
if (stored) {
banner.remove();
if (stored === "granted") injectStats();
}
})();</script><link rel="stylesheet" href="/_astro/cookies.a9D3y7n-.css"></head> <body> <header class="site-header"> <nav> <a class="brand" href="/">Validation Lab</a> <a href="/for-founders/" aria-current="page">For founders</a> <label class="switcher"> <span aria-hidden="true">Read this page in:</span> <select aria-label="Language" onchange="const u=new URL(this.value, location.origin); location.href = u.href;"> <option value="https://validationlab.eu/for-founders/" selected> English </option> </select> </label> </nav> </header> <main> <section class="hero"> <h1>Skip the opinions. Find out what your market thinks.</h1> <p class="hero-sub">You have an idea. Everyone around you has opinions. The only answers that count come from outside the building — and there is a right order to go get them.</p> </section> <section class="note"><p>We&#39;re onboarding founding teams in small cohorts. Early-access terms for the first teams through the door.</p></section> <p>Founders rarely fail for lack of ideas — they fail from building before
validating. Validation Lab walks your team through the full journey, one
focused stage at a time: frame the idea, build and stress-test the Business
Model Canvas, decide what you know versus what you’re merely assuming, and
only then explore which market opportunity to pursue. Later stages get
concrete: persona matrices, a positioning statement, a depth-interview panel
with a scripted interview guide, and a systematic analysis of what you heard.</p>
<p>You stay in the driving seat: the AI facilitator asks the hard questions,
drafts each document and challenges weak answers — but the team decides.
Everything you produce is a real, reusable document your accelerator,
institute or investor can read.</p>
<p>Mentors fit in naturally: hand them a stage to review, and their feedback
lands in the same documents.</p> <section class="lead-wrap"> <form id="lead-form" class="lead" data-webhook="REPLACE_ZOHO_FLOW_WEBHOOK_FOUNDERS" data-sending-label="Sending…" data-locale="en" data-type="founders" data-i18n-success="Thank you — your request is on its way. We'll be in touch shortly." data-i18n-error="Something went wrong sending your request. Please email us instead:" data-contact-email="hello@app.validationlab.eu"> <h2 id="lead-form">Talk to us about your startup</h2> <p class="lead-note">Tell us where you are on the journey — we&#39;ll get back to you within a few days.</p> <label> Name * <input type="text" name="name" required> </label><label> Email * <input type="email" name="email" required> </label><label> Startup stage <select name="stage"> <option value="idea">Idea</option><option value="prototype">Prototype</option><option value="launch">Launched</option> </select> </label><label> Sector <input type="text" name="sector"> </label><label> Country <input type="text" name="country"> </label><label> How did you hear about us? <input type="text" name="heard"> </label> <input class="hp" type="text" name="website" tabindex="-1" autocomplete="off" aria-hidden="true"> <input type="hidden" name="capabilities" value=""> <input type="hidden" name="locale" value="en"> <input type="hidden" name="source" value="founders"> <label class="consent"> <input type="checkbox" name="consent" required> <span>I agree that my details may be used to contact me about Validation Lab.</span> </label> <button class="button" type="submit">Send</button> </form> <script>
(() => {
const form = document.getElementById("lead-form");
if (!form || form.dataset.bound) return;
form.dataset.bound = "1";
const STRINGS = {
sending: form.dataset.sendingLabel,
};
// capability blocks tag the form (analyst clicks are separate, via
// data-umami-event attributes on the block links)
const capField = form.querySelector('input[name="capabilities"]');
document.querySelectorAll("[data-cap]").forEach((el) => {
el.addEventListener("click", () => {
if (!capField.value.split(",").includes(el.dataset.cap)) {
capField.value = capField.value
? capField.value + "," + el.dataset.cap
: el.dataset.cap;
}
});
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = form.querySelector('button[type="submit"]');
const data = new FormData(form);
const payload = {};
data.forEach((v, k) => { payload[k] = v; });
if (payload.website) return; // honeypot: pretend success, send nothing
if (capField && !payload.capabilities) payload.capabilities = capField.value;
button.disabled = true;
button.textContent = STRINGS.sending || "Sending…";
try {
const res = await fetch(form.dataset.webhook, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) throw new Error("HTTP " + res.status);
form.innerHTML =
'<p class="lead-ok"></p>';
form.querySelector(".lead-ok").textContent = form.dataset.i18nSuccess;
} catch {
const p = document.createElement("p");
p.className = "lead-err";
p.textContent = form.dataset.i18nError + " ";
const a = document.createElement("a");
a.href = `mailto:${form.dataset.contactEmail}?subject=Validation%20Lab`;
a.textContent = form.dataset.contactEmail;
p.appendChild(a);
form.innerHTML = "";
form.appendChild(p);
button.disabled = false;
}
});
})();
</script> </section> </main> <footer> <p>Guided validation for early-stage startups — from Business Model Canvas to validated learning.</p> <p> <a href="/privacy/">Privacy</a> ·
<a href="/cookies/">Cookies</a> ·
<a href="/admin/">This site is editable in the browser at /admin/ — no git knowledge required.</a> </p> <p>Hosted on EU infrastructure (Aruba, Italy).</p> </footer> <div id="cookie-consent" role="region" aria-label="We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in."> <p>We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in.</p> <button data-answer="yes">Allow analytics</button> <button data-answer="no">Decline</button> </div> </body></html>
+114
View File
@@ -0,0 +1,114 @@
<!DOCTYPE html><html lang="en" dir="ltr"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>For innovation hubs — a validation layer for your programme</title><meta name="description" content="Validation Lab gives incubators, EDIHs and accelerators an asynchronous, structured validation layer between mentoring sessions, with a cohort overview on the roadmap. Tell us which capabilities matter to you."><link rel="canonical" href="https://validationlab.eu/for-innovation-hubs/"><link rel="alternate" hreflang="en" href="https://validationlab.eu/for-innovation-hubs/"><link rel="alternate" hreflang="x-default" href="https://validationlab.eu/for-innovation-hubs/"><meta property="og:title" content="For innovation hubs — a validation layer for your programme"><meta property="og:description" content="Validation Lab gives incubators, EDIHs and accelerators an asynchronous, structured validation layer between mentoring sessions, with a cohort overview on the roadmap. Tell us which capabilities matter to you."><meta property="og:url" content="https://validationlab.eu/for-innovation-hubs/"><meta property="og:type" content="website"><meta property="og:locale" content="en"><meta name="twitter:card" content="summary"><script type="application/ld+json">{"@context":"https://schema.org","@type":"Service","serviceType":"Innovation hub programmes","provider":{"@type":"Organization","name":"Validation Lab","url":"https://validationlab.eu"},"areaServed":"EU","url":"https://validationlab.eu/for-innovation-hubs/","description":"Validation Lab gives incubators, EDIHs and accelerators an asynchronous, structured validation layer between mentoring sessions, with a cohort overview on the roadmap. Tell us which capabilities matter to you."}</script><script>(() => {
// Cookie-gated analytics: nothing loads until the visitor opts in,
// and the choice is remembered in localStorage.
const banner = document.getElementById("cookie-consent");
if (!banner) return;
const KEY = "vl-consent";
const STATS_URL = "REPLACE_STATS_SCRIPT_URL";
const STATS_ID = "REPLACE_STATS_WEBSITE_ID";
const injectStats = () => {
if (STATS_URL.indexOf("REPLACE_") === 0 || document.getElementById("vl-stats")) return;
const s = document.createElement("script");
s.id = "vl-stats";
s.defer = true;
s.src = STATS_URL + "";
s.setAttribute("data-website-id", STATS_ID);
document.head.appendChild(s);
};
const decide = (allow) => {
try { localStorage.setItem(KEY, allow ? "granted" : "denied"); } catch {}
banner.remove();
if (allow) injectStats();
};
banner.addEventListener("click", (event) => {
const b = event.target.closest("button");
if (!b) return;
decide(b.dataset.answer === "yes");
});
let stored = null;
try { stored = localStorage.getItem(KEY); } catch {}
if (stored) {
banner.remove();
if (stored === "granted") injectStats();
}
})();</script><link rel="stylesheet" href="/_astro/cookies.a9D3y7n-.css"></head> <body> <header class="site-header"> <nav> <a class="brand" href="/">Validation Lab</a> <a href="/for-innovation-hubs/" aria-current="page">For innovation hubs</a> <label class="switcher"> <span aria-hidden="true">Read this page in:</span> <select aria-label="Language" onchange="const u=new URL(this.value, location.origin); location.href = u.href;"> <option value="https://validationlab.eu/for-innovation-hubs/" selected> English </option> </select> </label> </nav> </header> <main> <section class="hero"> <h1>Your programme, with a validation spine.</h1> <p class="hero-sub">Mentoring hours are scarce. Validation Lab is the asynchronous layer between your sessions: a structured, fifteen-stage journey each startup works through — while your mentors intervene where they add most.</p> </section> <section class="capabilities"> <h2>The capabilities we&#39;re building towards</h2> <p class="capabilities-note">These are on our near-term roadmap, sequenced by what teams and hubs actually ask for. Click what matters to you — your click and your message arrive together in our CRM.</p> <div class="cards"> <article class="card"> <h3>White-labelling</h3> <p>Run the journey as your own branded programme, on your own server instance — your data, your look.</p> <a class="button button-secondary" data-umami-event="capability-white_label" data-cap="white_label" href="/for-innovation-hubs/#lead-form">I&#39;m interested in this</a> </article><article class="card"> <h3>Instructor-led breakpoints</h3> <p>Your mentors step in at defined break-points in the journey — reviewing and signing off each stage for each team.</p> <a class="button button-secondary" data-umami-event="capability-instructor_led" data-cap="instructor_led" href="/for-innovation-hubs/#lead-form">I&#39;m interested in this</a> </article><article class="card"> <h3>Team collaboration</h3> <p>Founding teams work the journey together: shared documents, shared edits, one team view.</p> <a class="button button-secondary" data-umami-event="capability-team_collaboration" data-cap="team_collaboration" href="/for-innovation-hubs/#lead-form">I&#39;m interested in this</a> </article><article class="card"> <h3>Cohort grouping and overview</h3> <p>Group startups into cohorts and see where each team stands across your programme — one overview for programme managers.</p> <a class="button button-secondary" data-umami-event="capability-cohort_dashboards" data-cap="cohort_dashboards" href="/for-innovation-hubs/#lead-form">I&#39;m interested in this</a> </article> </div> </section> <p>Innovation hubs — incubators, accelerators, EDIHs, EEN nodes, regional
agencies — run on two scarce resources: mentor hours and reviewer
attention. Validation Lab is designed to complement your programme, not
replace it: it is the structured layer a startup works through <em>between</em>
your sessions, producing documents your mentors and selection committees can
actually assess.</p>
<p>Use cases we’re building for:</p>
<ul>
<li><strong>Between mentor sessions.</strong> Teams arrive at each session with the stage
completed and the document drafted — the session starts from substance,
not from status updates.</li>
<li><strong>A selection funnel.</strong> Run candidates through the early stages and
read the canvas, focus and opportunity documents before you award a
place in your programme.</li>
<li><strong>White-label programmes.</strong> For hubs that want the journey under their own
brand and on their own infrastructure (roadmap capability above).</li>
</ul>
<p>The journey today is the fifteen-stage validation path — from the Business
Model Canvas, through market opportunities and personas, to scripted depth
interviews with systematic analysis. The hub-facing capabilities above are
the roadmap; the cohort overview and mentor sign-off gates are sequenced
first, and your signal below helps us sequence the rest.</p> <section class="lead-wrap"> <form id="lead-form" class="lead" data-webhook="REPLACE_ZOHO_FLOW_WEBHOOK_HUBS" data-sending-label="Sending…" data-locale="en" data-type="hubs" data-i18n-success="Thank you — your request is on its way. We'll be in touch shortly." data-i18n-error="Something went wrong sending your request. Please email us instead:" data-contact-email="hello@app.validationlab.eu"> <h2 id="lead-form">Talk to us about your hub</h2> <p class="lead-note">No long forms, no survey — the capabilities you clicked above arrive with your message.</p> <label> Organisation * <input type="text" name="organisation" required> </label><label> Name * <input type="text" name="name" required> </label><label> Email * <input type="email" name="email" required> </label><label> Country <input type="text" name="country"> </label><label> Programme type <select name="programme"> <option value="incubator">Incubator</option><option value="accelerator">Accelerator</option><option value="edih">EDIH</option><option value="een">EEN node</option><option value="agency">Regional agency</option><option value="other">Other</option> </select> </label><label> Message (optional) <textarea name="message"></textarea> </label> <input class="hp" type="text" name="website" tabindex="-1" autocomplete="off" aria-hidden="true"> <input type="hidden" name="capabilities" value=""> <input type="hidden" name="locale" value="en"> <input type="hidden" name="source" value="hubs"> <label class="consent"> <input type="checkbox" name="consent" required> <span>I agree that my details may be used to contact me about Validation Lab.</span> </label> <button class="button" type="submit">Send</button> </form> <script>
(() => {
const form = document.getElementById("lead-form");
if (!form || form.dataset.bound) return;
form.dataset.bound = "1";
const STRINGS = {
sending: form.dataset.sendingLabel,
};
// capability blocks tag the form (analyst clicks are separate, via
// data-umami-event attributes on the block links)
const capField = form.querySelector('input[name="capabilities"]');
document.querySelectorAll("[data-cap]").forEach((el) => {
el.addEventListener("click", () => {
if (!capField.value.split(",").includes(el.dataset.cap)) {
capField.value = capField.value
? capField.value + "," + el.dataset.cap
: el.dataset.cap;
}
});
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = form.querySelector('button[type="submit"]');
const data = new FormData(form);
const payload = {};
data.forEach((v, k) => { payload[k] = v; });
if (payload.website) return; // honeypot: pretend success, send nothing
if (capField && !payload.capabilities) payload.capabilities = capField.value;
button.disabled = true;
button.textContent = STRINGS.sending || "Sending…";
try {
const res = await fetch(form.dataset.webhook, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) throw new Error("HTTP " + res.status);
form.innerHTML =
'<p class="lead-ok"></p>';
form.querySelector(".lead-ok").textContent = form.dataset.i18nSuccess;
} catch {
const p = document.createElement("p");
p.className = "lead-err";
p.textContent = form.dataset.i18nError + " ";
const a = document.createElement("a");
a.href = `mailto:${form.dataset.contactEmail}?subject=Validation%20Lab`;
a.textContent = form.dataset.contactEmail;
p.appendChild(a);
form.innerHTML = "";
form.appendChild(p);
button.disabled = false;
}
});
})();
</script> </section> </main> <footer> <p>Guided validation for early-stage startups — from Business Model Canvas to validated learning.</p> <p> <a href="/privacy/">Privacy</a> ·
<a href="/cookies/">Cookies</a> ·
<a href="/admin/">This site is editable in the browser at /admin/ — no git knowledge required.</a> </p> <p>Hosted on EU infrastructure (Aruba, Italy).</p> </footer> <div id="cookie-consent" role="region" aria-label="We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in."> <p>We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in.</p> <button data-answer="yes">Allow analytics</button> <button data-answer="no">Decline</button> </div> </body></html>
+38 -6
View File
@@ -1,6 +1,38 @@
<!DOCTYPE html><html lang="en"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Home</title><style>:root{--ink: #1f2937;--muted: #6b7280;--accent: #4f46e5;--line: #e5e7eb}*{box-sizing:border-box}body{margin:0;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;color:var(--ink);line-height:1.65}nav{display:flex;gap:1.25rem;align-items:center;padding:.9rem 2rem;border-bottom:1px solid var(--line)}nav .brand{font-weight:700;margin-right:auto}nav a{color:var(--muted);text-decoration:none;font-size:.95rem}nav a:hover,nav a[aria-current=page]{color:var(--accent)}main{max-width:44rem;margin:0 auto;padding:2.5rem 1.25rem 4rem}main :is(h1,h2,h3){line-height:1.25}main h1{font-size:2.1rem;margin:0 0 1.25rem}main h2{font-size:1.45rem;margin-top:2.25rem}main img{max-width:100%;height:auto;border-radius:.5rem}main blockquote{margin:1.5rem 0;padding:.5rem 1.25rem;border-left:3px solid var(--accent);color:var(--muted)}main ul,main ol{padding-inline-start:1.5rem}footer{border-top:1px solid var(--line);color:var(--muted);font-size:.85rem;padding:1.25rem 2rem;text-align:center}
</style></head> <body> <nav> <span class="brand">Home</span> <a href="/" aria-current="page"> Home </a><a href="/about"> About </a> </nav> <main> <h1>Welcome</h1>
<p><strong>An editable static site.</strong> This page is a plain astro page — everything below this line is written by a <em>non-technical person in a browser</em> at <a href="/admin/">/admin/</a> and committed to the site's git repository behind the scenes.</p> </main> <footer>
This page is editable in the browser at
<a href="/admin/">/admin/</a> — no git knowledge required.
</footer> </body></html>
<!DOCTYPE html><html lang="en" dir="ltr"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Validation Lab — guided startup validation, from canvas to validated learning</title><meta name="description" content="A guided, AI-facilitated validation journey for early-stage startups: fifteen structured stages, real documents, from Business Model Canvas to validated learning. EU-hosted."><link rel="canonical" href="https://validationlab.eu/"><link rel="alternate" hreflang="en" href="https://validationlab.eu/"><link rel="alternate" hreflang="x-default" href="https://validationlab.eu/"><meta property="og:title" content="Validation Lab — guided startup validation, from canvas to validated learning"><meta property="og:description" content="A guided, AI-facilitated validation journey for early-stage startups: fifteen structured stages, real documents, from Business Model Canvas to validated learning. EU-hosted."><meta property="og:url" content="https://validationlab.eu/"><meta property="og:type" content="website"><meta property="og:locale" content="en"><meta name="twitter:card" content="summary"><script type="application/ld+json">{"@context":"https://schema.org","@type":"Organization","name":"Validation Lab","url":"https://validationlab.eu","description":"A guided, AI-facilitated validation journey for early-stage startups: fifteen structured stages, real documents, from Business Model Canvas to validated learning. EU-hosted."}</script><script>(() => {
// Cookie-gated analytics: nothing loads until the visitor opts in,
// and the choice is remembered in localStorage.
const banner = document.getElementById("cookie-consent");
if (!banner) return;
const KEY = "vl-consent";
const STATS_URL = "REPLACE_STATS_SCRIPT_URL";
const STATS_ID = "REPLACE_STATS_WEBSITE_ID";
const injectStats = () => {
if (STATS_URL.indexOf("REPLACE_") === 0 || document.getElementById("vl-stats")) return;
const s = document.createElement("script");
s.id = "vl-stats";
s.defer = true;
s.src = STATS_URL + "";
s.setAttribute("data-website-id", STATS_ID);
document.head.appendChild(s);
};
const decide = (allow) => {
try { localStorage.setItem(KEY, allow ? "granted" : "denied"); } catch {}
banner.remove();
if (allow) injectStats();
};
banner.addEventListener("click", (event) => {
const b = event.target.closest("button");
if (!b) return;
decide(b.dataset.answer === "yes");
});
let stored = null;
try { stored = localStorage.getItem(KEY); } catch {}
if (stored) {
banner.remove();
if (stored === "granted") injectStats();
}
})();</script><link rel="stylesheet" href="/_astro/cookies.a9D3y7n-.css"></head> <body> <header class="site-header"> <nav> <a class="brand" href="/">Validation Lab</a> <a href="/" aria-current="page">Home</a> <label class="switcher"> <span aria-hidden="true">Read this page in:</span> <select aria-label="Language" onchange="const u=new URL(this.value, location.origin); location.href = u.href;"> <option value="https://validationlab.eu/" selected> English </option> </select> </label> </nav> </header> <main> <section class="hero"> <h1>Validate your startup before you build it.</h1> <p class="hero-sub">Validation Lab walks founding teams through a fifteen-stage validation journey — from the Business Model Canvas to depth interviews and validated learning — with an AI facilitator that drafts, questions and challenges every step.</p> <p class="cta-row"> <a class="button" href="/for-founders/">I&#39;m a founder</a> <a class="button button-secondary" href="/for-innovation-hubs/">I run an innovation hub</a> </p> </section> <section class="cards" aria-label="Why teams use it"> <article class="card"> <h2>A guided path, not guesswork</h2> <p>Fifteen structured stages replace ad-hoc mentoring checklists. Every stage ends with a real document — canvas, assessment, persona set, positioning statement, interview script.</p> </article><article class="card"> <h2>AI-facilitated, human-steered</h2> <p>The agent interviews the team, drafts the documents and challenges weak assumptions. You and your mentor keep every decision.</p> </article><article class="card"> <h2>EU-hosted, GDPR-aligned</h2> <p>Served and stored on European infrastructure. Your startup&#39;s documents stay in the EU.</p> </article> </section> <section class="journey"> <h2>How the journey works</h2> <p class="journey-note">Fifteen guided stages in six phases — each producing documents the team keeps.</p> <ol> <li value="1"><strong>Frame the Startup Idea</strong><span> — the idea, the problem it solves, a validation self-rating.</span></li><li value="2"><strong>Model the business</strong><span> — build or normalise the Business Model Canvas, then assess it against Osterwalder&#39;s seven questions.</span></li><li value="3"><strong>Define the validation focus</strong><span> — turn the assessment into priorities — what is knowledge, what is assumption.</span></li><li value="4"><strong>Explore market opportunities</strong><span> — rank the segments, evaluate the shortlist, choose the focus opportunity.</span></li><li value="5"><strong>Personas and positioning</strong><span> — persona matrices, a focus persona, and a positioning statement on the Geoffrey Moore template.</span></li><li value="6"><strong>Interviews and analysis</strong><span> — plan and script depth interviews, then analyse the findings systematically.</span></li> </ol> </section> <p>Guided validation for early-stage startups: from Business Model Canvas to
validated learning. Piloted with early-stage teams and mentors in Italy and
Malta — tell us which language you’re reading this in, and you’ll hear from us.</p> </main> <footer> <p>Guided validation for early-stage startups — from Business Model Canvas to validated learning.</p> <p> <a href="/privacy/">Privacy</a> ·
<a href="/cookies/">Cookies</a> ·
<a href="/admin/">This site is editable in the browser at /admin/ — no git knowledge required.</a> </p> <p>Hosted on EU infrastructure (Aruba, Italy).</p> </footer> <div id="cookie-consent" role="region" aria-label="We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in."> <p>We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in.</p> <button data-answer="yes">Allow analytics</button> <button data-answer="no">Decline</button> </div> </body></html>
+50
View File
@@ -0,0 +1,50 @@
<!DOCTYPE html><html lang="en" dir="ltr"> <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Privacy notice</title><meta name="description" content="How this website handles personal data — hosting, forms, analytics and your rights."><link rel="canonical" href="https://validationlab.eu/privacy/"><link rel="alternate" hreflang="en" href="https://validationlab.eu/privacy/"><link rel="alternate" hreflang="x-default" href="https://validationlab.eu/privacy/"><meta property="og:title" content="Privacy notice"><meta property="og:description" content="How this website handles personal data — hosting, forms, analytics and your rights."><meta property="og:url" content="https://validationlab.eu/privacy/"><meta property="og:type" content="website"><meta property="og:locale" content="en"><meta name="twitter:card" content="summary"><script type="application/ld+json">{"@context":"https://schema.org","@type":"Service","serviceType":"Innovation hub programmes","provider":{"@type":"Organization","name":"Validation Lab","url":"https://validationlab.eu"},"areaServed":"EU","url":"https://validationlab.eu/privacy/","description":"How this website handles personal data — hosting, forms, analytics and your rights."}</script><script>(() => {
// Cookie-gated analytics: nothing loads until the visitor opts in,
// and the choice is remembered in localStorage.
const banner = document.getElementById("cookie-consent");
if (!banner) return;
const KEY = "vl-consent";
const STATS_URL = "REPLACE_STATS_SCRIPT_URL";
const STATS_ID = "REPLACE_STATS_WEBSITE_ID";
const injectStats = () => {
if (STATS_URL.indexOf("REPLACE_") === 0 || document.getElementById("vl-stats")) return;
const s = document.createElement("script");
s.id = "vl-stats";
s.defer = true;
s.src = STATS_URL + "";
s.setAttribute("data-website-id", STATS_ID);
document.head.appendChild(s);
};
const decide = (allow) => {
try { localStorage.setItem(KEY, allow ? "granted" : "denied"); } catch {}
banner.remove();
if (allow) injectStats();
};
banner.addEventListener("click", (event) => {
const b = event.target.closest("button");
if (!b) return;
decide(b.dataset.answer === "yes");
});
let stored = null;
try { stored = localStorage.getItem(KEY); } catch {}
if (stored) {
banner.remove();
if (stored === "granted") injectStats();
}
})();</script><link rel="stylesheet" href="/_astro/cookies.a9D3y7n-.css"></head> <body> <header class="site-header"> <nav> <a class="brand" href="/">Validation Lab</a> <a href="/privacy/" aria-current="page">Privacy</a> <label class="switcher"> <span aria-hidden="true">Read this page in:</span> <select aria-label="Language" onchange="const u=new URL(this.value, location.origin); location.href = u.href;"> <option value="https://validationlab.eu/privacy/" selected> English </option> </select> </label> </nav> </header> <main> <p><strong>DRAFT — this notice needs legal review before launch.</strong></p>
<p>This website is operated by Validation Lab. The pages you read are served
from a self-managed server hosted by Aruba S.p.A. in Italy — all hosting,
storage and content stay on EU infrastructure.</p>
<p><strong>What we process.</strong> Reading this site processes no personal data beyond
standard server logs. If you send a message through one of our forms, we
receive the details you type (name, email, and whichever optional fields
you complete) plus the page language, and pass them to our CRM provider,
Zoho (EU data centres), to reply to you. If you allow analytics, a
self-hosted, privacy-first analytics tool records page views, the referrer
and the language you read — without cookies and without sharing data with
third parties. Analytics loads only after you opt in via the banner.</p>
<p><strong>Your data rights.</strong> You may request access to, correction of, or
erasure of your data at any time — write to us and we will action it.</p>
<p><strong>Email:</strong> <a href="mailto:hello@app.validationlab.eu">hello@app.validationlab.eu</a></p> </main> <footer> <p>Guided validation for early-stage startups — from Business Model Canvas to validated learning.</p> <p> <a href="/privacy/">Privacy</a> ·
<a href="/cookies/">Cookies</a> ·
<a href="/admin/">This site is editable in the browser at /admin/ — no git knowledge required.</a> </p> <p>Hosted on EU infrastructure (Aruba, Italy).</p> </footer> <div id="cookie-consent" role="region" aria-label="We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in."> <p>We use a self-hosted, privacy-first analytics tool to understand which pages and languages matter. Nothing is loaded until you opt in.</p> <button data-answer="yes">Allow analytics</button> <button data-answer="no">Decline</button> </div> </body></html>
+5
View File
@@ -0,0 +1,5 @@
User-agent: *
Allow: /
Disallow: /admin/
Sitemap: https://validationlab.eu/sitemap-index.xml
+1
View File
@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"><url><loc>https://validationlab.eu/</loc></url><url><loc>https://validationlab.eu/cookies/</loc></url><url><loc>https://validationlab.eu/for-founders/</loc></url><url><loc>https://validationlab.eu/for-innovation-hubs/</loc></url><url><loc>https://validationlab.eu/privacy/</loc></url></urlset>
+1
View File
@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><sitemap><loc>https://validationlab.eu/sitemap-0.xml</loc></sitemap></sitemapindex>
+1 -1
View File
@@ -1 +1 @@
[["Map",1,2],"meta::meta",["Map",3,4,5,6],"astro-version","5.18.2","astro-config-digest","{\"root\":{},\"srcDir\":{},\"publicDir\":{},\"outDir\":{},\"cacheDir\":{},\"site\":\"https://astro.validationlab.eu\",\"compressHTML\":true,\"base\":\"/\",\"trailingSlash\":\"ignore\",\"output\":\"static\",\"scopedStyleStrategy\":\"attribute\",\"build\":{\"format\":\"directory\",\"client\":{},\"server\":{},\"assets\":\"_astro\",\"serverEntry\":\"entry.mjs\",\"redirects\":true,\"inlineStylesheets\":\"auto\",\"concurrency\":1},\"server\":{\"open\":false,\"host\":false,\"port\":4321,\"streaming\":true,\"allowedHosts\":[]},\"redirects\":{},\"image\":{\"endpoint\":{\"route\":\"/_image\"},\"service\":{\"entrypoint\":\"astro/assets/services/sharp\",\"config\":{}},\"domains\":[],\"remotePatterns\":[],\"responsiveStyles\":false},\"devToolbar\":{\"enabled\":true},\"markdown\":{\"syntaxHighlight\":{\"type\":\"shiki\",\"excludeLangs\":[\"math\"]},\"shikiConfig\":{\"langs\":[],\"langAlias\":{},\"theme\":\"github-dark\",\"themes\":{},\"wrap\":false,\"transformers\":[]},\"remarkPlugins\":[],\"rehypePlugins\":[],\"remarkRehype\":{},\"gfm\":true,\"smartypants\":true},\"security\":{\"checkOrigin\":true,\"allowedDomains\":[],\"actionBodySizeLimit\":1048576},\"env\":{\"schema\":{},\"validateSecrets\":false},\"experimental\":{\"clientPrerender\":false,\"contentIntellisense\":false,\"headingIdCompat\":false,\"preserveScriptOrder\":false,\"liveContentCollections\":false,\"csp\":false,\"staticImportMetaEnv\":false,\"chromeDevtoolsWorkspace\":false,\"failOnPrerenderConflict\":false,\"svgo\":false},\"legacy\":{\"collections\":false}}"]
[["Map",1,2],"meta::meta",["Map",3,4,5,6],"astro-version","5.18.2","astro-config-digest","{\"root\":{},\"srcDir\":{},\"publicDir\":{},\"outDir\":{},\"cacheDir\":{},\"site\":\"https://validationlab.eu\",\"compressHTML\":true,\"base\":\"/\",\"trailingSlash\":\"ignore\",\"output\":\"static\",\"scopedStyleStrategy\":\"attribute\",\"build\":{\"format\":\"directory\",\"client\":{},\"server\":{},\"assets\":\"_astro\",\"serverEntry\":\"entry.mjs\",\"redirects\":true,\"inlineStylesheets\":\"auto\",\"concurrency\":1},\"server\":{\"open\":false,\"host\":false,\"port\":4321,\"streaming\":true,\"allowedHosts\":[]},\"redirects\":{},\"image\":{\"endpoint\":{\"route\":\"/_image\"},\"service\":{\"entrypoint\":\"astro/assets/services/sharp\",\"config\":{}},\"domains\":[],\"remotePatterns\":[],\"responsiveStyles\":false},\"devToolbar\":{\"enabled\":true},\"markdown\":{\"syntaxHighlight\":{\"type\":\"shiki\",\"excludeLangs\":[\"math\"]},\"shikiConfig\":{\"langs\":[],\"langAlias\":{},\"theme\":\"github-dark\",\"themes\":{},\"wrap\":false,\"transformers\":[]},\"remarkPlugins\":[],\"rehypePlugins\":[],\"remarkRehype\":{},\"gfm\":true,\"smartypants\":true},\"security\":{\"checkOrigin\":true,\"allowedDomains\":[],\"actionBodySizeLimit\":1048576},\"env\":{\"schema\":{},\"validateSecrets\":false},\"experimental\":{\"clientPrerender\":false,\"contentIntellisense\":false,\"headingIdCompat\":false,\"preserveScriptOrder\":false,\"liveContentCollections\":false,\"csp\":false,\"staticImportMetaEnv\":false,\"chromeDevtoolsWorkspace\":false,\"failOnPrerenderConflict\":false,\"svgo\":false},\"legacy\":{\"collections\":false}}"]
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../sitemap/dist/cli.js
+61
View File
@@ -57,6 +57,25 @@
"node": "18.20.8 || ^20.3.0 || >=22.0.0"
}
},
"node_modules/@astrojs/sitemap": {
"version": "3.7.6",
"resolved": "https://registry.npmjs.org/@astrojs/sitemap/-/sitemap-3.7.6.tgz",
"integrity": "sha512-QEKD3ubC0iJxpNzC4KvcKdxSP97U5SjuQ16+VkmUwx1TT+Hq7TIV8QGm/d2pvkN6+3GqGXLRzm7j6lZxHETm3A==",
"license": "MIT",
"dependencies": {
"sitemap": "^10.0.0",
"zod": "^4.6.7"
}
},
"node_modules/@astrojs/sitemap/node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/@astrojs/telemetry": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.0.tgz",
@@ -514,6 +533,24 @@
"@types/unist": "*"
}
},
"node_modules/@types/node": {
"version": "26.6.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/sax": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@types/sax/-/sax-1.2.7.tgz",
"integrity": "sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -3310,6 +3347,24 @@
"integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==",
"license": "MIT"
},
"node_modules/sitemap": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/sitemap/-/sitemap-10.0.0.tgz",
"integrity": "sha512-KSjl4H4KBEnGX5KXgzInPAycdOFhwLar0EmksDcYn6NqW2O+zLiMGeV2THE6tpuv3LCVdv+6xsSo2SWLGaBDKw==",
"license": "MIT",
"dependencies": {
"@types/node": "^22.0.0 || ^24.0.0 || ^26.0.0",
"@types/sax": "^1.2.1",
"sax": "^1.4.1"
},
"bin": {
"sitemap": "dist/cli.js"
},
"engines": {
"node": ">=22.22.1",
"npm": ">=10.8.2"
}
},
"node_modules/smol-toml": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz",
@@ -3556,6 +3611,12 @@
"node": ">=22.19.0"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"license": "MIT"
},
"node_modules/unified": {
"version": "11.0.5",
"resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
+6 -6
View File
@@ -1,25 +1,25 @@
{
"hash": "251abc19",
"hash": "d5107548",
"configHash": "7fd3838c",
"lockfileHash": "c4cec013",
"browserHash": "28dc24f4",
"lockfileHash": "256cca60",
"browserHash": "d846223f",
"optimized": {
"astro > cssesc": {
"src": "../../cssesc/cssesc.js",
"file": "astro___cssesc.js",
"fileHash": "621ff8f6",
"fileHash": "7182d6c6",
"needsInterop": true
},
"astro > aria-query": {
"src": "../../aria-query/lib/index.js",
"file": "astro___aria-query.js",
"fileHash": "82695953",
"fileHash": "9223ca2a",
"needsInterop": true
},
"astro > axobject-query": {
"src": "../../axobject-query/lib/index.js",
"file": "astro___axobject-query.js",
"fileHash": "26965e41",
"fileHash": "f86a104f",
"needsInterop": true
}
},
+59
View File
@@ -0,0 +1,59 @@
MIT License
Copyright (c) 2021 Fred K. Schott
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
"""
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
+38
View File
@@ -0,0 +1,38 @@
# @astrojs/sitemap 🗺
This **[Astro integration][astro-integration]** generates a sitemap based on your pages when you build your Astro project.
## Documentation
Read the [`@astrojs/sitemap` docs][docs]
## Support
- Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more!
- Check our [Astro Integration Documentation][astro-integration] for more on integrations.
- Submit bug reports and feature requests as [GitHub issues][issues].
## Contributing
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started:
- [Contributor Manual][contributing]
- [Code of Conduct][coc]
- [Community Guide][community]
## License
MIT
Copyright (c) 2023–present [Astro][astro]
[astro]: https://astro.build/
[docs]: https://docs.astro.build/en/guides/integrations-guide/sitemap/
[contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md
[coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md
[community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md
[discord]: https://astro.build/chat/
[issues]: https://github.com/withastro/astro/issues
[astro-integration]: https://docs.astro.build/en/guides/integrations/
+10
View File
@@ -0,0 +1,10 @@
export declare const SITEMAP_CONFIG_DEFAULTS: {
filenameBase: string;
entryLimit: number;
namespaces: {
news: true;
xhtml: true;
image: true;
video: true;
};
};
+10
View File
@@ -0,0 +1,10 @@
export const SITEMAP_CONFIG_DEFAULTS = {
filenameBase: "sitemap",
entryLimit: 45e3,
namespaces: {
news: true,
xhtml: true,
image: true,
video: true
}
};
+3
View File
@@ -0,0 +1,3 @@
import type { SitemapItem, SitemapOptions } from './index.js';
/** Construct sitemap.xml given a set of URLs */
export declare function generateSitemap(pages: string[], finalSiteUrl: string, opts?: SitemapOptions): SitemapItem[];
+57
View File
@@ -0,0 +1,57 @@
import { parseI18nUrl } from "./utils/parse-i18n-url.js";
/** Construct sitemap.xml given a set of URLs */
export function generateSitemap(pages, finalSiteUrl, opts) {
const { changefreq, priority, lastmod: lastmodSrc, i18n } = opts ?? {};
// TODO: find way to respect <link rel="canonical"> URLs here
const urls = [...pages];
urls.sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
const lastmod = lastmodSrc?.toISOString();
// Parse URLs for i18n matching later
const { defaultLocale, locales } = i18n ?? {};
let getI18nLinks;
if (defaultLocale && locales) {
getI18nLinks = createGetI18nLinks(urls, defaultLocale, locales, finalSiteUrl);
}
const urlData = urls.map((url, i) => ({
url,
links: getI18nLinks?.(i),
lastmod,
priority,
changefreq
}));
return urlData;
}
function createGetI18nLinks(urls, defaultLocale, locales, finalSiteUrl) {
// `parsedI18nUrls` will have the same length as `urls`, matching correspondingly
const parsedI18nUrls = urls.map((url) => parseI18nUrl(url, defaultLocale, locales, finalSiteUrl));
// Cache as multiple i18n URLs with the same path will have the same links
const i18nPathToLinksCache = new Map();
return (urlIndex) => {
const i18nUrl = parsedI18nUrls[urlIndex];
if (!i18nUrl) {
return undefined;
}
const cached = i18nPathToLinksCache.get(i18nUrl.path);
if (cached) {
return cached;
}
// Find all URLs with the same path (without the locale part), e.g. /en/foo and /es/foo
const links = [];
for (let i = 0; i < parsedI18nUrls.length; i++) {
const parsed = parsedI18nUrls[i];
if (parsed?.path === i18nUrl.path) {
links.push({
url: urls[i],
lang: locales[parsed.locale]
});
}
}
// If 0 or 1 (which is itself), return undefined to not create any links.
// We also don't need to cache this as we know there's no other URLs that would've match this.
if (links.length <= 1) {
return undefined;
}
i18nPathToLinksCache.set(i18nUrl.path, links);
return links;
};
}
+31
View File
@@ -0,0 +1,31 @@
import type { AstroIntegration } from 'astro';
import type { EnumChangefreq, LinkItem as LinkItemBase, SitemapItemLoose } from 'sitemap';
export { EnumChangefreq as ChangeFreqEnum } from 'sitemap';
export type ChangeFreq = `${EnumChangefreq}`;
export type SitemapItem = Pick<SitemapItemLoose, 'url' | 'lastmod' | 'changefreq' | 'priority' | 'links'>;
export type LinkItem = LinkItemBase;
export type SitemapOptions = {
filenameBase?: string;
filter?(page: string): boolean;
customSitemaps?: string[];
customPages?: string[];
i18n?: {
defaultLocale: string;
locales: Record<string, string>;
};
entryLimit?: number;
changefreq?: ChangeFreq;
lastmod?: Date;
priority?: number;
serialize?(item: SitemapItem): SitemapItem | Promise<SitemapItem | undefined> | undefined;
xslURL?: string;
chunks?: Record<string, (item: SitemapItem) => SitemapItem | Promise<SitemapItem | undefined> | undefined>;
namespaces?: {
news?: boolean;
xhtml?: boolean;
image?: boolean;
video?: boolean;
};
} | undefined;
declare const createPlugin: (options?: SitemapOptions) => AstroIntegration;
export default createPlugin;
+188
View File
@@ -0,0 +1,188 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import { ZodError } from "zod/v4";
import { generateSitemap } from "./generate-sitemap.js";
import { validateOptions } from "./validate-options.js";
import { writeSitemap } from "./write-sitemap.js";
import { writeSitemapChunk } from "./write-sitemap-chunk.js";
export { EnumChangefreq as ChangeFreqEnum } from "sitemap";
function formatConfigErrorMessage(err) {
const errorList = err.issues.map((issue) => ` ${issue.path.join(".")} ${issue.message + "."}`);
return errorList.join("\n");
}
const PKG_NAME = "@astrojs/sitemap";
const STATUS_CODE_PAGES = new Set(["404", "500"]);
const isStatusCodePage = (locales) => {
const statusPathNames = new Set(locales.flatMap((locale) => [...STATUS_CODE_PAGES].map((page) => `${locale}/${page}`)).concat([...STATUS_CODE_PAGES]));
return (pathname) => {
if (pathname.endsWith("/")) {
pathname = pathname.slice(0, -1);
}
if (pathname.startsWith("/")) {
pathname = pathname.slice(1);
}
return statusPathNames.has(pathname);
};
};
const createPlugin = (options) => {
let _routes;
let config;
return {
name: PKG_NAME,
hooks: {
"astro:routes:resolved": ({ routes }) => {
_routes = routes;
},
"astro:config:done": async ({ config: cfg }) => {
config = cfg;
},
"astro:build:done": async ({ dir, pages, logger }) => {
try {
if (!config.site) {
logger.warn("The Sitemap integration requires the `site` astro.config option. Skipping.");
return;
}
const opts = validateOptions(config.site, options);
const { filenameBase, filter, customPages, customSitemaps, serialize, entryLimit, chunks } = opts;
const outFile = `${filenameBase}-index.xml`;
const finalSiteUrl = new URL(config.base, config.site);
const shouldIgnoreStatus = isStatusCodePage(Object.keys(opts.i18n?.locales ?? {}));
let pageUrls = pages.filter((p) => !shouldIgnoreStatus(p.pathname)).map((p) => {
if (p.pathname !== "" && !finalSiteUrl.pathname.endsWith("/")) finalSiteUrl.pathname += "/";
if (p.pathname.startsWith("/")) p.pathname = p.pathname.slice(1);
const fullPath = finalSiteUrl.pathname + p.pathname;
return new URL(fullPath, finalSiteUrl).href;
});
const addRouteUrl = (urls, r) => {
/**
* Dynamic URLs have entries with `undefined` pathnames
*/
if (r.pathname) {
if (shouldIgnoreStatus(r.pathname ?? r.pattern)) return;
// `finalSiteUrl` may end with a trailing slash
// or not because of base paths.
let fullPath = finalSiteUrl.pathname;
if (fullPath.endsWith("/")) fullPath += r.generate(r.pathname).substring(1);
else fullPath += r.generate(r.pathname);
const newUrl = new URL(fullPath, finalSiteUrl).href;
if (config.trailingSlash === "never") {
urls.push(newUrl);
} else if (config.build.format === "directory" && !newUrl.endsWith("/")) {
urls.push(newUrl + "/");
} else {
urls.push(newUrl);
}
}
};
const routeUrls = _routes.reduce((urls, r) => {
// Only expose pages, not endpoints or redirects
if (r.type !== "page") return urls;
addRouteUrl(urls, r);
// Include i18n fallback routes (e.g. /fr/ falling back to /en/)
for (const fallbackRoute of r.fallbackRoutes ?? []) {
addRouteUrl(urls, fallbackRoute);
}
return urls;
}, []);
pageUrls = Array.from(new Set([
...pageUrls,
...routeUrls,
...customPages ?? []
]));
if (filter) {
pageUrls = pageUrls.filter((value) => filter(value));
}
if (pageUrls.length === 0) {
logger.warn(`No pages found!\n\`${outFile}\` not created.`);
return;
}
let urlData = generateSitemap(pageUrls, finalSiteUrl.href, opts);
if (serialize) {
try {
const serializedUrls = [];
for (const item of urlData) {
const serialized = await Promise.resolve(serialize(item));
if (serialized) {
serializedUrls.push(serialized);
}
}
if (serializedUrls.length === 0) {
logger.warn("No pages found!");
return;
}
urlData = serializedUrls;
} catch (err) {
logger.error(`Error serializing pages\n${err.toString()}`);
return;
}
}
const destDir = fileURLToPath(dir);
const lastmod = opts.lastmod?.toISOString();
const xslURL = opts.xslURL ? new URL(opts.xslURL, finalSiteUrl).href : undefined;
if (chunks) {
try {
const groupedUrlCollection = new Set();
const chunksItem = {};
for (const [key, cb] of Object.entries(chunks)) {
// Create a new, separate collection for each key
const collection = [];
for (const item of urlData) {
// Await the asynchronous operation
const collect = await Promise.resolve(cb(item));
if (collect) {
collection.push(collect);
}
}
// Assign the specific collection to its key
chunksItem[key] = collection;
for (const { url } of collection) {
groupedUrlCollection.add(url);
}
}
chunksItem["pages"] = urlData.filter((urlDataItem) => !groupedUrlCollection.has(urlDataItem.url));
// Process each chunk here
await writeSitemapChunk({
filenameBase,
hostname: finalSiteUrl.href,
sitemapHostname: finalSiteUrl.href,
sourceData: chunksItem,
destinationDir: destDir,
publicBasePath: config.base,
customSitemaps,
limit: entryLimit,
xslURL,
lastmod,
namespaces: opts.namespaces
});
logger.info(`\`${outFile}\` created at \`${path.relative(process.cwd(), destDir)}\``);
return;
} catch (err) {
logger.error(`Error chunking sitemaps\n${err.toString()}`);
return;
}
}
await writeSitemap({
filenameBase,
hostname: finalSiteUrl.href,
destinationDir: destDir,
publicBasePath: config.base,
sourceData: urlData,
limit: entryLimit,
customSitemaps,
xslURL,
lastmod,
namespaces: opts.namespaces
});
logger.info(`\`${outFile}\` created at \`${path.relative(process.cwd(), destDir)}\``);
} catch (err) {
if (err instanceof ZodError) {
logger.warn(formatConfigErrorMessage(err));
} else {
throw err;
}
}
}
}
};
};
export default createPlugin;
+26
View File
@@ -0,0 +1,26 @@
import { EnumChangefreq as ChangeFreq } from 'sitemap';
import * as z from 'zod/v4';
export declare const SitemapOptionsSchema: z.ZodDefault<z.ZodObject<{
filenameBase: z.ZodPrefault<z.ZodString>;
filter: z.ZodOptional<z.ZodFunction<z.ZodTuple<readonly [z.ZodString], null>, z.ZodBoolean>>;
customSitemaps: z.ZodOptional<z.ZodArray<z.ZodURL>>;
customPages: z.ZodOptional<z.ZodArray<z.ZodURL>>;
canonicalURL: z.ZodOptional<z.ZodURL>;
xslURL: z.ZodOptional<z.ZodString>;
i18n: z.ZodOptional<z.ZodObject<{
defaultLocale: z.ZodString;
locales: z.ZodRecord<z.ZodString, z.ZodString>;
}, z.core.$strip>>;
entryLimit: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
serialize: z.ZodOptional<z.ZodFunction<z.ZodTuple<readonly [z.ZodAny], null>, z.ZodAny>>;
changefreq: z.ZodOptional<z.ZodEnum<typeof ChangeFreq>>;
lastmod: z.ZodOptional<z.ZodDate>;
priority: z.ZodOptional<z.ZodNumber>;
namespaces: z.ZodDefault<z.ZodOptional<z.ZodObject<{
news: z.ZodOptional<z.ZodBoolean>;
xhtml: z.ZodOptional<z.ZodBoolean>;
image: z.ZodOptional<z.ZodBoolean>;
video: z.ZodOptional<z.ZodBoolean>;
}, z.core.$strip>>>;
chunks: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodFunction<z.ZodTuple<readonly [z.ZodAny], null>, z.ZodAny>>>;
}, z.core.$strict>>;
+37
View File
@@ -0,0 +1,37 @@
import { EnumChangefreq as ChangeFreq } from "sitemap";
import * as z from "zod/v4";
import { SITEMAP_CONFIG_DEFAULTS } from "./config-defaults.js";
const localeKeySchema = z.string().min(1);
export const SitemapOptionsSchema = z.object({
filenameBase: z.string().prefault(SITEMAP_CONFIG_DEFAULTS.filenameBase),
filter: z.function({
input: [z.string()],
output: z.boolean()
}).optional(),
customSitemaps: z.array(z.url()).optional(),
customPages: z.array(z.url()).optional(),
canonicalURL: z.url().optional(),
xslURL: z.string().optional(),
i18n: z.object({
defaultLocale: localeKeySchema,
locales: z.record(localeKeySchema, z.string().min(2).regex(/^[a-zA-Z\-]+$/gm, { message: "Only English alphabet symbols and hyphen allowed" }))
}).refine((val) => !val || Object.hasOwn(val.locales, val.defaultLocale), { message: "`defaultLocale` must exist in `locales` keys" }).optional(),
entryLimit: z.number().nonnegative().optional().default(SITEMAP_CONFIG_DEFAULTS.entryLimit),
serialize: z.function({
input: [z.any()],
output: z.any()
}).optional(),
changefreq: z.enum(ChangeFreq).optional(),
lastmod: z.date().optional(),
priority: z.number().min(0).max(1).optional(),
namespaces: z.object({
news: z.boolean().optional(),
xhtml: z.boolean().optional(),
image: z.boolean().optional(),
video: z.boolean().optional()
}).optional().default(SITEMAP_CONFIG_DEFAULTS.namespaces),
chunks: z.record(z.string(), z.function({
input: [z.any()],
output: z.any()
})).optional()
}).strict().default(SITEMAP_CONFIG_DEFAULTS);
+10
View File
@@ -0,0 +1,10 @@
import type { SitemapItem } from '../index.js';
/**
* Returns the most recent `lastmod` among the given sitemap items as an
* ISO 8601 string, or `undefined` when none of them carry a valid `lastmod`.
*
* Used to stamp each `<sitemap>` entry in the sitemap index with the freshest
* date present in the child sitemap it points to, so search engines can tell
* which child sitemaps actually changed without refetching all of them.
*/
export declare function getLatestLastmod(items: SitemapItem[]): string | undefined;
+20
View File
@@ -0,0 +1,20 @@
/**
* Returns the most recent `lastmod` among the given sitemap items as an
* ISO 8601 string, or `undefined` when none of them carry a valid `lastmod`.
*
* Used to stamp each `<sitemap>` entry in the sitemap index with the freshest
* date present in the child sitemap it points to, so search engines can tell
* which child sitemaps actually changed without refetching all of them.
*/
export function getLatestLastmod(items) {
let latest;
for (const item of items) {
if (!item.lastmod) continue;
const time = new Date(item.lastmod).getTime();
if (Number.isNaN(time)) continue;
if (latest === undefined || time > latest) {
latest = time;
}
}
return latest === undefined ? undefined : new Date(latest).toISOString();
}
+6
View File
@@ -0,0 +1,6 @@
interface ParsedI18nUrl {
locale: string;
path: string;
}
export declare function parseI18nUrl(url: string, defaultLocale: string, locales: Record<string, string>, base: string): ParsedI18nUrl | undefined;
export {};
+38
View File
@@ -0,0 +1,38 @@
// NOTE: The parameters have been schema-validated with Zod
export function parseI18nUrl(url, defaultLocale, locales, base) {
if (!url.startsWith(base)) {
return undefined;
}
let s = url.slice(base.length);
// Handle root URL
if (!s || s === "/") {
return {
locale: defaultLocale,
path: "/"
};
}
if (s[0] !== "/") {
s = "/" + s;
}
// Get locale from path, e.g.
// "/en-US/" -> "en-US"
// "/en-US/foo" -> "en-US"
const locale = s.split("/")[1];
// `Object.hasOwn`, not `in`: a page such as `/constructor/` or `/toString/`
// would otherwise match a property of `Object.prototype`.
if (Object.hasOwn(locales, locale)) {
// "/en-US/foo" -> "/foo"
let path = s.slice(1 + locale.length);
if (!path) {
path = "/";
}
return {
locale,
path
};
}
return {
locale: defaultLocale,
path: s
};
}
+1
View File
@@ -0,0 +1 @@
export {};
+14
View File
@@ -0,0 +1,14 @@
import * as z from "zod/v4";
import { SitemapOptionsSchema } from "./schema.js";
// @internal
export const validateOptions = (site, opts) => {
const result = SitemapOptionsSchema.parse(opts);
z.object({
site: z.string().optional(),
canonicalURL: z.string().optional()
}).refine((options) => options.site || options.canonicalURL, { message: "Required `site` astro.config option or `canonicalURL` integration option" }).parse({
site,
canonicalURL: result.canonicalURL
});
return result;
};
+21
View File
@@ -0,0 +1,21 @@
import type { SitemapItem } from './index.js';
type WriteSitemapChunkConfig = {
filenameBase: string;
hostname: string;
sitemapHostname?: string;
sourceData: Record<string, SitemapItem[]>;
destinationDir: string;
customSitemaps?: string[];
publicBasePath?: string;
limit?: number;
xslURL?: string;
lastmod?: string;
namespaces?: {
news?: boolean;
xhtml?: boolean;
image?: boolean;
video?: boolean;
};
};
export declare function writeSitemapChunk({ filenameBase, hostname, sitemapHostname, sourceData, destinationDir, limit, customSitemaps, publicBasePath, xslURL: xslUrl, lastmod, namespaces, }: WriteSitemapChunkConfig): Promise<void>;
export {};
+86
View File
@@ -0,0 +1,86 @@
import { createWriteStream } from "node:fs";
import { mkdir } from "node:fs/promises";
import { normalize, resolve } from "node:path";
import { pipeline, Readable } from "node:stream";
import { promisify } from "node:util";
import { SitemapAndIndexStream, SitemapIndexStream, SitemapStream } from "sitemap";
import { getLatestLastmod } from "./utils/lastmod.js";
// adapted from sitemap.js/sitemap-simple
export async function writeSitemapChunk({ filenameBase, hostname, sitemapHostname = hostname, sourceData, destinationDir, limit = 5e4, customSitemaps = [], publicBasePath = "./", xslURL: xslUrl, lastmod, namespaces = {
news: true,
xhtml: true,
image: true,
video: true
} }) {
await mkdir(destinationDir, { recursive: true });
// Normalize publicBasePath
let normalizedPublicBasePath = publicBasePath;
if (!normalizedPublicBasePath.endsWith("/")) {
normalizedPublicBasePath += "/";
}
// Array to collect all sitemap URLs for the index
const sitemapUrls = [];
// Process each chunk separately
for (const [chunkName, items] of Object.entries(sourceData)) {
const sitemapAndIndexStream = new SitemapAndIndexStream({
limit,
xslUrl,
getSitemapStream: (i) => {
const sitemapStream = new SitemapStream({
hostname,
xslUrl,
// Custom namespace handling
xmlns: {
news: namespaces?.news !== false,
xhtml: namespaces?.xhtml !== false,
image: namespaces?.image !== false,
video: namespaces?.video !== false
}
});
const path = `./${filenameBase}-${chunkName}-${i}.xml`;
const writePath = resolve(destinationDir, path);
const publicPath = normalize(normalizedPublicBasePath + path);
const stream = sitemapStream.pipe(createWriteStream(writePath));
const url = new URL(publicPath, sitemapHostname).toString();
// Stamp this index entry with the freshest lastmod among the
// URLs that land in this file (items are written in order,
// `limit` per file), falling back to the global `lastmod`.
const fileLastmod = getLatestLastmod(items.slice(i * limit, (i + 1) * limit)) ?? lastmod;
// Collect this sitemap URL for the index
sitemapUrls.push({
url,
lastmod: fileLastmod
});
return [
{
url,
lastmod: fileLastmod
},
sitemapStream,
stream
];
}
});
// Create a readable stream from this chunk's items
const dataStream = Readable.from(items);
// Write this chunk's sitemap(s)
await promisify(pipeline)(dataStream, sitemapAndIndexStream);
}
// Now create the sitemap index with all the generated sitemaps
const indexStream = new SitemapIndexStream({ xslUrl });
const indexPath = resolve(destinationDir, `./${filenameBase}-index.xml`);
const indexWriteStream = createWriteStream(indexPath);
// Add custom sitemaps to the index
for (const url of customSitemaps) {
indexStream.write({
url,
lastmod
});
}
// Add all generated sitemaps to the index
for (const sitemapUrl of sitemapUrls) {
indexStream.write(sitemapUrl);
}
indexStream.end();
return await promisify(pipeline)(indexStream, indexWriteStream);
}
+21
View File
@@ -0,0 +1,21 @@
import type { SitemapItem } from './index.js';
type WriteSitemapConfig = {
filenameBase: string;
hostname: string;
sitemapHostname?: string;
customSitemaps?: string[];
sourceData: SitemapItem[];
destinationDir: string;
publicBasePath?: string;
limit?: number;
xslURL?: string;
lastmod?: string;
namespaces?: {
news?: boolean;
xhtml?: boolean;
image?: boolean;
video?: boolean;
};
};
export declare function writeSitemap({ filenameBase, hostname, sitemapHostname, sourceData, destinationDir, limit, customSitemaps, publicBasePath, xslURL: xslUrl, lastmod, namespaces, }: WriteSitemapConfig): Promise<void>;
export {};
+62
View File
@@ -0,0 +1,62 @@
import { createWriteStream } from "node:fs";
import { mkdir } from "node:fs/promises";
import { normalize, resolve } from "node:path";
import { pipeline, Readable } from "node:stream";
import { promisify } from "node:util";
import { SitemapAndIndexStream, SitemapIndexStream, SitemapStream } from "sitemap";
import { getLatestLastmod } from "./utils/lastmod.js";
// adapted from sitemap.js/sitemap-simple
export async function writeSitemap({ filenameBase, hostname, sitemapHostname = hostname, sourceData, destinationDir, limit = 5e4, customSitemaps = [], publicBasePath = "./", xslURL: xslUrl, lastmod, namespaces = {
news: true,
xhtml: true,
image: true,
video: true
} }) {
await mkdir(destinationDir, { recursive: true });
const sitemapAndIndexStream = new SitemapAndIndexStream({
limit,
xslUrl,
getSitemapStream: (i) => {
const sitemapStream = new SitemapStream({
hostname,
xslUrl,
// Custom namespace handling
xmlns: {
news: namespaces?.news !== false,
xhtml: namespaces?.xhtml !== false,
image: namespaces?.image !== false,
video: namespaces?.video !== false
}
});
const path = `./${filenameBase}-${i}.xml`;
const writePath = resolve(destinationDir, path);
if (!publicBasePath.endsWith("/")) {
publicBasePath += "/";
}
const publicPath = normalize(publicBasePath + path);
const stream = sitemapStream.pipe(createWriteStream(writePath));
const url = new URL(publicPath, sitemapHostname).toString();
// Stamp this index entry with the freshest lastmod among the URLs
// that land in this file (items are written in order, `limit` per
// file), falling back to the configured global `lastmod`.
const fileLastmod = getLatestLastmod(sourceData.slice(i * limit, (i + 1) * limit)) ?? lastmod;
return [
{
url,
lastmod: fileLastmod
},
sitemapStream,
stream
];
}
});
const src = Readable.from(sourceData);
const indexPath = resolve(destinationDir, `./${filenameBase}-index.xml`);
for (const url of customSitemaps) {
SitemapIndexStream.prototype._transform.call(sitemapAndIndexStream, {
url,
lastmod
}, "utf8", () => {});
}
return promisify(pipeline)(src, sitemapAndIndexStream, createWriteStream(indexPath));
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Colin McDonnell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+218
View File
@@ -0,0 +1,218 @@
<p align="center">
<img src="logo.svg" width="200px" align="center" alt="Zod logo" />
<h1 align="center">Zod</h1>
<p align="center">
TypeScript-first schema validation with static type inference
<br/>
by <a href="https://x.com/colinhacks">@colinhacks</a>
</p>
</p>
<br/>
<p align="center">
<a href="https://github.com/colinhacks/zod/actions?query=branch%3Amain"><img src="https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="Zod CI status" /></a>
<a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/colinhacks/zod" alt="License"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a>
<a href="https://discord.gg/KaSRdyX2vc" rel="nofollow"><img src="https://img.shields.io/discord/893487829802418277?label=Discord&logo=discord&logoColor=white" alt="discord server"></a>
<a href="https://github.com/colinhacks/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/colinhacks/zod" alt="stars"></a>
</p>
<div align="center">
<a href="https://zod.dev/api">Docs</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://discord.gg/RcG33DQJdf">Discord</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://twitter.com/colinhacks">𝕏</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://bsky.app/profile/zod.dev">Bluesky</a>
<br />
</div>
<br/>
<br/>
### [Read the docs →](https://zod.dev/api)
<br/>
<br/>
## What is Zod?
Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result.
```ts
import * as z from "zod";
const User = z.object({
name: z.string(),
});
// some untrusted data...
const input = {
/* stuff */
};
// the parsed result is validated and type safe!
const data = User.parse(input);
// so you can use it with confidence :)
console.log(data.name);
```
<br/>
## Features
- Zero external dependencies
- Works in Node.js and all modern browsers
- Tiny: `2kb` core bundle (gzipped)
- Immutable API: methods return a new instance
- Concise interface
- Works with TypeScript and plain JS
- Built-in JSON Schema conversion
- Extensive ecosystem
<br/>
## Installation
```sh
npm install zod
```
<br/>
## Basic usage
Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema.
```ts
import * as z from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
```
### Parsing data
Given any Zod schema, use `.parse` to validate an input. If it's valid, Zod returns a strongly-typed _deep clone_ of the input.
```ts
Player.parse({ username: "billie", xp: 100 });
// => returns { username: "billie", xp: 100 }
```
**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](https://zod.dev/api#refinements) or [transforms](https://zod.dev/api#transforms), you'll need to use the `.parseAsync()` method instead.
```ts
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.parseAsync("hello");
// => "hello"
```
### AOT compilation
For hot validation paths, `z.compile(schema)` returns a schema clone with an ahead-of-time compiled fast path. Valid inputs take the compiled path; invalid inputs fall back to the regular parser so error reporting stays identical.
Across a 55-schema benchmark the median speedup is **2.4x**, and it scales with how much work the schema does per parse: a large array of objects is ~9x, a 20-key object ~9x, a nested object ~4.5x, while a bare `z.string()` gains nothing — compilation removes per-node dispatch and allocation, and a single `typeof` has none to remove.
```ts
const CompiledPlayer = z.compile(Player);
CompiledPlayer.parse({ username: "billie", xp: 100 });
```
To enable compilation globally for schemas constructed after import:
```ts
import "zod/compile"; // place before modules that define schemas
```
Things to know:
- Compilation uses `new Function`. Global mode is automatically disabled when `z.config({ jitless: true })` is set (e.g. CSP environments); calling `z.compile()` directly is an explicit opt-in.
- Schemas with async refinements or transforms can't be compiled, and neither can a few other constructs. That is not an error: `z.compile()` hands the schema back unchanged and it keeps using the regular parser, exactly as global mode leaves it. Pass `{ strict: true }` to throw `ZodCompileAsyncError` / `ZodCompileUnsupportedError` instead.
- On invalid input, refinements and transforms may run twice (fast path, then fallback).
- Deriving a new schema from a compiled one (`.refine()`, `.extend()`, etc.) returns an uncompiled schema — compile the final schema.
See [`compile` docs](https://zod.dev/compile) for details.
### Handling errors
When validation fails, the `.parse()` method will throw a `ZodError` instance with granular information about the validation issues.
```ts
try {
Player.parse({ username: 42, xp: "100" });
} catch (err) {
if (err instanceof z.ZodError) {
err.issues;
/* [
{
expected: 'string',
code: 'invalid_type',
path: [ 'username' ],
message: 'Invalid input: expected string, received number'
},
{
expected: 'number',
code: 'invalid_type',
path: [ 'xp' ],
message: 'Invalid input: expected number, received string'
}
] */
}
}
```
To avoid a `try/catch` block, you can use the `.safeParse()` method to get back a plain result object containing either the successfully parsed data or a `ZodError`. The result type is a [discriminated union](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions), so you can handle both cases conveniently.
```ts
const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
result.error; // ZodError instance
} else {
result.data; // { username: string; xp: number }
}
```
**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](https://zod.dev/api#refinements) or [transforms](https://zod.dev/api#transforms), you'll need to use the `.safeParseAsync()` method instead.
```ts
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.safeParseAsync("hello");
// => { success: true; data: "hello" }
```
### Inferring types
Zod infers a static type from your schema definitions. You can extract this type with the `z.infer<>` utility and use it however you like.
```ts
const Player = z.object({
username: z.string(),
xp: z.number(),
});
// extract the inferred type
type Player = z.infer<typeof Player>;
// use it in your code
const player: Player = { username: "billie", xp: 100 };
```
In some cases, the input & output types of a schema can diverge. For instance, the `.transform()` API can convert the input from one type to another. In these cases, you can extract the input and output types independently:
```ts
const mySchema = z.string().transform((val) => val.length);
type MySchemaIn = z.input<typeof mySchema>;
// => string
type MySchemaOut = z.output<typeof mySchema>; // equivalent to z.infer<typeof mySchema>
// number
```
+96
View File
@@ -0,0 +1,96 @@
"use strict";
// Side-effect-only: installs the post-processor on `globalConfig`. Listed in `package.json`'s `sideEffects`, and nothing else references it, so apps that never import it drop the compiler.
//
// Usage:
//
// import "zod/compile";
// import * as z from "zod";
// // every schema constructed below this is compiled on first parse
//
// Module evaluation order matters: schemas constructed in modules that evaluate before this import will not be compiled. Place this import in the app entry point, before any module that constructs schemas at top level.
//
// Failure handling: if the compiler refuses a schema (async refinement, unsupported feature, etc.) the shim permanently restores the runtime `_zod.run` for that schema. The schema continues to work via the regular runtime parser — no observable difference to the caller.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__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 });
const compile_js_1 = require("./v4/core/compile.cjs");
const core = __importStar(require("./v4/core/index.cjs"));
let compiling = false;
core.globalConfig.postProcessor = (inst) => {
if (compiling)
return;
const originalRun = inst._zod?.run;
if (typeof originalRun !== "function")
return;
const shim = (payload, ctx) => {
// Bypass the fast path for any non-forward / non-sync / check-skipping call. The runtime owns those contracts.
if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks) {
return originalRun(payload, ctx);
}
compiling = true;
try {
// Respect the jitless config: it exists precisely so CSP/no-eval environments never reach `new Function`. Global mode must not bypass it (explicit z.compile calls remain an explicit opt-in).
if (core.globalConfig.jitless) {
inst._zod.run = originalRun;
return originalRun(payload, ctx);
}
// Strict: the shim owns its own fallback below, and a non-strict compile would hand back `inst` — whose run is this shim — and reinstall it on itself.
const compiled = (0, compile_js_1.compile)(inst, { strict: true });
// Only the run wrapper. Copying the compiled parse/safeParse closures would make their fallback re-enter this instance and run user callbacks a third time.
inst._zod.run = compiled._zod.run;
inst._zod.bag.fallbackRun = compiled._zod.bag.fallbackRun;
inst._zod.bag.validator = compiled._zod.bag.validator;
}
catch {
// Permanent fallback for unsupported schemas.
inst._zod.run = originalRun;
}
finally {
compiling = false;
}
return inst._zod.run(payload, ctx);
};
// Expose the pre-shim runtime so `compile()` invoked elsewhere can unwrap past the shim and capture the source-of-truth runtime. Without this, a user calling `z.compile(s)` after global mode is enabled would capture the shim itself, which would feed the wrapper into itself on fallback.
shim.__originalRun = originalRun;
inst._zod.run = shim;
};
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+1
View File
@@ -0,0 +1 @@
export {};
+1
View File
@@ -0,0 +1 @@
export {};
+52
View File
@@ -0,0 +1,52 @@
// Side-effect-only: installs the post-processor on `globalConfig`. Listed in `package.json`'s `sideEffects`, and nothing else references it, so apps that never import it drop the compiler.
//
// Usage:
//
// import "zod/compile";
// import * as z from "zod";
// // every schema constructed below this is compiled on first parse
//
// Module evaluation order matters: schemas constructed in modules that evaluate before this import will not be compiled. Place this import in the app entry point, before any module that constructs schemas at top level.
//
// Failure handling: if the compiler refuses a schema (async refinement, unsupported feature, etc.) the shim permanently restores the runtime `_zod.run` for that schema. The schema continues to work via the regular runtime parser — no observable difference to the caller.
import { compile } from "./v4/core/compile.js";
import * as core from "./v4/core/index.js";
let compiling = false;
core.globalConfig.postProcessor = (inst) => {
if (compiling)
return;
const originalRun = inst._zod?.run;
if (typeof originalRun !== "function")
return;
const shim = (payload, ctx) => {
// Bypass the fast path for any non-forward / non-sync / check-skipping call. The runtime owns those contracts.
if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks) {
return originalRun(payload, ctx);
}
compiling = true;
try {
// Respect the jitless config: it exists precisely so CSP/no-eval environments never reach `new Function`. Global mode must not bypass it (explicit z.compile calls remain an explicit opt-in).
if (core.globalConfig.jitless) {
inst._zod.run = originalRun;
return originalRun(payload, ctx);
}
// Strict: the shim owns its own fallback below, and a non-strict compile would hand back `inst` — whose run is this shim — and reinstall it on itself.
const compiled = compile(inst, { strict: true });
// Only the run wrapper. Copying the compiled parse/safeParse closures would make their fallback re-enter this instance and run user callbacks a third time.
inst._zod.run = compiled._zod.run;
inst._zod.bag.fallbackRun = compiled._zod.bag.fallbackRun;
inst._zod.bag.validator = compiled._zod.bag.validator;
}
catch {
// Permanent fallback for unsupported schemas.
inst._zod.run = originalRun;
}
finally {
compiling = false;
}
return inst._zod.run(payload, ctx);
};
// Expose the pre-shim runtime so `compile()` invoked elsewhere can unwrap past the shim and capture the source-of-truth runtime. Without this, a user calling `z.compile(s)` after global mode is enabled would capture the shim itself, which would feed the wrapper into itself on fallback.
shim.__originalRun = originalRun;
inst._zod.run = shim;
};
+52
View File
@@ -0,0 +1,52 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__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;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.z = void 0;
const z = __importStar(require("./v4/classic/external.cjs"));
exports.z = z;
exports.default = z;
__exportStar(require("./v4/classic/external.cjs"), exports);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+3
View File
@@ -0,0 +1,3 @@
import * as z from "./v4/classic/external.cjs";
export * from "./v4/classic/external.cjs";
export { z, z as default };
+3
View File
@@ -0,0 +1,3 @@
import * as z from "./v4/classic/external.js";
export * from "./v4/classic/external.js";
export { z, z as default };
+7
View File
@@ -0,0 +1,7 @@
import * as z from "./v4/classic/external.js";
export * from "./v4/classic/external.js";
// Aliasing the binding, instead of `export default z`, keeps the default export a
// re-export of `z` rather than a fresh namespace value. Rollup and Webpack can then
// shake `import z from "zod"` as they already shake `import { z } from "zod"` — without
// this they pull in every locale. See #6050.
export { z, z as default };
+36
View File
@@ -0,0 +1,36 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("../v4/locales/index.cjs"), exports);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+1
View File
@@ -0,0 +1 @@
export * from "../v4/locales/index.cjs";
+1
View File
@@ -0,0 +1 @@
export * from "../v4/locales/index.js";
+1
View File
@@ -0,0 +1 @@
export * from "../v4/locales/index.js";
+7
View File
@@ -0,0 +1,7 @@
{
"type": "module",
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.cts",
"sideEffects": false
}
+51
View File
@@ -0,0 +1,51 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__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;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.z = void 0;
const z = __importStar(require("../v4/mini/external.cjs"));
exports.z = z;
__exportStar(require("../v4/mini/external.cjs"), exports);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+3
View File
@@ -0,0 +1,3 @@
import * as z from "../v4/mini/external.cjs";
export * from "../v4/mini/external.cjs";
export { z };
+3
View File
@@ -0,0 +1,3 @@
import * as z from "../v4/mini/external.js";
export * from "../v4/mini/external.js";
export { z };
+3
View File
@@ -0,0 +1,3 @@
import * as z from "../v4/mini/external.js";
export * from "../v4/mini/external.js";
export { z };
+7
View File
@@ -0,0 +1,7 @@
{
"type": "module",
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.cts",
"sideEffects": false
}
+147
View File
@@ -0,0 +1,147 @@
{
"name": "zod",
"version": "4.6.7",
"type": "module",
"license": "MIT",
"author": "Colin McDonnell <zod@colinhacks.com>",
"description": "TypeScript-first schema declaration and validation library with static type inference",
"homepage": "https://zod.dev",
"llms": "https://zod.dev/llms.txt",
"llmsFull": "https://zod.dev/llms-full.txt",
"mcpServer": "https://mcp.inkeep.com/zod/mcp",
"funding": "https://github.com/sponsors/colinhacks",
"sideEffects": [
"./compile.js",
"./compile.cjs",
"./src/compile.ts"
],
"files": [
"src",
"**/*.js",
"**/*.mjs",
"**/*.cjs",
"**/*.d.ts",
"**/*.d.mts",
"**/*.d.cts",
"**/package.json"
],
"keywords": [
"typescript",
"schema",
"validation",
"type",
"inference"
],
"main": "./index.cjs",
"types": "./index.d.cts",
"module": "./index.js",
"zshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts",
"./mini": "./src/mini/index.ts",
"./compile": "./src/compile.ts",
"./locales": "./src/locales/index.ts",
"./v3": "./src/v3/index.ts",
"./v4": "./src/v4/index.ts",
"./v4-mini": "./src/v4-mini/index.ts",
"./v4/mini": "./src/v4/mini/index.ts",
"./v4/core": "./src/v4/core/index.ts",
"./v4/locales": "./src/v4/locales/index.ts",
"./v4/locales/*": "./src/v4/locales/*"
},
"conditions": {
"@zod/source": "src"
},
"sealCjsExports": true
},
"exports": {
"./package.json": "./package.json",
".": {
"@zod/source": "./src/index.ts",
"types": "./index.d.cts",
"import": "./index.js",
"require": "./index.cjs"
},
"./mini": {
"@zod/source": "./src/mini/index.ts",
"types": "./mini/index.d.cts",
"import": "./mini/index.js",
"require": "./mini/index.cjs"
},
"./compile": {
"@zod/source": "./src/compile.ts",
"types": "./compile.d.cts",
"import": "./compile.js",
"require": "./compile.cjs"
},
"./locales": {
"@zod/source": "./src/locales/index.ts",
"types": "./locales/index.d.cts",
"import": "./locales/index.js",
"require": "./locales/index.cjs"
},
"./v3": {
"@zod/source": "./src/v3/index.ts",
"types": "./v3/index.d.cts",
"import": "./v3/index.js",
"require": "./v3/index.cjs"
},
"./v4": {
"@zod/source": "./src/v4/index.ts",
"types": "./v4/index.d.cts",
"import": "./v4/index.js",
"require": "./v4/index.cjs"
},
"./v4-mini": {
"@zod/source": "./src/v4-mini/index.ts",
"types": "./v4-mini/index.d.cts",
"import": "./v4-mini/index.js",
"require": "./v4-mini/index.cjs"
},
"./v4/mini": {
"@zod/source": "./src/v4/mini/index.ts",
"types": "./v4/mini/index.d.cts",
"import": "./v4/mini/index.js",
"require": "./v4/mini/index.cjs"
},
"./v4/core": {
"@zod/source": "./src/v4/core/index.ts",
"types": "./v4/core/index.d.cts",
"import": "./v4/core/index.js",
"require": "./v4/core/index.cjs"
},
"./v4/locales": {
"@zod/source": "./src/v4/locales/index.ts",
"types": "./v4/locales/index.d.cts",
"import": "./v4/locales/index.js",
"require": "./v4/locales/index.cjs"
},
"./v4/locales/*": {
"@zod/source": "./src/v4/locales/*",
"types": "./v4/locales/*",
"import": "./v4/locales/*",
"require": "./v4/locales/*"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/colinhacks/zod.git"
},
"bugs": {
"url": "https://github.com/colinhacks/zod/issues"
},
"support": {
"backing": {
"npm-funding": true
}
},
"scripts": {
"clean": "git clean -xdf . -e node_modules",
"build": "nub exec --node zshy --project tsconfig.build.json",
"postbuild": "nub ../../scripts/write-stub-package-jsons.ts && nub exec --node biome check --write .",
"test:watch": "nub exec --node vitest",
"test": "nub exec --node vitest run",
"prepublishOnly": "nub ../../scripts/check-versions.ts"
}
}
+56
View File
@@ -0,0 +1,56 @@
// Side-effect-only: installs the post-processor on `globalConfig`. Listed in `package.json`'s `sideEffects`, and nothing else references it, so apps that never import it drop the compiler.
//
// Usage:
//
// import "zod/compile";
// import * as z from "zod";
// // every schema constructed below this is compiled on first parse
//
// Module evaluation order matters: schemas constructed in modules that evaluate before this import will not be compiled. Place this import in the app entry point, before any module that constructs schemas at top level.
//
// Failure handling: if the compiler refuses a schema (async refinement, unsupported feature, etc.) the shim permanently restores the runtime `_zod.run` for that schema. The schema continues to work via the regular runtime parser — no observable difference to the caller.
import { compile } from "./v4/core/compile.js";
import * as core from "./v4/core/index.js";
let compiling = false;
core.globalConfig.postProcessor = (inst: any) => {
if (compiling) return;
const originalRun = inst._zod?.run;
if (typeof originalRun !== "function") return;
const shim = (payload: any, ctx: any): any => {
// Bypass the fast path for any non-forward / non-sync / check-skipping call. The runtime owns those contracts.
if (ctx?.async || ctx?.direction === "backward" || ctx?.skipChecks) {
return originalRun(payload, ctx);
}
compiling = true;
try {
// Respect the jitless config: it exists precisely so CSP/no-eval environments never reach `new Function`. Global mode must not bypass it (explicit z.compile calls remain an explicit opt-in).
if (core.globalConfig.jitless) {
inst._zod.run = originalRun;
return originalRun(payload, ctx);
}
// Strict: the shim owns its own fallback below, and a non-strict compile would hand back `inst` — whose run is this shim — and reinstall it on itself.
const compiled = compile(inst, { strict: true });
// Only the run wrapper. Copying the compiled parse/safeParse closures would make their fallback re-enter this instance and run user callbacks a third time.
inst._zod.run = compiled._zod.run;
inst._zod.bag.fallbackRun = compiled._zod.bag.fallbackRun;
inst._zod.bag.validator = compiled._zod.bag.validator;
} catch {
// Permanent fallback for unsupported schemas.
inst._zod.run = originalRun;
} finally {
compiling = false;
}
return inst._zod.run(payload, ctx);
};
// Expose the pre-shim runtime so `compile()` invoked elsewhere can unwrap past the shim and capture the source-of-truth runtime. Without this, a user calling `z.compile(s)` after global mode is enabled would capture the shim itself, which would feed the wrapper into itself on fallback.
(shim as any).__originalRun = originalRun;
inst._zod.run = shim;
};
+7
View File
@@ -0,0 +1,7 @@
import * as z from "./v4/classic/external.js";
export * from "./v4/classic/external.js";
// Aliasing the binding, instead of `export default z`, keeps the default export a
// re-export of `z` rather than a fresh namespace value. Rollup and Webpack can then
// shake `import z from "zod"` as they already shake `import { z } from "zod"` — without
// this they pull in every locale. See #6050.
export { z, z as default };
+1
View File
@@ -0,0 +1 @@
export * from "../v4/locales/index.js";
+3
View File
@@ -0,0 +1,3 @@
import * as z from "../v4/mini/external.js";
export * from "../v4/mini/external.js";
export { z };
+340
View File
@@ -0,0 +1,340 @@
import type { Primitive } from "./helpers/typeAliases.js";
import { util, type ZodParsedType } from "./helpers/util.js";
import type { TypeOf, ZodType } from "./index.js";
type allKeys<T> = T extends any ? keyof T : never;
export type inferFlattenedErrors<T extends ZodType<any, any, any>, U = string> = typeToFlattenedError<TypeOf<T>, U>;
export type typeToFlattenedError<T, U = string> = {
formErrors: U[];
fieldErrors: {
[P in allKeys<T>]?: U[];
};
};
export const ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite",
]);
export type ZodIssueCode = keyof typeof ZodIssueCode;
export type ZodIssueBase = {
path: (string | number)[];
message?: string | undefined;
};
export interface ZodInvalidTypeIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_type;
expected: ZodParsedType;
received: ZodParsedType;
}
export interface ZodInvalidLiteralIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_literal;
expected: unknown;
received: unknown;
}
export interface ZodUnrecognizedKeysIssue extends ZodIssueBase {
code: typeof ZodIssueCode.unrecognized_keys;
keys: string[];
}
export interface ZodInvalidUnionIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_union;
unionErrors: ZodError[];
}
export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_union_discriminator;
options: Primitive[];
}
export interface ZodInvalidEnumValueIssue extends ZodIssueBase {
received: string | number;
code: typeof ZodIssueCode.invalid_enum_value;
options: (string | number)[];
}
export interface ZodInvalidArgumentsIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_arguments;
argumentsError: ZodError;
}
export interface ZodInvalidReturnTypeIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_return_type;
returnTypeError: ZodError;
}
export interface ZodInvalidDateIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_date;
}
export type StringValidation =
| "email"
| "url"
| "emoji"
| "uuid"
| "nanoid"
| "regex"
| "cuid"
| "cuid2"
| "ulid"
| "datetime"
| "date"
| "time"
| "duration"
| "ip"
| "cidr"
| "base64"
| "jwt"
| "base64url"
| { includes: string; position?: number | undefined }
| { startsWith: string }
| { endsWith: string };
export interface ZodInvalidStringIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_string;
validation: StringValidation;
}
export interface ZodTooSmallIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_small;
minimum: number | bigint;
inclusive: boolean;
exact?: boolean;
type: "array" | "string" | "number" | "set" | "date" | "bigint";
}
export interface ZodTooBigIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_big;
maximum: number | bigint;
inclusive: boolean;
exact?: boolean;
type: "array" | "string" | "number" | "set" | "date" | "bigint";
}
export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_intersection_types;
}
export interface ZodNotMultipleOfIssue extends ZodIssueBase {
code: typeof ZodIssueCode.not_multiple_of;
multipleOf: number | bigint;
}
export interface ZodNotFiniteIssue extends ZodIssueBase {
code: typeof ZodIssueCode.not_finite;
}
export interface ZodCustomIssue extends ZodIssueBase {
code: typeof ZodIssueCode.custom;
params?: { [k: string]: any };
}
export type DenormalizedError = { [k: string]: DenormalizedError | string[] };
export type ZodIssueOptionalMessage =
| ZodInvalidTypeIssue
| ZodInvalidLiteralIssue
| ZodUnrecognizedKeysIssue
| ZodInvalidUnionIssue
| ZodInvalidUnionDiscriminatorIssue
| ZodInvalidEnumValueIssue
| ZodInvalidArgumentsIssue
| ZodInvalidReturnTypeIssue
| ZodInvalidDateIssue
| ZodInvalidStringIssue
| ZodTooSmallIssue
| ZodTooBigIssue
| ZodInvalidIntersectionTypesIssue
| ZodNotMultipleOfIssue
| ZodNotFiniteIssue
| ZodCustomIssue;
export type ZodIssue = ZodIssueOptionalMessage & {
fatal?: boolean | undefined;
message: string;
};
export const quotelessJson = (obj: any) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
type recursiveZodFormattedError<T> = T extends [any, ...any[]]
? { [K in keyof T]?: ZodFormattedError<T[K]> }
: T extends any[]
? { [k: number]: ZodFormattedError<T[number]> }
: T extends object
? { [K in keyof T]?: ZodFormattedError<T[K]> }
: unknown;
export type ZodFormattedError<T, U = string> = {
_errors: U[];
} & recursiveZodFormattedError<NonNullable<T>>;
export type inferFormattedError<T extends ZodType<any, any, any>, U = string> = ZodFormattedError<TypeOf<T>, U>;
export class ZodError<T = any> extends Error {
issues: ZodIssue[] = [];
get errors() {
return this.issues;
}
constructor(issues: ZodIssue[]) {
super();
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
// eslint-disable-next-line ban/ban
Object.setPrototypeOf(this, actualProto);
} else {
(this as any).__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(): ZodFormattedError<T>;
format<U>(mapper: (issue: ZodIssue) => U): ZodFormattedError<T, U>;
format(_mapper?: any) {
const mapper: (issue: ZodIssue) => any =
_mapper ||
function (issue: ZodIssue) {
return issue.message;
};
const fieldErrors: ZodFormattedError<T> = { _errors: [] } as any;
const processError = (error: ZodError) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
(fieldErrors as any)._errors.push(mapper(issue));
} else {
let curr: any = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i]!;
const terminal = i === issue.path.length - 1;
// `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.
if (el === "_errors") {
if (terminal) curr._errors.push(mapper(issue));
i++;
continue;
}
// Create `el` as an own data property. A segment naming an inherited member ("toString", "constructor") would otherwise read through to the prototype, and assigning "__proto__" would hit the setter and walk into Object.prototype.
if (!Object.prototype.hasOwnProperty.call(curr, el)) {
if (el === "__proto__") {
Object.defineProperty(curr, el, {
value: { _errors: [] },
writable: true,
enumerable: true,
configurable: true,
});
} else {
curr[el] = { _errors: [] };
}
}
curr = curr[el];
if (terminal) {
curr._errors.push(mapper(issue));
}
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static create = (issues: ZodIssue[]) => {
const error = new ZodError(issues);
return error;
};
static assert(value: unknown): asserts value is ZodError {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
override toString() {
return this.message;
}
override get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty(): boolean {
return this.issues.length === 0;
}
addIssue = (sub: ZodIssue) => {
this.issues = [...this.issues, sub];
};
addIssues = (subs: ZodIssue[] = []) => {
this.issues = [...this.issues, ...subs];
};
flatten(): typeToFlattenedError<T>;
flatten<U>(mapper?: (issue: ZodIssue) => U): typeToFlattenedError<T, U>;
flatten<U = string>(mapper: (issue: ZodIssue) => U = (issue: ZodIssue) => issue.message as any): any {
const fieldErrors: any = Object.create(null);
const formErrors: U[] = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
const firstEl = sub.path[0]!;
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
type stripPath<T extends object> = T extends any ? util.OmitKeys<T, "path"> : never;
export type IssueData = stripPath<ZodIssueOptionalMessage> & {
path?: (string | number)[];
fatal?: boolean | undefined;
};
export type ErrorMapCtx = {
defaultError: string;
data: any;
};
export type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => { message: string };
@@ -0,0 +1,58 @@
import Benchmark from "benchmark";
const datetimeValidationSuite = new Benchmark.Suite("datetime");
const DATA = "2021-01-01";
const MONTHS_31 = new Set([1, 3, 5, 7, 8, 10, 12]);
const MONTHS_30 = new Set([4, 6, 9, 11]);
const simpleDatetimeRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
const datetimeRegexNoLeapYearValidation =
/^\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d))$/;
const datetimeRegexWithLeapYearValidation =
/^((\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])))$/;
datetimeValidationSuite
.add("new Date()", () => {
return !Number.isNaN(new Date(DATA).getTime());
})
.add("regex (no validation)", () => {
return simpleDatetimeRegex.test(DATA);
})
.add("regex (no leap year)", () => {
return datetimeRegexNoLeapYearValidation.test(DATA);
})
.add("regex (w/ leap year)", () => {
return datetimeRegexWithLeapYearValidation.test(DATA);
})
.add("capture groups + code", () => {
const match = DATA.match(simpleDatetimeRegex);
if (!match) return false;
// Extract year, month, and day from the capture groups
const year = Number.parseInt(match[1], 10);
const month = Number.parseInt(match[2], 10); // month is 0-indexed in JavaScript Date, so subtract 1
const day = Number.parseInt(match[3], 10);
if (month === 2) {
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
return day <= 29;
}
return day <= 28;
}
if (MONTHS_30.has(month)) {
return day <= 30;
}
if (MONTHS_31.has(month)) {
return day <= 31;
}
return false;
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${datetimeValidationSuite.name!}: ${e.target}`);
});
export default {
suites: [datetimeValidationSuite],
};
@@ -0,0 +1,80 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const doubleSuite = new Benchmark.Suite("z.discriminatedUnion: double");
const manySuite = new Benchmark.Suite("z.discriminatedUnion: many");
const aSchema = z.object({
type: z.literal("a"),
});
const objA = {
type: "a",
};
const bSchema = z.object({
type: z.literal("b"),
});
const objB = {
type: "b",
};
const cSchema = z.object({
type: z.literal("c"),
});
const objC = {
type: "c",
};
const dSchema = z.object({
type: z.literal("d"),
});
const double = z.discriminatedUnion("type", [aSchema, bSchema]);
const many = z.discriminatedUnion("type", [aSchema, bSchema, cSchema, dSchema]);
doubleSuite
.add("valid: a", () => {
double.parse(objA);
})
.add("valid: b", () => {
double.parse(objB);
})
.add("invalid: null", () => {
try {
double.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
double.parse(objC);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(doubleSuite as any).name}: ${e.target}`);
});
manySuite
.add("valid: a", () => {
many.parse(objA);
})
.add("valid: c", () => {
many.parse(objC);
})
.add("invalid: null", () => {
try {
many.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
many.parse({ type: "unknown" });
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(manySuite as any).name}: ${e.target}`);
});
export default {
suites: [doubleSuite, manySuite],
};
@@ -0,0 +1,59 @@
import type Benchmark from "benchmark";
import datetimeBenchmarks from "./datetime.js";
import discriminatedUnionBenchmarks from "./discriminatedUnion.js";
import ipv4Benchmarks from "./ipv4.js";
import objectBenchmarks from "./object.js";
import primitiveBenchmarks from "./primitives.js";
import realworld from "./realworld.js";
import stringBenchmarks from "./string.js";
import unionBenchmarks from "./union.js";
const argv = process.argv.slice(2);
let suites: Benchmark.Suite[] = [];
if (!argv.length) {
suites = [
...realworld.suites,
...primitiveBenchmarks.suites,
...stringBenchmarks.suites,
...objectBenchmarks.suites,
...unionBenchmarks.suites,
...discriminatedUnionBenchmarks.suites,
];
} else {
if (argv.includes("--realworld")) {
suites.push(...realworld.suites);
}
if (argv.includes("--primitives")) {
suites.push(...primitiveBenchmarks.suites);
}
if (argv.includes("--string")) {
suites.push(...stringBenchmarks.suites);
}
if (argv.includes("--object")) {
suites.push(...objectBenchmarks.suites);
}
if (argv.includes("--union")) {
suites.push(...unionBenchmarks.suites);
}
if (argv.includes("--discriminatedUnion")) {
suites.push(...datetimeBenchmarks.suites);
}
if (argv.includes("--datetime")) {
suites.push(...datetimeBenchmarks.suites);
}
if (argv.includes("--ipv4")) {
suites.push(...ipv4Benchmarks.suites);
}
}
for (const suite of suites) {
suite.run({});
}
// exit on Ctrl-C
process.on("SIGINT", function () {
console.log("Exiting...");
process.exit();
});
@@ -0,0 +1,57 @@
import Benchmark from "benchmark";
const suite = new Benchmark.Suite("ipv4");
const DATA = "127.0.0.1";
const ipv4RegexA =
/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
const ipv4RegexB =
/^(?:(?:(?=(25[0-5]))\1|(?=(2[0-4][0-9]))\2|(?=(1[0-9]{2}))\3|(?=([0-9]{1,2}))\4)\.){3}(?:(?=(25[0-5]))\5|(?=(2[0-4][0-9]))\6|(?=(1[0-9]{2}))\7|(?=([0-9]{1,2}))\8)$/;
const ipv4RegexC = /^(?:(?: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)$/;
const ipv4RegexD = /^(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/;
const ipv4RegexE = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)$/;
const ipv4RegexF = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
const ipv4RegexG = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
const ipv4RegexH = /^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$/;
const ipv4RegexI =
/^(?:(?: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])$/;
suite
.add("A", () => {
return ipv4RegexA.test(DATA);
})
.add("B", () => {
return ipv4RegexB.test(DATA);
})
.add("C", () => {
return ipv4RegexC.test(DATA);
})
.add("D", () => {
return ipv4RegexD.test(DATA);
})
.add("E", () => {
return ipv4RegexE.test(DATA);
})
.add("F", () => {
return ipv4RegexF.test(DATA);
})
.add("G", () => {
return ipv4RegexG.test(DATA);
})
.add("H", () => {
return ipv4RegexH.test(DATA);
})
.add("I", () => {
return ipv4RegexI.test(DATA);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${suite.name!}: ${e.target}`);
});
export default {
suites: [suite],
};
if (require.main === module) {
suite.run();
}
@@ -0,0 +1,69 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const emptySuite = new Benchmark.Suite("z.object: empty");
const shortSuite = new Benchmark.Suite("z.object: short");
const longSuite = new Benchmark.Suite("z.object: long");
const empty = z.object({});
const short = z.object({
string: z.string(),
});
const long = z.object({
string: z.string(),
number: z.number(),
boolean: z.boolean(),
});
emptySuite
.add("valid", () => {
empty.parse({});
})
.add("valid: extra keys", () => {
empty.parse({ string: "string" });
})
.add("invalid: null", () => {
try {
empty.parse(null);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(emptySuite as any).name}: ${e.target}`);
});
shortSuite
.add("valid", () => {
short.parse({ string: "string" });
})
.add("valid: extra keys", () => {
short.parse({ string: "string", number: 42 });
})
.add("invalid: null", () => {
try {
short.parse(null);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(shortSuite as any).name}: ${e.target}`);
});
longSuite
.add("valid", () => {
long.parse({ string: "string", number: 42, boolean: true });
})
.add("valid: extra keys", () => {
long.parse({ string: "string", number: 42, boolean: true, list: [] });
})
.add("invalid: null", () => {
try {
long.parse(null);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(longSuite as any).name}: ${e.target}`);
});
export default {
suites: [emptySuite, shortSuite, longSuite],
};
@@ -0,0 +1,162 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
import { Mocker } from "../tests/Mocker.js";
const val = new Mocker();
const enumSuite = new Benchmark.Suite("z.enum");
const enumSchema = z.enum(["a", "b", "c"]);
enumSuite
.add("valid", () => {
enumSchema.parse("a");
})
.add("invalid", () => {
try {
enumSchema.parse("x");
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.enum: ${e.target}`);
});
const longEnumSuite = new Benchmark.Suite("long z.enum");
const longEnumSchema = z.enum([
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
]);
longEnumSuite
.add("valid", () => {
longEnumSchema.parse("five");
})
.add("invalid", () => {
try {
longEnumSchema.parse("invalid");
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`long z.enum: ${e.target}`);
});
const undefinedSuite = new Benchmark.Suite("z.undefined");
const undefinedSchema = z.undefined();
undefinedSuite
.add("valid", () => {
undefinedSchema.parse(undefined);
})
.add("invalid", () => {
try {
undefinedSchema.parse(1);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.undefined: ${e.target}`);
});
const literalSuite = new Benchmark.Suite("z.literal");
const short = "short";
const bad = "bad";
const literalSchema = z.literal("short");
literalSuite
.add("valid", () => {
literalSchema.parse(short);
})
.add("invalid", () => {
try {
literalSchema.parse(bad);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.literal: ${e.target}`);
});
const numberSuite = new Benchmark.Suite("z.number");
const numberSchema = z.number().int();
numberSuite
.add("valid", () => {
numberSchema.parse(1);
})
.add("invalid type", () => {
try {
numberSchema.parse("bad");
} catch (_e: any) {}
})
.add("invalid number", () => {
try {
numberSchema.parse(0.5);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.number: ${e.target}`);
});
const dateSuite = new Benchmark.Suite("z.date");
const plainDate = z.date();
const minMaxDate = z.date().min(new Date("2021-01-01")).max(new Date("2030-01-01"));
dateSuite
.add("valid", () => {
plainDate.parse(new Date());
})
.add("invalid", () => {
try {
plainDate.parse(1);
} catch (_e: any) {}
})
.add("valid min and max", () => {
minMaxDate.parse(new Date("2023-01-01"));
})
.add("invalid min", () => {
try {
minMaxDate.parse(new Date("2019-01-01"));
} catch (_e: any) {}
})
.add("invalid max", () => {
try {
minMaxDate.parse(new Date("2031-01-01"));
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.date: ${e.target}`);
});
const symbolSuite = new Benchmark.Suite("z.symbol");
const symbolSchema = z.symbol();
symbolSuite
.add("valid", () => {
symbolSchema.parse(val.symbol);
})
.add("invalid", () => {
try {
symbolSchema.parse(1);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.symbol: ${e.target}`);
});
export default {
suites: [enumSuite, longEnumSuite, undefinedSuite, literalSuite, numberSuite, dateSuite, symbolSuite],
};
@@ -0,0 +1,63 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const shortSuite = new Benchmark.Suite("realworld");
const People = z.array(
z.object({
type: z.literal("person"),
hair: z.enum(["blue", "brown"]),
active: z.boolean(),
name: z.string(),
age: z.number().int(),
hobbies: z.array(z.string()),
address: z.object({
street: z.string(),
zip: z.string(),
country: z.string(),
}),
})
);
let i = 0;
function num() {
return ++i;
}
function str() {
return (++i % 100).toString(16);
}
function array<T>(fn: () => T): T[] {
return Array.from({ length: ++i % 10 }, () => fn());
}
const people = Array.from({ length: 100 }, () => {
return {
type: "person",
hair: i % 2 ? "blue" : "brown",
active: !!(i % 2),
name: str(),
age: num(),
hobbies: array(str),
address: {
street: str(),
zip: str(),
country: str(),
},
};
});
shortSuite
.add("valid", () => {
People.parse(people);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(shortSuite as any).name}: ${e.target}`);
});
export default {
suites: [shortSuite],
};
@@ -0,0 +1,55 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const SUITE_NAME = "z.string";
const suite = new Benchmark.Suite(SUITE_NAME);
const empty = "";
const short = "short";
const long = "long".repeat(256);
const manual = (str: unknown) => {
if (typeof str !== "string") {
throw new Error("Not a string");
}
return str;
};
const stringSchema = z.string();
const optionalStringSchema = z.string().optional();
const optionalNullableStringSchema = z.string().optional().nullable();
suite
.add("empty string", () => {
stringSchema.parse(empty);
})
.add("short string", () => {
stringSchema.parse(short);
})
.add("long string", () => {
stringSchema.parse(long);
})
.add("optional string", () => {
optionalStringSchema.parse(long);
})
.add("nullable string", () => {
optionalNullableStringSchema.parse(long);
})
.add("nullable (null) string", () => {
optionalNullableStringSchema.parse(null);
})
.add("invalid: null", () => {
try {
stringSchema.parse(null);
} catch (_err) {}
})
.add("manual parser: long", () => {
manual(long);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${SUITE_NAME}: ${e.target}`);
});
export default {
suites: [suite],
};
@@ -0,0 +1,80 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const doubleSuite = new Benchmark.Suite("z.union: double");
const manySuite = new Benchmark.Suite("z.union: many");
const aSchema = z.object({
type: z.literal("a"),
});
const objA = {
type: "a",
};
const bSchema = z.object({
type: z.literal("b"),
});
const objB = {
type: "b",
};
const cSchema = z.object({
type: z.literal("c"),
});
const objC = {
type: "c",
};
const dSchema = z.object({
type: z.literal("d"),
});
const double = z.union([aSchema, bSchema]);
const many = z.union([aSchema, bSchema, cSchema, dSchema]);
doubleSuite
.add("valid: a", () => {
double.parse(objA);
})
.add("valid: b", () => {
double.parse(objB);
})
.add("invalid: null", () => {
try {
double.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
double.parse(objC);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(doubleSuite as any).name}: ${e.target}`);
});
manySuite
.add("valid: a", () => {
many.parse(objA);
})
.add("valid: c", () => {
many.parse(objC);
})
.add("invalid: null", () => {
try {
many.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
many.parse({ type: "unknown" });
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(manySuite as any).name}: ${e.target}`);
});
export default {
suites: [doubleSuite, manySuite],
};
+13
View File
@@ -0,0 +1,13 @@
import type { ZodErrorMap } from "./ZodError.js";
import defaultErrorMap from "./locales/en.js";
let overrideErrorMap = defaultErrorMap;
export { defaultErrorMap };
export function setErrorMap(map: ZodErrorMap) {
overrideErrorMap = map;
}
export function getErrorMap() {
return overrideErrorMap;
}
+6
View File
@@ -0,0 +1,6 @@
export * from "./errors.js";
export * from "./helpers/parseUtil.js";
export * from "./helpers/typeAliases.js";
export * from "./helpers/util.js";
export * from "./types.js";
export * from "./ZodError.js";
@@ -0,0 +1,17 @@
export namespace enumUtil {
type UnionToIntersectionFn<T> = (T extends unknown ? (k: () => T) => void : never) extends (
k: infer Intersection
) => void
? Intersection
: never;
type GetUnionLast<T> = UnionToIntersectionFn<T> extends () => infer Last ? Last : never;
type UnionToTuple<T, Tuple extends unknown[] = []> = [T] extends [never]
? Tuple
: UnionToTuple<Exclude<T, GetUnionLast<T>>, [GetUnionLast<T>, ...Tuple]>;
type CastToStringTuple<T> = T extends [string, ...string[]] ? T : never;
export type UnionToTupleString<T> = CastToStringTuple<UnionToTuple<T>>;
}
@@ -0,0 +1,8 @@
export namespace errorUtil {
export type ErrMessage = string | { message?: string | undefined };
export const errToObj = (message?: ErrMessage): { message?: string | undefined } =>
typeof message === "string" ? { message } : message || {};
// biome-ignore lint/suspicious/noShadowRestrictedNames: renaming churns 31 v3 call sites
export const toString = (message?: ErrMessage): string | undefined =>
typeof message === "string" ? message : message?.message;
}
@@ -0,0 +1,176 @@
import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.js";
import { getErrorMap } from "../errors.js";
import defaultErrorMap from "../locales/en.js";
import type { ZodParsedType } from "./util.js";
export const makeIssue = (params: {
data: any;
path: (string | number)[];
errorMaps: ZodErrorMap[];
issueData: IssueData;
}): ZodIssue => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...(issueData.path || [])];
const fullIssue = {
...issueData,
path: fullPath,
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message,
};
}
let errorMessage = "";
const maps = errorMaps
.filter((m) => !!m)
.slice()
.reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage,
};
};
export type ParseParams = {
path: (string | number)[];
errorMap: ZodErrorMap;
async: boolean;
};
export type ParsePathComponent = string | number;
export type ParsePath = ParsePathComponent[];
export const EMPTY_PATH: ParsePath = [];
export interface ParseContext {
readonly common: {
readonly issues: ZodIssue[];
readonly contextualErrorMap?: ZodErrorMap | undefined;
readonly async: boolean;
};
readonly path: ParsePath;
readonly schemaErrorMap?: ZodErrorMap | undefined;
readonly parent: ParseContext | null;
readonly data: any;
readonly parsedType: ZodParsedType;
}
export type ParseInput = {
data: any;
path: (string | number)[];
parent: ParseContext;
};
export function addIssueToContext(ctx: ParseContext, issueData: IssueData): void {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData: issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap, // contextual error map is first priority
ctx.schemaErrorMap, // then schema-bound map if available
overrideMap, // then global override map
overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map
].filter((x) => !!x),
});
ctx.common.issues.push(issue);
}
export type ObjectPair = {
key: SyncParseReturnType<any>;
value: SyncParseReturnType<any>;
};
export class ParseStatus {
value: "aborted" | "dirty" | "valid" = "valid";
dirty(): void {
if (this.value === "valid") this.value = "dirty";
}
abort(): void {
if (this.value !== "aborted") this.value = "aborted";
}
static mergeArray(status: ParseStatus, results: SyncParseReturnType<any>[]): SyncParseReturnType {
const arrayValue: any[] = [];
for (const s of results) {
if (s.status === "aborted") return INVALID;
if (s.status === "dirty") status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(
status: ParseStatus,
pairs: { key: ParseReturnType<any>; value: ParseReturnType<any> }[]
): Promise<SyncParseReturnType<any>> {
const syncPairs: ObjectPair[] = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(
status: ParseStatus,
pairs: {
key: SyncParseReturnType<any>;
value: SyncParseReturnType<any>;
alwaysSet?: boolean;
}[]
): SyncParseReturnType {
const finalObject: any = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID;
if (value.status === "aborted") return INVALID;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
export interface ParseResult {
status: "aborted" | "dirty" | "valid";
data: any;
}
export type INVALID = { status: "aborted" };
export const INVALID: INVALID = Object.freeze({
status: "aborted",
});
export type DIRTY<T> = { status: "dirty"; value: T };
export const DIRTY = <T>(value: T): DIRTY<T> => ({ status: "dirty", value });
export type OK<T> = { status: "valid"; value: T };
export const OK = <T>(value: T): OK<T> => ({ status: "valid", value });
export type SyncParseReturnType<T = any> = OK<T> | DIRTY<T> | INVALID;
export type AsyncParseReturnType<T> = Promise<SyncParseReturnType<T>>;
export type ParseReturnType<T> = SyncParseReturnType<T> | AsyncParseReturnType<T>;
export const isAborted = (x: ParseReturnType<any>): x is INVALID => (x as any).status === "aborted";
export const isDirty = <T>(x: ParseReturnType<T>): x is OK<T> | DIRTY<T> => (x as any).status === "dirty";
export const isValid = <T>(x: ParseReturnType<T>): x is OK<T> => (x as any).status === "valid";
export const isAsync = <T>(x: ParseReturnType<T>): x is AsyncParseReturnType<T> =>
typeof Promise !== "undefined" && x instanceof Promise;
@@ -0,0 +1,34 @@
import type {
ZodArray,
ZodNullable,
ZodObject,
ZodOptional,
ZodRawShape,
ZodTuple,
ZodTupleItems,
ZodTypeAny,
} from "../types.js";
export namespace partialUtil {
export type DeepPartial<T extends ZodTypeAny> = T extends ZodObject<ZodRawShape>
? ZodObject<
{ [k in keyof T["shape"]]: ZodOptional<DeepPartial<T["shape"][k]>> },
T["_def"]["unknownKeys"],
T["_def"]["catchall"]
>
: T extends ZodArray<infer Type, infer Card>
? ZodArray<DeepPartial<Type>, Card>
: T extends ZodOptional<infer Type>
? ZodOptional<DeepPartial<Type>>
: T extends ZodNullable<infer Type>
? ZodNullable<DeepPartial<Type>>
: T extends ZodTuple<infer Items>
? {
[k in keyof Items]: Items[k] extends ZodTypeAny ? DeepPartial<Items[k]> : never;
} extends infer PI
? PI extends ZodTupleItems
? ZodTuple<PI>
: never
: never
: T;
}
@@ -0,0 +1,2 @@
export type Primitive = string | number | symbol | bigint | boolean | null | undefined;
export type Scalars = Primitive | Primitive[];
+224
View File
@@ -0,0 +1,224 @@
export namespace util {
type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : false;
export type isAny<T> = 0 extends 1 & T ? true : false;
export const assertEqual = <A, B>(_: AssertEqual<A, B>): void => {};
export function assertIs<T>(_arg: T): void {}
export function assertNever(_x: never): never {
throw new Error();
}
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
export type MakePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type Exactly<T, X> = T & Record<Exclude<keyof X, keyof T>, never>;
export type InexactPartial<T> = { [k in keyof T]?: T[k] | undefined };
export const arrayToEnum = <T extends string, U extends [T, ...T[]]>(items: U): { [k in U[number]]: k } => {
const obj: any = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
export const getValidEnumValues = (obj: any): any[] => {
const validKeys = objectKeys(obj).filter((k: any) => typeof obj[obj[k]] !== "number");
const filtered: any = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return objectValues(filtered);
};
export const objectValues = (obj: any): any[] => {
return objectKeys(obj).map(function (e) {
return obj[e];
});
};
export const objectKeys: ObjectConstructor["keys"] =
typeof Object.keys === "function" // eslint-disable-line ban/ban
? (obj: any) => Object.keys(obj) // eslint-disable-line ban/ban
: (object: any) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
export const find = <T>(arr: T[], checker: (arg: T) => any): T | undefined => {
for (const item of arr) {
if (checker(item)) return item;
}
return undefined;
};
export type identity<T> = objectUtil.identity<T>;
export type flatten<T> = objectUtil.flatten<T>;
export type noUndefined<T> = T extends undefined ? never : T;
export const isInteger: NumberConstructor["isInteger"] =
typeof Number.isInteger === "function"
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
: (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
export function joinValues<T extends any[]>(array: T, separator = " | "): string {
return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
}
export const jsonStringifyReplacer = (_: string, value: any): any => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
}
export namespace objectUtil {
export type MergeShapes<U, V> =
// fast path when there is no keys overlap
keyof U & keyof V extends never
? U & V
: {
[k in Exclude<keyof U, keyof V>]: U[k];
} & V;
type optionalKeys<T extends object> = {
[k in keyof T]: undefined extends T[k] ? k : never;
}[keyof T];
type requiredKeys<T extends object> = {
[k in keyof T]: undefined extends T[k] ? never : k;
}[keyof T];
export type addQuestionMarks<T extends object, _O = any> = {
[K in requiredKeys<T>]: T[K];
} & {
[K in optionalKeys<T>]?: T[K];
} & { [k in keyof T]?: unknown };
export type identity<T> = T;
export type flatten<T> = identity<{ [k in keyof T]: T[k] }>;
export type noNeverKeys<T> = {
[k in keyof T]: [T[k]] extends [never] ? never : k;
}[keyof T];
export type noNever<T> = identity<{
[k in noNeverKeys<T>]: k extends keyof T ? T[k] : never;
}>;
export const mergeShapes = <U, T>(first: U, second: T): T & U => {
return {
...first,
...second, // second overwrites first
};
};
export type extendShape<A extends object, B extends object> = keyof A & keyof B extends never // fast path when there is no keys overlap
? A & B
: {
[K in keyof A as K extends keyof B ? never : K]: A[K];
} & {
[K in keyof B]: B[K];
};
}
export const ZodParsedType: {
string: "string";
nan: "nan";
number: "number";
integer: "integer";
float: "float";
boolean: "boolean";
date: "date";
bigint: "bigint";
symbol: "symbol";
function: "function";
undefined: "undefined";
null: "null";
array: "array";
object: "object";
unknown: "unknown";
promise: "promise";
void: "void";
never: "never";
map: "map";
set: "set";
} = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set",
]);
export type ZodParsedType = keyof typeof ZodParsedType;
export const getParsedType = (data: any): ZodParsedType => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./external.js";
export * from "./external.js";
export { z };
export default z;
+124
View File
@@ -0,0 +1,124 @@
import { type ZodErrorMap, ZodIssueCode } from "../ZodError.js";
import { util, ZodParsedType } from "../helpers/util.js";
const errorMap: ZodErrorMap = (issue, _ctx) => {
let message: string;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${
issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`
} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${
issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`
} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${
issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `
}${issue.minimum}`;
else if (issue.type === "bigint")
message = `Number must be ${
issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `
}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${
issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `
}${new Date(Number(issue.minimum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${
issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`
} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${
issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`
} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${
issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`
} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${
issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`
} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${
issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`
} ${new Date(Number(issue.maximum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
export default errorMap;
@@ -0,0 +1,113 @@
/**
* The Standard Schema interface.
*/
export type StandardSchemaV1<Input = unknown, Output = Input> = {
/**
* The Standard Schema properties.
*/
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
};
export declare namespace StandardSchemaV1 {
/**
* The Standard Schema properties interface.
*/
export interface Props<Input = unknown, Output = Input> {
/**
* The version number of the standard.
*/
readonly version: 1;
/**
* The vendor name of the schema library.
*/
readonly vendor: string;
/**
* Validates unknown input values.
*/
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
/**
* Inferred types associated with the schema.
*/
readonly types?: Types<Input, Output> | undefined;
}
/**
* The result interface of the validate function.
*/
export type Result<Output> = SuccessResult<Output> | FailureResult;
/**
* The result interface if validation succeeds.
*/
export interface SuccessResult<Output> {
/**
* The typed output value.
*/
readonly value: Output;
/**
* The non-existent issues.
*/
readonly issues?: undefined;
}
/**
* The result interface if validation fails.
*/
export interface FailureResult {
/**
* The issues of failed validation.
*/
readonly issues: ReadonlyArray<Issue>;
}
/**
* The issue interface of the failure output.
*/
export interface Issue {
/**
* The error message of the issue.
*/
readonly message: string;
/**
* The path of the issue, if any.
*/
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
}
/**
* The path segment interface of the issue.
*/
export interface PathSegment {
/**
* The key representing a path segment.
*/
readonly key: PropertyKey;
}
/**
* The Standard Schema types interface.
*/
export interface Types<Input = unknown, Output = Input> {
/**
* The input type of the schema.
*/
readonly input: Input;
/**
* The output type of the schema.
*/
readonly output: Output;
}
/**
* Infers the input type of a Standard Schema.
*/
export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
/**
* Infers the output type of a Standard Schema.
*/
export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
// biome-ignore lint/complexity/noUselessEmptyExport: needed for granular visibility control of TS namespace
export {};
}
+54
View File
@@ -0,0 +1,54 @@
function getRandomInt(max: number) {
return Math.floor(Math.random() * Math.floor(max));
}
const testSymbol = Symbol("test");
export class Mocker {
pick = (...args: any[]): any => {
return args[getRandomInt(args.length)];
};
get string(): string {
return Math.random().toString(36).substring(7);
}
get number(): number {
return Math.random() * 100;
}
get bigint(): bigint {
return BigInt(Math.floor(Math.random() * 10000));
}
get boolean(): boolean {
return Math.random() < 0.5;
}
get date(): Date {
return new Date(Math.floor(Date.now() * Math.random()));
}
get symbol(): symbol {
return testSymbol;
}
get null(): null {
return null;
}
get undefined(): undefined {
return undefined;
}
get stringOptional(): string | undefined {
return this.pick(this.string, this.undefined);
}
get stringNullable(): string | null {
return this.pick(this.string, this.null);
}
get numberOptional(): number | undefined {
return this.pick(this.number, this.undefined);
}
get numberNullable(): number | null {
return this.pick(this.number, this.null);
}
get booleanOptional(): boolean | undefined {
return this.pick(this.boolean, this.undefined);
}
get booleanNullable(): boolean | null {
return this.pick(this.boolean, this.null);
}
}
@@ -0,0 +1,157 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
const Test = z.object({
f1: z.number(),
f2: z.string().optional(),
f3: z.string().nullable(),
f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })),
});
type TestFlattenedErrors = z.inferFlattenedErrors<typeof Test, { message: string; code: number }>;
type TestFormErrors = z.inferFlattenedErrors<typeof Test>;
test("default flattened errors type inference", () => {
type TestTypeErrors = {
formErrors: string[];
fieldErrors: { [P in keyof z.TypeOf<typeof Test>]?: string[] };
};
util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(true);
util.assertEqual<z.inferFlattenedErrors<typeof Test, { message: string }>, TestTypeErrors>(false);
});
test("custom flattened errors type inference", () => {
type ErrorType = { message: string; code: number };
type TestTypeErrors = {
formErrors: ErrorType[];
fieldErrors: {
[P in keyof z.TypeOf<typeof Test>]?: ErrorType[];
};
};
util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(false);
util.assertEqual<z.inferFlattenedErrors<typeof Test, { message: string; code: number }>, TestTypeErrors>(true);
util.assertEqual<z.inferFlattenedErrors<typeof Test, { message: string }>, TestTypeErrors>(false);
});
test("form errors type inference", () => {
type TestTypeErrors = {
formErrors: string[];
fieldErrors: { [P in keyof z.TypeOf<typeof Test>]?: string[] };
};
util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(true);
});
test(".flatten() type assertion", () => {
const parsed = Test.safeParse({}) as z.SafeParseError<void>;
const validFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(() => ({ message: "", code: 0 }));
// @ts-expect-error should fail assertion between `TestFlattenedErrors` and unmapped `flatten()`.
const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.flatten();
const validFormErrors: TestFormErrors = parsed.error.flatten();
// @ts-expect-error should fail assertion between `TestFormErrors` and mapped `flatten()`.
const invalidFormErrors: TestFormErrors = parsed.error.flatten(() => ({
message: "string",
code: 0,
}));
[validFlattenedErrors, invalidFlattenedErrors, validFormErrors, invalidFormErrors];
});
test(".formErrors type assertion", () => {
const parsed = Test.safeParse({}) as z.SafeParseError<void>;
const validFormErrors: TestFormErrors = parsed.error.formErrors;
// @ts-expect-error should fail assertion between `TestFlattenedErrors` and `.formErrors`.
const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.formErrors;
[validFormErrors, invalidFlattenedErrors];
});
test("all errors", () => {
const propertySchema = z.string();
const schema = z
.object({
a: propertySchema,
b: propertySchema,
})
.refine(
(val) => {
return val.a === val.b;
},
{ message: "Must be equal" }
);
try {
schema.parse({
a: "asdf",
b: "qwer",
});
} catch (error) {
if (error instanceof z.ZodError) {
expect(error.flatten()).toEqual({
formErrors: ["Must be equal"],
fieldErrors: {},
});
}
}
try {
schema.parse({
a: null,
b: null,
});
} catch (_error) {
const error = _error as z.ZodError;
expect(error.flatten()).toEqual({
formErrors: [],
fieldErrors: {
a: ["Expected string, received null"],
b: ["Expected string, received null"],
},
});
expect(error.flatten((iss) => iss.message.toUpperCase())).toEqual({
formErrors: [],
fieldErrors: {
a: ["EXPECTED STRING, RECEIVED NULL"],
b: ["EXPECTED STRING, RECEIVED NULL"],
},
});
// Test identity
expect(error.flatten((i: z.ZodIssue) => i)).toEqual({
formErrors: [],
fieldErrors: {
a: [
{
code: "invalid_type",
expected: "string",
message: "Expected string, received null",
path: ["a"],
received: "null",
},
],
b: [
{
code: "invalid_type",
expected: "string",
message: "Expected string, received null",
path: ["b"],
received: "null",
},
],
},
});
// Test mapping
expect(error.flatten((i: z.ZodIssue) => i.message.length)).toEqual({
formErrors: [],
fieldErrors: {
a: ["Expected string, received null".length],
b: ["Expected string, received null".length],
},
});
}
});
@@ -0,0 +1,28 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("check any inference", () => {
const t1 = z.any();
t1.optional();
t1.nullable();
type t1 = z.infer<typeof t1>;
util.assertEqual<t1, any>(true);
});
test("check unknown inference", () => {
const t1 = z.unknown();
t1.optional();
t1.nullable();
type t1 = z.infer<typeof t1>;
util.assertEqual<t1, unknown>(true);
});
test("check never inference", () => {
const t1 = z.never();
expect(() => t1.parse(undefined)).toThrow();
expect(() => t1.parse("asdf")).toThrow();
expect(() => t1.parse(null)).toThrow();
});
@@ -0,0 +1,71 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
const minTwo = z.string().array().min(2);
const maxTwo = z.string().array().max(2);
const justTwo = z.string().array().length(2);
const intNum = z.string().array().nonempty();
const nonEmptyMax = z.string().array().nonempty().max(2);
type t1 = z.infer<typeof nonEmptyMax>;
util.assertEqual<[string, ...string[]], t1>(true);
type t2 = z.infer<typeof minTwo>;
util.assertEqual<string[], t2>(true);
test("passing validations", () => {
minTwo.parse(["a", "a"]);
minTwo.parse(["a", "a", "a"]);
maxTwo.parse(["a", "a"]);
maxTwo.parse(["a"]);
justTwo.parse(["a", "a"]);
intNum.parse(["a"]);
nonEmptyMax.parse(["a"]);
});
test("failing validations", () => {
expect(() => minTwo.parse(["a"])).toThrow();
expect(() => maxTwo.parse(["a", "a", "a"])).toThrow();
expect(() => justTwo.parse(["a"])).toThrow();
expect(() => justTwo.parse(["a", "a", "a"])).toThrow();
expect(() => intNum.parse([])).toThrow();
expect(() => nonEmptyMax.parse([])).toThrow();
expect(() => nonEmptyMax.parse(["a", "a", "a"])).toThrow();
});
test("parse empty array in nonempty", () => {
expect(() =>
z
.array(z.string())
.nonempty()
.parse([] as any)
).toThrow();
});
test("get element", () => {
justTwo.element.parse("asdf");
expect(() => justTwo.element.parse(12)).toThrow();
});
test("continue parsing despite array size error", () => {
const schema = z.object({
people: z.string().array().min(2),
});
const result = schema.safeParse({
people: [123],
});
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues.length).toEqual(2);
}
});
test("parse should fail given sparse array", () => {
const schema = z.array(z.string()).nonempty().min(1).max(3);
expect(() => schema.parse(new Array(3))).toThrow();
});
@@ -0,0 +1,388 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
/// string
const stringSchema = z.string();
test("string async parse", async () => {
const goodData = "XXX";
const badData = 12;
const goodResult = await stringSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await stringSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// number
const numberSchema = z.number();
test("number async parse", async () => {
const goodData = 1234.2353;
const badData = "1234";
const goodResult = await numberSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await numberSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// bigInt
const bigIntSchema = z.bigint();
test("bigInt async parse", async () => {
const goodData = BigInt(145);
const badData = 134;
const goodResult = await bigIntSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await bigIntSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// boolean
const booleanSchema = z.boolean();
test("boolean async parse", async () => {
const goodData = true;
const badData = 1;
const goodResult = await booleanSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await booleanSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// date
const dateSchema = z.date();
test("date async parse", async () => {
const goodData = new Date();
const badData = new Date().toISOString();
const goodResult = await dateSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await dateSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// undefined
const undefinedSchema = z.undefined();
test("undefined async parse", async () => {
const goodData = undefined;
const badData = "XXX";
const goodResult = await undefinedSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(undefined);
const badResult = await undefinedSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// null
const nullSchema = z.null();
test("null async parse", async () => {
const goodData = null;
const badData = undefined;
const goodResult = await nullSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await nullSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// any
const anySchema = z.any();
test("any async parse", async () => {
const goodData = [{}];
// const badData = 'XXX';
const goodResult = await anySchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
// const badResult = await anySchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// unknown
const unknownSchema = z.unknown();
test("unknown async parse", async () => {
const goodData = ["asdf", 124, () => {}];
// const badData = 'XXX';
const goodResult = await unknownSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
// const badResult = await unknownSchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// void
const voidSchema = z.void();
test("void async parse", async () => {
const goodData = undefined;
const badData = 0;
const goodResult = await voidSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await voidSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// array
const arraySchema = z.array(z.string());
test("array async parse", async () => {
const goodData = ["XXX"];
const badData = "XXX";
const goodResult = await arraySchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await arraySchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// object
const objectSchema = z.object({ string: z.string() });
test("object async parse", async () => {
const goodData = { string: "XXX" };
const badData = { string: 12 };
const goodResult = await objectSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await objectSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// union
const unionSchema = z.union([z.string(), z.undefined()]);
test("union async parse", async () => {
const goodData = undefined;
const badData = null;
const goodResult = await unionSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await unionSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// record
const recordSchema = z.record(z.object({}));
test("record async parse", async () => {
const goodData = { adsf: {}, asdf: {} };
const badData = [{}];
const goodResult = await recordSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await recordSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// function
const functionSchema = z.function();
test("function async parse", async () => {
const goodData = () => {};
const badData = "XXX";
const goodResult = await functionSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(typeof goodResult.data).toEqual("function");
const badResult = await functionSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// literal
const literalSchema = z.literal("asdf");
test("literal async parse", async () => {
const goodData = "asdf";
const badData = "asdff";
const goodResult = await literalSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await literalSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// enum
const enumSchema = z.enum(["fish", "whale"]);
test("enum async parse", async () => {
const goodData = "whale";
const badData = "leopard";
const goodResult = await enumSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await enumSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// nativeEnum
enum nativeEnumTest {
asdf = "qwer",
}
// @ts-ignore
const nativeEnumSchema = z.nativeEnum(nativeEnumTest);
test("nativeEnum async parse", async () => {
const goodData = nativeEnumTest.asdf;
const badData = "asdf";
const goodResult = await nativeEnumSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await nativeEnumSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// promise
const promiseSchema = z.promise(z.number());
test("promise async parse good", async () => {
const goodData = Promise.resolve(123);
const goodResult = await promiseSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) {
expect(goodResult.data).toBeInstanceOf(Promise);
const data = await goodResult.data;
expect(data).toEqual(123);
// expect(goodResult.data).resolves.toEqual(124);
// return goodResult.data;
} else {
throw new Error("success should be true");
}
});
test("promise async parse bad", async () => {
const badData = Promise.resolve("XXX");
const badResult = await promiseSchema.safeParseAsync(badData);
expect(badResult.success).toBe(true);
if (badResult.success) {
await expect(badResult.data).rejects.toBeInstanceOf(z.ZodError);
} else {
throw new Error("success should be true");
}
});
test("async validation non-empty strings", async () => {
const base = z.object({
hello: z.string().refine((x) => x && x.length > 0),
foo: z.string().refine((x) => x && x.length > 0),
});
const testval = { hello: "", foo: "" };
const result1 = base.safeParse(testval);
const result2 = base.safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
if (r1.success === false && r2.success === false) expect(r1.error.issues.length).toBe(r2.error.issues.length); // <--- r1 has length 2, r2 has length 1
});
});
test("async validation multiple errors 1", async () => {
const base = z.object({
hello: z.string(),
foo: z.number(),
});
const testval = { hello: 3, foo: "hello" };
const result1 = base.safeParse(testval);
const result2 = base.safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length);
});
});
test("async validation multiple errors 2", async () => {
const base = (is_async?: boolean) =>
z.object({
hello: z.string(),
foo: z.object({
bar: z.number().refine(is_async ? async () => false : () => false),
}),
});
const testval = { hello: 3, foo: { bar: 4 } };
const result1 = base().safeParse(testval);
const result2 = base(true).safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length);
});
});
test("ensure early async failure prevents follow-up refinement checks", async () => {
let count = 0;
const base = z.object({
hello: z.string(),
foo: z
.number()
.refine(async () => {
count++;
return true;
})
.refine(async () => {
count++;
return true;
}, "Good"),
});
const testval = { hello: "bye", foo: 3 };
const result = await base.safeParseAsync(testval);
if (result.success === false) {
expect(result.error.issues.length).toBe(1);
expect(count).toBe(1);
}
// await result.then((r) => {
// if (r.success === false) expect(r.error.issues.length).toBe(1);
// expect(count).toBe(2);
// });
});
@@ -0,0 +1,46 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("parse async test", async () => {
const schema1 = z.string().refine(async (_val) => false);
expect(() => schema1.parse("asdf")).toThrow();
const schema2 = z.string().refine((_val) => Promise.resolve(true));
return await expect(() => schema2.parse("asdf")).toThrow();
});
test("parseAsync async test", async () => {
const schema1 = z.string().refine(async (_val) => true);
await schema1.parseAsync("asdf");
const schema2 = z.string().refine(async (_val) => false);
return await expect(schema2.parseAsync("asdf")).rejects.toBeDefined();
// expect(async () => await schema2.parseAsync('asdf')).toThrow();
});
test("parseAsync async test", async () => {
// expect.assertions(2);
const schema1 = z.string().refine((_val) => Promise.resolve(true));
const v1 = await schema1.parseAsync("asdf");
expect(v1).toEqual("asdf");
const schema2 = z.string().refine((_val) => Promise.resolve(false));
await expect(schema2.parseAsync("asdf")).rejects.toBeDefined();
const schema3 = z.string().refine((_val) => Promise.resolve(true));
await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf");
return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer");
});
test("parseAsync async with value", async () => {
const schema1 = z.string().refine(async (val) => {
return val.length > 5;
});
await expect(schema1.parseAsync("asdf")).rejects.toBeDefined();
const v = await schema1.parseAsync("asdf123");
return await expect(v).toEqual("asdf123");
});
@@ -0,0 +1,29 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("type guard", () => {
const stringToNumber = z.string().transform((arg) => arg.length);
const s1 = z.object({
stringToNumber,
});
type t1 = z.input<typeof s1>;
const data = { stringToNumber: "asdf" };
const parsed = s1.safeParse(data);
if (parsed.success) {
util.assertEqual<typeof data, t1>(true);
}
});
test("test this binding", () => {
const callback = (predicate: (val: string) => boolean) => {
return predicate("hello");
};
expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true
expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true
});
@@ -0,0 +1,55 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const gtFive = z.bigint().gt(BigInt(5));
const gteFive = z.bigint().gte(BigInt(5));
const ltFive = z.bigint().lt(BigInt(5));
const lteFive = z.bigint().lte(BigInt(5));
const positive = z.bigint().positive();
const negative = z.bigint().negative();
const nonnegative = z.bigint().nonnegative();
const nonpositive = z.bigint().nonpositive();
const multipleOfFive = z.bigint().multipleOf(BigInt(5));
test("passing validations", () => {
z.bigint().parse(BigInt(1));
z.bigint().parse(BigInt(0));
z.bigint().parse(BigInt(-1));
gtFive.parse(BigInt(6));
gteFive.parse(BigInt(5));
gteFive.parse(BigInt(6));
ltFive.parse(BigInt(4));
lteFive.parse(BigInt(5));
lteFive.parse(BigInt(4));
positive.parse(BigInt(3));
negative.parse(BigInt(-2));
nonnegative.parse(BigInt(0));
nonnegative.parse(BigInt(7));
nonpositive.parse(BigInt(0));
nonpositive.parse(BigInt(-12));
multipleOfFive.parse(BigInt(15));
});
test("failing validations", () => {
expect(() => gtFive.parse(BigInt(5))).toThrow();
expect(() => gteFive.parse(BigInt(4))).toThrow();
expect(() => ltFive.parse(BigInt(5))).toThrow();
expect(() => lteFive.parse(BigInt(6))).toThrow();
expect(() => positive.parse(BigInt(0))).toThrow();
expect(() => positive.parse(BigInt(-2))).toThrow();
expect(() => negative.parse(BigInt(0))).toThrow();
expect(() => negative.parse(BigInt(3))).toThrow();
expect(() => nonnegative.parse(BigInt(-1))).toThrow();
expect(() => nonpositive.parse(BigInt(1))).toThrow();
expect(() => multipleOfFive.parse(BigInt(13))).toThrow();
});
test("min max getters", () => {
expect(z.bigint().min(BigInt(5)).minValue).toEqual(BigInt(5));
expect(z.bigint().min(BigInt(5)).min(BigInt(10)).minValue).toEqual(BigInt(10));
expect(z.bigint().max(BigInt(5)).maxValue).toEqual(BigInt(5));
expect(z.bigint().max(BigInt(5)).max(BigInt(1)).maxValue).toEqual(BigInt(1));
});
@@ -0,0 +1,53 @@
// @ts-ignore TS6133
import { test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("branded types", () => {
const mySchema = z
.object({
name: z.string(),
})
.brand<"superschema">();
// simple branding
type MySchema = z.infer<typeof mySchema>;
util.assertEqual<MySchema, { name: string } & { [z.BRAND]: { superschema: true } }>(true);
const doStuff = (arg: MySchema) => arg;
doStuff(mySchema.parse({ name: "hello there" }));
// inheritance
const extendedSchema = mySchema.brand<"subschema">();
type ExtendedSchema = z.infer<typeof extendedSchema>;
util.assertEqual<ExtendedSchema, { name: string } & z.BRAND<"superschema"> & z.BRAND<"subschema">>(true);
doStuff(extendedSchema.parse({ name: "hello again" }));
// number branding
const numberSchema = z.number().brand<42>();
type NumberSchema = z.infer<typeof numberSchema>;
util.assertEqual<NumberSchema, number & { [z.BRAND]: { 42: true } }>(true);
// symbol branding
const MyBrand: unique symbol = Symbol("hello");
type MyBrand = typeof MyBrand;
const symbolBrand = z.number().brand<"sup">().brand<typeof MyBrand>();
type SymbolBrand = z.infer<typeof symbolBrand>;
// number & { [z.BRAND]: { sup: true, [MyBrand]: true } }
util.assertEqual<SymbolBrand, number & z.BRAND<"sup"> & z.BRAND<MyBrand>>(true);
// keeping brands out of input types
const age = z.number().brand<"age">();
type Age = z.infer<typeof age>;
type AgeInput = z.input<typeof age>;
util.assertEqual<AgeInput, Age>(false);
util.assertEqual<number, AgeInput>(true);
util.assertEqual<number & z.BRAND<"age">, Age>(true);
// @ts-expect-error
doStuff({ name: "hello there!" });
});
@@ -0,0 +1,220 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import { z } from "zod/v3";
import { util } from "../helpers/util.js";
test("basic catch", () => {
expect(z.string().catch("default").parse(undefined)).toBe("default");
});
test("catch fn does not run when parsing succeeds", () => {
let isCalled = false;
const cb = () => {
isCalled = true;
return "asdf";
};
expect(z.string().catch(cb).parse("test")).toBe("test");
expect(isCalled).toEqual(false);
});
test("basic catch async", async () => {
const result = await z.string().catch("default").parseAsync(1243);
expect(result).toBe("default");
});
test("catch replace wrong types", () => {
expect(z.string().catch("default").parse(true)).toBe("default");
expect(z.string().catch("default").parse(true)).toBe("default");
expect(z.string().catch("default").parse(15)).toBe("default");
expect(z.string().catch("default").parse([])).toBe("default");
expect(z.string().catch("default").parse(new Map())).toBe("default");
expect(z.string().catch("default").parse(new Set())).toBe("default");
expect(z.string().catch("default").parse({})).toBe("default");
});
test("catch with transform", () => {
const stringWithDefault = z
.string()
.transform((val) => val.toUpperCase())
.catch("default");
expect(stringWithDefault.parse(undefined)).toBe("default");
expect(stringWithDefault.parse(15)).toBe("default");
expect(stringWithDefault).toBeInstanceOf(z.ZodCatch);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects);
expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("catch on existing optional", () => {
const stringWithDefault = z.string().optional().catch("asdf");
expect(stringWithDefault.parse(undefined)).toBe(undefined);
expect(stringWithDefault.parse(15)).toBe("asdf");
expect(stringWithDefault).toBeInstanceOf(z.ZodCatch);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional);
expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("optional on catch", () => {
const stringWithDefault = z.string().catch("asdf").optional();
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("complex chain example", () => {
const complex = z
.string()
.catch("asdf")
.transform((val) => val + "!")
.transform((val) => val.toUpperCase())
.catch("qwer")
.removeCatch()
.optional()
.catch("asdfasdf");
expect(complex.parse("qwer")).toBe("QWER!");
expect(complex.parse(15)).toBe("ASDF!");
expect(complex.parse(true)).toBe("ASDF!");
});
test("removeCatch", () => {
const stringWithRemovedDefault = z.string().catch("asdf").removeCatch();
type out = z.output<typeof stringWithRemovedDefault>;
util.assertEqual<out, string>(true);
});
test("nested", () => {
const inner = z.string().catch("asdf");
const outer = z.object({ inner }).catch({
inner: "asdf",
});
type input = z.input<typeof outer>;
util.assertEqual<input, unknown>(true);
type out = z.output<typeof outer>;
util.assertEqual<out, { inner: string }>(true);
expect(outer.parse(undefined)).toEqual({ inner: "asdf" });
expect(outer.parse({})).toEqual({ inner: "asdf" });
expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" });
});
test("chained catch", () => {
const stringWithDefault = z.string().catch("inner").catch("outer");
const result = stringWithDefault.parse(undefined);
expect(result).toEqual("inner");
const resultDiff = stringWithDefault.parse(5);
expect(resultDiff).toEqual("inner");
});
test("factory", () => {
z.ZodCatch.create(z.string(), {
catch: "asdf",
}).parse(undefined);
});
test("native enum", () => {
enum Fruits {
apple = "apple",
orange = "orange",
}
const schema = z.object({
fruit: z.nativeEnum(Fruits).catch(Fruits.apple),
});
expect(schema.parse({})).toEqual({ fruit: Fruits.apple });
expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple });
});
test("enum", () => {
const schema = z.object({
fruit: z.enum(["apple", "orange"]).catch("apple"),
});
expect(schema.parse({})).toEqual({ fruit: "apple" });
expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" });
expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" });
});
test("reported issues with nested usage", () => {
const schema = z.object({
string: z.string(),
obj: z.object({
sub: z.object({
lit: z.literal("a"),
subCatch: z.number().catch(23),
}),
midCatch: z.number().catch(42),
}),
number: z.number().catch(0),
bool: z.boolean(),
});
try {
schema.parse({
string: {},
obj: {
sub: {
lit: "b",
subCatch: "24",
},
midCatch: 444,
},
number: "",
bool: "yes",
});
} catch (error) {
const issues = (error as z.ZodError).issues;
expect(issues.length).toEqual(3);
expect(issues[0].message).toMatch("string");
expect(issues[1].message).toMatch("literal");
expect(issues[2].message).toMatch("boolean");
}
});
test("catch error", () => {
let catchError: z.ZodError | undefined = undefined;
const schema = z.object({
age: z.number(),
name: z.string().catch((ctx) => {
catchError = ctx.error;
return "John Doe";
}),
});
const result = schema.safeParse({
age: null,
name: null,
});
expect(result.success).toEqual(false);
expect(!result.success && result.error.issues.length).toEqual(1);
expect(!result.success && result.error.issues[0].message).toMatch("number");
expect(catchError).toBeInstanceOf(z.ZodError);
expect(catchError !== undefined && (catchError as z.ZodError).issues.length).toEqual(1);
expect(catchError !== undefined && (catchError as z.ZodError).issues[0].message).toMatch("string");
});
test("ctx.input", () => {
const schema = z.string().catch((ctx) => {
return String(ctx.input);
});
expect(schema.parse(123)).toEqual("123");
});
@@ -0,0 +1,133 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("string coercion", () => {
const schema = z.coerce.string();
expect(schema.parse("sup")).toEqual("sup");
expect(schema.parse("")).toEqual("");
expect(schema.parse(12)).toEqual("12");
expect(schema.parse(0)).toEqual("0");
expect(schema.parse(-12)).toEqual("-12");
expect(schema.parse(3.14)).toEqual("3.14");
expect(schema.parse(BigInt(15))).toEqual("15");
expect(schema.parse(Number.NaN)).toEqual("NaN");
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual("Infinity");
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual("-Infinity");
expect(schema.parse(true)).toEqual("true");
expect(schema.parse(false)).toEqual("false");
expect(schema.parse(null)).toEqual("null");
expect(schema.parse(undefined)).toEqual("undefined");
expect(schema.parse({ hello: "world!" })).toEqual("[object Object]");
expect(schema.parse(["item", "another_item"])).toEqual("item,another_item");
expect(schema.parse([])).toEqual("");
expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual(new Date("2022-01-01T00:00:00.000Z").toString());
});
test("number coercion", () => {
const schema = z.coerce.number();
expect(schema.parse("12")).toEqual(12);
expect(schema.parse("0")).toEqual(0);
expect(schema.parse("-12")).toEqual(-12);
expect(schema.parse("3.14")).toEqual(3.14);
expect(schema.parse("")).toEqual(0);
expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError
expect(schema.parse(12)).toEqual(12);
expect(schema.parse(0)).toEqual(0);
expect(schema.parse(-12)).toEqual(-12);
expect(schema.parse(3.14)).toEqual(3.14);
expect(schema.parse(BigInt(15))).toEqual(15);
expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(Number.POSITIVE_INFINITY);
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(Number.NEGATIVE_INFINITY);
expect(schema.parse(true)).toEqual(1);
expect(schema.parse(false)).toEqual(0);
expect(schema.parse(null)).toEqual(0);
expect(() => schema.parse(undefined)).toThrow(); // z.ZodError
expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError
expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError
expect(schema.parse([])).toEqual(0);
expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496);
});
test("boolean coercion", () => {
const schema = z.coerce.boolean();
expect(schema.parse("true")).toEqual(true);
expect(schema.parse("false")).toEqual(true);
expect(schema.parse("0")).toEqual(true);
expect(schema.parse("1")).toEqual(true);
expect(schema.parse("")).toEqual(false);
expect(schema.parse(1)).toEqual(true);
expect(schema.parse(0)).toEqual(false);
expect(schema.parse(-1)).toEqual(true);
expect(schema.parse(3.14)).toEqual(true);
expect(schema.parse(BigInt(15))).toEqual(true);
expect(schema.parse(Number.NaN)).toEqual(false);
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(true);
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(true);
expect(schema.parse(true)).toEqual(true);
expect(schema.parse(false)).toEqual(false);
expect(schema.parse(null)).toEqual(false);
expect(schema.parse(undefined)).toEqual(false);
expect(schema.parse({ hello: "world!" })).toEqual(true);
expect(schema.parse(["item", "another_item"])).toEqual(true);
expect(schema.parse([])).toEqual(true);
expect(schema.parse(new Date(1670139203496))).toEqual(true);
});
test("bigint coercion", () => {
const schema = z.coerce.bigint();
expect(schema.parse("5")).toEqual(BigInt(5));
expect(schema.parse("0")).toEqual(BigInt(0));
expect(schema.parse("-5")).toEqual(BigInt(-5));
expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError!
expect(schema.parse("")).toEqual(BigInt(0));
expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError!
expect(schema.parse(5)).toEqual(BigInt(5));
expect(schema.parse(0)).toEqual(BigInt(0));
expect(schema.parse(-5)).toEqual(BigInt(-5));
expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError!
expect(schema.parse(BigInt(5))).toEqual(BigInt(5));
expect(() => schema.parse(Number.NaN)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // not a z.ZodError!
expect(schema.parse(true)).toEqual(BigInt(1));
expect(schema.parse(false)).toEqual(BigInt(0));
expect(() => schema.parse(null)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError!
expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError!
expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError!
expect(schema.parse([])).toEqual(BigInt(0));
expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496));
});
test("date coercion", () => {
const schema = z.coerce.date();
expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date);
expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date);
expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date);
expect(schema.parse("5")).toBeInstanceOf(Date);
expect(schema.parse("2000-01-01")).toBeInstanceOf(Date);
// expect(schema.parse("0")).toBeInstanceOf(Date);
// expect(schema.parse("-5")).toBeInstanceOf(Date);
// expect(schema.parse("3.14")).toBeInstanceOf(Date);
expect(() => schema.parse("")).toThrow(); // z.ZodError
expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError
expect(schema.parse(5)).toBeInstanceOf(Date);
expect(schema.parse(0)).toBeInstanceOf(Date);
expect(schema.parse(-5)).toBeInstanceOf(Date);
expect(schema.parse(3.14)).toBeInstanceOf(Date);
expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError
expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // z.ZodError
expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // z.ZodError
expect(schema.parse(true)).toBeInstanceOf(Date);
expect(schema.parse(false)).toBeInstanceOf(Date);
expect(schema.parse(null)).toBeInstanceOf(Date);
expect(() => schema.parse(undefined)).toThrow(); // z.ZodError
expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError
expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError
expect(() => schema.parse([])).toThrow(); // z.ZodError
expect(schema.parse(new Date())).toBeInstanceOf(Date);
});
@@ -0,0 +1,70 @@
import { expect, test } from "vitest";
import * as z from "zod/v3";
const crazySchema = z.object({
tuple: z.tuple([
z.string().nullable().optional(),
z.number().nullable().optional(),
z.boolean().nullable().optional(),
z.null().nullable().optional(),
z.undefined().nullable().optional(),
z.literal("1234").nullable().optional(),
]),
merged: z
.object({
k1: z.string().optional(),
})
.merge(z.object({ k1: z.string().nullable(), k2: z.number() })),
union: z.array(z.union([z.literal("asdf"), z.literal(12)])).nonempty(),
array: z.array(z.number()),
// sumTransformer: z.transformer(z.array(z.number()), z.number(), (arg) => {
// return arg.reduce((a, b) => a + b, 0);
// }),
sumMinLength: z.array(z.number()).refine((arg) => arg.length > 5),
intersection: z.intersection(z.object({ p1: z.string().optional() }), z.object({ p1: z.number().optional() })),
enum: z.intersection(z.enum(["zero", "one"]), z.enum(["one", "two"])),
nonstrict: z.object({ points: z.number() }).nonstrict(),
numProm: z.promise(z.number()),
lenfun: z.function(z.tuple([z.string()]), z.boolean()),
});
// const asyncCrazySchema = crazySchema.extend({
// // async_transform: z.transformer(
// // z.array(z.number()),
// // z.number(),
// // async (arg) => {
// // return arg.reduce((a, b) => a + b, 0);
// // }
// // ),
// async_refine: z.array(z.number()).refine(async (arg) => arg.length > 5),
// });
test("parse", () => {
const input = {
tuple: ["asdf", 1234, true, null, undefined, "1234"],
merged: { k1: "asdf", k2: 12 },
union: ["asdf", 12, "asdf", 12, "asdf", 12],
array: [12, 15, 16],
// sumTransformer: [12, 15, 16],
sumMinLength: [12, 15, 16, 98, 24, 63],
intersection: {},
enum: "one",
nonstrict: { points: 1234 },
numProm: Promise.resolve(12),
lenfun: (x: string) => x.length,
};
const result = crazySchema.parse(input);
// Verify the parsed result structure
expect(result.tuple).toEqual(input.tuple);
expect(result.merged).toEqual(input.merged);
expect(result.union).toEqual(input.union);
expect(result.array).toEqual(input.array);
expect(result.sumMinLength).toEqual(input.sumMinLength);
expect(result.intersection).toEqual(input.intersection);
expect(result.enum).toEqual(input.enum);
expect(result.nonstrict).toEqual(input.nonstrict);
expect(result.numProm).toBeInstanceOf(Promise);
expect(typeof result.lenfun).toBe("function");
});
@@ -0,0 +1,31 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("passing validations", () => {
const example1 = z.custom<number>((x) => typeof x === "number");
example1.parse(1234);
expect(() => example1.parse({})).toThrow();
});
test("string params", () => {
const example1 = z.custom<number>((x) => typeof x !== "number", "customerr");
const result = example1.safeParse(1234);
expect(result.success).toEqual(false);
// @ts-ignore
expect(JSON.stringify(result.error).includes("customerr")).toEqual(true);
});
test("async validations", async () => {
const example1 = z.custom<number>(async (x) => {
return typeof x === "number";
});
const r1 = await example1.safeParseAsync(1234);
expect(r1.success).toEqual(true);
expect(r1.data).toEqual(1234);
const r2 = await example1.safeParseAsync("asdf");
expect(r2.success).toEqual(false);
expect(r2.error!.issues.length).toEqual(1);
});
@@ -0,0 +1,32 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const beforeBenchmarkDate = new Date(2022, 10, 4);
const benchmarkDate = new Date(2022, 10, 5);
const afterBenchmarkDate = new Date(2022, 10, 6);
const minCheck = z.date().min(benchmarkDate);
const maxCheck = z.date().max(benchmarkDate);
test("passing validations", () => {
minCheck.parse(benchmarkDate);
minCheck.parse(afterBenchmarkDate);
maxCheck.parse(benchmarkDate);
maxCheck.parse(beforeBenchmarkDate);
});
test("failing validations", () => {
expect(() => minCheck.parse(beforeBenchmarkDate)).toThrow();
expect(() => maxCheck.parse(afterBenchmarkDate)).toThrow();
});
test("min max getters", () => {
expect(minCheck.minDate).toEqual(benchmarkDate);
expect(minCheck.min(afterBenchmarkDate).minDate).toEqual(afterBenchmarkDate);
expect(maxCheck.maxDate).toEqual(benchmarkDate);
expect(maxCheck.max(beforeBenchmarkDate).maxDate).toEqual(beforeBenchmarkDate);
});
@@ -0,0 +1,186 @@
// @ts-ignore TS6133
import { test } from "vitest";
import * as z from "zod/v3";
test("test", () => {
z;
});
// const fish = z.object({
// name: z.string(),
// props: z.object({
// color: z.string(),
// numScales: z.number(),
// }),
// });
// const nonStrict = z
// .object({
// name: z.string(),
// color: z.string(),
// })
// .nonstrict();
// test('object pick type', () => {
// const modNonStrictFish = nonStrict.omit({ name: true });
// modNonStrictFish.parse({ color: 'asdf' });
// const bad1 = () => fish.pick({ props: { unknown: true } } as any);
// const bad2 = () => fish.omit({ name: true, props: { unknown: true } } as any);
// expect(bad1).toThrow();
// expect(bad2).toThrow();
// });
// test('f1', () => {
// const f1 = fish.pick(true);
// f1.parse({ name: 'a', props: { color: 'b', numScales: 3 } });
// });
// test('f2', () => {
// const f2 = fish.pick({ props: true });
// f2.parse({ props: { color: 'asdf', numScales: 1 } });
// const badcheck2 = () => f2.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// expect(badcheck2).toThrow();
// });
// test('f3', () => {
// const f3 = fish.pick({ props: { color: true } });
// f3.parse({ props: { color: 'b' } });
// const badcheck3 = () => f3.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// expect(badcheck3).toThrow();
// });
// test('f4', () => {
// const badcheck4 = () => fish.pick({ props: { color: true, unknown: true } });
// expect(badcheck4).toThrow();
// });
// test('f6', () => {
// const f6 = fish.omit({ props: true });
// const badcheck6 = () => f6.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// f6.parse({ name: 'adsf' });
// expect(badcheck6).toThrow();
// });
// test('f7', () => {
// const f7 = fish.omit({ props: { color: true } });
// f7.parse({ name: 'a', props: { numScales: 3 } });
// const badcheck7 = () => f7.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// expect(badcheck7).toThrow();
// });
// test('f8', () => {
// const badcheck8 = () => fish.omit({ props: { color: true, unknown: true } });
// expect(badcheck8).toThrow();
// });
// test('f9', () => {
// const f9 = nonStrict.pick(true);
// f9.parse({ name: 'a', color: 'asdf' });
// });
// test('f10', () => {
// const f10 = nonStrict.pick({ name: true });
// f10.parse({ name: 'a' });
// const val = f10.parse({ name: 'a', color: 'b' });
// expect(val).toEqual({ name: 'a' });
// });
// test('f12', () => {
// const badfcheck12 = () => nonStrict.omit({ color: true, asdf: true });
// expect(badfcheck12).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const modFishArray = fishArray.pick({
// name: true,
// props: {
// numScales: true,
// },
// });
// modFishArray.parse([{ name: 'fish', props: { numScales: 12 } }]);
// const bad1 = () => modFishArray.parse([{ name: 'fish', props: { numScales: 12, color: 'asdf' } }] as any);
// expect(bad1).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const fail = () =>
// fishArray.pick({
// name: true,
// props: {
// whatever: true,
// },
// } as any);
// expect(fail).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const fail = () =>
// fishArray.omit({
// whateve: true,
// } as any);
// expect(fail).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const modFishList = fishArray.omit({
// name: true,
// props: {
// color: true,
// },
// });
// modFishList.parse([{ props: { numScales: 12 } }]);
// const fail = () => modFishList.parse([{ name: 'hello', props: { numScales: 12 } }] as any);
// expect(fail).toThrow();
// });
// test('primitive array masking', () => {
// const fishArray = z.array(z.number());
// const fail = () => fishArray.pick({} as any);
// expect(fail).toThrow();
// });
// test('other array masking', () => {
// const fishArray = z.array(z.array(z.number()));
// const fail = () => fishArray.pick({} as any);
// expect(fail).toThrow();
// });
// test('invalid mask #1', () => {
// const fail = () => fish.pick(1 as any);
// expect(fail).toThrow();
// });
// test('invalid mask #2', () => {
// const fail = () => fish.pick([] as any);
// expect(fail).toThrow();
// });
// test('invalid mask #3', () => {
// const fail = () => fish.pick(false as any);
// expect(fail).toThrow();
// });
// test('invalid mask #4', () => {
// const fail = () => fish.pick('asdf' as any);
// expect(fail).toThrow();
// });
// test('invalid mask #5', () => {
// const fail = () => fish.omit(1 as any);
// expect(fail).toThrow();
// });
// test('invalid mask #6', () => {
// const fail = () => fish.omit([] as any);
// expect(fail).toThrow();
// });
// test('invalid mask #7', () => {
// const fail = () => fish.omit(false as any);
// expect(fail).toThrow();
// });
// test('invalid mask #8', () => {
// const fail = () => fish.omit('asdf' as any);
// expect(fail).toThrow();
// });
@@ -0,0 +1,112 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import { z } from "zod/v3";
import { util } from "../helpers/util.js";
test("basic defaults", () => {
expect(z.string().default("default").parse(undefined)).toBe("default");
});
test("default with transform", () => {
const stringWithDefault = z
.string()
.transform((val) => val.toUpperCase())
.default("default");
expect(stringWithDefault.parse(undefined)).toBe("DEFAULT");
expect(stringWithDefault).toBeInstanceOf(z.ZodDefault);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects);
expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, string | undefined>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("default on existing optional", () => {
const stringWithDefault = z.string().optional().default("asdf");
expect(stringWithDefault.parse(undefined)).toBe("asdf");
expect(stringWithDefault).toBeInstanceOf(z.ZodDefault);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional);
expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, string | undefined>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("optional on default", () => {
const stringWithDefault = z.string().default("asdf").optional();
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, string | undefined>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("complex chain example", () => {
const complex = z
.string()
.default("asdf")
.transform((val) => val.toUpperCase())
.default("qwer")
.removeDefault()
.optional()
.default("asdfasdf");
expect(complex.parse(undefined)).toBe("ASDFASDF");
});
test("removeDefault", () => {
const stringWithRemovedDefault = z.string().default("asdf").removeDefault();
type out = z.output<typeof stringWithRemovedDefault>;
util.assertEqual<out, string>(true);
});
test("nested", () => {
const inner = z.string().default("asdf");
const outer = z.object({ inner }).default({
inner: undefined,
});
type input = z.input<typeof outer>;
util.assertEqual<input, { inner?: string | undefined } | undefined>(true);
type out = z.output<typeof outer>;
util.assertEqual<out, { inner: string }>(true);
expect(outer.parse(undefined)).toEqual({ inner: "asdf" });
expect(outer.parse({})).toEqual({ inner: "asdf" });
expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" });
});
test("chained defaults", () => {
const stringWithDefault = z.string().default("inner").default("outer");
const result = stringWithDefault.parse(undefined);
expect(result).toEqual("outer");
});
test("factory", () => {
expect(z.ZodDefault.create(z.string(), { default: "asdf" }).parse(undefined)).toEqual("asdf");
});
test("native enum", () => {
enum Fruits {
apple = "apple",
orange = "orange",
}
const schema = z.object({
fruit: z.nativeEnum(Fruits).default(Fruits.apple),
});
expect(schema.parse({})).toEqual({ fruit: Fruits.apple });
});
test("enum", () => {
const schema = z.object({
fruit: z.enum(["apple", "orange"]).default("apple"),
});
expect(schema.parse({})).toEqual({ fruit: "apple" });
});
@@ -0,0 +1,33 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const description = "a description";
test("passing `description` to schema should add a description", () => {
expect(z.string({ description }).description).toEqual(description);
expect(z.number({ description }).description).toEqual(description);
expect(z.boolean({ description }).description).toEqual(description);
});
test("`.describe` should add a description", () => {
expect(z.string().describe(description).description).toEqual(description);
expect(z.number().describe(description).description).toEqual(description);
expect(z.boolean().describe(description).description).toEqual(description);
});
test("description should carry over to chained schemas", () => {
const schema = z.string({ description });
expect(schema.description).toEqual(description);
expect(schema.optional().description).toEqual(description);
expect(schema.optional().nullable().default("default").description).toEqual(description);
});
test("description should not carry over to chained array schema", () => {
const schema = z.string().describe(description);
expect(schema.description).toEqual(description);
expect(schema.array().description).toEqual(undefined);
expect(z.array(schema).description).toEqual(undefined);
});
@@ -0,0 +1,315 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("valid", () => {
expect(
z
.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
])
.parse({ type: "a", a: "abc" })
).toEqual({ type: "a", a: "abc" });
});
test("valid - discriminator value of various primitive types", () => {
const schema = z.discriminatedUnion("type", [
z.object({ type: z.literal("1"), val: z.literal(1) }),
z.object({ type: z.literal(1), val: z.literal(2) }),
z.object({ type: z.literal(BigInt(1)), val: z.literal(3) }),
z.object({ type: z.literal("true"), val: z.literal(4) }),
z.object({ type: z.literal(true), val: z.literal(5) }),
z.object({ type: z.literal("null"), val: z.literal(6) }),
z.object({ type: z.literal(null), val: z.literal(7) }),
z.object({ type: z.literal("undefined"), val: z.literal(8) }),
z.object({ type: z.literal(undefined), val: z.literal(9) }),
z.object({ type: z.literal("transform"), val: z.literal(10) }),
z.object({ type: z.literal("refine"), val: z.literal(11) }),
z.object({ type: z.literal("superRefine"), val: z.literal(12) }),
]);
expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 });
expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 });
expect(schema.parse({ type: BigInt(1), val: 3 })).toEqual({
type: BigInt(1),
val: 3,
});
expect(schema.parse({ type: "true", val: 4 })).toEqual({
type: "true",
val: 4,
});
expect(schema.parse({ type: true, val: 5 })).toEqual({
type: true,
val: 5,
});
expect(schema.parse({ type: "null", val: 6 })).toEqual({
type: "null",
val: 6,
});
expect(schema.parse({ type: null, val: 7 })).toEqual({
type: null,
val: 7,
});
expect(schema.parse({ type: "undefined", val: 8 })).toEqual({
type: "undefined",
val: 8,
});
expect(schema.parse({ type: undefined, val: 9 })).toEqual({
type: undefined,
val: 9,
});
});
test("invalid - null", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
]).parse(null);
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: z.ZodIssueCode.invalid_type,
expected: z.ZodParsedType.object,
message: "Expected object, received null",
received: z.ZodParsedType.null,
path: [],
},
]);
}
});
test("invalid discriminator value", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
]).parse({ type: "x", a: "abc" });
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: z.ZodIssueCode.invalid_union_discriminator,
options: ["a", "b"],
message: "Invalid discriminator value. Expected 'a' | 'b'",
path: ["type"],
},
]);
}
});
test("valid discriminator value, invalid data", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
]).parse({ type: "a", b: "abc" });
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: z.ZodIssueCode.invalid_type,
expected: z.ZodParsedType.string,
message: "Required",
path: ["a"],
received: z.ZodParsedType.undefined,
},
]);
}
});
test("wrong schema - missing discriminator", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ b: z.string() }) as any,
]);
throw new Error();
} catch (e: any) {
expect(e.message.includes("could not be extracted")).toBe(true);
}
});
test("wrong schema - duplicate discriminator values", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("a"), b: z.string() }),
]);
throw new Error();
} catch (e: any) {
expect(e.message.includes("has duplicate value")).toEqual(true);
}
});
test("async - valid", async () => {
expect(
await z
.discriminatedUnion("type", [
z.object({
type: z.literal("a"),
a: z
.string()
.refine(async () => true)
.transform(async (val) => Number(val)),
}),
z.object({
type: z.literal("b"),
b: z.string(),
}),
])
.parseAsync({ type: "a", a: "1" })
).toEqual({ type: "a", a: 1 });
});
test("async - invalid", async () => {
try {
await z
.discriminatedUnion("type", [
z.object({
type: z.literal("a"),
a: z
.string()
.refine(async () => true)
.transform(async (val) => val),
}),
z.object({
type: z.literal("b"),
b: z.string(),
}),
])
.parseAsync({ type: "a", a: 1 });
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: "invalid_type",
expected: "string",
received: "number",
path: ["a"],
message: "Expected string, received number",
},
]);
}
});
test("valid - literals with .default or .preprocess", () => {
const schema = z.discriminatedUnion("type", [
z.object({
type: z.literal("foo").default("foo"),
a: z.string(),
}),
z.object({
type: z.literal("custom"),
method: z.string(),
}),
z.object({
type: z.preprocess((val) => String(val), z.literal("bar")),
c: z.string(),
}),
]);
expect(schema.parse({ type: "foo", a: "foo" })).toEqual({
type: "foo",
a: "foo",
});
});
test("enum and nativeEnum", () => {
enum MyEnum {
d = 0,
e = "e",
}
const schema = z.discriminatedUnion("key", [
z.object({
key: z.literal("a"),
// Add other properties specific to this option
}),
z.object({
key: z.enum(["b", "c"]),
// Add other properties specific to this option
}),
z.object({
key: z.nativeEnum(MyEnum),
// Add other properties specific to this option
}),
]);
// type schema = z.infer<typeof schema>;
schema.parse({ key: "a" });
schema.parse({ key: "b" });
schema.parse({ key: "c" });
schema.parse({ key: MyEnum.d });
schema.parse({ key: MyEnum.e });
schema.parse({ key: "e" });
});
test("branded", () => {
const schema = z.discriminatedUnion("key", [
z.object({
key: z.literal("a"),
// Add other properties specific to this option
}),
z.object({
key: z.literal("b").brand("asdfaf"),
// Add other properties specific to this option
}),
]);
// type schema = z.infer<typeof schema>;
schema.parse({ key: "a" });
schema.parse({ key: "b" });
expect(() => {
schema.parse({ key: "c" });
}).toThrow();
});
test("optional and nullable", () => {
const schema = z.discriminatedUnion("key", [
z.object({
key: z.literal("a").optional(),
a: z.literal(true),
}),
z.object({
key: z.literal("b").nullable(),
b: z.literal(true),
// Add other properties specific to this option
}),
]);
type schema = z.infer<typeof schema>;
z.util.assertEqual<schema, { key?: "a" | undefined; a: true } | { key: "b" | null; b: true }>(true);
schema.parse({ key: "a", a: true });
schema.parse({ key: undefined, a: true });
schema.parse({ key: "b", b: true });
schema.parse({ key: null, b: true });
expect(() => {
schema.parse({ key: null, a: true });
}).toThrow();
expect(() => {
schema.parse({ key: "b", a: true });
}).toThrow();
const value = schema.parse({ key: null, b: true });
if (!("key" in value)) value.a;
if (value.key === undefined) value.a;
if (value.key === "a") value.a;
if (value.key === "b") value.b;
if (value.key === null) value.b;
});
test("readonly array of options", () => {
const options = [
z.object({ type: z.literal("x"), val: z.literal(1) }),
z.object({ type: z.literal("y"), val: z.literal(2) }),
] as const;
expect(z.discriminatedUnion("type", options).parse({ type: "x", val: 1 })).toEqual({ type: "x", val: 1 });
});

Some files were not shown because too many files have changed in this diff Show More