viborm 1.7.0 → 1.8.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.
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{batch-refs-DWMYN0fw.mjs → batch-refs-ZHBzfoBC.mjs} +2 -2
- package/dist/{batch-refs-DWMYN0fw.mjs.map → batch-refs-ZHBzfoBC.mjs.map} +1 -1
- package/dist/{builder-B4n-7I7Q.mjs → builder-Ct1qPFc8.mjs} +2 -2
- package/dist/{builder-B4n-7I7Q.mjs.map → builder-Ct1qPFc8.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{chain-DVuRxjPO.mjs → chain--uZ0O7_Y.mjs} +2 -2
- package/dist/{chain-DVuRxjPO.mjs.map → chain--uZ0O7_Y.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/client-BAxU6jnw.mjs +2 -0
- package/dist/client-BAxU6jnw.mjs.map +1 -0
- package/dist/{client-7ApJka0M.d.mts → client-DP6gM_tf.d.mts} +2 -2
- package/dist/{client-l7dSOul5.mjs → client-mQcOvDdK.mjs} +3 -3
- package/dist/client-mQcOvDdK.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{driver-DaBNytbz.mjs → driver-NtekjA3W.mjs} +2 -2
- package/dist/{driver-DaBNytbz.mjs.map → driver-NtekjA3W.mjs.map} +1 -1
- package/dist/{driver-CK_IKqDa.mjs → driver-XlmOJFRH.mjs} +2 -2
- package/dist/{driver-CK_IKqDa.mjs.map → driver-XlmOJFRH.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/every-Xql4tHDz.mjs +2 -0
- package/dist/{every-6VrIclsx.mjs.map → every-Xql4tHDz.mjs.map} +1 -1
- package/dist/{hydration-BUBkHlCK.mjs → hydration-BNEFeV5v.mjs} +2 -2
- package/dist/{hydration-BUBkHlCK.mjs.map → hydration-BNEFeV5v.mjs.map} +1 -1
- package/dist/{identifier-conversion-BXrBYgAq.mjs → identifier-conversion-C_XCo9es.mjs} +2 -2
- package/dist/{identifier-conversion-BXrBYgAq.mjs.map → identifier-conversion-C_XCo9es.mjs.map} +1 -1
- package/dist/{index-CsO6vG2h.d.mts → index-DBhpNR0X.d.mts} +70 -8
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{key-Cz83fdLO.mjs → key-QgLg2Kve.mjs} +2 -2
- package/dist/{key-Cz83fdLO.mjs.map → key-QgLg2Kve.mjs.map} +1 -1
- package/dist/{keys-EP1Eq2eD.mjs → keys-D5hv9EaJ.mjs} +2 -2
- package/dist/{keys-EP1Eq2eD.mjs.map → keys-D5hv9EaJ.mjs.map} +1 -1
- package/dist/{libsql-ClGi2zY2.mjs → libsql-BsJdPDES.mjs} +2 -2
- package/dist/{libsql-ClGi2zY2.mjs.map → libsql-BsJdPDES.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-B1GnzgZr.mjs → memory-BEaJ0-FU.mjs} +2 -2
- package/dist/{memory-B1GnzgZr.mjs.map → memory-BEaJ0-FU.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{model-DsXZ_pHE.mjs → model-D94xU8jq.mjs} +2 -2
- package/dist/{model-DsXZ_pHE.mjs.map → model-D94xU8jq.mjs.map} +1 -1
- package/dist/{mysql-hoo290Dd.mjs → mysql-DT_dTWDi.mjs} +2 -2
- package/dist/{mysql-hoo290Dd.mjs.map → mysql-DT_dTWDi.mjs.map} +1 -1
- package/dist/{mysql-adapter-D-Dq2FN9.mjs → mysql-adapter-BUwzKlbt.mjs} +2 -2
- package/dist/{mysql-adapter-D-Dq2FN9.mjs.map → mysql-adapter-BUwzKlbt.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{normalized-result-23DWxZVY.mjs → normalized-result-ByvlIQqa.mjs} +2 -2
- package/dist/{normalized-result-23DWxZVY.mjs.map → normalized-result-ByvlIQqa.mjs.map} +1 -1
- package/dist/{object-store-9VfS-3sY.d.mts → object-store-35LjwOS-.d.mts} +3 -3
- package/dist/on.d.mts +1 -1
- package/dist/ordering.d.mts +41 -19
- package/dist/ordering.mjs +8 -8
- package/dist/ordering.mjs.map +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-Cc3ABIUU.d.mts → planner-CmDw5jPb.d.mts} +1 -1
- package/dist/{postgres-CqcP_qv-.mjs → postgres-Do0nq95P.mjs} +2 -2
- package/dist/{postgres-CqcP_qv-.mjs.map → postgres-Do0nq95P.mjs.map} +1 -1
- package/dist/{postgres-adapter-_o6EWuxW.mjs → postgres-adapter-DFzjbAP7.mjs} +2 -2
- package/dist/{postgres-adapter-_o6EWuxW.mjs.map → postgres-adapter-DFzjbAP7.mjs.map} +1 -1
- package/dist/{postgres-adapter-CYZAL2uo.mjs → postgres-adapter-Dvt16rbl.mjs} +2 -2
- package/dist/{postgres-adapter-CYZAL2uo.mjs.map → postgres-adapter-Dvt16rbl.mjs.map} +1 -1
- package/dist/{postgres-result-D94PyZ78.mjs → postgres-result-ehQiy2H-.mjs} +2 -2
- package/dist/{postgres-result-D94PyZ78.mjs.map → postgres-result-ehQiy2H-.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/{result-shape-uaCsF_SZ.mjs → result-shape-DwoSyWnq.mjs} +2 -2
- package/dist/{result-shape-uaCsF_SZ.mjs.map → result-shape-DwoSyWnq.mjs.map} +1 -1
- package/dist/{rows-AtX0guAb.mjs → rows-ig1gjVRb.mjs} +2 -2
- package/dist/{rows-AtX0guAb.mjs.map → rows-ig1gjVRb.mjs.map} +1 -1
- package/dist/rows-of-Djavcb19.mjs +2 -0
- package/dist/rows-of-Djavcb19.mjs.map +1 -0
- package/dist/{scalar-CZ_q89Hc.mjs → scalar-BgxfbRLw.mjs} +2 -2
- package/dist/{scalar-CZ_q89Hc.mjs.map → scalar-BgxfbRLw.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-CT57uls5.mjs +2 -0
- package/dist/{schema-CZTCxG2p.mjs.map → schema-CT57uls5.mjs.map} +1 -1
- package/dist/{schema-introspection-DoZHc1o7.mjs → schema-introspection-BFDAX5Ol.mjs} +2 -2
- package/dist/{schema-introspection-DoZHc1o7.mjs.map → schema-introspection-BFDAX5Ol.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BtNtBsUh.mjs → select-assembly-Dcaqm09G.mjs} +2 -2
- package/dist/{select-assembly-BtNtBsUh.mjs.map → select-assembly-Dcaqm09G.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +116 -14
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-BsBoKwaf.mjs +2 -0
- package/dist/sql-BsBoKwaf.mjs.map +1 -0
- package/dist/{sql-BnXk8adi.d.mts → sql-D7JnXgUh.d.mts} +5 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-CnAwmszh.mjs → sqlite-adapter-eGsbASDR.mjs} +2 -2
- package/dist/{sqlite-adapter-CnAwmszh.mjs.map → sqlite-adapter-eGsbASDR.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-Ci8ROrql.mjs → standard-sql-BtzSzrof.mjs} +2 -2
- package/dist/standard-sql-BtzSzrof.mjs.map +1 -0
- package/dist/{to-many-BtLpp5cW.mjs → to-many-CJ-8_caR.mjs} +2 -2
- package/dist/{to-many-BtLpp5cW.mjs.map → to-many-CJ-8_caR.mjs.map} +1 -1
- package/dist/{utils-CAACs9Jw.mjs → utils-DYz-Xm59.mjs} +2 -2
- package/dist/{utils-CAACs9Jw.mjs.map → utils-DYz-Xm59.mjs.map} +1 -1
- package/dist/{v-Pb_jJOjC.mjs → v-C2XN11Gy.mjs} +2 -2
- package/dist/{v-Pb_jJOjC.mjs.map → v-C2XN11Gy.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-Dthaj1Hz.mjs → validator-DqI5RlVU.mjs} +2 -2
- package/dist/{validator-Dthaj1Hz.mjs.map → validator-DqI5RlVU.mjs.map} +1 -1
- package/dist/version-DyH_HopX.mjs +2 -0
- package/dist/{version-DvynkoaW.mjs.map → version-DyH_HopX.mjs.map} +1 -1
- package/package.json +21 -21
- package/dist/client-Yqn0LqmI.mjs +0 -2
- package/dist/client-Yqn0LqmI.mjs.map +0 -1
- package/dist/client-l7dSOul5.mjs.map +0 -1
- package/dist/every-6VrIclsx.mjs +0 -2
- package/dist/insert-value-Cbp_bNxj.mjs +0 -2
- package/dist/insert-value-Cbp_bNxj.mjs.map +0 -1
- package/dist/schema-CZTCxG2p.mjs +0 -2
- package/dist/sql-DGtEeP8z.mjs +0 -2
- package/dist/sql-DGtEeP8z.mjs.map +0 -1
- package/dist/standard-sql-Ci8ROrql.mjs.map +0 -1
- package/dist/version-DvynkoaW.mjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./sql-BsBoKwaf.mjs";var InsertValue=class{},JoinedValue=class extends InsertValue{};const n=new WeakMap;var r=class RowsOf extends t{model;alias;judgement;where;constructor(e,t,n,r){super([`(viborm: rows of a model rendered outside a query)`],[]),this.model=e,this.alias=t,this.judgement=n,this.where=r}settle(e){RowsOf.fill(this,e)}};export{n as i,InsertValue as n,JoinedValue as r,r as t};
|
|
2
|
+
//# sourceMappingURL=rows-of-Djavcb19.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rows-of-Djavcb19.mjs","names":[],"sources":["../src/query-engine/raptor3/shared/insert-value.ts","../src/query-engine/raptor3/shared/rows-of.ts"],"sourcesContent":["import type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport type { Queries } from \"./query\";\nimport type { Input } from \"./schema\";\n\n/** What an {@link InsertValue} is given to compute its values with. */\nexport interface InsertValueContext {\n readonly model: AnyModel;\n /** The INSERT's rows, every value final but the computed ones. */\n readonly rows: readonly Input[];\n /** The field the value is written to. */\n readonly field: string;\n readonly queries: Queries;\n readonly dialect: \"postgresql\" | \"mysql\" | \"sqlite\";\n /**\n * Run one read in the operation (its transaction, if any) and return its\n * raw rows; absent where the operation cannot read before writing (an\n * array transaction's batch), so the value must be an SQL expression.\n */\n readonly read?: (statement: Sql) => Promise<readonly Input[]>;\n}\n\n/**\n * A create value its extension computes once the rows of one INSERT are\n * final, after every incoming foreign key is assigned: a stamp of the `data`\n * capability that is an instance of this class is written where the caller\n * left the field out, not admitted as data. `compute` answers one value per\n * row it is asked about (the indexes of `rows` whose field holds this\n * instance), each a plain value or an SQL expression the INSERT evaluates.\n * An `update`'s data may hold one too (an official extension's call, never a\n * caller's payload): set aside from admission, its expression is the SET's.\n * The official ordering extension's appended and moved keys are the ones.\n */\nexport abstract class InsertValue {\n abstract compute(\n context: InsertValueContext,\n indexes: readonly number[]\n ): readonly unknown[] | Promise<readonly unknown[]>;\n}\n\n/**\n * An `updateMany` value read from a derived table the UPDATE joins (an\n * official extension's call, never a caller's payload): `join` answers that\n * table, aliased, and the condition matching it to the row written, over the\n * target's columns qualified by `target`; `compute` answers the SET\n * expression over the table's columns. The engine joins it (`UPDATE … FROM`,\n * MySQL's `UPDATE … JOIN`), so one statement writes each row its own value\n * and the source is read once, before any row changes. Respacing's keys.\n */\nexport abstract class JoinedValue extends InsertValue {\n abstract join(\n queries: Queries,\n target: string\n ): { readonly source: Sql; readonly on: Sql };\n}\n\n/**\n * Each engine's renderer, by its schema then its driver's adapter: an\n * official extension that writes a statement of its own (ordering's\n * respacing) names tables and columns and binds values as the engine's\n * queries do, without importing the engine into its entry.\n */\nexport const renderers = new WeakMap<object, WeakMap<object, Queries>>();\n","import type { AnyModel } from \"@schema/model\";\nimport { Sql } from \"../../../sql/sql\";\nimport type { RowJudgement } from \"./row-scope\";\n\n/**\n * The rows of `model` the operation rendering it may see, under `alias`: a\n * condition an extension that writes its own SQL (ordering's subqueries)\n * puts beside a read of `model AS alias`, so that read takes the call's row\n * domain as every read of the engine does. The operation's `Queries`\n * settles it when it lowers the caller's fragment holding it (the call's\n * root domain at that alias, or `1 = 1`); rendered anywhere else, its text\n * is not SQL, so it cannot read past the domain unnoticed. With `judgement`,\n * the rows the call may write so (an update of those fields); with `where`,\n * of those the ones it matches, admitted as a `findMany`'s.\n */\nexport class RowsOf extends Sql {\n readonly model: AnyModel;\n readonly alias: string;\n readonly judgement: RowJudgement | undefined;\n readonly where: unknown;\n constructor(\n model: AnyModel,\n alias: string,\n judgement?: RowJudgement,\n where?: unknown\n ) {\n super([\"(viborm: rows of a model rendered outside a query)\"], []);\n this.model = model;\n this.alias = alias;\n this.judgement = judgement;\n this.where = where;\n }\n settle(condition: Sql): void {\n RowsOf.fill(this, condition);\n }\n}\n"],"mappings":"2EAiCA,IAAsB,YAAtB,KAAkC,GAgBZ,YAAtB,cAA0C,WAAY,GAatD,MAAa,EAAY,IAAI,QC/C7B,IAAa,EAAb,MAAa,eAAe,CAAI,CAC9B,MACA,MACA,UACA,MACA,YACE,EACA,EACA,EACA,EACA,CACA,MAAM,CAAC,qDAAqD,CAAE,EAAE,CAAC,CACjE,KAAK,MAAQ,EACb,KAAK,MAAQ,EACb,KAAK,UAAY,EACjB,KAAK,MAAQ,EAEf,OAAO,EAAsB,CAC3B,OAAO,KAAK,KAAM,EAAU"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{n,t as r}from"./base-wlv81COV.mjs";import{t as i}from"./validation-pfpKPPZ_.mjs";import{n as a}from"./v-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{n,t as r}from"./base-wlv81COV.mjs";import{t as i}from"./validation-pfpKPPZ_.mjs";import{n as a}from"./v-C2XN11Gy.mjs";import{Ct as o,St as s,Tt as c,_t as l,bt as u,ct as d,dt as f,ft as p,gt as m,ht as h,lt as g,mt as _,pt as v,ut as y,vt as b,wt as x,xt as S,yt as C}from"./geo-point-codec-CIZxuIvE.mjs";import{a as w,i as T,n as E,r as D,t as O}from"./native-types-CQH05hcr.mjs";function preflightModelRegistrationIdentity(e){let t=new Map;for(let[n,r]of e){if(typeof r!=`object`||!r||!r[`~`]?.names||!r[`~`]?.state?.scalars)return{code:`M008`,message:`Schema entry '${n}' is not a model; pass an explicit object containing only s.model() definitions`,severity:`error`,model:n};let e=r[`~`].names.ts??t.get(r);if(e!==void 0&&e!==n)return doubleRegistrationIssue(e,n);t.set(r,n)}}function doubleRegistrationIssue(e,t){return{code:`M003`,message:`Model registered as '${e}' cannot also be registered as '${t}'; one model object binds one schema key`,severity:`error`,model:t}}var SchemaValidationError=class extends r{static diagnosticName=`SchemaValidationError`;issues;constructor(e,t){let r=Object.freeze(e.map(e=>Object.freeze(e.candidates?{...e,candidates:Object.freeze([...e.candidates])}:{...e}))),i=r.map(e=>[`[${e.code}] ${e.message}`,e.candidates?.length?`Candidates: ${e.candidates.join(`, `)}`:``,e.repair??``].filter(Boolean).join(`
|
|
2
2
|
`));super(`Schema validation failed:\n${i.join(`
|
|
3
3
|
`)}`,n.INVALID_INPUT,t?.cause?{cause:t.cause}:void 0),this.issues=r}toJSON(){return{...super.toJSON(),issues:this.issues}}};function isSchemaValidationError(e){return e instanceof SchemaValidationError}function thrownAsError(e){return e instanceof Error?e:Error(String(e))}const k=new WeakSet;function generatorDefault(e){return k.add(e),e}function refuseListGenerator(e){throw new i({kind:`schema-builder`,builder:e,path:`array`},[{path:`array`,message:`Scalar generation is not supported on lists; declare an explicit array default`}])}function nullableDefault(e){return e.hasDefault?e.default:null}function isGeneratorDefault(e){return typeof e==`function`&&k.has(e)}const updateState=(e,t)=>({...e[`~`].state,...t}),createDefaultState=(e,t)=>({type:e,nullable:!1,array:!1,hasDefault:!1,isId:!1,isUnique:!1,default:void 0,autoGenerate:void 0,disallowZero:!1,schema:void 0,columnName:void 0,optional:!1,withTimezone:!1,base:t}),A=[[],[1],[1,2]],j=/^\d+$/,M=/^[A-Za-z_][A-Za-z0-9_]*(\(\d+(,\d+)*\))?$/,N={pg:`PG`,mysql:`MYSQL`,sqlite:`SQLITE`};let P;function isNativeTypeInCatalog(e,t){P??=buildCatalogs();let n=P[e];if(n.exact.has(t))return!0;if(!M.test(t))return!1;let r=t.indexOf(`(`);if(r===-1)return n.templates.get(t)?.has(0)===!0;let i=t.slice(0,r),a=t.slice(r+1,-1).split(`,`).length;return n.templates.get(i)?.has(a)===!0}function nativeTypeRefusal(e){return`A \`native.type\` is written into DDL verbatim, so a document may carry only a native type from the '${e}' dialect's closed catalog — the values the ${N[e]} native-type constants produce. See the native types documentation (docs/schema/native-types).`}function refuse(e,t,n){throw new i({kind:`schema-builder`,builder:e,path:t},[{path:t,message:n}])}function admitNativeType(e,t){return t===void 0?void 0:admitDeclaredNativeType(e,t)}function admitDeclaredNativeType(e,n){if(t(n)||refuse(e,`nativeType`,"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)"),w(n)){let{db:t,type:r}=n;(!E.includes(t)||typeof r!=`string`)&&refuse(e,`nativeType`,`A tagged native type is \`{ db, type }\`: \`db\` one of ${E.join(`, `)} and \`type\` a string`);let i=E.find(e=>Object.hasOwn(n,e));return i!==void 0&&refuse(e,`nativeType.${i}`,`A tagged native type ('db: ${t}') cannot also carry a '${i}' entry: declare one tagged type, or a map by dialect (\`{ pg, mysql, sqlite }\`)`),n}return admitNativeTypeMap(e,n)}function admitNativeTypeMap(e,t){for(let n of Object.keys(t))E.some(e=>e===n)||refuse(e,`nativeType.${n}`,`'${n}' is not a dialect: a native-type map names only ${E.join(`, `)}`);let n={};return Object.hasOwn(t,`pg`)&&(n.pg=admitEntry(e,`pg`,t.pg)),Object.hasOwn(t,`mysql`)&&(n.mysql=admitEntry(e,`mysql`,t.mysql)),Object.hasOwn(t,`sqlite`)&&(n.sqlite=admitEntry(e,`sqlite`,t.sqlite)),Object.keys(n).length===0&&refuse(e,`nativeType`,`A native-type map names at least one dialect; omit the argument to keep every automatic column`),Object.freeze(n)}function admitEntry(e,n,r){let i=t(r)?r.db:void 0,a=t(r)?r.type:void 0;return(i!==n||typeof a!=`string`)&&refuse(e,`nativeType.${n}`,`The '${n}' entry must be a ${N[n]} native type (\`{ db: "${n}", type }\`)`),Object.freeze({db:n,type:a})}function buildCatalogs(){let e={pg:emptyCatalog(),mysql:emptyCatalog(),sqlite:emptyCatalog()};return walk(D,e.pg),walk(O,e.mysql),walk(T,e.sqlite),e}function emptyCatalog(){return{exact:new Set,templates:new Map}}function walk(e,t){if(typeof e==`function`){deriveFunction(e,t);return}let n=e.type;if(typeof n==`string`){t.exact.add(n);return}for(let n of Object.values(e))walk(n,t)}function deriveFunction(e,t){for(let n of A){let r=e(...n).type,i=r.indexOf(`(`);if(i===-1){admit(t,r,0);continue}let a=r.slice(i+1,-1).split(`,`);a.every(e=>j.test(e))&&admit(t,r.slice(0,i),a.length)}}function admit(e,t,n){let r=e.templates.get(t);if(r===void 0){e.templates.set(t,new Set([n]));return}r.add(n)}const F=new DataView(new ArrayBuffer(192));for(let[e,t]of[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648].entries())F.setInt32(e*4,t,!0);const I=new DataView(new Uint8Array([0,1,62,28,27,36,44,6,55,20,3,10,43,25,39,41,45,15,21,8,18,2,61,56,14]).buffer),L=new DataView(new Uint8Array([0,10,20,5,15,16,1,11,21,6,7,17,2,12,22,23,8,18,3,13,14,24,9,19,4]).buffer),R=new Uint8Array(200),z=new DataView(R.buffer),B=new DataView(new ArrayBuffer(200)),V=new DataView(new ArrayBuffer(40));function permute(){for(let e=0;e<24;e++){for(let e=0;e<5;e++){let t=0,n=0;for(let r=0;r<25;r+=5)t^=z.getInt32((e+r)*8,!0),n^=z.getInt32((e+r)*8+4,!0);V.setInt32(e*8,t,!0),V.setInt32(e*8+4,n,!0)}for(let e=0;e<5;e++){let t=V.getInt32((e+1)%5*8,!0),n=V.getInt32((e+1)%5*8+4,!0),r=V.getInt32((e+4)%5*8,!0)^(t<<1|n>>>31),i=V.getInt32((e+4)%5*8+4,!0)^(n<<1|t>>>31);for(let t=0;t<25;t+=5){let n=(e+t)*8;z.setInt32(n,z.getInt32(n,!0)^r,!0),z.setInt32(n+4,z.getInt32(n+4,!0)^i,!0)}}B.setInt32(0,z.getInt32(0,!0),!0),B.setInt32(4,z.getInt32(4,!0),!0);for(let e=1;e<25;e++){let t=I.getUint8(e),n=z.getInt32(e*8,!0),r=z.getInt32(e*8+4,!0),i=L.getUint8(e)*8;if(t<32)B.setInt32(i,n<<t|r>>>32-t,!0),B.setInt32(i+4,r<<t|n>>>32-t,!0);else{let e=t-32;B.setInt32(i,r<<e|n>>>32-e,!0),B.setInt32(i+4,n<<e|r>>>32-e,!0)}}for(let e=0;e<25;e+=5)for(let t=0;t<5;t++){let n=(e+t)*8,r=(e+(t+1)%5)*8,i=(e+(t+2)%5)*8;z.setInt32(n,B.getInt32(n,!0)^~B.getInt32(r,!0)&B.getInt32(i,!0),!0),z.setInt32(n+4,B.getInt32(n+4,!0)^~B.getInt32(r+4,!0)&B.getInt32(i+4,!0),!0)}z.setInt32(0,z.getInt32(0,!0)^F.getInt32(e*8,!0),!0),z.setInt32(4,z.getInt32(4,!0)^F.getInt32(e*8+4,!0),!0)}}function absorb(e,t){for(let n=0;n<72;n+=4)z.setInt32(n,z.getInt32(n,!0)^e.getInt32(t+n,!0),!0);permute()}function sha3_512(e){R.fill(0);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),r=Math.floor(t/72);for(let e=0;e<r;e++)absorb(n,e*72);let i=new Uint8Array(72),a=t-r*72;return i.set(e.subarray(r*72)),i[a]=6,i[71]=a===71?134:128,absorb(new DataView(i.buffer),0),Uint8Array.from(R.subarray(0,64))}function uuidV4(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():b(x(S(_,`uuid`)))}const defaultUuid=e=>()=>h(e,uuidV4()),defaultUuidV7=e=>()=>h(e,b(c(Date.now(),S(v,`uuidv7`))));function incrementUlidRandom(e){let t=Uint8Array.from(e),n=new DataView(t.buffer);for(let e=t.length-1;e>=0;e--){let r=n.getUint8(e)+1;if(n.setUint8(e,r&255),r<=255)return t}return s(`s.string().ulid`,`generate`,`This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier`)}function createUlidGenerator(e={}){let t=e.now??Date.now,n=e.random??(e=>S(e,`ulid`)),r;return()=>{let e=t();return r=r!==void 0&&e<=r.time?{time:r.time,random:incrementUlidRandom(r.random)}:{time:e,random:n(p)},l(o(r.time,r.random))}}const H=createUlidGenerator(),defaultUlid=e=>()=>h(e,H()),defaultKsuid=e=>()=>h(e,m(u(Math.floor(Date.now()/1e3),S(d,`ksuid`)))),defaultNanoid=(e,t)=>{let n=e??f;return(!Number.isInteger(n)||n<1||n>g)&&s(`s.string().nanoid`,`length`,`A nanoid length must be a whole number of characters between 1 and ${g}; received ${n}`),()=>{let e=``;for(let t of S(n,`nanoid`))e+=y.charAt(t&63);return h(t,e)}},U=new TextEncoder;function secureFloat(){let e=S(4,`cuid`);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0)/4294967296}function createEntropy(e,t){let n=``;for(;n.length<e;)n+=Math.floor(t()*36).toString(36);return n}function hashBase36(e){let t=0n;for(let n of sha3_512(U.encode(e)))t=t<<8n|BigInt(n);return t.toString(36).slice(1)}function createFingerprint(e){return hashBase36(Object.keys(globalThis).toString()+createEntropy(32,e)).substring(0,32)}function createCuid2(e={}){let t=e.random??secureFloat,n=e.counter??createCounter(Math.floor(t()*476782367)),r=e.length??24,i=e.fingerprint??createFingerprint(t);return()=>{let e=`abcdefghijklmnopqrstuvwxyz`.charAt(Math.floor(t()*26)),a=Date.now().toString(36),o=n().toString(36);return e+hashBase36(a+createEntropy(r,t)+o+i).substring(1,r)}}function createCounter(e){let t=e;return()=>{let e=t;return t++,e}}let W;const defaultCuid=e=>()=>h(e,(W??=createCuid2())());function identifierGenerator(e){let{kind:t,prefix:n,length:r}=e;switch(t){case`uuid`:return defaultUuid(n);case`uuidv7`:return defaultUuidV7(n);case`ulid`:return defaultUlid(n);case`ksuid`:return defaultKsuid(n);case`nanoid`:return defaultNanoid(r,n);case`cuid`:return defaultCuid(n);default:return s(`s.string`,`generate`,`This generator is not a string identifier format`)}}const G=a.string();var K=class StringScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new StringScalar(updateState(this,{nullable:!0,hasDefault:!0,default:nullableDefault(this.state),optional:!0,base:a.string({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return isGeneratorDefault(this.state.default)&&refuseListGenerator(`s.string`),new StringScalar(updateState(this,{array:!0,base:a.string({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(e){let t=typeof e==`object`?e.generate:void 0,n=typeof e==`string`?e:e?.prefix,r=this.state.autoGenerate;r&&C(n)&&refuseSecondIdPrefix(r);let i=r?{...r,generate:t??r.generate}:{kind:`ulid`,prefix:n,implicit:!0,generate:t};return this.withIdentifier(i,!0)}unique(){return new StringScalar(updateState(this,{isUnique:!0}),this._nativeType)}default(e){return new StringScalar(updateState(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}schema(e){return new StringScalar(updateState(this,{schema:e,base:a.string({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}map(e){return new StringScalar(updateState(this,{columnName:e}),this._nativeType)}uuid(e){return this.withFormat(`uuid`,e)}uuidv7(e){return this.withFormat(`uuidv7`,e)}ksuid(e){return this.withFormat(`ksuid`,e)}ulid(e){return this.withFormat(`ulid`,e)}cuid(e){return this.withFormat(`cuid`,e)}nanoid(e,t){return this.withFormat(`nanoid`,typeof e==`number`?{length:e,prefix:t}:e??{prefix:t})}withFormat(e,t){let n=typeof t==`string`?{prefix:t}:t;return this.withIdentifier({kind:e,prefix:n?.prefix,length:e===`nanoid`?n?.length:void 0,generate:n?.generate??this.state.autoGenerate?.generate},this.state.isId)}withIdentifier(e,t){let n=identifierGenerator(e),r=this.state.hasDefault&&!isGeneratorDefault(this.state.default),i=(e.generate===!0||t&&e.generate!==!1)&&!r;return this.state.array&&i&&refuseListGenerator(`s.string`),new StringScalar(updateState(this,{isId:t,isUnique:t||this.state.isUnique,autoGenerate:e,hasDefault:r||i,optional:r||i,default:i?generatorDefault(n):r?this.state.default:void 0}),this._nativeType)}_internal;get"~"(){return this._internal??={state:this.state,nativeType:this._nativeType}}};const string=e=>new K(createDefaultState(`string`,G),admitNativeType(`s.string`,e));function refuseSecondIdPrefix(e){return s(`s.string().id`,`prefix`,`This field already declares a '${e.kind}' generator${e.prefix?` with the prefix '${e.prefix}'`:``}. A prefix is spelled once, on the call that declares the format`)}export{createDefaultState as a,nullableDefault as c,SchemaValidationError as d,isSchemaValidationError as f,nativeTypeRefusal as i,refuseListGenerator as l,preflightModelRegistrationIdentity as m,admitNativeType as n,generatorDefault as o,thrownAsError as p,isNativeTypeInCatalog as r,isGeneratorDefault as s,string as t,updateState as u};
|
|
4
|
-
//# sourceMappingURL=scalar-
|
|
4
|
+
//# sourceMappingURL=scalar-BgxfbRLw.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scalar-CZ_q89Hc.mjs","names":["state","catalogs","v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/common.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\n */\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\n */\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\n );\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\n */\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport v from \"@validation/primitives/v\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<State extends ScalarState<\"string\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new StringScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.string<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n unique() {\n return new StringScalar(\n updateState(this, {\n isUnique: true,\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new StringScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new StringScalar(\n updateState(this, {\n schema,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new StringScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n"],"mappings":"8dAWA,SAAgB,mCACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAU,KAAU,EAAe,CAC7C,GAEE,OAAO,GAAU,WADjB,GAEA,CAAC,EAAM,MAAM,OACb,CAAC,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,KAAM,OACN,QAAS,iBAAiB,EAAS,iFACnC,SAAU,QACV,MAAO,EACR,CACH,IAAM,EAAU,EAAM,KAAK,MAAM,IAAM,EAAkB,IAAI,EAAM,CACnE,GAAI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EACT,mBAAmB,SAAU,EAAW,CACxC,gBAAgB,WAAY,EAAW,CACxC,CAGH,SAAS,qBAAqB,EAGpB,CACR,OAAO,EACL,gBACA,SACA,kCAAkC,EAAS,KAAK,aAAa,EAAS,OAAS,qBAAqB,EAAS,OAAO,GAAK,GAAG,kEAC7H"}
|
|
1
|
+
{"version":3,"file":"scalar-BgxfbRLw.mjs","names":["state","catalogs","v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/common.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\n */\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\n */\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\n );\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\n */\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport v from \"@validation/primitives/v\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<State extends ScalarState<\"string\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new StringScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.string<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n unique() {\n return new StringScalar(\n updateState(this, {\n isUnique: true,\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new StringScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new StringScalar(\n updateState(this, {\n schema,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new StringScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n"],"mappings":"8dAWA,SAAgB,mCACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAU,KAAU,EAAe,CAC7C,GAEE,OAAO,GAAU,WADjB,GAEA,CAAC,EAAM,MAAM,OACb,CAAC,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,KAAM,OACN,QAAS,iBAAiB,EAAS,iFACnC,SAAU,QACV,MAAO,EACR,CACH,IAAM,EAAU,EAAM,KAAK,MAAM,IAAM,EAAkB,IAAI,EAAM,CACnE,GAAI,IAAY,IAAA,IAAa,IAAY,EACvC,OAAO,wBAAwB,EAAS,EAAS,CACnD,EAAkB,IAAI,EAAO,EAAS,EAK1C,SAAS,wBACP,EACA,EACuB,CACvB,MAAO,CACL,KAAM,OACN,QAAS,wBAAwB,EAAQ,kCAAkC,EAAS,0CACpF,SAAU,QACV,MAAO,EACR,CC1CH,IAAa,sBAAb,cAA2C,CAAY,CACrD,OAAyB,eAAiB,wBAG1C,OAEA,YACE,EACA,EACA,CAIA,IAAM,EAAW,OAAO,OACtB,EAAO,IAAK,GACV,OAAO,OACL,EAAM,WACF,CAAE,GAAG,EAAO,WAAY,OAAO,OAAO,CAAC,GAAG,EAAM,WAAW,CAAC,CAAE,CAC9D,CAAE,GAAG,EAAO,CACjB,CACF,CACF,CACK,EAAW,EAAS,IAAK,GAC7B,CACE,IAAI,EAAM,KAAK,IAAI,EAAM,UACzB,EAAM,YAAY,OACd,eAAe,EAAM,WAAW,KAAK,KAAK,GAC1C,GACJ,EAAM,QAAU,G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AAM,cAAc,SAC/D,CACD,KAAK,MAAM,KACZ,CAGH,eAAuB,EAA2B,EAAe,CAC/D,IAAM,EAAY,oBAAoB,EAAY,CAC5C,EACJ,KAAK,MAAM,YAAc,CAAC,mBAAmB,KAAK,MAAM,QAAQ,CAG5D,GADJ,EAAY,WAAa,IAAS,GAAQ,EAAY,WAAa,KACvC,CAAC,EAE/B,OADI,KAAK,MAAM,OAAS,GAAW,oBAAoB,WAAW,CAC3D,IAAI,aACT,YAAY,KAAM,CAChB,OACA,SAAU,GAAQ,KAAK,MAAM,SAC7B,aAAc,EACd,WAAY,GAAiB,EAC7B,SAAU,GAAiB,EAC3B,QAAS,EACL,iBAAiB,EAAU,CAC3B,EACE,KAAK,MAAM,QACX,IAAA,GACP,CAAC,CACF,KAAK,YACN,CAGH,UAKA,GAAK,KAAO,CACV,MAAQ,MAAK,YAAc,CACzB,MAAO,KAAK,MACZ,WAAY,KAAK,YAClB,GAIL,MAAa,OAIX,GAEO,IAAI,EACT,mBAAmB,SAAU,EAAW,CACxC,gBAAgB,WAAY,EAAW,CACxC,CAGH,SAAS,qBAAqB,EAGpB,CACR,OAAO,EACL,gBACA,SACA,kCAAkC,EAAS,KAAK,aAAa,EAAS,OAAS,qBAAqB,EAAS,OAAO,GAAK,GAAG,kEAC7H"}
|
package/dist/schema/json.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $r as JunctionReferentialAction, It as VibORMClient, Lt as VibORMConfig, Zn as IndexType, ar as AutoGenerateType, bn as Schema, ea as NativeType, ei as ReferentialAction, lr as ScalarType, ta as NativeTypeMap, wr as JsonValue } from "../index-DBhpNR0X.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema/json/document.d.ts
|