from-schema
Version:
Infer TypeScript types from JSON schemas
1,660 lines (1,631 loc) • 49.4 kB
JavaScript
var J = Object.defineProperty;
var C = (e, t, r) => t in e ? J(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
var E = (e, t, r) => (C(e, typeof t != "symbol" ? t + "" : t, r), r);
const R = (e) => ({
type: "object",
..."description" in e ? { description: e.description } : {},
properties: Object.fromEntries(
Object.entries(e.properties).map(([t, r]) => [
t,
y(r)
])
),
..."required" in e ? { required: e.required } : {},
..."minProperties" in e ? { minProperties: e.minProperties } : {},
..."maxProperties" in e ? { maxProperties: e.maxProperties } : {},
..."examples" in e ? { examples: e.examples } : {}
}), L = (e) => {
const t = {
type: "string",
...e
};
return delete t.bsonType, t;
}, x = (e) => {
const t = { ...e };
return delete t.bsonType, t;
}, G = (e) => ({
type: "number",
...x(e)
}), K = (e) => ({
type: "array",
...x(e),
items: y(e.items)
}), W = (e) => ({
enum: e.enum.map((t) => y(t))
}), H = (e) => ({
type: "boolean",
...x(e)
}), X = (e) => ({
type: "string",
pattern: "^[0-9a-f]{24}$"
}), Q = (e) => ({
type: "string",
format: "date-time"
}), Y = (e) => ({
oneOf: e.oneOf.map((t) => y(t))
}), k = (e) => ({
allOf: e.allOf.map((t) => y(t))
}), ee = (e) => ({
anyOf: e.anyOf.map((t) => y(t))
}), q = (e) => e instanceof Date && !isNaN(e.getTime()), w = (e, t = "", r = /* @__PURE__ */ new Set()) => {
if (e === null)
return "null";
if (typeof e == "object" && e !== null) {
if (r.has(e))
throw new Error("Circular reference detected during stringification");
r.add(e);
}
switch (typeof e) {
case "string": {
let n = e;
return n = n.replace(/\\/g, "\\\\"), n = n.replace(/"/g, '\\"'), n.includes(`
`) && (n = n.replace(/\n/g, "\\n")), n.includes("\r") && (n = n.replace(/\r/g, "\\r")), n.includes(" ") && (n = n.replace(/\t/g, "\\t")), n.includes("\f") && (n = n.replace(/\f/g, "\\f")), n.includes("\b") && (n = n.replace(/\b/g, "\\b")), `"${n}"`;
}
case "undefined":
return "undefined";
case "number":
return isNaN(e) ? "NaN" : isFinite(e) ? e.toString() : e < 0 ? "-Infinity" : "Infinity";
case "boolean":
return e.toString();
case "symbol":
case "function":
return e.toString();
case "bigint":
return e.toString() + "n";
case "object":
if (Array.isArray(e)) {
const n = [];
for (let u = 0; u < e.length; u++)
u in e ? n.push(w(e[u], t, r)) : n.push("undefined");
return `[${n.join(", ")}]`;
}
if (q(e))
return `new Date("${e.toISOString()}")`;
if (e instanceof Error) {
const n = {};
e.message && (n.message = e.message), e.name && (n.name = e.name), e.stack && (n.stack = e.stack);
for (const c of Object.keys(e))
n[c] = e[c];
const u = Object.entries(n).map(([c, o]) => {
const a = `"${c.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`, l = w(o, t, r);
return `${a}: ${l}`;
}).join(", ");
return r.delete(e), `{${u}}`;
}
const i = Object.entries(e).map(([n, u]) => {
const c = `"${n.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`, o = w(u, t, r);
return `${c}: ${o}`;
}).join(", ");
return r.delete(e), `{${i}}`;
}
throw new Error("Unsupported type: " + typeof e);
};
class f extends Error {
constructor(r, i) {
super(`${r} at position ${i}`);
E(this, "position");
this.position = i;
}
}
const te = 1e4, F = 1e8, D = 1e8;
function re(e) {
const t = [];
let r = 0;
const i = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z/;
if (i.test(e))
return t.push({ type: "string", value: e, position: 0 }), t;
for (; r < e.length; ) {
const n = e[r];
if (/\s/.test(n)) {
r++;
continue;
}
if (n === "{") {
t.push({ type: "object_start", value: "{", position: r }), r++;
continue;
}
if (n === "}") {
t.push({ type: "object_end", value: "}", position: r }), r++;
continue;
}
if (n === "[") {
t.push({ type: "array_start", value: "[", position: r }), r++;
continue;
}
if (n === "]") {
t.push({ type: "array_end", value: "]", position: r }), r++;
continue;
}
if (n === ":") {
t.push({ type: "colon", value: ":", position: r }), r++;
continue;
}
if (n === ",") {
t.push({ type: "comma", value: ",", position: r }), r++;
continue;
}
if (n === '"') {
let o = "", a = r;
for (r++; r < e.length; ) {
const l = e[r];
if (l === "\\" && r + 1 < e.length) {
const p = e[r + 1];
if (p === '"') {
o += '"', r += 2;
continue;
}
o += l + p, r += 2;
continue;
}
if (l === '"') {
r++;
break;
}
o += l, r++;
}
t.push({ type: "string", value: o, position: a });
continue;
}
const c = e.substring(r).match(i);
if (c && c.index === 0) {
const o = c[0];
t.push({ type: "string", value: o, position: r }), r += o.length;
continue;
}
if (e.startsWith("true", r)) {
t.push({ type: "true", value: "true", position: r }), r += 4;
continue;
}
if (e.startsWith("false", r)) {
t.push({ type: "false", value: "false", position: r }), r += 5;
continue;
}
if (e.startsWith("null", r)) {
t.push({ type: "null", value: "null", position: r }), r += 4;
continue;
}
if (e.startsWith("undefined", r)) {
t.push({ type: "undefined", value: "undefined", position: r }), r += 9;
continue;
}
if (/[\d.-]/.test(n)) {
let o = "", a = r, l = !1;
for (; r < e.length; ) {
const p = e[r];
if (p === "n") {
l = !0, r++;
break;
}
if (/[\d.e+-]/.test(p)) {
o += p, r++;
continue;
}
break;
}
l ? t.push({ type: "bigint", value: o, position: a }) : t.push({ type: "number", value: o, position: a });
continue;
}
throw new f(`Unexpected character '${n}'`, r);
}
return t;
}
function A(e, t = 0, r = 0) {
var n, u, c, o, a, l, p, d, v, T, S, I, N, B, _;
if (r > te)
throw new f(
"Maximum nesting depth exceeded",
((n = e[t]) == null ? void 0 : n.position) || -1
);
if (t >= e.length)
throw new f("Unexpected end of input", -1);
const i = e[t];
switch (i.type) {
case "string":
if (i.value.length > F)
throw new f(
`String length exceeds maximum allowed (${F})`,
i.position
);
return { value: i.value, nextIdx: t + 1 };
case "number": {
const s = Number(i.value);
if (!Number.isFinite(s) && !Number.isNaN(s))
throw new f(
`Invalid number value: ${i.value}`,
i.position
);
return { value: s, nextIdx: t + 1 };
}
case "bigint":
try {
return { value: BigInt(i.value), nextIdx: t + 1 };
} catch {
throw new f(
`Invalid BigInt value: ${i.value}`,
i.position
);
}
case "true":
return { value: !0, nextIdx: t + 1 };
case "false":
return { value: !1, nextIdx: t + 1 };
case "null":
return { value: null, nextIdx: t + 1 };
case "undefined":
return { value: void 0, nextIdx: t + 1 };
case "object_start": {
let s = t + 1;
const m = {};
let V = 0;
if (s < e.length && e[s].type === "object_end")
return { value: {}, nextIdx: s + 1 };
for (; s < e.length; ) {
if (V > 1e5)
throw new f(
"Object contains too many properties",
i.position
);
if (((u = e[s]) == null ? void 0 : u.type) !== "string")
throw new f(
`Expected string key, got ${((c = e[s]) == null ? void 0 : c.type) || "undefined"}`,
((o = e[s]) == null ? void 0 : o.position) || -1
);
const $ = e[s].value;
if ($ === "__proto__" || $ === "constructor" || $ === "prototype")
throw new f(
`Potentially unsafe property name: ${$}`,
e[s].position
);
if (s++, s >= e.length || ((a = e[s]) == null ? void 0 : a.type) !== "colon")
throw new f(
'Expected ":"',
s < e.length && ((l = e[s]) == null ? void 0 : l.position) || -1
);
s++;
const { value: M, nextIdx: Z } = A(e, s, r + 1);
if (m[$] = M, s = Z, V++, s >= e.length)
throw new f("Unexpected end of input", -1);
if (((p = e[s]) == null ? void 0 : p.type) === "object_end")
return { value: m, nextIdx: s + 1 };
if (((d = e[s]) == null ? void 0 : d.type) !== "comma")
throw new f(
`Expected "," or "}", got ${((v = e[s]) == null ? void 0 : v.type) || "undefined"}`,
((T = e[s]) == null ? void 0 : T.position) || -1
);
s++;
}
throw new f("Unexpected end of input", -1);
}
case "array_start": {
let s = t + 1;
const m = [];
if (s < e.length && ((S = e[s]) == null ? void 0 : S.type) === "array_end")
return { value: [], nextIdx: s + 1 };
for (; s < e.length; ) {
if (m.length > 1e7)
throw new f(
"Array contains too many elements",
i.position
);
const { value: V, nextIdx: $ } = A(e, s, r + 1);
if (m.push(V), s = $, s >= e.length)
throw new f("Unexpected end of input", -1);
if (((I = e[s]) == null ? void 0 : I.type) === "array_end")
return { value: m, nextIdx: s + 1 };
if (((N = e[s]) == null ? void 0 : N.type) !== "comma")
throw new f(
`Expected "," or "]", got ${((B = e[s]) == null ? void 0 : B.type) || "undefined"}`,
((_ = e[s]) == null ? void 0 : _.position) || -1
);
s++;
}
throw new f("Unexpected end of input", -1);
}
default:
throw new f(
`Unexpected token type: ${i.type}`,
i.position
);
}
}
function ne(e) {
return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/.test(e);
}
function O(e) {
if (e == null)
return e;
if (typeof e == "string" && ne(e)) {
const t = new Date(e);
if (q(t))
return t;
}
if (Array.isArray(e))
return e.map(O);
if (typeof e == "object") {
const t = {};
for (const [r, i] of Object.entries(e))
t[r] = O(i);
return t;
}
return e;
}
const ie = (e) => {
try {
if (e == null)
throw new Error("Input cannot be null or undefined");
if (typeof e != "string")
throw new Error("Input must be a string");
if (e.length === 0)
throw new Error("Empty input");
if (e.length > D)
throw new Error(
`Input exceeds maximum allowed length (${D})`
);
const t = re(e);
if (t.length === 0)
throw new Error("No valid tokens found in input");
const { value: r, nextIdx: i } = A(t, 0, 0);
if (i < t.length)
throw new f(
`Unexpected token after end of BON: ${t[i].type}`,
t[i].position
);
return O(r);
} catch (t) {
throw t instanceof f ? new Error(`BON parse error: ${t.message}`) : t;
}
}, Ge = (e) => typeof e == "string" ? ie(e) : null, oe = {
type: "string",
description: "Some text i guess lmao"
}, ae = {
type: "boolean",
description: "Either true or false"
}, se = {
type: "number",
description: "Any number, should probably be constrained at some point"
}, ue = {
type: "bigint",
description: "Any bigint"
}, le = {
type: "integer",
description: "Any natural number",
minimum: 1
}, ce = {
type: "date",
description: "Any date"
}, Ke = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
bigint: ue,
boolean: ae,
date: ce,
natural: le,
number: se,
string: oe
}, Symbol.toStringTag, { value: "Module" })), y = (e) => {
if (typeof e == "string" || typeof e == "boolean" || typeof e == "number")
return e;
if (typeof e == "object") {
if ("enum" in e)
return W(e);
if ("oneOf" in e)
return Y(e);
if ("allOf" in e)
return k(e);
if ("anyOf" in e)
return ee(e);
if ("bsonType" in e)
switch (e.bsonType) {
case "array":
return K(e);
case "object":
return R(e);
case "string":
return L(e);
case "decimal":
case "int":
case "long":
case "double":
return G(e);
case "bool":
return H(e);
case "objectId":
return X();
case "date":
return Q();
default:
throw new Error(`Unsupported bsonType: ${e.bsonType}`);
}
throw new Error(
`Invalid BSON schema: object must have either "enum" or "bsonType" property: ${w(e)}`
);
}
throw new Error("Invalid BSON schema: unexpected type");
}, We = (e) => ({
type: "number",
...x(e)
});
function He(e) {
return typeof e == "object" && e !== null && !Array.isArray(e);
}
const g = (e) => {
if (typeof e == "string")
return `"${e}"`;
if (typeof e == "boolean" || typeof e == "number")
return e.toString();
if (typeof e == "object") {
if ("enum" in e)
return `${e.enum.map((t) => g(t)).join(" | ")}`;
if ("oneOf" in e)
return `(${e.oneOf.map((t) => g(t)).join(" | ")})`;
if ("allOf" in e)
return `(${e.allOf.map((t) => g(t)).join(" & ")})`;
if ("anyOf" in e)
return `(${e.anyOf.map((t) => g(t)).join(" | ")})`;
if ("type" in e)
switch (e.type) {
case "array":
return `Array<${g(e.items)}>`;
case "object": {
const t = Object.entries(
e.properties
), r = "required" in e ? e.required : [];
return `{ ${t.map(([i, n]) => `${i}${r.includes(i) ? "" : "?"}: ${g(n)}`).join("; ")} }`;
}
case "string":
return "string";
case "boolean":
return "boolean";
case "integer":
return "number";
case "number":
return "number";
default:
throw new Error(`Unknown type: ${e.type}`);
}
throw new Error(`Unknown json object schema: ${e}`);
}
throw new Error(`Unknown bson schema type ${typeof e}: ${e}`);
}, pe = {
type: "string",
description: "Some text i guess lmao"
}, fe = {
type: "boolean",
description: "Either true or false"
}, de = {
type: "number",
description: "Any number, should probably be constrained at some point"
}, $e = {
type: "integer",
description: "Any integer"
}, ge = {
type: "integer",
description: "Any whole number",
minimum: 0
}, me = {
type: "integer",
description: "Any natural number",
minimum: 1
}, be = {
type: "string",
format: "date-time"
}, he = {
type: "string",
format: "email"
}, we = {
type: "string",
pattern: "^[0-9a-f]{24}$",
description: "MongoDB UID (24 character hex string)"
}, ye = {
type: "string",
pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
description: "UUID v4 (36 character hex string)"
}, Ee = {
type: "string",
pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
description: "UUID v5 (36 character hex string)"
}, Xe = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
boolean: fe,
date: be,
email: he,
integer: $e,
natural: me,
number: de,
string: pe,
uid: we,
uuidv4: ye,
uuidv5: Ee,
whole: ge
}, Symbol.toStringTag, { value: "Module" })), Ve = {
bsonType: "string",
description: "Some text i guess lmao"
}, xe = {
bsonType: "bool",
description: "Either true or false"
}, Ae = {
bsonType: "long",
description: "Any number, should probably be constrained at some point"
}, Oe = {
bsonType: "int",
description: "Any integer"
}, je = {
bsonType: "long",
description: "Any whole number",
minimum: 0
}, ve = {
bsonType: "double",
description: "A double-precision floating point number"
}, Te = {
bsonType: "long",
description: "Any natural number",
minimum: 1
}, Se = {
bsonType: "objectId",
description: "BSON ObjectId"
}, Ie = {
bsonType: "date",
description: "BSON Date"
}, Ne = {
bsonType: "string",
format: "email"
}, Be = {
bsonType: "string",
pattern: "^[0-9a-f]{24}$",
description: "MongoDB UID (24 character hex string)"
}, _e = {
bsonType: "string",
pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
description: "UUID v4 (36 character hex string)"
}, Fe = {
bsonType: "string",
pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
description: "UUID v5 (36 character hex string)"
}, Qe = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
bool: xe,
date: Ie,
double: ve,
email: Ne,
int: Oe,
long: Ae,
natural: Te,
objectId: Se,
string: Ve,
uid: Be,
uuidv4: _e,
uuidv5: Fe,
whole: je
}, Symbol.toStringTag, { value: "Module" })), b = (e) => {
if (typeof e == "string")
return `"${e}"`;
if (typeof e == "boolean" || typeof e == "number")
return e.toString();
if (typeof e == "object") {
if ("enum" in e)
return `${e.enum.map((t) => b(t)).join(" | ")}`;
if ("oneOf" in e)
return `(${e.oneOf.map((t) => b(t)).join(" | ")})`;
if ("allOf" in e)
return `(${e.allOf.map((t) => b(t)).join(" & ")})`;
if ("anyOf" in e)
return `(${e.anyOf.map((t) => b(t)).join(" | ")})`;
if ("bsonType" in e)
switch (e.bsonType) {
case "array":
return `Array<${b(e.items)}>`;
case "object": {
const t = Object.entries(
e.properties
), r = "required" in e ? e.required : [];
return `{ ${t.map(([i, n]) => `${i}${r.includes(i) ? "" : "?"}: ${b(n)}`).join("; ")} }`;
}
case "string":
return "string";
case "bool":
return "boolean";
case "int":
return "number";
case "long":
return "number";
case "double":
return "number";
case "decimal":
return "number";
case "date":
return "Date";
default:
throw new Error(`Unknown bsonType: ${e.bsonType}`);
}
throw new Error(`Unknown bson object schema: ${e}`);
}
throw new Error(`Unknown bson schema type ${typeof e}: ${e}`);
}, z = (e) => {
if (!e.type)
throw new Error(`erm ${w(e)}`);
switch (e.type) {
case "enum":
return e;
case "array":
return { ...e, items: z(e.items) };
case "char":
case "character":
case "bpchar":
case "text":
case "varchar":
case "character varying":
return { ...e, type: "string" };
case "bool":
case "boolean":
return { ...e, type: "boolean" };
case "int8":
case "bigint":
case "bigserial":
case "serial8":
return {
...e,
type: "bigint",
...e.default ? { default: e.default === "nextval" ? -1n : e.default } : {}
};
case "double precision":
case "float8":
case "int":
case "smallint":
case "int2":
case "int4":
case "integer":
case "money":
case "serial":
case "serial4":
case "smallserial":
case "serial2":
case "numeric":
return {
...e,
type: "number",
...typeof e.default < "u" ? { default: e.default === "nextval" ? -1 : e.default } : {}
};
case "date":
case "timestamp":
case "timestamptz":
return { ...e, type: "date" };
case "jsonb":
return e.schema ?? { type: "object", properties: {}, required: [] };
default:
throw console.log("Invalid model", e), new Error(`Unknown type: ${e.type} on ${w(e)}`);
}
}, Ye = (e, t) => {
const r = Object.entries(
e.properties
), i = "required" in e ? e.required : [], n = t ? i.filter((u) => "default" in e || "generated" in e) : i;
return {
type: "object",
properties: Object.fromEntries(
r.map(([u, c]) => [u, z(c)])
),
required: n
};
};
class ke {
constructor(t = "generated") {
E(this, "indent", "");
E(this, "messages", /* @__PURE__ */ new Set());
E(this, "enums", /* @__PURE__ */ new Set());
this.packageName = t;
}
incrementIndent() {
this.indent += " ";
}
decrementIndent() {
this.indent = this.indent.slice(2);
}
typeToProto(t) {
return t.type === "enum" || t.enum ? "enum" : {
string: "string",
text: "string",
number: "double",
integer: "int32",
boolean: "bool",
bigint: "int64",
bigserial: "int64",
object: "message",
array: "repeated"
}[t.type] || "string";
}
generateEnum(t, r) {
const i = [`enum ${t} {`];
return this.incrementIndent(), r.forEach((n, u) => {
const c = n.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^[0-9]/, "_$&");
i.push(`${this.indent}${c} = ${u};`);
}), this.decrementIndent(), i.push("}"), i.join(`
`);
}
generateMessage(t, r) {
if (r.type === "enum" || r.enum) {
const o = r.enum || [], a = this.generateEnum(t, o);
return this.enums.add(a), "";
}
const i = [`message ${t} {`];
this.incrementIndent();
let n = 1;
const u = r.properties || {};
for (const [o, a] of Object.entries(u)) {
let l = this.typeToProto(a), p = "";
if (l === "enum") {
const d = `${t}${o.charAt(0).toUpperCase()}${o.slice(1)}Enum`;
this.enums.add(this.generateEnum(d, a.enum)), p = `${this.indent}${d} ${o} = ${n};`;
} else if (l === "message") {
const d = `${t}${o.charAt(0).toUpperCase()}${o.slice(1)}`;
this.generateMessage(d, a), p = `${this.indent}${d} ${o} = ${n};`;
} else if (l === "repeated") {
const d = this.typeToProto(a.items);
p = `${this.indent}repeated ${d} ${o} = ${n};`;
} else
p = `${this.indent}${l} ${o} = ${n};`;
i.push(p), n++;
}
this.decrementIndent(), i.push("}");
const c = i.join(`
`);
return this.messages.add(c), c;
}
generateSchema(t) {
this.messages.clear(), this.enums.clear();
for (const [i, n] of Object.entries(t)) {
const u = i.charAt(0).toUpperCase() + i.slice(1);
this.generateMessage(u, n);
}
return [
'syntax = "proto3";',
"",
`package ${this.packageName};`,
"",
'import "google/protobuf/timestamp.proto";',
"",
...Array.from(this.enums),
"",
...Array.from(this.messages)
].join(`
`);
}
}
const h = (e) => {
if (typeof e == "string")
return `"${e}"`;
if (typeof e == "boolean" || typeof e == "number" || typeof e == "bigint")
return e.toString();
if (typeof e == "object") {
if ("$ref" in e)
return e.$ref, "any";
if ("enum" in e)
return `${e.enum.map((t) => h(t)).join(" | ")}`;
if ("oneOf" in e)
return `(${e.oneOf.map((t) => h(t)).join(" | ")})`;
if ("allOf" in e)
return `(${e.allOf.map((t) => h(t)).join(" & ")})`;
if ("anyOf" in e)
return `(${e.anyOf.map((t) => h(t)).join(" | ")})`;
if ("type" in e)
switch (e.type) {
case "array":
return `Array<${h(e.items)}>`;
case "object": {
const t = e.properties ? Object.entries(
e.properties
) : [], r = "required" in e ? e.required : [];
return `{ ${t.map(([i, n]) => `${i}${r.includes(i) ? "" : "?"}: ${h(n)}`).join("; ")} }`;
}
case "string":
return "string";
case "boolean":
return "boolean";
case "integer":
case "number":
return "number";
case "bigint":
return "bigint";
case "date":
return "Date";
default:
throw new Error(`Unknown type: ${e.type}`);
}
throw new Error(`Unknown tson schema: ${JSON.stringify(e, null, 4)}`);
}
throw new Error(`Unknown tson schema type ${typeof e}: ${e}`);
}, U = (e) => {
switch (e.type) {
case "enum":
return `${e.enum.map((t) => `'${t}'`).join(" | ")}`;
case "array":
return `Array<${U(e.items)}>`;
case "char":
case "character":
case "bpchar":
case "text":
case "varchar":
case "character varying":
return "string";
case "bool":
case "boolean":
return "boolean";
case "int8":
case "bigint":
return "bigint";
case "int":
case "smallint":
case "int2":
case "int4":
case "integer":
case "double precision":
case "float8":
case "money":
return "number";
case "bigserial":
case "serial8":
return "Generated<bigint>";
case "serial":
case "serial4":
case "serial2":
case "smallserial":
return "Generated<number>";
case "date":
case "timestamp":
case "timestamptz":
return "Date";
case "jsonb":
return e.schema ? g(e.schema) : "unknown";
default:
throw new Error(`Unknown type: ${e.type}`);
}
}, et = (e) => {
const t = Object.entries(
e.properties
), r = "required" in e ? e.required : [];
return `{ ${t.map(([i, n]) => `${i}${r.includes(i) ? "" : "?"}: ${U(n)}`).join("; ")} }`;
};
function De(e, t) {
const r = {};
let i = "", n = "", u = "";
for (const [o, a] of Object.entries(t.properties || {})) {
const l = `${e}["${o}"]`;
r[o] = j(l, a), i += `
if ("${o}" in ${e}) {
try {
${r[o].validateOrThrow}
} catch (error) {
throw new Error(\`Property "${o}": \${error.message}\`);
}
}
`, n += `
if ("${o}" in ${e}) {
const propResult = (() => {
${r[o].isValid}
return true;
})();
if (propResult !== true) {
return \`Property "${o}": \${propResult}\`;
}
}
`, u += `
if ("${o}" in ${e}) {
const propErrors = [];
{
let allErrors = propErrors;
${r[o].validate}
}
for (const error of propErrors) {
allErrors.push(\`Property "${o}": \${error}\`);
}
}
`;
}
const c = "required" in t ? t.required : [];
return {
validateOrThrow: `
if (typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e})) {
throw new Error('Value must be an object');
}
for (const prop of ${JSON.stringify(c)}) {
if (!(prop in ${e})) {
throw new Error(\`Missing required property: \${prop}\`);
}
}
${i}
`,
isValid: `
if (typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e})) {
return 'Value must be an object';
}
for (const prop of ${JSON.stringify(c)}) {
if (!(prop in ${e})) {
return \`Missing required property: \${prop}\`;
}
}
${n}`,
validate: `
if (typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e})) {
allErrors.push('Value must be an object');
} else {
for (const prop of ${JSON.stringify(c)}) {
if (!(prop in ${e})) {
allErrors.push(\`Missing required property: \${prop}\`);
}
}
${u}
}`
};
}
const qe = {
date: /^\d{4}-\d{2}-\d{2}$/,
time: /^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.\d+)?(Z|[+-]\d{2}:[0-5][0-9])?$/,
"date-time": /^\d{4}-\d{2}-\d{2}T([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.\d+)?(Z|[+-]\d{2}:[0-5][0-9])?$/,
email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
hostname: /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
ipv6: /^(?:(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}|(?:[a-fA-F0-9]{1,4}:){1,7}:|(?:[a-fA-F0-9]{1,4}:){1,6}:[a-fA-F0-9]{1,4}|(?:[a-fA-F0-9]{1,4}:){1,5}(?::[a-fA-F0-9]{1,4}){1,2}|(?:[a-fA-F0-9]{1,4}:){1,4}(?::[a-fA-F0-9]{1,4}){1,3}|(?:[a-fA-F0-9]{1,4}:){1,3}(?::[a-fA-F0-9]{1,4}){1,4}|(?:[a-fA-F0-9]{1,4}:){1,2}(?::[a-fA-F0-9]{1,4}){1,5}|[a-fA-F0-9]{1,4}:(?:(?::[a-fA-F0-9]{1,4}){1,6})|:(?:(?::[a-fA-F0-9]{1,4}){1,7}|:))$/,
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
"uri-reference": /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?(?:\/\/(?:(?:[a-zA-Z0-9\-._~!$&'()*+,;=:]|%[0-9A-F]{2})*@)?(?:\[(?:(?:(?:(?:[0-9A-F]{1,4}:){6}|::(?:[0-9A-F]{1,4}:){5}|(?:[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){4}|(?:(?:[0-9A-F]{1,4}:){0,1}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){3}|(?:(?:[0-9A-F]{1,4}:){0,2}[0-9A-F]{1,4})?::(?:[0-9A-F]{1,4}:){2}|(?:(?:[0-9A-F]{1,4}:){0,3}[0-9A-F]{1,4})?::[0-9A-F]{1,4}:|(?:(?:[0-9A-F]{1,4}:){0,4}[0-9A-F]{1,4})?::)(?:[0-9A-F]{1,4}:[0-9A-F]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(?:(?:[0-9A-F]{1,4}:){0,5}[0-9A-F]{1,4})?::[0-9A-F]{1,4}|(?:(?:[0-9A-F]{1,4}:){0,6}[0-9A-F]{1,4})?::)|[Vv][0-9A-F]+\.[a-zA-Z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|(?:[a-zA-Z0-9\-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::[0-9]*)?(?:\/(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@]|%[0-9A-F]{2})*)*|\/(?:(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:\/(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@]|%[0-9A-F]{2})*)*)?|(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:\/(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@]|%[0-9A-F]{2})*)*)?(?:\?(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-F]{2})*)?(?:#(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-F]{2})*)?$/i,
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
"uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
"json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
"relative-json-pointer": /^\d+(?:\/(?:[^~/]|~0|~1)*)*$/,
regex: /^(?:(?:[^?*+{}()[\]\\|/]|\\.|\[(?:[^\]\\]|\\.)*\]|\((?:[^)\\]|\\.)*\)|\{(?:[^}\\]|\\.)*\})+|[?*+{}()[\]\\|/])$/
};
function ze(e, t) {
var o;
if ("const" in t) {
const a = t.const, l = `
if (typeof ${e} !== "string") throw new Error("Value must be a string");
else if (${e} !== "${a}") throw new Error('Expected "${a}", got "' + ${e} + '"');
`, p = `
if (typeof ${e} !== "string") return "Value must be a string";
else if (${e} !== "${a}") return 'Expected "${a}", got "' + ${e} + '"';
`;
return {
validate: `
if (typeof ${e} !== "string") {
allErrors.push("Value must be a string");
}
else if (${e} !== "${a}") {
allErrors.push('Expected "${a}", got "' + ${e} + '"');
}
`,
validateOrThrow: l,
isValid: p
};
}
const r = [], i = [];
if (t.minLength !== void 0 && (r.push(
`if (${e}.length < ${t.minLength}) return "String must be at least ${t.minLength} characters long";`
), i.push(
`if (${e}.length < ${t.minLength}) throw new Error("String must be at least ${t.minLength} characters long");`
)), t.maxLength !== void 0 && (r.push(
`if (${e}.length > ${t.maxLength}) return "String must be at most ${t.maxLength} characters long";`
), i.push(
`if (${e}.length > ${t.maxLength}) throw new Error("String must be at most ${t.maxLength} characters long");`
)), t.format !== void 0) {
const a = qe[t.format];
if (a) {
const l = ((o = a.toString().match(/\/([gimuy]*)$/)) == null ? void 0 : o[1]) || "", p = a.toString().slice(1, -1 - (l.length ? l.length + 1 : 0)).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, "\\$");
r.push(
`if (!new RegExp("${p}", "${l}").test(${e})) return "String must be a valid ${t.format} format";`
), i.push(
`if (!new RegExp("${p}", "${l}").test(${e})) throw new Error("String must be a valid ${t.format} format");`
);
}
}
t.pattern !== void 0 && (r.push(
`if (!new RegExp("${t.pattern}").test(${e})) return "String must match pattern: ${t.pattern}";`
), i.push(
`if (!new RegExp("${t.pattern}").test(${e})) throw new Error("String must match pattern: ${t.pattern}");`
));
const n = `
if (typeof ${e} !== "string") throw new Error("Value must be a string");
${i.reduce((a, l) => a + " else " + l, "")}
`, u = `
if (typeof ${e} !== "string") return "Value must be a string";
${r.reduce((a, l) => a + " else " + l, "")}
`;
return {
validate: `
if (typeof ${e} !== "string") {
allErrors.push("Value must be a string");
} else {
${r.map(
(a) => a.replace("return", "allErrors.push(").replace(/;$/, ");")
).join(`
`)}
}
`,
validateOrThrow: n,
isValid: u
};
}
function Ue(e, t) {
if ("const" in t) {
const n = t.const;
return {
validateOrThrow: `
if (typeof ${e} !== 'boolean') throw new Error("Expected boolean, got " + typeof ${e});
if (${e} !== ${n}) throw new Error("Expected ${n}, got " + ${e});
`,
isValid: `
if (typeof ${e} !== 'boolean') return "Expected boolean, got " + typeof ${e};
if (${e} !== ${n}) return "Expected ${n}, got " + ${e};
`,
validate: `
if (typeof ${e} !== 'boolean') allErrors.push("Expected boolean, got " + typeof ${e});
else if (${e} !== ${n}) allErrors.push("Expected ${n}, got " + ${e});
`
};
}
const r = t.default !== void 0, i = t.default;
return {
validateOrThrow: `
${r ? `if (typeof ${e} === 'undefined') return ${JSON.stringify(i)};` : ""}
if(typeof ${e} !== 'boolean') throw new Error("Expected boolean, got " + typeof ${e});
return ${e};
`,
isValid: `
${r ? `if (typeof ${e} === 'undefined') {} else` : ""}
if (typeof ${e} !== 'boolean')
return "Expected boolean, got " + typeof ${e};
`,
validate: `
${r ? `if (typeof ${e} === 'undefined') {} else` : ""}
if (typeof ${e} !== 'boolean') {
allErrors.push("Expected boolean, got " + typeof ${e});
}
`
};
}
function Pe(e, t) {
if ("const" in t) {
const o = t.const, a = `
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
throw new Error("Value must be a valid number");
}
} else if (typeof ${e} !== "number") {
throw new Error("Value must be a number");
}
if (numValue !== ${o}) throw new Error("Expected ${o}, got " + numValue);
`, l = `
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
return "Value must be a valid number";
}
} else if (typeof ${e} !== "number") {
return "Value must be a number";
}
if (numValue !== ${o}) return "Expected ${o}, got " + numValue;
`;
return {
validate: `
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
allErrors.push("Value must be a valid number");
} else if (numValue !== ${o}) {
allErrors.push("Expected ${o}, got " + numValue);
}
} else if (typeof ${e} !== "number") {
allErrors.push("Value must be a number");
} else if (numValue !== ${o}) {
allErrors.push("Expected ${o}, got " + numValue);
}
`,
validateOrThrow: a,
isValid: l
};
}
const r = [];
t.minimum !== void 0 && r.push(
`if (numValue < ${t.minimum}) return "Value must be greater than or equal to ${t.minimum}";`
), t.maximum !== void 0 && r.push(
`if (numValue > ${t.maximum}) return "Value must be less than or equal to ${t.maximum}";`
);
const i = `
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
return "Value must be a valid number";
}
} else if (typeof ${e} !== "number") {
return "Value must be a number";
}
${t.type === "integer" ? `if (!Number.isInteger(numValue)) {
return "Value must be an integer";
}` : ""}
`, n = `
${i.replace(/return "(.*?)";/g, 'throw new Error("$1");')}
${r.map((o) => o.replace(/return "(.*?)";/g, 'throw new Error("$1");')).join(`
`)}
`, u = `
${i}
${r.join(`
`)}
`;
return {
validate: `
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
allErrors.push("Value must be a valid number");
} else {
${t.type === "integer" ? `if (!Number.isInteger(numValue)) {
allErrors.push("Value must be an integer");
} else {` : ""}
${r.map((o) => o.replace(
/return "(.*?)";/,
'allErrors.push("$1");'
)).join(" else ")}
${t.type === "integer" ? "}" : ""}
}
} else if (typeof ${e} !== "number") {
allErrors.push("Value must be a number");
} else {
${t.type === "integer" ? `if (!Number.isInteger(${e})) {
allErrors.push("Value must be an integer");
} else {` : ""}
${r.map((o) => o.replace(/numValue/g, e).replace(/return "(.*?)";/, 'allErrors.push("$1");')).join(" else ")}
${t.type === "integer" ? "}" : ""}
}
`,
validateOrThrow: n,
isValid: u
};
}
function Me(e, t) {
if ("const" in t) {
const o = t.const, a = `
let bigintValue = ${e};
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
throw new Error("Value must be a bigint");
}
} else if (typeof ${e} !== "bigint") {
throw new Error("Value must be a bigint");
}
if (bigintValue !== ${o}n) throw new Error("Expected ${o}, got " + bigintValue);
`, l = `
let bigintValue = ${e};
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
return "Value must be a bigint";
}
} else if (typeof ${e} !== "bigint") {
return "Value must be a bigint";
}
if (bigintValue !== ${o}n) return "Expected ${o}, got " + bigintValue;
`;
return {
validate: `
let bigintValue = ${e};
let hasError = false;
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
allErrors.push("Value must be a bigint");
hasError = true;
}
} else if (typeof ${e} !== "bigint") {
allErrors.push("Value must be a bigint");
hasError = true;
}
if (!hasError && bigintValue !== ${o}n) {
allErrors.push("Expected ${o}, got " + bigintValue);
}
`,
validateOrThrow: a,
isValid: l
};
}
const r = [];
if (t.minimum !== void 0) {
const o = t.minimum.toString();
r.push(
`if (bigintValue < ${o}n) return "Value must be greater than or equal to ${o}";`
);
}
if (t.maximum !== void 0) {
const o = t.maximum.toString();
r.push(
`if (bigintValue > ${o}n) return "Value must be less than or equal to ${o}";`
);
}
const i = `
let bigintValue = ${e};
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
return "Value must be a bigint";
}
} else if (typeof ${e} !== "bigint") {
return "Value must be a bigint";
}
`, n = `
${i.replace(/return "(.*?)";/g, 'throw new Error("$1");')}
${r.map((o) => o.replace(/return "(.*?)";/g, 'throw new Error("$1");')).join(`
`)}
`, u = `
${i}
${r.join(`
`)}
`;
return {
validate: `
let bigintValue = ${e};
let hasError = false;
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
allErrors.push("Value must be a bigint");
hasError = true;
}
} else if (typeof ${e} !== "bigint") {
allErrors.push("Value must be a bigint");
hasError = true;
}
if (!hasError) {
${r.map((o) => o.replace(
/return "(.*?)";/,
'allErrors.push("$1");'
)).join(" else ")}
}
`,
validateOrThrow: n,
isValid: u
};
}
function Ze(e, t) {
const r = "default" in t, i = r ? JSON.stringify(t.default) : void 0, n = t.enum.map((c) => JSON.stringify(c)).join(", "), u = t.enum.join(", ");
return {
isValid: `
if (${e} === undefined) {
${r ? "return true;" : 'return "Expected string, got undefined";'}
} else if (typeof ${e} !== "string") {
return "Expected string, got " + typeof ${e};
} else if (![${n}].includes(${e})) {
return "Value must be one of: ${u}";
}`,
validateOrThrow: `
if (${e} === undefined) {
${r ? `return ${i};` : 'throw new Error("Expected string, got undefined");'}
} else if (typeof ${e} !== "string") {
throw new Error("Expected string, got " + typeof ${e});
} else if (![${n}].includes(${e})) {
throw new Error("Value must be one of: ${u}");
} else {
return ${e};
}`,
validate: `
if (${e} === undefined) {
${r ? "" : 'allErrors.push("Expected string, got undefined");'}
} else if (typeof ${e} !== "string") {
allErrors.push("Expected string, got " + typeof ${e});
} else if (![${n}].includes(${e})) {
allErrors.push("Value must be one of: ${u}");
}`
};
}
const P = (e) => btoa(e).replace(/=/g, "");
function Je(e, t) {
const r = t.oneOf.map(
(a) => j(e, a)
), i = "Value must match one of the allowed schemas", n = P(e), u = `
let anyMatch_${n} = false;
${r.reduce(
(a, l, p) => `
try {
${l.validateOrThrow};
anyMatch_${n} = true;
} catch {${a}}`,
""
)}
if (!anyMatch_${n}) {
throw new Error("${i}");
}
`, c = `
let anyMatch_${n} = false;
${r.map(
(a, l) => `
if (typeof (()=>{${a.isValid}})() !== 'string') {
anyMatch_${n} = true;
}`
).join(" else ")}
if(!anyMatch_${n}) return "${i}";
`;
return {
validate: `
let anyMatch_${n} = false;
${r.map(
(a, l) => `
{
const tempErrors = [];
{
let allErrors = tempErrors;
${a.validate}
}
if (tempErrors.length === 0) {
anyMatch_${n} = true;
}
}
`
).join("")}
if (!anyMatch_${n}) {
allErrors.push("${i}");
}
`,
validateOrThrow: u,
isValid: c
};
}
const Ce = (e, t) => {
if ("const" in t) {
const n = t.const.getTime();
return {
validateOrThrow: `
if (!(${e} instanceof Date)) {
throw new Error("Value must be a Date");
}
if (isNaN(${e}.getTime())) throw new Error("Value must be a valid Date");
if (${e}.getTime() !== ${n}) throw new Error('Expected ' + new Date(${n}).toISOString() + ', got ' + ${e}.toISOString());
`,
isValid: `
if (!(${e} instanceof Date)) {
return "Value must be a Date";
}
if (isNaN(value.getTime())) return "Value must be a valid Date";
if (${e}.getTime() !== ${n}) return 'Expected ' + new Date(${n}).toISOString() + ', got ' + value.toISOString();
`,
validate: `
if (!(${e} instanceof Date)) {
allErrors.push("Value must be a Date");
}
if (isNaN(value.getTime())) {
allErrors.push("Value must be a valid Date");
}
if (${e}.getTime() !== ${n}) allErrors.push('Expected ' + new Date(${n}).toISOString() + ', got ' + ${e}.toISOString());
`
};
}
const r = [];
if ("minimum" in t && t.minimum !== void 0) {
const n = t.minimum.getTime();
r.push(
`if (${e}.getTime() < ${n}) return 'Date must be greater than or equal to ' + new Date(${n}).toISOString();`
);
}
if ("maximum" in t && t.maximum !== void 0) {
const n = t.maximum.getTime();
r.push(
`if (${e}.getTime() > ${n}) return 'Date must be less than or equal to ' + new Date(${n}).toISOString();`
);
}
const i = `
if (!(${e} instanceof Date)) {
return "Value must be a Date";
}
if (isNaN(${e}.getTime())) return "Value must be a valid Date";
`;
return {
validateOrThrow: `
${i.replace(/return "(.*?)";/g, 'throw new Error("$1");')}
${r.map((n) => n.replace(/return "(.*?)";/g, 'throw new Error("$1");')).join(`
`)}
`,
isValid: `
${i}
${r.join(`
`)}
`,
validate: `
if (!(${e} instanceof Date)) {
allErrors.push("Value must be a Date");
}
else if (isNaN(${e}.getTime())) {
allErrors.push("Value must be a valid Date");
}
${r.map((n) => n.replace(/return "(.*?)";/, 'allErrors.push("$1");')).join(`
`)}
`
};
};
function j(e, t) {
switch (typeof t) {
case "string":
case "number":
case "boolean":
case "bigint": {
const r = t;
return {
validate: `
if(${e} !== ${JSON.stringify(r)})
allErrors.push('Expected ${typeof t == "string" ? `"${t}"` : t}, got ' + ${e})
`,
validateOrThrow: `
if (${e} !== ${JSON.stringify(r)}) {
throw new Error('Expected ${typeof t == "string" ? `"${t}"` : t}, got ' + ${e});
}
`,
isValid: `
if(${e} !== ${JSON.stringify(r)})
return 'Expected ${typeof t == "string" ? `"${t}"` : t}, got ' + ${e}
`
};
}
}
if (Array.isArray(t)) {
const r = t;
return {
validate: `
${e} === ${JSON.stringify(r)} ? [] : allErrors.push('Expected ${t}, got ' + ${e})`,
validateOrThrow: `
if (${e} !== ${JSON.stringify(r)}) {
throw new Error('Expected ${t}, got ' + ${e});
}
`,
isValid: `
${e} === ${JSON.stringify(r)} ? true : 'Expected ${t}, got ' + ${e}`
};
}
if ("enum" in t)
return Ze(e, t);
if ("oneOf" in t)
return Je(e, t);
switch ("type" in t && t.type) {
case "array":
return Re(e, t);
case "object":
return De(e, t);
case "string":
return ze(e, t);
case "bigint":
return Me(e, t);
case "number":
case "integer":
return Pe(e, t);
case "boolean":
return Ue(e, t);
case "date":
return Ce(e, t);
default:
throw new Error(`Invalid schema: ${JSON.stringify(t, null, 4)}`);
}
}
function Re(e, t) {
const r = P(e) + "_item", i = j(r, t.items), n = `
if (!Array.isArray(${e})) {
allErrors.push('Value must be an array');
} else {
${t.minItems !== void 0 ? `
if (${e}.length < ${t.minItems}) {
allErrors.push(\`Array length \${${e}.length} is less than minimum length ${t.minItems}\`);
}
` : ""}
${t.maxItems !== void 0 ? `
if (${e}.length > ${t.maxItems}) {
allErrors.push(\`Array length \${${e}.length} exceeds maximum length ${t.maxItems}\`);
}
` : ""}
for (let i = 0; i < ${e}.length; i++) {
const ${r} = ${e}[i];
const itemErrors = [];
{
let allErrors = itemErrors;
${i.validate}
}
for (const error of itemErrors) {
allErrors.push(\`Invalid item at index \${i}: \${error}\`);
}
}
}
`, u = `
if (!Array.isArray(${e})) {
throw new Error('Value must be an array');
}
${t.minItems !== void 0 ? `
if (${e}.length < ${t.minItems}) {
throw new Error(\`Array length \${${e}.length} is less than minimum length ${t.minItems}\`);
}
` : ""}
${t.maxItems !== void 0 ? `
if (${e}.length > ${t.maxItems}) {
throw new Error(\`Array length \${${e}.length} exceeds maximum length ${t.maxItems}\`);
}
` : ""}
for (let i = 0; i < ${e}.length; i++) {
const ${r} = ${e}[i];
try {
${i.validateOrThrow}
} catch (error) {
throw new Error(\`Invalid item at index \${i}: \${error.message}\`);
}
}
`, c = `
if (!Array.isArray(${e})) {
return 'Value must be an array';
}
${t.minItems !== void 0 ? `
if (${e}.length < ${t.minItems}) {
return \`Array length \${${e}.length} is less than minimum length ${t.minItems}\`;
}
` : ""}
${t.maxItems !== void 0 ? `
if (${e}.length > ${t.maxItems}) {
return \`Array length \${${e}.length} exceeds maximum length ${t.maxItems}\`;
}
` : ""}
for (let i = 0; i < ${e}.length; i++) {
const ${r} = ${e}[i];
const itemResult = (() => {
${i.isValid}
return true;
})();
if (itemResult !== true) {
return \`Invalid item at index \${i}: \${itemResult}\`;
}
}
`;
return {
validate: n,
validateOrThrow: u,
isValid: c
};
}
class tt extends Error {
constructor(t) {
super(t), this.name = "ValidationError";
}
}
export {
ke as ProtoGenerator,
tt as ValidationError,
K as arrayBsonToJson,
H as booleanBsonToJson,
Qe as bsonPrimitives,
y as bsonToJson,
b as bsonToType,
Re as buildArrayValidator,
Me as buildBigintValidator,
Ue as buildBooleanValidator,
Ce as buildDateValidator,
Ze as buildEnumValidator,
Pe as buildNumberValidator,
De as buildObjectValidator,
Je as buildOneOfValidator,
ze as buildStringValidator,
j as buildValidator,
W as enumBsonToJson,
He as isObject,
Xe as jsonPrimitives,
g as jsonToType,
G as numberBsonToJson,
R as objectBsonToJson,
ie as parseBON,
Ge as parsePossibleBON,
U as postgresColumnToKysely,
z as postgresColumnToTson,
et as postgresRecordToKysely,
Ye as postgresRecordToTson,
L as stringBsonToJson,
w as stringifyBON,
x as stripBsonType,
Ke as tsonPrimitives,
h as tsonToType,
We as wholeBsonToJson
};