viborm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +529 -0
  2. package/dist/adapters.d.mts +2 -0
  3. package/dist/adapters.mjs +1 -0
  4. package/dist/bun-sql.d.mts +3 -0
  5. package/dist/bun-sql.mjs +2 -0
  6. package/dist/bun-sql.mjs.map +1 -0
  7. package/dist/bun-sqlite.d.mts +3 -0
  8. package/dist/bun-sqlite.mjs +2 -0
  9. package/dist/bun-sqlite.mjs.map +1 -0
  10. package/dist/cache/cloudflare-kv.d.mts +3 -0
  11. package/dist/cache/cloudflare-kv.mjs +2 -0
  12. package/dist/cache/cloudflare-kv.mjs.map +1 -0
  13. package/dist/cache/memory.d.mts +3 -0
  14. package/dist/cache/memory.mjs +2 -0
  15. package/dist/cache/memory.mjs.map +1 -0
  16. package/dist/cache.d.mts +4 -0
  17. package/dist/cache.mjs +1 -0
  18. package/dist/cli.d.mts +1 -0
  19. package/dist/cli.mjs +41 -0
  20. package/dist/cli.mjs.map +1 -0
  21. package/dist/client-CgdtiDGV.mjs +2 -0
  22. package/dist/client-CgdtiDGV.mjs.map +1 -0
  23. package/dist/client.d.mts +3 -0
  24. package/dist/client.mjs +1 -0
  25. package/dist/cloudflare-kv-DauXhtnT.d.mts +1110 -0
  26. package/dist/d1-http.d.mts +3 -0
  27. package/dist/d1-http.mjs +2 -0
  28. package/dist/d1-http.mjs.map +1 -0
  29. package/dist/d1.d.mts +3 -0
  30. package/dist/d1.mjs +2 -0
  31. package/dist/d1.mjs.map +1 -0
  32. package/dist/driver-B_vBzQ6A.mjs +2 -0
  33. package/dist/driver-B_vBzQ6A.mjs.map +1 -0
  34. package/dist/driver-Cj1EbciY.mjs +2 -0
  35. package/dist/driver-Cj1EbciY.mjs.map +1 -0
  36. package/dist/driver.d.mts +2 -0
  37. package/dist/driver.mjs +1 -0
  38. package/dist/errors-DvcqIdEo.mjs +2 -0
  39. package/dist/errors-DvcqIdEo.mjs.map +1 -0
  40. package/dist/helper-cDCDjRAD.d.mts +3020 -0
  41. package/dist/helpers-WNr9B-2U.mjs +2 -0
  42. package/dist/helpers-WNr9B-2U.mjs.map +1 -0
  43. package/dist/hydration-CFnwc7j6.mjs +2 -0
  44. package/dist/hydration-CFnwc7j6.mjs.map +1 -0
  45. package/dist/index-3sdVKfeG.d.mts +1447 -0
  46. package/dist/index-BGmpst1h.d.mts +2158 -0
  47. package/dist/index.d.mts +46 -0
  48. package/dist/index.mjs +2 -0
  49. package/dist/index.mjs.map +1 -0
  50. package/dist/instrumentation.d.mts +2 -0
  51. package/dist/instrumentation.mjs +1 -0
  52. package/dist/libsql.d.mts +3 -0
  53. package/dist/libsql.mjs +2 -0
  54. package/dist/libsql.mjs.map +1 -0
  55. package/dist/migrations.d.mts +1588 -0
  56. package/dist/migrations.mjs +11 -0
  57. package/dist/migrations.mjs.map +1 -0
  58. package/dist/mysql-adapter-0catKeCI.mjs +6 -0
  59. package/dist/mysql-adapter-0catKeCI.mjs.map +1 -0
  60. package/dist/mysql-utils-BPw9qhac.mjs +2 -0
  61. package/dist/mysql-utils-BPw9qhac.mjs.map +1 -0
  62. package/dist/mysql2.d.mts +3 -0
  63. package/dist/mysql2.mjs +2 -0
  64. package/dist/mysql2.mjs.map +1 -0
  65. package/dist/native-types-BwICkVjz.mjs +2 -0
  66. package/dist/native-types-BwICkVjz.mjs.map +1 -0
  67. package/dist/neon-http.d.mts +3 -0
  68. package/dist/neon-http.mjs +2 -0
  69. package/dist/neon-http.mjs.map +1 -0
  70. package/dist/pending-operation-CkzYTpi4.mjs +2 -0
  71. package/dist/pending-operation-CkzYTpi4.mjs.map +1 -0
  72. package/dist/pg.d.mts +3 -0
  73. package/dist/pg.mjs +2 -0
  74. package/dist/pg.mjs.map +1 -0
  75. package/dist/pglite.d.mts +3 -0
  76. package/dist/pglite.mjs +2 -0
  77. package/dist/pglite.mjs.map +1 -0
  78. package/dist/planetscale.d.mts +3 -0
  79. package/dist/planetscale.mjs +2 -0
  80. package/dist/planetscale.mjs.map +1 -0
  81. package/dist/postgres-adapter-Blzqj1bl.mjs +6 -0
  82. package/dist/postgres-adapter-Blzqj1bl.mjs.map +1 -0
  83. package/dist/postgres.d.mts +3 -0
  84. package/dist/postgres.mjs +2 -0
  85. package/dist/postgres.mjs.map +1 -0
  86. package/dist/push-qZreXYkb.mjs +252 -0
  87. package/dist/push-qZreXYkb.mjs.map +1 -0
  88. package/dist/result-parsing-FNQbuHvC.mjs +2 -0
  89. package/dist/result-parsing-FNQbuHvC.mjs.map +1 -0
  90. package/dist/schema-DeAJZocc.mjs +2 -0
  91. package/dist/schema-DeAJZocc.mjs.map +1 -0
  92. package/dist/schema.d.mts +293 -0
  93. package/dist/schema.mjs +2 -0
  94. package/dist/schema.mjs.map +1 -0
  95. package/dist/spans-CJt5UgbJ.mjs +2 -0
  96. package/dist/spans-CJt5UgbJ.mjs.map +1 -0
  97. package/dist/sqlite-adapter-5Em_-oGU.mjs +6 -0
  98. package/dist/sqlite-adapter-5Em_-oGU.mjs.map +1 -0
  99. package/dist/sqlite-utils-BW7elKTz.mjs +2 -0
  100. package/dist/sqlite-utils-BW7elKTz.mjs.map +1 -0
  101. package/dist/sqlite3.d.mts +3 -0
  102. package/dist/sqlite3.mjs +2 -0
  103. package/dist/sqlite3.mjs.map +1 -0
  104. package/dist/tracer-CGzIAsj8.mjs +2 -0
  105. package/dist/tracer-CGzIAsj8.mjs.map +1 -0
  106. package/dist/validation-RtU-wu4N.mjs +2 -0
  107. package/dist/validation-RtU-wu4N.mjs.map +1 -0
  108. package/dist/validation.d.mts +2 -0
  109. package/dist/validation.mjs +1 -0
  110. package/dist/validator-DpJsJcd7.mjs +3 -0
  111. package/dist/validator-DpJsJcd7.mjs.map +1 -0
  112. package/package.json +278 -0
  113. package/readme/README.md +69 -0
@@ -0,0 +1,2 @@
1
+ var e=class e{constructor(t,n){if(t.length-1!==n.length)throw t.length===0?TypeError(`Expected at least 1 string`):TypeError(`Expected ${t.length} strings to have ${t.length-1} values`);let r=0;for(let t of n)r+=t instanceof e?t.values.length:1;this.values=Array(r),this.strings=Array(r+1),this.strings[0]=t[0];let i=0,a=0;for(;i<n.length;){let r=n[i++],o=t[i];if(r instanceof e){this.strings[a]+=r.strings[0];let e=0;for(;e<r.values.length;)this.values[a++]=r.values[e++],this.strings[a]=r.strings[e];this.strings[a]+=o}else this.values[a++]=r,this.strings[a]=o}}toStatement(e=`?`){if(e===`$n`){if(this._stmt$n!==void 0)return this._stmt$n}else if(e===`:n`){if(this._stmt$!==void 0)return this._stmt$}else if(this._stmtQ!==void 0)return this._stmtQ;let t=this.strings,n=t.length;if(n===1){let e=t[0];return this._stmt$n=this._stmt$=this._stmtQ=e,e}let r=Array(n*2-1);if(r[0]=t[0],e===`?`)for(let e=1;e<n;e++)r[e*2-1]=`?`,r[e*2]=t[e];else{let i=e===`$n`?`$`:`:`;for(let e=1;e<n;e++)r[e*2-1]=i+e,r[e*2]=t[e]}let i=r.join(``);return e===`$n`?this._stmt$n=i:e===`:n`?this._stmt$=i:this._stmtQ=i,i}};function t(...t){let n=t[0],r=Object.keys(n),i=new Set,a=t.map(t=>{let n=Object.keys(t),r=n.map(e=>t[e]);return i.add(r.length),new e([`(`,...Array(n.length-1).fill(`,`),`)`],r)});if(i.size>1)throw TypeError(`All inserted rows must have the same number of values`);return i.clear(),new e([`(${r.join(`,`)}) VALUES `,...Array(a.length-1).fill(`,`),`)`],a)}function n(t,...n){return new e([t.reduce((e,t,r)=>e+t+(n[r]??``),``)],[])}const r=(t,n,r)=>n?a:o`${new e([t],[])}${n}${new e([r],[])}`;function i(t,n=`,`,r=``,i=``){let a=t.length;if(a===0)return new e([r+i],[]);let o=Array(a+1);o[0]=r;for(let e=1;e<a;e++)o[e]=n;return o[a]=i,new e(o,t)}const a=n``;function o(t,...n){return new e(t,n)}const s=new Proxy(o,{get(e,o){return o===`raw`?n:o===`spreadValues`?t:o===`empty`?a:o===`wrap`?r:o===`join`?i:(t,...n)=>e(t,...n)}}),c=`_result`;function l(e){if(typeof e!=`string`)return;let t=e.trim();if(t.startsWith(`[`)&&t.endsWith(`]`)||t.startsWith(`{`)&&t.endsWith(`}`))try{return JSON.parse(e)}catch{return}}function u(e){if(typeof e==`number`)return e===1;if(e==null)return null}function d(e){if(typeof e==`bigint`)return Number(e)}function f(e){if(Array.isArray(e)&&e.length>0){let t=e[0];if(typeof t==`object`&&t){let e=p(t);if(e!==void 0)return[{[c]:e}]}}if(typeof e==`object`&&e&&!Array.isArray(e)){let t=p(e);if(t!==void 0)return[{[c]:t}]}}function p(e){let t=Object.keys(e);for(let n of t){let t=n.toLowerCase();if(t===`count`||t.startsWith(`count(`))return e[n]}}export{l as a,u as i,d as n,s as o,f as r,c as t};
2
+ //# sourceMappingURL=result-parsing-FNQbuHvC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-parsing-FNQbuHvC.mjs","names":["result","values","raw"],"sources":["../src/sql/sql.ts","../src/adapters/shared/result-parsing.ts"],"sourcesContent":["/**\n * Values supported by SQL engine.\n */\nexport type Value = unknown;\n\n/**\n * Supported value or SQL instance.\n */\nexport type RawValue = Value | Sql;\n\n/**\n * A SQL instance can be nested within each other to build SQL strings.\n */\nexport class Sql {\n readonly values: Value[];\n readonly strings: string[];\n\n // Cached statement strings (memoized per placeholder type)\n private _stmt$n: string | undefined;\n private _stmt$: string | undefined;\n private _stmtQ: string | undefined;\n\n constructor(rawStrings: readonly string[], rawValues: readonly RawValue[]) {\n if (rawStrings.length - 1 !== rawValues.length) {\n if (rawStrings.length === 0) {\n throw new TypeError(\"Expected at least 1 string\");\n }\n throw new TypeError(\n `Expected ${rawStrings.length} strings to have ${\n rawStrings.length - 1\n } values`\n );\n }\n\n // Single pass to count values (avoid reduce overhead)\n let valuesLength = 0;\n for (const v of rawValues) {\n valuesLength += v instanceof Sql ? v.values.length : 1;\n }\n\n this.values = new Array(valuesLength);\n this.strings = new Array(valuesLength + 1);\n\n this.strings[0] = rawStrings[0]!;\n\n // Iterate over raw values, strings, and children. The value is always\n // positioned between two strings, e.g. `index + 1`.\n let i = 0;\n let pos = 0;\n while (i < rawValues.length) {\n const child = rawValues[i++]!;\n const rawString = rawStrings[i]!;\n\n // Check for nested `sql` queries.\n if (child instanceof Sql) {\n // Append child prefix text to current string.\n this.strings[pos] += child.strings[0]!;\n\n let childIndex = 0;\n while (childIndex < child.values.length) {\n this.values[pos++] = child.values[childIndex++]!;\n this.strings[pos] = child.strings[childIndex]!;\n }\n\n // Append raw string to current string.\n this.strings[pos] += rawString;\n } else {\n this.values[pos++] = child;\n this.strings[pos] = rawString;\n }\n }\n }\n\n /**\n * Build the final SQL statement string with placeholders.\n * Results are cached per placeholder type for reuse.\n */\n toStatement(placeholder: \"$n\" | \":n\" | \"?\" = \"?\"): string {\n // Check cache first\n if (placeholder === \"$n\") {\n if (this._stmt$n !== undefined) return this._stmt$n;\n } else if (placeholder === \":n\") {\n if (this._stmt$ !== undefined) return this._stmt$;\n } else if (this._stmtQ !== undefined) return this._stmtQ;\n\n // Build the statement\n const strings = this.strings;\n const len = strings.length;\n\n if (len === 1) {\n // No placeholders needed\n const result = strings[0]!;\n this._stmt$n = this._stmt$ = this._stmtQ = result;\n return result;\n }\n\n // Pre-calculate total length for better string allocation\n // Use array join for better performance with many segments\n const parts = new Array<string>(len * 2 - 1);\n parts[0] = strings[0]!;\n\n if (placeholder === \"?\") {\n // Simple ? placeholders (MySQL/SQLite style)\n for (let i = 1; i < len; i++) {\n parts[i * 2 - 1] = \"?\";\n parts[i * 2] = strings[i]!;\n }\n } else {\n // Numbered placeholders ($1, $2 or :1, :2)\n const prefix = placeholder === \"$n\" ? \"$\" : \":\";\n for (let i = 1; i < len; i++) {\n parts[i * 2 - 1] = prefix + i;\n parts[i * 2] = strings[i]!;\n }\n }\n\n const result = parts.join(\"\");\n\n // Cache the result\n if (placeholder === \"$n\") {\n this._stmt$n = result;\n } else if (placeholder === \":n\") {\n this._stmt$ = result;\n } else {\n this._stmtQ = result;\n }\n\n return result;\n }\n}\n\nfunction spreadValues(...data: Record<string, RawValue>[]) {\n const firstRow = data[0]!;\n // Assuming all rows have the same keys\n const valueKeys = Object.keys(firstRow) as string[];\n const allLengths = new Set();\n\n const values = data.map((item) => {\n const keys = Object.keys(item);\n const values = keys.map((key) => item[key]);\n allLengths.add(values.length);\n return new Sql([\"(\", ...new Array(keys.length - 1).fill(\",\"), \")\"], values);\n });\n\n if (allLengths.size > 1) {\n throw new TypeError(\n \"All inserted rows must have the same number of values\"\n );\n }\n\n allLengths.clear();\n\n return new Sql(\n [\n `(${valueKeys.join(\",\")}) VALUES `,\n ...new Array(values.length - 1).fill(\",\"),\n \")\",\n ],\n values\n );\n}\n\n/**\n * Create raw SQL statement.\n */\nfunction raw(strings: readonly string[], ...values: readonly RawValue[]) {\n const concatenated = strings.reduce((acc, string, index) => {\n return acc + string + (values[index] ?? \"\");\n }, \"\");\n return new Sql([concatenated], []);\n}\n\nconst wrap = (prefix: string, wrapped: Sql | undefined, suffix: string) => {\n return wrapped\n ? empty\n : sql`${new Sql([prefix], [])}${wrapped}${new Sql([suffix], [])}`;\n};\n\n/**\n * Create a SQL query for a list of values.\n */\nfunction join(\n values: readonly Sql[],\n separator = \",\",\n prefix = \"\",\n suffix = \"\"\n) {\n const len = values.length;\n if (len === 0) {\n return new Sql([prefix + suffix], []);\n }\n\n // Pre-allocate array with exact size instead of spread + fill\n const strings = new Array<string>(len + 1);\n strings[0] = prefix;\n for (let i = 1; i < len; i++) {\n strings[i] = separator;\n }\n strings[len] = suffix;\n\n return new Sql(strings, values);\n}\n\n/**\n * Placeholder value for \"no text\".\n */\nconst empty = raw``;\n\n/**\n * Create a SQL object from a template string.\n */\nfunction sql(strings: readonly string[], ...values: readonly RawValue[]) {\n return new Sql(strings, values);\n}\n\nconst sqlProxy = new Proxy(sql, {\n get(target, prop) {\n if (prop === \"raw\") {\n return raw;\n }\n if (prop === \"spreadValues\") {\n return spreadValues;\n }\n if (prop === \"empty\") {\n return empty;\n }\n if (prop === \"wrap\") {\n return wrap;\n }\n if (prop === \"join\") {\n return join;\n }\n return (strings: TemplateStringsArray, ...values: RawValue[]) => {\n return target(strings, ...values);\n };\n },\n}) as typeof sql & {\n raw: typeof raw;\n wrap: typeof wrap;\n spreadValues: typeof spreadValues;\n empty: typeof empty;\n join: typeof join;\n};\n\nexport { sqlProxy as sql };\n","/**\n * Shared Result Parsing Utilities\n *\n * Common parsing logic used by adapters for database-specific type conversions.\n * These utilities use `undefined` as a sentinel to indicate \"not handled\" -\n * allowing the caller to fall through to default parsing.\n *\n * @example\n * const parsed = tryParseJsonString(value);\n * if (parsed !== undefined) {\n * // Use parsed value\n * } else {\n * // Fall through to default\n * }\n */\n\n/**\n * Normalized column name for COUNT results.\n * Used by adapters to normalize database-specific column names.\n */\nexport const COUNT_RESULT_KEY = \"_result\" as const;\n\n/**\n * Parse JSON string values (MySQL/SQLite return JSON as strings).\n *\n * @param value - Raw value from database\n * @returns Parsed JSON object/array, or `undefined` if not a JSON string\n *\n * @example\n * tryParseJsonString('[1,2,3]') // [1, 2, 3]\n * tryParseJsonString('{\"a\":1}') // { a: 1 }\n * tryParseJsonString('hello') // undefined (not JSON)\n * tryParseJsonString(123) // undefined (not a string)\n * tryParseJsonString('[invalid') // undefined (invalid JSON)\n */\nexport function tryParseJsonString(value: unknown): unknown | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert SQLite/MySQL integer to boolean.\n * These databases store booleans as 0/1 integers.\n *\n * @param value - Raw value from database\n * @returns `true` for 1, `false` for 0, `null` for null/undefined,\n * or `undefined` if value is not an integer (fall through to default)\n *\n * @example\n * parseIntegerBoolean(1) // true\n * parseIntegerBoolean(0) // false\n * parseIntegerBoolean(null) // null\n * parseIntegerBoolean('true') // undefined (not handled, fall through)\n */\nexport function parseIntegerBoolean(\n value: unknown\n): boolean | null | undefined {\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (value === null || value === undefined) {\n return null;\n }\n return undefined;\n}\n\n/**\n * Convert BigInt to Number.\n * PostgreSQL returns COUNT as bigint, which needs conversion.\n *\n * @param value - Raw value from database\n * @returns Number if value is bigint, or `undefined` to fall through\n *\n * @example\n * convertBigIntToNumber(5n) // 5\n * convertBigIntToNumber(123) // undefined (already a number)\n */\nexport function convertBigIntToNumber(value: unknown): number | undefined {\n if (typeof value === \"bigint\") {\n return Number(value);\n }\n return undefined;\n}\n\n/**\n * Normalize COUNT result column name.\n * Different databases return COUNT(*) with different column names:\n * - PostgreSQL: \"count\" (lowercase)\n * - MySQL: \"COUNT(*)\" (uppercase with parens)\n * - SQLite: \"COUNT(*)\" (uppercase with parens)\n *\n * This normalizes to `{ [COUNT_RESULT_KEY]: N }` for consistent parsing.\n *\n * @param raw - Raw database result (array or object)\n * @returns Normalized result with `_result` key, or `undefined` if not a COUNT result\n *\n * @example\n * normalizeCountResult([{ 'COUNT(*)': 5 }]) // [{ _result: 5 }]\n * normalizeCountResult([{ count: 5 }]) // [{ _result: 5 }]\n * normalizeCountResult([{ name: 'Alice' }]) // undefined (not a COUNT)\n */\nexport function normalizeCountResult(\n raw: unknown\n): [{ [COUNT_RESULT_KEY]: unknown }] | undefined {\n // Handle array with single row\n if (Array.isArray(raw) && raw.length > 0) {\n const firstRow = raw[0];\n if (typeof firstRow === \"object\" && firstRow !== null) {\n const countValue = extractCountValue(firstRow as Record<string, unknown>);\n if (countValue !== undefined) {\n return [{ [COUNT_RESULT_KEY]: countValue }];\n }\n }\n }\n\n // Handle single object\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const countValue = extractCountValue(raw as Record<string, unknown>);\n if (countValue !== undefined) {\n return [{ [COUNT_RESULT_KEY]: countValue }];\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract count value from a result row, checking common column names.\n * Case-insensitive to handle variations across databases.\n */\nfunction extractCountValue(row: Record<string, unknown>): unknown | undefined {\n const keys = Object.keys(row);\n\n for (const key of keys) {\n const lowerKey = key.toLowerCase();\n // Match: count, count(*), COUNT(*), count(distinct x), etc.\n if (lowerKey === \"count\" || lowerKey.startsWith(\"count(\")) {\n return row[key];\n }\n }\n\n return undefined;\n}\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./errors-DvcqIdEo.mjs";import{r as t}from"./validation-RtU-wu4N.mjs";const n={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},r=Object.keys(n).join(`, `),i=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function a(t){if(typeof t==`number`){if(t<=0)throw new e(`TTL must be positive, got: ${t}`);return t}let a=t.trim().toLowerCase().match(i);if(!a)throw new e(`Invalid TTL format: "${t}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let o=a[1],s=a[2],c=Number.parseFloat(o),l=n[s];if(l===void 0)throw new e(`Unknown time unit: "${s}". Valid units: ${r}`);let u=Math.floor(c*l);if(u<=0)throw new e(`TTL must be positive, got: ${u}ms from "${t}"`);return u}const o=t.object({invalidate:t.string({array:!0,optional:!0}),autoInvalidate:t.boolean({optional:!0,default:!1})},{optional:!0,default:{autoInvalidate:!1}}),s=300*1e3,c=t.object({ttl:t.coerce(t.optional(t.union([t.string(),t.number()]),s),e=>a(e??s)),swr:t.coerce(t.optional(t.union([t.boolean(),t.string(),t.number()])),e=>e===void 0||typeof e==`boolean`?e:a(e)),key:t.string({optional:!0}),bypass:t.boolean({optional:!0})},{optional:!0,default:{ttl:s,swr:!1,bypass:!1}});export{a as i,o as n,c as r,s as t};
2
+ //# sourceMappingURL=schema-DeAJZocc.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-DeAJZocc.mjs","names":["v"],"sources":["../src/cache/ttl.ts","../src/cache/schema.ts"],"sourcesContent":["/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/**\n * Time unit multipliers in milliseconds\n */\nconst TIME_UNITS: Record<string, number> = {\n ms: 1,\n millisecond: 1,\n milliseconds: 1,\n s: 1000,\n sec: 1000,\n second: 1000,\n seconds: 1000,\n m: 60 * 1000,\n min: 60 * 1000,\n minute: 60 * 1000,\n minutes: 60 * 1000,\n h: 60 * 60 * 1000,\n hr: 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n hours: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n day: 24 * 60 * 60 * 1000,\n days: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n week: 7 * 24 * 60 * 60 * 1000,\n weeks: 7 * 24 * 60 * 60 * 1000,\n month: 30 * 24 * 60 * 60 * 1000,\n months: 30 * 24 * 60 * 60 * 1000,\n};\n\nconst VALID_UNITS = Object.keys(TIME_UNITS).join(\", \");\n\n/**\n * Parse a TTL string into milliseconds\n *\n * @example\n * parseTTL(\"1 hour\") // 3600000\n * parseTTL(\"20 seconds\") // 20000\n * parseTTL(\"5m\") // 300000\n * parseTTL(\"2.5 hours\") // 9000000\n * parseTTL(3000) // 3000 (passthrough)\n *\n * @throws CacheInvalidTTLError if format is invalid\n */\nconst TTL_PATTERN = /^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/;\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (ttl <= 0) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const normalized = ttl.trim().toLowerCase();\n\n // Match patterns like \"1 hour\", \"20seconds\", \"2.5 h\"\n const match = normalized.match(TTL_PATTERN);\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\")`\n );\n }\n\n const valueStr = match[1] as string;\n const unit = match[2] as string;\n const value = Number.parseFloat(valueStr);\n const multiplier = TIME_UNITS[unit];\n\n if (multiplier === undefined) {\n throw new CacheInvalidTTLError(\n `Unknown time unit: \"${unit}\". Valid units: ${VALID_UNITS}`\n );\n }\n\n const result = Math.floor(value * multiplier);\n\n if (result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import v, { type V } from \"@validation\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\nexport type CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nexport const cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all cache entries for this model after mutation\n * @default false\n */\n autoInvalidate: v.boolean({ optional: true, default: false }),\n },\n { optional: true, default: { autoInvalidate: false } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nexport const DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\nexport type WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nexport const withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n (value: string | number) => {\n return parseTTL(value ?? DEFAULT_CACHE_TTL);\n }\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) => {\n if (value === undefined || typeof value === \"boolean\") {\n return value;\n }\n return parseTTL(value);\n }\n ),\n /**\n * Custom cache key override\n * If not provided, key is generated from model, operation, and args\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n\ntype T = WithCacheSchema[\" vibInferred\"][\"0\"];\n"],"mappings":"wFAWA,MAAM,EAAqC,CACzC,GAAI,EACJ,YAAa,EACb,aAAc,EACd,EAAG,IACH,IAAK,IACL,OAAQ,IACR,QAAS,IACT,EAAG,GAAK,IACR,IAAK,GAAK,IACV,OAAQ,GAAK,IACb,QAAS,GAAK,IACd,EAAG,KAAU,IACb,GAAI,KAAU,IACd,KAAM,KAAU,IAChB,MAAO,KAAU,IACjB,EAAG,KAAU,GAAK,IAClB,IAAK,KAAU,GAAK,IACpB,KAAM,KAAU,GAAK,IACrB,EAAG,MAAc,GAAK,IACtB,KAAM,MAAc,GAAK,IACzB,MAAO,MAAc,GAAK,IAC1B,MAAO,IAAU,GAAK,GAAK,IAC3B,OAAQ,IAAU,GAAK,GAAK,IAC7B,CAEK,EAAc,OAAO,KAAK,EAAW,CAAC,KAAK,KAAK,CAchD,EAAc,+BAEpB,SAAgB,EAAS,EAA8B,CACrD,GAAI,OAAO,GAAQ,SAAU,CAC3B,GAAI,GAAO,EACT,MAAM,IAAI,EAAqB,8BAA8B,IAAM,CAErE,OAAO,EAMT,IAAM,EAHa,EAAI,MAAM,CAAC,aAAa,CAGlB,MAAM,EAAY,CAE3C,GAAI,CAAC,EACH,MAAM,IAAI,EACR,wBAAwB,EAAI,sEAC7B,CAGH,IAAM,EAAW,EAAM,GACjB,EAAO,EAAM,GACb,EAAQ,OAAO,WAAW,EAAS,CACnC,EAAa,EAAW,GAE9B,GAAI,IAAe,IAAA,GACjB,MAAM,IAAI,EACR,uBAAuB,EAAK,kBAAkB,IAC/C,CAGH,IAAM,EAAS,KAAK,MAAM,EAAQ,EAAW,CAE7C,GAAI,GAAU,EACZ,MAAM,IAAI,EACR,8BAA8B,EAAO,WAAW,EAAI,GACrD,CAGH,OAAO,EC1ET,MAAa,EAA0BA,EAAE,OACvC,CAKE,WAAYA,EAAE,OAAO,CAAE,MAAO,GAAM,SAAU,GAAM,CAAC,CAKrD,eAAgBA,EAAE,QAAQ,CAAE,SAAU,GAAM,QAAS,GAAO,CAAC,CAC9D,CACD,CAAE,SAAU,GAAM,QAAS,CAAE,eAAgB,GAAO,CAAE,CACvD,CAeY,EAAoB,IAAS,IAc7B,EAAkBA,EAAE,OAC/B,CAME,IAAKA,EAAE,OACLA,EAAE,SAASA,EAAE,MAAM,CAACA,EAAE,QAAQ,CAAEA,EAAE,QAAQ,CAAC,CAAC,CAAE,EAAkB,CAC/D,GACQ,EAAS,GAAS,EAAkB,CAE9C,CAcD,IAAKA,EAAE,OACLA,EAAE,SAASA,EAAE,MAAM,CAACA,EAAE,SAAS,CAAEA,EAAE,QAAQ,CAAEA,EAAE,QAAQ,CAAC,CAAC,CAAC,CACzD,GACK,IAAU,IAAA,IAAa,OAAO,GAAU,UACnC,EAEF,EAAS,EAAM,CAEzB,CAKD,IAAKA,EAAE,OAAO,CAAE,SAAU,GAAM,CAAC,CAMjC,OAAQA,EAAE,QAAQ,CAAE,SAAU,GAAM,CAAC,CACtC,CACD,CACE,SAAU,GACV,QAAS,CACP,IAAK,EACL,IAAK,GACL,OAAQ,GACT,CACF,CACF"}
@@ -0,0 +1,293 @@
1
+ import { A as TimeField, B as Getter, C as VectorField, D as FloatField, E as IntField, F as MYSQL, H as RelationType, I as NativeType, L as PG, M as DateField, N as BooleanField, O as EnumField, P as BlobField, R as SQLITE, S as NumberField, T as JsonField, V as ReferentialAction, _ as Model, a as AnyRelation, b as Field, c as ManyToManyRelation, g as AnyModel, i as UniqueFields, j as DateTimeField, k as DecimalField, n as RelationFields, o as ToOneRelation, r as ScalarFields, s as ToManyRelation, t as FieldRecord, v as ModelState, w as StringField, x as BigIntField, y as UpdateState } from "./helper-cDCDjRAD.mjs";
2
+ import { At as EnumSchema, D as StringSchema, Ht as BlobSchema, Kt as BigIntSchema, Rt as BooleanSchema, U as IntegerSchema, W as NumberSchema, bt as IsoTimestampSchema, dt as JsonValue, ut as JsonSchema, vt as IsoDateSchema, x as VectorSchema, yt as IsoTimeSchema } from "./index-3sdVKfeG.mjs";
3
+
4
+ //#region src/schema/hydration.d.ts
5
+
6
+ /**
7
+ * Schema type - record of model names to Model instances
8
+ */
9
+ type Schema = Record<string, Model<any>>;
10
+ /**
11
+ * Hydrate name slots for all models, fields, and relations in a schema.
12
+ *
13
+ * This function populates the model's nameRegistry:
14
+ * - model["~"].names.ts = schema key (e.g., "User")
15
+ * - model["~"].names.sql = tableName ?? schema key (e.g., "users")
16
+ * - model["~"].nameRegistry.fields.get(fieldKey) = {ts, sql}
17
+ * - model["~"].nameRegistry.relations.get(relationKey) = {ts, sql}
18
+ *
19
+ * Note: Full schemas are built lazily when first accessed via model["~"].schemas.
20
+ * This allows circular references to work correctly - thunks are evaluated
21
+ * at validation time when all models' schemas are available.
22
+ *
23
+ * @param schema - The schema object mapping model names to Model instances
24
+ */
25
+ declare function hydrateSchemaNames(schema: Schema): void;
26
+ /**
27
+ * Check if a schema has been hydrated
28
+ */
29
+ declare function isSchemaHydrated(schema: Schema): boolean;
30
+ /**
31
+ * Get the SQL name for a model (throws if not hydrated)
32
+ */
33
+ declare function getModelSqlName(model: Model<any>): string;
34
+ /**
35
+ * Get the SQL name for a field.
36
+ * Delegates to model["~"].getFieldName().
37
+ */
38
+ declare function getFieldSqlName(model: Model<any>, fieldKey: string): string;
39
+ //#endregion
40
+ //#region src/schema/index.d.ts
41
+ /**
42
+ * Main schema builder object
43
+ * Use this to define models, fields, and relations
44
+ *
45
+ * Relations use a chainable API:
46
+ * - ToOne (oneToOne, manyToOne): .fields(), .references(), .optional(), .onDelete(), .onUpdate()
47
+ * - ToMany (oneToMany): minimal config - just .name() if needed
48
+ * - ManyToMany: .through(), .A(), .B(), .onDelete(), .onUpdate()
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * import { s } from "viborm";
53
+ *
54
+ * const user = s.model({
55
+ * id: s.string().id().ulid(),
56
+ * name: s.string(),
57
+ * email: s.string().unique(),
58
+ * posts: s.oneToMany(() => post),
59
+ * profile: s.oneToOne(() => profile).optional(),
60
+ * }).map("users");
61
+ *
62
+ * const post = s.model({
63
+ * id: s.string().id().ulid(),
64
+ * authorId: s.string(),
65
+ * author: s.manyToOne(() => user).fields("authorId").references("id"),
66
+ * }).map("posts");
67
+ * ```
68
+ */
69
+ declare const s: {
70
+ model: <TFields extends FieldRecord>(fields: TFields) => Model<UpdateState<ModelState, {
71
+ fields: TFields;
72
+ scalars: ScalarFields<TFields>;
73
+ relations: RelationFields<TFields>;
74
+ uniques: UniqueFields<TFields>;
75
+ omit: undefined;
76
+ }>>;
77
+ string: (nativeType?: NativeType) => StringField<{
78
+ type: "string";
79
+ nullable: boolean;
80
+ array: boolean;
81
+ hasDefault: boolean;
82
+ isId: boolean;
83
+ isUnique: boolean;
84
+ default: undefined;
85
+ autoGenerate: undefined;
86
+ schema: undefined;
87
+ columnName: undefined;
88
+ optional: boolean;
89
+ withTimezone: boolean;
90
+ base: StringSchema<string, string>;
91
+ }>;
92
+ boolean: (nativeType?: NativeType) => BooleanField<{
93
+ type: "boolean";
94
+ nullable: boolean;
95
+ array: boolean;
96
+ hasDefault: boolean;
97
+ isId: boolean;
98
+ isUnique: boolean;
99
+ default: undefined;
100
+ autoGenerate: undefined;
101
+ schema: undefined;
102
+ columnName: undefined;
103
+ optional: boolean;
104
+ withTimezone: boolean;
105
+ base: BooleanSchema<boolean, boolean>;
106
+ }>;
107
+ int: (nativeType?: NativeType) => IntField<{
108
+ type: "int";
109
+ nullable: boolean;
110
+ array: boolean;
111
+ hasDefault: boolean;
112
+ isId: boolean;
113
+ isUnique: boolean;
114
+ default: undefined;
115
+ autoGenerate: undefined;
116
+ schema: undefined;
117
+ columnName: undefined;
118
+ optional: boolean;
119
+ withTimezone: boolean;
120
+ base: IntegerSchema<number, number>;
121
+ }>;
122
+ float: (nativeType?: NativeType) => FloatField<{
123
+ type: "float";
124
+ nullable: boolean;
125
+ array: boolean;
126
+ hasDefault: boolean;
127
+ isId: boolean;
128
+ isUnique: boolean;
129
+ default: undefined;
130
+ autoGenerate: undefined;
131
+ schema: undefined;
132
+ columnName: undefined;
133
+ optional: boolean;
134
+ withTimezone: boolean;
135
+ base: NumberSchema<number, number>;
136
+ }>;
137
+ decimal: (nativeType?: NativeType) => DecimalField<{
138
+ type: "decimal";
139
+ nullable: boolean;
140
+ array: boolean;
141
+ hasDefault: boolean;
142
+ isId: boolean;
143
+ isUnique: boolean;
144
+ default: undefined;
145
+ autoGenerate: undefined;
146
+ schema: undefined;
147
+ columnName: undefined;
148
+ optional: boolean;
149
+ withTimezone: boolean;
150
+ base: NumberSchema<number, number>;
151
+ }>;
152
+ bigInt: (nativeType?: NativeType) => BigIntField<{
153
+ type: "bigint";
154
+ nullable: boolean;
155
+ array: boolean;
156
+ hasDefault: boolean;
157
+ isId: boolean;
158
+ isUnique: boolean;
159
+ default: undefined;
160
+ autoGenerate: undefined;
161
+ schema: undefined;
162
+ columnName: undefined;
163
+ optional: boolean;
164
+ withTimezone: boolean;
165
+ base: BigIntSchema<bigint, bigint>;
166
+ }>;
167
+ dateTime: (nativeType?: NativeType) => DateTimeField<{
168
+ withTimezone: true;
169
+ type: "datetime";
170
+ nullable: boolean;
171
+ array: boolean;
172
+ hasDefault: boolean;
173
+ isId: boolean;
174
+ isUnique: boolean;
175
+ default: undefined;
176
+ autoGenerate: undefined;
177
+ schema: undefined;
178
+ columnName: undefined;
179
+ optional: boolean;
180
+ base: IsoTimestampSchema<string | Date, string>;
181
+ }>;
182
+ date: (nativeType?: NativeType) => DateField<{
183
+ type: "date";
184
+ nullable: boolean;
185
+ array: boolean;
186
+ hasDefault: boolean;
187
+ isId: boolean;
188
+ isUnique: boolean;
189
+ default: undefined;
190
+ autoGenerate: undefined;
191
+ schema: undefined;
192
+ columnName: undefined;
193
+ optional: boolean;
194
+ withTimezone: boolean;
195
+ base: IsoDateSchema<string | Date, string>;
196
+ }>;
197
+ time: (nativeType?: NativeType) => TimeField<{
198
+ withTimezone: true;
199
+ type: "time";
200
+ nullable: boolean;
201
+ array: boolean;
202
+ hasDefault: boolean;
203
+ isId: boolean;
204
+ isUnique: boolean;
205
+ default: undefined;
206
+ autoGenerate: undefined;
207
+ schema: undefined;
208
+ columnName: undefined;
209
+ optional: boolean;
210
+ base: IsoTimeSchema<string | Date, string>;
211
+ }>;
212
+ json: (nativeType?: NativeType) => JsonField<{
213
+ type: "json";
214
+ nullable: boolean;
215
+ array: boolean;
216
+ hasDefault: boolean;
217
+ isId: boolean;
218
+ isUnique: boolean;
219
+ default: undefined;
220
+ autoGenerate: undefined;
221
+ schema: undefined;
222
+ columnName: undefined;
223
+ optional: boolean;
224
+ withTimezone: boolean;
225
+ base: JsonSchema<JsonValue, JsonValue>;
226
+ }>;
227
+ blob: (nativeType?: NativeType) => BlobField<{
228
+ type: "blob";
229
+ nullable: boolean;
230
+ array: boolean;
231
+ hasDefault: boolean;
232
+ isId: boolean;
233
+ isUnique: boolean;
234
+ default: undefined;
235
+ autoGenerate: undefined;
236
+ schema: undefined;
237
+ columnName: undefined;
238
+ optional: boolean;
239
+ withTimezone: boolean;
240
+ base: BlobSchema<Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>>;
241
+ }>;
242
+ enum: <const T extends string[]>(values: T, nativeType?: NativeType) => EnumField<{
243
+ type: "enum";
244
+ nullable: boolean;
245
+ array: boolean;
246
+ hasDefault: boolean;
247
+ isId: boolean;
248
+ isUnique: boolean;
249
+ default: undefined;
250
+ autoGenerate: undefined;
251
+ schema: undefined;
252
+ columnName: undefined;
253
+ optional: boolean;
254
+ withTimezone: boolean;
255
+ base: EnumSchema<T, T[number], T[number]>;
256
+ }>;
257
+ vector: (nativeType?: NativeType) => VectorField<{
258
+ type: "vector";
259
+ nullable: boolean;
260
+ array: boolean;
261
+ hasDefault: boolean;
262
+ isId: boolean;
263
+ isUnique: boolean;
264
+ default: undefined;
265
+ autoGenerate: undefined;
266
+ schema: undefined;
267
+ columnName: undefined;
268
+ optional: boolean;
269
+ withTimezone: boolean;
270
+ base: VectorSchema<number[], number[]> & {
271
+ dimensions?: number;
272
+ };
273
+ }>;
274
+ oneToOne: <G extends Getter>(getter: G) => ToOneRelation<{
275
+ type: "oneToOne";
276
+ getter: G;
277
+ }>;
278
+ manyToOne: <G extends Getter>(getter: G) => ToOneRelation<{
279
+ type: "manyToOne";
280
+ getter: G;
281
+ }>;
282
+ oneToMany: <G extends Getter>(getter: G) => ToManyRelation<{
283
+ type: "oneToMany";
284
+ getter: G;
285
+ }>;
286
+ manyToMany: <G extends Getter>(getter: G) => ManyToManyRelation<{
287
+ type: "manyToMany";
288
+ getter: G;
289
+ }>;
290
+ };
291
+ //#endregion
292
+ export { type AnyModel, type AnyRelation, type Field, type Getter, MYSQL, type Model, type ModelState, type NativeType, type NumberField, PG, type ReferentialAction, type RelationType, SQLITE, getFieldSqlName, getModelSqlName, hydrateSchemaNames, isSchemaHydrated, s };
293
+ //# sourceMappingURL=schema.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{n as e,r as t}from"./validation-RtU-wu4N.mjs";import{n}from"./schema-DeAJZocc.mjs";import{i as r,n as i,r as a,t as o}from"./hydration-CFnwc7j6.mjs";import{n as s,r as c,t as ee}from"./native-types-BwICkVjz.mjs";import{createId as l}from"@paralleldrive/cuid2";import{nanoid as u}from"nanoid";import{monotonicFactory as te}from"ulidx";const d=(e,t)=>({...e[`~`].state,...t}),f=(e,t)=>({type:e,nullable:!1,array:!1,hasDefault:!1,isId:!1,isUnique:!1,default:void 0,autoGenerate:void 0,schema:void 0,columnName:void 0,optional:!1,withTimezone:!1,base:t}),p=e=>t.coerce(e,e=>({equals:e})),m=e=>t.coerce(e,e=>({set:e})),h=e=>t.coerce(e,e=>[e]),g=t.bigint();t.bigint({nullable:!0});const _=t.bigint({array:!0});t.bigint({array:!0,nullable:!0});const ne=t.object({in:_,notIn:_,lt:g,lte:g,gt:g,gte:g}),re=e=>{let n=ne.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},ie=t.object({has:g,hasEvery:_,hasSome:_,isEmpty:t.boolean()}),ae=e=>{let n=ie.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},oe=e=>t.union([m(e),t.object({set:e,increment:g,decrement:g,multiply:g,divide:g})]),se=e=>t.union([m(e),t.object({set:e,push:t.union([h(g),_]),unshift:t.union([h(g),_])})]),ce=e=>({base:e.base,create:t.bigint(e),update:e.array?se(e.base):oe(e.base),filter:e.array?ae(e.base):re(e.base)});var le=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.bigint({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{...this.state,array:!0,base:t.bigint({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.bigint({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}increment(){return new e(d(this,{hasDefault:!0,autoGenerate:`increment`,default:0n,optional:!0}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=ce(this.state),nativeType:this._nativeType}}};const ue=e=>new le(f(`bigint`,g),e),de=t.blob();t.blob({nullable:!0});const fe=e=>{let n=t.object({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},pe=e=>t.union([m(e),t.object({set:e},{partial:!1})]),me=e=>({base:e.base,create:t.blob(e),update:pe(e.base),filter:fe(e.base)});var he=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.blob({nullable:!0})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}array(){throw Error(`Blob fields don't support array modifier`)}id(){throw Error(`Blob fields cannot be used as IDs`)}unique(){throw Error(`Blob fields cannot be unique`)}get"~"(){return{state:this.state,schemas:this._schemas??=me(this.state),nativeType:this._nativeType}}};const ge=e=>new he(f(`blob`,de),e),v=t.boolean();t.boolean({nullable:!0});const y=t.boolean({array:!0});t.boolean({array:!0,nullable:!0});const _e=e=>{let n=t.object({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},ve=t.object({has:v,hasEvery:y,hasSome:y,isEmpty:t.boolean()}),ye=e=>{let n=ve.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},be=e=>t.union([m(e),t.object({set:e},{partial:!1})]),xe=e=>t.union([m(e),t.object({set:e,push:t.union([h(v),y]),unshift:t.union([h(v),y])})]),Se=e=>({base:e.base,create:t.boolean(e),update:e.array?xe(e.base):be(e.base),filter:e.array?ye(e.base):_e(e.base)});var Ce=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.boolean({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.boolean({nullable:this.state.nullable,array:!0})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=Se(this.state),nativeType:this._nativeType}}};const we=e=>new Ce(f(`boolean`,v),e),b=t.isoTimestamp();t.isoTimestamp({nullable:!0});const x=t.isoTimestamp({array:!0});t.isoTimestamp({array:!0,nullable:!0});const S=t.isoDate();t.isoDate({nullable:!0});const C=t.isoDate({array:!0});t.isoDate({array:!0,nullable:!0});const w=t.isoTime();t.isoTime({nullable:!0});const T=t.isoTime({array:!0});t.isoTime({array:!0,nullable:!0});const Te=t.object({in:x,notIn:x,lt:b,lte:b,gt:b,gte:b}),Ee=e=>{let n=Te.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},De=t.object({has:b,hasEvery:x,hasSome:x,isEmpty:t.boolean()}),Oe=e=>{let n=De.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},ke=e=>t.union([m(e),t.object({set:e},{partial:!1})]),Ae=e=>t.union([m(e),t.object({set:e,push:t.union([h(b),x]),unshift:t.union([h(b),x])})]),je=e=>({base:e.base,create:t.isoTimestamp(e),update:e.array?Ae(e.base):ke(e.base),filter:e.array?Oe(e.base):Ee(e.base)}),Me=t.object({in:C,notIn:C,lt:S,lte:S,gt:S,gte:S}),Ne=e=>{let n=Me.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Pe=t.object({has:S,hasEvery:C,hasSome:C,isEmpty:t.boolean()}),Fe=e=>{let n=Pe.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Ie=e=>t.union([m(e),t.object({set:e},{partial:!1})]),Le=e=>t.union([m(e),t.object({set:e,push:t.union([h(S),C]),unshift:t.union([h(S),C])})]),Re=e=>({base:e.base,create:t.isoDate(e),update:e.array?Le(e.base):Ie(e.base),filter:e.array?Fe(e.base):Ne(e.base)}),ze=t.object({in:T,notIn:T,lt:w,lte:w,gt:w,gte:w}),Be=e=>{let n=ze.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Ve=t.object({has:w,hasEvery:T,hasSome:T,isEmpty:t.boolean()}),He=e=>{let n=Ve.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Ue=e=>t.union([m(e),t.object({set:e},{partial:!1})]),We=e=>t.union([m(e),t.object({set:e,push:t.union([h(w),T]),unshift:t.union([h(w),T])})]),Ge=e=>({base:e.base,create:t.isoTime(e),update:e.array?We(e.base):Ue(e.base),filter:e.array?He(e.base):Be(e.base)}),Ke=()=>new Date().toISOString().split(`T`)[0],qe=()=>new Date().toISOString().split(`T`)[0];var Je=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.isoDate({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.isoDate({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.isoDate({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}now(){return new e(d(this,{hasDefault:!0,autoGenerate:`now`,default:Ke,optional:!0}),this._nativeType)}updatedAt(){return new e(d(this,{hasDefault:!0,autoGenerate:`updatedAt`,default:qe,optional:!0}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=Re(this.state),nativeType:this._nativeType}}};const Ye=e=>new Je(f(`date`,S),e),Xe=()=>new Date().toISOString(),Ze=()=>new Date().toISOString();var Qe=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.isoTimestamp({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.isoTimestamp({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.isoTimestamp({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}now(){return new e(d(this,{hasDefault:!0,autoGenerate:`now`,default:Xe,optional:!0}),this._nativeType)}updatedAt(){return new e(d(this,{hasDefault:!0,autoGenerate:`updatedAt`,default:Ze,optional:!0}),this._nativeType)}withoutTimezone(){return new e(d(this,{withTimezone:!1}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=je(this.state),nativeType:this._nativeType}}};const $e=e=>new Qe({...f(`datetime`,b),withTimezone:!0},e),et=()=>new Date().toISOString().split(`T`)[1]?.split(`.`)[0]??``,tt=()=>new Date().toISOString().split(`T`)[1]?.split(`.`)[0]??``;var nt=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.isoTime({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.isoTime({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.isoTime({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}now(){return new e(d(this,{hasDefault:!0,autoGenerate:`now`,default:et,optional:!0}),this._nativeType)}updatedAt(){return new e(d(this,{hasDefault:!0,autoGenerate:`updatedAt`,default:tt,optional:!0}),this._nativeType)}withoutTimezone(){return new e(d(this,{withTimezone:!1}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=Ge(this.state),nativeType:this._nativeType}}};const rt=e=>new nt({...f(`time`,w),withTimezone:!0},e),E=t.number();t.number({nullable:!0});const D=t.number({array:!0});t.number({array:!0,nullable:!0});const it=t.object({in:D,notIn:D,lt:E,lte:E,gt:E,gte:E}),O=e=>{let n=it.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},at=t.object({has:E,hasEvery:D,hasSome:D,isEmpty:t.boolean()}),k=e=>{let n=at.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},ot=e=>t.union([m(e),t.object({set:e,increment:E,decrement:E,multiply:E,divide:E})]),st=e=>t.union([m(e),t.object({set:e,push:t.union([h(E),D]),unshift:t.union([h(E),D])})]),ct=e=>({base:e.base,create:t.number(e),update:e.array?st(e.base):ot(e.base),filter:e.array?k(e.base):O(e.base)}),lt=t.number();t.number({nullable:!0}),t.number({array:!0}),t.number({array:!0,nullable:!0});const ut=e=>({base:e.base,create:t.number(e),update:e.array?st(e.base):ot(e.base),filter:e.array?k(e.base):O(e.base)});var dt=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.number({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.number({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.number({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=ut(this.state),nativeType:this._nativeType}}};const ft=e=>new dt(f(`decimal`,lt),e),pt=e=>t.enum(e),A=e=>t.enum(e,{array:!0}),mt=(e,n)=>{let r=A(n),i=t.object({equals:e,in:r,notIn:r});return t.union([p(e),i.extend({not:t.union([p(e),i])})])},ht=(e,n)=>{let r=pt(n),i=A(n),a=t.object({has:r,hasEvery:i,hasSome:i,isEmpty:t.boolean()}).extend({equals:e});return t.union([p(e),a.extend({not:t.union([p(e),a])})])},gt=e=>t.union([m(e),t.object({set:e},{partial:!1})]),_t=(e,n)=>{let r=pt(n),i=A(n);return t.union([m(e),t.object({set:e,push:t.union([h(r),i]),unshift:t.union([h(r),i])})])},vt=(e,n)=>({base:n.base,create:t.enum(e,n),update:n.array?_t(n.base,e):gt(n.base),filter:n.array?ht(n.base,e):mt(n.base,e)});var yt=class e{constructor(e,t){this.state=e,this._nativeType=t}get enumValues(){return`values`in this.state.base?this.state.base.values:[]}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.enum(this.enumValues,{nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.enum(this.enumValues,{nullable:this.state.nullable,array:!0})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}name(t){return new e(d(this,{enumName:t}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=vt(this.enumValues,this.state),nativeType:this._nativeType}}};const bt=(e,n)=>new yt(f(`enum`,t.enum(e)),n);var xt=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.number({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.number({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.number({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=ct(this.state),nativeType:this._nativeType}}};const St=e=>new xt(f(`float`,E),e),j=t.integer();t.integer({nullable:!0});const M=t.integer({array:!0});t.integer({array:!0,nullable:!0});const Ct=t.object({in:M,notIn:M,lt:j,lte:j,gt:j,gte:j}),wt=e=>{let n=Ct.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Tt=t.object({has:j,hasEvery:M,hasSome:M,isEmpty:t.boolean()}),Et=e=>{let n=Tt.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Dt=e=>t.union([m(e),t.object({set:e,increment:j,decrement:j,multiply:j,divide:j})]),Ot=e=>t.union([m(e),t.object({set:e,push:t.union([h(j),M]),unshift:t.union([h(j),M])})]),kt=e=>({base:e.base,create:t.integer(e),update:e.array?Ot(e.base):Dt(e.base),filter:e.array?Et(e.base):wt(e.base)});var At=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.integer({nullable:!0,array:this.state.array})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.integer({nullable:this.state.nullable,array:!0})}),this._nativeType)}id(){return new e(d(this,{isId:!0,isUnique:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.integer({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}increment(){return new e(d(this,{hasDefault:!0,autoGenerate:`increment`,default:0,optional:!0}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=kt(this.state),nativeType:this._nativeType}}};const jt=e=>new At(f(`int`,j),e),Mt=t.json();t.json({nullable:!0});const Nt=e=>{let n=t.object({equals:e,path:t.array(t.string()),string_contains:t.string(),string_starts_with:t.string(),string_ends_with:t.string(),array_contains:e,array_starts_with:e,array_ends_with:e});return n.extend({not:n})},Pt=e=>t.coerce(e,e=>({set:e})),Ft=e=>({base:e.base,create:t.json(e),update:Pt(e.base),filter:Nt(e.base)});var It=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.json({nullable:!0,schema:this.state.schema})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.json({nullable:this.state.nullable,schema:n})}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=Ft(this.state),nativeType:this._nativeType}}};const Lt=e=>new It(f(`json`,Mt),e),Rt=te(),zt=e=>()=>e?`${e}-${crypto.randomUUID()}`:crypto.randomUUID(),Bt=e=>()=>e?`${e}-${Rt()}`:Rt(),Vt=(e,t)=>()=>t?`${t}-${u(e)}`:u(e),Ht=e=>()=>e?`${e}-${l()}`:l(),N=t.string();t.string({nullable:!0});const P=t.string({array:!0});t.string({array:!0,nullable:!0});const Ut=t.object({in:P,notIn:P,contains:N,startsWith:N,endsWith:N,mode:t.enum([`default`,`insensitive`])}),Wt=e=>{let n=Ut.extend({equals:e,lt:e,lte:e,gt:e,gte:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},Gt=t.object({has:N,hasEvery:P,hasSome:P,isEmpty:t.boolean()}),Kt=e=>{let n=Gt.extend({equals:e});return t.union([p(e),n.extend({not:t.union([p(e),n])})])},qt=e=>t.union([m(e),t.object({set:e},{partial:!1})]),Jt=e=>t.union([m(e),t.object({set:e,push:t.union([h(N),P]),unshift:t.union([h(N),P])})]),Yt=e=>({base:e.base,create:t.string(e),update:e.array?Jt(e.base):qt(e.base),filter:e.array?Kt(e.base):Wt(e.base)});var Xt=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.string({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return new e(d(this,{array:!0,base:t.string({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(t){return new e(d(this,{isId:!0,isUnique:!0,autoGenerate:`ulid`,default:Bt(t),optional:!0}),this._nativeType)}unique(){return new e(d(this,{isUnique:!0}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}schema(n){return new e(d(this,{schema:n,base:t.string({nullable:this.state.nullable,array:this.state.array,schema:n})}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}uuid(t){return new e(d(this,{hasDefault:!0,default:zt(t),autoGenerate:`uuid`,optional:!0}),this._nativeType)}ulid(t){return new e(d(this,{hasDefault:!0,default:Bt(t),autoGenerate:`ulid`,optional:!0}),this._nativeType)}nanoid(t,n){return new e(d(this,{hasDefault:!0,default:Vt(t,n),autoGenerate:`nanoid`,optional:!0}),this._nativeType)}cuid(t){return new e(d(this,{hasDefault:!0,default:Ht(t),autoGenerate:`cuid`,optional:!0}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=Yt(this.state),nativeType:this._nativeType}}};const Zt=e=>new Xt(f(`string`,N),e),Qt=t.vector();t.vector(void 0,{nullable:!0});const $t=e=>t.coerce(e,e=>({cosine:e})),en=e=>{let n=t.object({l2:e,cosine:e});return t.union([$t(e),n])},tn=e=>t.union([m(e),t.object({set:e},{partial:!1})]),nn=e=>({base:e.base,create:t.vector(void 0,e),update:tn(e.base),filter:en(e.base)});var rn=class e{constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new e(d(this,{nullable:!0,hasDefault:!0,default:null,optional:!0,base:t.vector(void 0,{nullable:!0})}),this._nativeType)}default(t){return new e(d(this,{hasDefault:!0,default:t,optional:!0}),this._nativeType)}map(t){return new e(d(this,{columnName:t}),this._nativeType)}dimension(t){return new e(d(this,{dimension:t}),this._nativeType)}get"~"(){return{state:this.state,schemas:this._schemas??=nn(this.state),nativeType:this._nativeType}}};const an=e=>new rn(f(`vector`,Qt),e);function F(e){if(!e||typeof e!=`object`)return!1;let t=e;if(!t[`~`]?.state?.type)return!1;let n=t[`~`].state.type;return n===`oneToOne`||n===`oneToMany`||n===`manyToOne`||n===`manyToMany`}const I=e=>Object.entries(e).reduce((e,[t,n])=>(F(n)||(e[t]=n),e),{}),L=e=>Object.entries(e).reduce((e,[t,n])=>(F(n)&&(e[t]=n),e),{}),R=e=>Object.entries(e).reduce((e,[t,n])=>(!F(n)&&(n[`~`].state.isUnique||n[`~`].state.isId)&&(e[t]=n),e),{}),z=(e,t)=>e??t.join(`_`),B=(e,t)=>{for(let[n,r]of Object.entries(e.scalars))t(n,r)},V=e=>{let n=[`_all`],r=[],i=[];B(e,(e,t)=>{let a=t[`~`].state.type;n.push(e),[`int`,`float`,`decimal`,`bigint`].includes(a)&&r.push(e),i.push(e)});let a=t.boolean({optional:!0});return{count:t.fromKeys(n,a),avg:t.fromKeys(r,a),sum:t.fromKeys(r,a),min:t.fromKeys(i,a),max:t.fromKeys(i,a)}},on=(e,n)=>{let r=V(e);return t.object({where:n.where,cursor:n.whereUnique,take:t.number(),skip:t.number(),select:r.count},{optional:!0})},sn=(e,n)=>{let r=V(e);return t.object({where:n.where,orderBy:t.union([n.orderBy,t.array(n.orderBy)]),cursor:n.whereUnique,take:t.number(),skip:t.number(),_count:t.union([t.literal(!0),r.count]),_avg:r.avg,_sum:r.sum,_min:r.min,_max:r.max})},H=t.object({equals:t.number(),gt:t.number(),gte:t.number(),lt:t.number(),lte:t.number(),not:t.number()},{optional:!0}),cn=t.object({_count:H,_avg:H,_sum:H,_min:H,_max:H},{optional:!0}),ln=e=>{let n={};return B(e,(e,r)=>{n[e]=t.union([cn,r[`~`].schemas.filter])}),t.object(n,{optional:!0})},un=(e,n)=>{let r=Object.keys(e.scalars),i=t.enum(r),a=V(e),o=ln(e);return t.object({by:t.union([i,t.array(i)]),where:n.where,having:o,orderBy:t.union([n.orderBy,t.array(n.orderBy)]),take:t.number(),skip:t.number(),_count:t.union([t.literal(!0),a.count]),_avg:a.avg,_sum:a.sum,_min:a.min,_max:a.max},{atLeast:[`by`]})},dn=e=>t.object({where:e.whereUnique,select:e.select,include:e.include},{atLeast:[`where`]}),fn=e=>t.object({where:e.where,orderBy:t.union([e.orderBy,t.array(e.orderBy)]),take:t.number(),skip:t.number(),cursor:e.whereUnique,select:e.select,include:e.include},{optional:!0}),pn=(e,n)=>{let r=Object.keys(e.scalars);return t.object({where:n.where,orderBy:t.union([n.orderBy,t.array(n.orderBy)]),take:t.number(),skip:t.number(),cursor:n.whereUnique,select:n.select,include:n.include,distinct:t.enum(r,{array:!0})},{optional:!0})},mn=e=>t.object({data:e.create,select:e.select,include:e.include,cache:n},{atLeast:[`data`]}),hn=e=>t.object({data:t.array(e.scalarCreate),skipDuplicates:t.boolean({optional:!0}),cache:n},{atLeast:[`data`]}),gn=e=>t.object({where:e.whereUnique,data:e.update,select:e.select,include:e.include,cache:n},{atLeast:[`where`,`data`]}),_n=e=>t.object({where:e.where,data:e.update,cache:n},{atLeast:[`data`]}),vn=e=>t.object({where:e.whereUnique,select:e.select,include:e.include,cache:n},{atLeast:[`where`]}),yn=e=>t.object({where:e.where,cache:n},{optional:!0}),bn=e=>t.object({where:e.whereUnique,create:e.create,update:e.update,select:e.select,include:e.include,cache:n,targetWhere:e.where,setWhere:e.where},{atLeast:[`where`,`create`,`update`]}),xn=e=>{let n=Object.keys(e.scalars).filter(t=>!e.fields[t][`~`].state.optional);return t.fromObject(e.scalars,`~.schemas.create`,{atLeast:n})},Sn=e=>t.fromObject(e.relations,`~.schemas.create`);function Cn(e){let t=new Set;for(let n of Object.values(e.relations)){let e=n[`~`]?.state;if(e&&(e.type===`manyToOne`||e.type===`oneToOne`)&&e.fields){let n=Array.isArray(e.fields)?e.fields:[e.fields];for(let e of n)t.add(e)}}return t}const wn=e=>{let n=Cn(e),r=Object.keys(e.scalars).filter(t=>{if(n.has(t))return!1;let r=e.scalars[t]?.[`~`]?.state;return!(r.hasDefault||r.optional)}),i=t.fromObject(e.scalars,`~.schemas.create`),a=t.fromObject(e.relations,`~.schemas.create`);return t.object({...i.entries,...a.entries},{atLeast:r})},Tn=e=>t.fromObject(e.scalars,`~.schemas.filter`),En=e=>t.fromObject(e.uniques,`~.schemas.base`),Dn=e=>t.fromObject(e.relations,`~.schemas.filter`),U=e=>e.compoundUniques||e.compoundId?e.compoundUniques?e.compoundId?t.object(e.compoundUniques).extend(e.compoundId):t.object(e.compoundUniques):t.object(e.compoundId):t.object({}),On=e=>e.compoundId?t.object(e.compoundId):t.object({}),W=t.enum([`asc`,`desc`]),kn=t.union([W,t.object({sort:W,nulls:t.enum([`first`,`last`],{optional:!0})},{partial:!1})]),An=e=>{let n=Object.keys(e.scalars),r=t.fromKeys(n,kn),i=t.fromObject(e.relations,`~.schemas.orderBy`);return t.object({...r.entries,...i.entries})},jn=e=>{let n=Object.keys(e.scalars),r=t.boolean({optional:!0}),i=t.fromKeys(n,r),a=t.fromObject(e.relations,`~.schemas.select`),o=t.fromObject(e.relations,`~.schemas.countFilter`,{optional:!0});return t.object({...i.entries,...a.entries,_count:t.object({select:o},{optional:!0})})},Mn=e=>t.fromObject(e.relations,`~.schemas.include`,{optional:!0}),Nn=e=>t.fromObject(e.scalars,`~.schemas.update`),Pn=e=>t.fromObject(e.relations,`~.schemas.update`),Fn=e=>{let n=t.fromObject(e.scalars,`~.schemas.update`),r=t.fromObject(e.relations,`~.schemas.update`);return n.extend(r.entries)},In=e=>{let n=t.fromObject(e.scalars,`~.schemas.filter`),r=t.fromObject(e.relations,`~.schemas.filter`),i=t.object({AND:()=>t.optional(t.union([i,t.array(i)])),OR:()=>t.optional(t.array(i)),NOT:()=>t.optional(t.union([i,t.array(i)]))}).extend(n.entries).extend(r.entries);return i},Ln=e=>{let n=t.fromObject(e.uniques,`~.schemas.base`),r=U(e);return t.object({...n.entries,...r.entries})};var Rn=class{constructor(e,t){this.schemas=e,this.state=t}get findUnique(){return this._findUnique??=dn(this.schemas)}get findFirst(){return this._findFirst??=fn(this.schemas)}get findMany(){return this._findMany??=pn(this.state,this.schemas)}get create(){return this._create??=mn(this.schemas)}get createMany(){return this._createMany??=hn(this.schemas)}get update(){return this._update??=gn(this.schemas)}get updateMany(){return this._updateMany??=_n(this.schemas)}get delete(){return this._delete??=vn(this.schemas)}get deleteMany(){return this._deleteMany??=yn(this.schemas)}get upsert(){return this._upsert??=bn(this.schemas)}get count(){return this._count??=on(this.state,this.schemas)}get aggregate(){return this._aggregate??=sn(this.state,this.schemas)}get groupBy(){return this._groupBy??=un(this.state,this.schemas)}},zn=class{constructor(e){this.state=e}get scalarFilter(){return this._scalarFilter??=Tn(this.state)}get uniqueFilter(){return this._uniqueFilter??=En(this.state)}get relationFilter(){return this._relationFilter??=Dn(this.state)}get compoundIdFilter(){return this._compoundIdFilter??=On(this.state)}get compoundConstraintFilter(){return this._compoundConstraintFilter??=U(this.state)}get scalarCreate(){return this._scalarCreate??=xn(this.state)}get relationCreate(){return this._relationCreate??=Sn(this.state)}get scalarUpdate(){return this._scalarUpdate??=Nn(this.state)}get relationUpdate(){return this._relationUpdate??=Pn(this.state)}get where(){return this._where??=In(this.state)}get whereUnique(){return this._whereUnique??=Ln(this.state)}get create(){return this._create??=wn(this.state)}get update(){return this._update??=Fn(this.state)}get select(){return this._select??=jn(this.state)}get include(){return this._include??=Mn(this.state)}get orderBy(){return this._orderBy??=An(this.state)}get args(){return this._args??=new Rn(this,this.state)}};const Bn=(e,t)=>[...e.indexes,t];var Vn=class e{constructor(e){this._names={},this._nameRegistry={fields:new Map,relations:new Map},this.state=e}map(t){return new e({...this.state,tableName:t})}omit(t){return new e({...this.state,omit:t})}index(t,n={}){return new e({...this.state,indexes:Bn(this.state,{fields:t,options:n})})}id(n,r){let i=z(r?.name,n),a=n.reduce((e,t)=>{let n=t in this.state.scalars?this.state.scalars[t]:void 0;return n&&(e[t]=n[`~`].schemas.base),e},{}),o={[i]:t.object(a,{partial:!1})};return new e({...this.state,compoundId:o})}unique(n,r){let i=z(r?.name,n),a=n.reduce((e,t)=>{let n=t in this.state.scalars?this.state.scalars[t]:void 0;return n&&(e[t]=n[`~`].schemas.base),e},{}),o={[i]:t.object(a,{partial:!1})};return new e({...this.state,compoundUniques:o})}extends(t){let n={...this.state.fields,...t};return new e({...this.state,fields:n,scalars:I(n),relations:L(n),uniques:R(n)})}get"~"(){let e=this;return{state:this.state,get schemas(){return e._schemas??=new zn(e.state)},names:this._names,nameRegistry:this._nameRegistry,getFieldName:t=>{let n=e._nameRegistry.fields.get(t);if(n)return n;throw Error(`Field "${t}" not found in nameRegistry`)},getRelationName:t=>{let n=e._nameRegistry.relations.get(t);if(n)return n;throw Error(`Relation "${t}" not found in nameRegistry`)},get scalarFieldNames(){return e._scalarFieldNames??=Object.keys(e.state.scalars)},get scalarFieldSet(){return e._scalarFieldSet??=new Set(this.scalarFieldNames)},get relationNames(){return e._relationNames??=Object.keys(e.state.relations)},get relationSet(){return e._relationSet??=new Set(this.relationNames)}}}};const Hn=e=>new Vn({compoundId:void 0,compoundUniques:void 0,tableName:void 0,indexes:[],omit:void 0,fields:e,scalars:I(e),relations:L(e),uniques:R(e)}),G=(e,t)=>()=>e.getter()[`~`].schemas[t],K=e=>G(e,`where`),q=e=>G(e,`whereUnique`),J=e=>G(e,`create`),Un=e=>G(e,`scalarCreate`),Wn=e=>G(e,`update`),Y=e=>G(e,`select`),Gn=e=>G(e,`include`),X=e=>G(e,`orderBy`),Z=e=>t.union([t.coerce(e,e=>[e]),t.array(e)]),Kn=e=>t.union([t.literal(!0),t.object({where:K(e)})]),qn=t=>e.object({create:J(t),connect:q(t),connectOrCreate:e.object({where:q(t),create:J(t)})},{optional:!0}),Jn=t=>e.object({create:()=>Z(J(t)()),createMany:e.object({data:()=>e.array(Un(t)()),skipDuplicates:e.boolean({optional:!0})}),connect:()=>Z(q(t)()),connectOrCreate:()=>Z(e.object({where:q(t),create:J(t)},{partial:!1}))},{optional:!0}),Yn=t=>e.object({is:()=>e.maybeNullable(K(t)(),t.optional),isNot:()=>e.maybeNullable(K(t)(),t.optional)}),Xn=t=>e.object({some:K(t),every:K(t),none:K(t)}),Zn=e=>X(e),Qn=e=>t.object({_count:t.enum([`asc`,`desc`])}),$n=e=>{let t=e.getter()[`~`].state,n={},r=new Set(Object.keys(t.omit||{}));for(let e of Object.keys(t.scalars))r.has(e)||(n[e]=!0);return n},er=e=>t=>`select`in t&&t.select!==!1?t:{...t,select:$n(e)},Q=e=>t.coerce(t.boolean(),t=>t?{select:$n(e)}:{select:!1}),tr=e=>t.union([Q(e),t.object({select:Y(e)})]),nr=e=>t.union([Q(e),t.object({where:K(e),orderBy:X(e),take:t.number(),skip:t.number(),cursor:t.string(),select:Y(e)})]),rr=e=>t.union([Q(e),t.coerce(t.object({select:Y(e),include:Gn(e)}),er(e))]),ir=e=>t.union([Q(e),t.coerce(t.object({where:K(e),orderBy:X(e),take:t.number(),skip:t.number(),cursor:t.string(),select:Y(e),include:Gn(e)}),er(e))]),ar=e=>{let n=J(e),r=Wn(e),i=q(e),a=t.object({where:i,create:n}),o=t.object({create:n,connect:i,connectOrCreate:a,update:r,upsert:t.object({create:n,update:r})}),s=o.extend({disconnect:t.boolean(),delete:t.boolean()});return e.optional?s:o},or=e=>{let n=J(e),r=Wn(e),i=K(e),a=q(e),o=t.object({where:a,data:r}),s=t.object({where:i,data:r}),c=t.object({where:a,create:n,update:r}),ee=t.object({where:a,create:n});return t.object({create:()=>Z(n()),connect:()=>Z(a()),disconnect:()=>t.union([t.boolean(),Z(a())]),delete:()=>Z(a()),connectOrCreate:Z(ee),set:()=>Z(a()),update:Z(o),updateMany:Z(s),deleteMany:()=>Z(i()),upsert:Z(c)})},sr=e=>({filter:Yn(e),create:qn(e),update:ar(e),select:tr(e),include:rr(e),orderBy:Zn(e),countFilter:Kn(e)}),cr=e=>({filter:Xn(e),create:Jn(e),update:or(e),select:nr(e),include:ir(e),orderBy:Qn(e),countFilter:Kn(e)}),$=e=>e.type===`manyToMany`||e.type===`oneToMany`?cr(e):sr(e);var lr=class e{constructor(e){this._state=e}through(t){return new e({...this._state,through:t})}A(t){return new e({...this._state,A:t})}B(t){return new e({...this._state,B:t})}onDelete(t){return new e({...this._state,onDelete:t})}onUpdate(t){return new e({...this._state,onUpdate:t})}name(t){return new e({...this._state,name:t})}get"~"(){return{state:this._state,schemas:this._schemas??=$(this._state)}}};const ur=e=>new lr({type:`manyToMany`,getter:e});var dr=class e{constructor(e){this._state=e}name(t){return new e({...this._state,name:t})}get"~"(){return{state:this._state,schemas:this._schemas??=$(this._state)}}};const fr=e=>new dr({type:`oneToMany`,getter:e});var pr=class e{constructor(e){this._state=e}fields(...t){return new e({...this._state,fields:t})}references(...t){return new e({...this._state,references:t})}optional(){return new e({...this._state,optional:!0})}onDelete(t){return new e({...this._state,onDelete:t})}onUpdate(t){return new e({...this._state,onUpdate:t})}name(t){return new e({...this._state,name:t})}get"~"(){return{state:this._state,schemas:this._schemas??=$(this._state)}}};const mr={model:Hn,string:Zt,boolean:we,int:jt,float:St,decimal:ft,bigInt:ue,dateTime:$e,date:Ye,time:rt,json:Lt,blob:ge,enum:bt,vector:an,oneToOne:e=>new pr({type:`oneToOne`,getter:e}),manyToOne:e=>new pr({type:`manyToOne`,getter:e}),oneToMany:fr,manyToMany:ur};export{ee as MYSQL,s as PG,c as SQLITE,o as getFieldSqlName,i as getModelSqlName,a as hydrateSchemaNames,r as isSchemaHydrated,mr as s};
2
+ //# sourceMappingURL=schema.mjs.map