viborm 1.3.1 → 1.3.3
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/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-CWLEmon2.mjs} +2 -2
- package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-CWLEmon2.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DGJPz8-G.mjs} +2 -2
- package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DGJPz8-G.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-qfEejeOX.mjs → bind-parameter-capacity-DiwRmZ1h.mjs} +2 -2
- package/dist/{bind-parameter-capacity-qfEejeOX.mjs.map → bind-parameter-capacity-DiwRmZ1h.mjs.map} +1 -1
- package/dist/{builder-s1ySUuMb.mjs → builder-D6Ug-zjM.mjs} +2 -2
- package/dist/{builder-s1ySUuMb.mjs.map → builder-D6Ug-zjM.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/cache.mjs.map +1 -1
- package/dist/chain-B5IbqLGi.mjs +2 -0
- package/dist/chain-B5IbqLGi.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/client-BmcHzDBa.mjs +2 -0
- package/dist/client-BmcHzDBa.mjs.map +1 -0
- package/dist/{client-70MrTq1E.d.mts → client-DR0vYetv.d.mts} +2 -2
- package/dist/{client-BgJ7Faln.mjs → client-DjtWangN.mjs} +3 -3
- package/dist/{client-BgJ7Faln.mjs.map → client-DjtWangN.mjs.map} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
- package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +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/datetime-physical-codec-qKxFtI3B.mjs +2 -0
- package/dist/datetime-physical-codec-qKxFtI3B.mjs.map +1 -0
- package/dist/{driver-vn-9CN0y.mjs → driver-BvP7eW0A.mjs} +2 -2
- package/dist/{driver-vn-9CN0y.mjs.map → driver-BvP7eW0A.mjs.map} +1 -1
- package/dist/{driver-B9fIori_.mjs → driver-Bzc0GCQ4.mjs} +2 -2
- package/dist/{driver-B9fIori_.mjs.map → driver-Bzc0GCQ4.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
- package/dist/error-mapping-6op318w6.mjs.map +1 -0
- package/dist/every-WUr3mlvg.mjs +2 -0
- package/dist/{every-CcpKWCVo.mjs.map → every-WUr3mlvg.mjs.map} +1 -1
- package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
- package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
- package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
- package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
- package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
- package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
- package/dist/{hydration-BsPZI4jE.mjs → hydration-BflrXEIQ.mjs} +2 -2
- package/dist/{hydration-BsPZI4jE.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
- package/dist/{identifier-conversion-BneQiLxQ.mjs → identifier-conversion-Bs7A2GGU.mjs} +2 -2
- package/dist/{identifier-conversion-BneQiLxQ.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map} +1 -1
- package/dist/identity-Bj2EN6Ss.mjs +2 -0
- package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
- package/dist/{index-VsM29vYN.d.mts → index-B_jh2oaQ.d.mts} +38 -11
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{key-D9LtHxVK.mjs → key-B89Z4vxn.mjs} +2 -2
- package/dist/{key-D9LtHxVK.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
- package/dist/{libsql-BlSBYwd_.mjs → libsql-C8dn4id0.mjs} +2 -2
- package/dist/{libsql-BlSBYwd_.mjs.map → libsql-C8dn4id0.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-C0k-_S_n.mjs → memory-B7CcHS6I.mjs} +2 -2
- package/dist/{memory-C0k-_S_n.mjs.map → memory-B7CcHS6I.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/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.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/mysql-adapter-ABpgFB2N.mjs +2 -0
- package/dist/mysql-adapter-ABpgFB2N.mjs.map +1 -0
- package/dist/{mysql-DOLHwIM_.mjs → mysql-mUmhH9Cf.mjs} +2 -2
- package/dist/{mysql-DOLHwIM_.mjs.map → mysql-mUmhH9Cf.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/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
- package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
- package/dist/{object-store-D9mvOHP4.d.mts → object-store-Ds9NKRU6.d.mts} +3 -3
- package/dist/permissions.d.mts +2 -2
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +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/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
- package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
- package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-C79aDzOg.mjs} +2 -2
- package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-C79aDzOg.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C1NzLBge.d.mts → planner-DHZG9Vy7.d.mts} +1 -1
- package/dist/{postgres-DQVSTqVm.mjs → postgres-BACQ_wqF.mjs} +2 -2
- package/dist/{postgres-DQVSTqVm.mjs.map → postgres-BACQ_wqF.mjs.map} +1 -1
- package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-Ci07rgh_.mjs} +2 -2
- package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-Ci07rgh_.mjs.map} +1 -1
- package/dist/postgres-adapter-DaMvNOkx.mjs +2 -0
- package/dist/postgres-adapter-DaMvNOkx.mjs.map +1 -0
- package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-D403cLyA.mjs} +2 -2
- package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-D403cLyA.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-DSv2tYFr.mjs} +2 -2
- package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-DSv2tYFr.mjs.map} +1 -1
- package/dist/result-shape-BKydBCsR.mjs +2 -0
- package/dist/result-shape-BKydBCsR.mjs.map +1 -0
- package/dist/rows-v1VuwOTa.mjs +2 -0
- package/dist/rows-v1VuwOTa.mjs.map +1 -0
- package/dist/{scalar-CpEwuJvn.mjs → scalar-Cm7nMFmO.mjs} +2 -2
- package/dist/{scalar-CpEwuJvn.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BnzGHn7k.mjs → schema-D3-ScVH6.mjs} +2 -2
- package/dist/{schema-BnzGHn7k.mjs.map → schema-D3-ScVH6.mjs.map} +1 -1
- package/dist/{schema-introspection-DZsdP6bi.mjs → schema-introspection-TdJrSaKd.mjs} +3 -3
- package/dist/{schema-introspection-DZsdP6bi.mjs.map → schema-introspection-TdJrSaKd.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-uZfvbYjz.mjs} +2 -2
- package/dist/select-assembly-uZfvbYjz.mjs.map +1 -0
- package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
- package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
- package/dist/sha256-CEYo7k7R.mjs +2 -0
- package/dist/sha256-CEYo7k7R.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/sql-BvHwL73I.mjs +2 -0
- package/dist/sql-BvHwL73I.mjs.map +1 -0
- package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
- package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
- package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-DPc9T6Lh.mjs +2 -0
- package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +1 -0
- package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-BvSlEs5W.mjs} +2 -2
- package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-BvSlEs5W.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-CYdZ_KXH.mjs} +2 -2
- package/dist/standard-sql-CYdZ_KXH.mjs.map +1 -0
- package/dist/{to-many-C5RMZl05.mjs → to-many-Btc9X5Ga.mjs} +2 -2
- package/dist/{to-many-C5RMZl05.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
- package/dist/{utils-C3r4gO3Y.mjs → utils-Qr8ug94X.mjs} +2 -2
- package/dist/{utils-C3r4gO3Y.mjs.map → utils-Qr8ug94X.mjs.map} +1 -1
- package/dist/v-514RME2X.mjs +2 -0
- package/dist/v-514RME2X.mjs.map +1 -0
- package/dist/{validation-BQtO6srU.mjs → validation-CPnrLcjW.mjs} +2 -2
- package/dist/{validation-BQtO6srU.mjs.map → validation-CPnrLcjW.mjs.map} +1 -1
- package/dist/validation-gwZYm3Yn.mjs +2 -0
- package/dist/validation-gwZYm3Yn.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CVSrhn0u.mjs → validator-CQOw7G3q.mjs} +2 -2
- package/dist/{validator-CVSrhn0u.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
- package/dist/version-0RVYpih5.mjs +2 -0
- package/dist/{version-C8QLCt1n.mjs.map → version-0RVYpih5.mjs.map} +1 -1
- package/package.json +15 -15
- package/dist/chain-7qiFSE8J.mjs +0 -2
- package/dist/chain-7qiFSE8J.mjs.map +0 -1
- package/dist/client-6YgGlXzN.mjs +0 -2
- package/dist/client-6YgGlXzN.mjs.map +0 -1
- package/dist/controls-KQ85SWfT.mjs +0 -2
- package/dist/controls-KQ85SWfT.mjs.map +0 -1
- package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
- package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
- package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
- package/dist/every-CcpKWCVo.mjs +0 -2
- package/dist/identity-oQvIe7u8.mjs +0 -2
- package/dist/identity-oQvIe7u8.mjs.map +0 -1
- package/dist/mysql-adapter-C6c5govr.mjs +0 -2
- package/dist/mysql-adapter-C6c5govr.mjs.map +0 -1
- package/dist/postgres-adapter-CxEit2-v.mjs +0 -2
- package/dist/postgres-adapter-CxEit2-v.mjs.map +0 -1
- package/dist/result-shape-B6yWtnx_.mjs +0 -2
- package/dist/result-shape-B6yWtnx_.mjs.map +0 -1
- package/dist/select-assembly-CkGe2ABs.mjs.map +0 -1
- package/dist/sql-Bhxq9arK.mjs +0 -2
- package/dist/sql-Bhxq9arK.mjs.map +0 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +0 -2
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +0 -1
- package/dist/standard-sql-CoGqv-iX.mjs.map +0 -1
- package/dist/v-DtLdBQYg.mjs +0 -2
- package/dist/v-DtLdBQYg.mjs.map +0 -1
- package/dist/validation-BamBwne9.mjs +0 -2
- package/dist/validation-BamBwne9.mjs.map +0 -1
- package/dist/version-C8QLCt1n.mjs +0 -2
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{b as r,t as i}from"./base-D3m1S7Uc.mjs";import{p as a,r as o,t as s}from"./validation-BamBwne9.mjs";import{a as c}from"./key-D9LtHxVK.mjs";const l=`viborm.cache`,u=Object.freeze({cache:Object.freeze({schema:Object.freeze({"~standard":Object.freeze({version:1,vendor:`viborm`,validate:e=>Object.freeze({value:officialCacheRuntime().admitMutationCacheOptions(e)})})}),on:`writes`})}),d=new WeakMap,f=new WeakMap,p=new WeakMap;let m;function registerOfficialCacheQuery(e,t,n){m=n,d.set(e,t)}function installOfficialCacheRuntime(e){m=e}function officialCacheRuntime(){if(m===void 0)throw Error(`The official cache runtime is not loaded: import cache() from viborm/cache.`);return m}function getOfficialCacheQueryCapability(e){return t(e)?d.get(e):void 0}function getOfficialCacheChainDefinition(e){return e===void 0?void 0:f.get(e)}function getOfficialCacheChainCapability(e){return e===void 0?void 0:p.get(e)}function registerOfficialCacheChain(e,t){f.set(e,t)}function setOfficialCacheChainCapability(e,t){p.set(e,t)}function bindOfficialCacheChain(e,t){f.get(e)!==void 0&&officialCacheRuntime().bindChain(e,t)}function isCacheManagedExecution(e){return e?.skipSpan===!0}const h=new Set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function isReadOperation(e){return h.has(e)}const g=new Set([...h,`create`,`update`,`delete`,`upsert`,`createMany`,`updateMany`,`deleteMany`]);function isWriteOperation(e){return g.has(e)&&!isReadOperation(e)}function baseOperation(e){return e===`findUniqueOrThrow`?`findUnique`:e===`findFirstOrThrow`?`findFirst`:e}const _={reads:new Set([...g].filter(isReadOperation)),writes:new Set([...g].filter(isWriteOperation)),all:g},v=new Set([...g].filter(e=>e!==`create`&&e!==`createMany`)),y=new Set([`delete`,`deleteMany`]);function placeControls(e){let t=[],{name:n,controls:r,rows:i,deletion:a,data:o}=e,s=a?.removeWhen??{},c=new Set(Object.keys(a?.models??{})),l=new Set([...c,...Object.keys(i?.models??{}),...Object.keys(i?.verbs??{}),...Object.keys(o?.models??{})]),u=l.size===0?!0:l;for(let[e,i]of Object.entries(r??{})){let r=Object.hasOwn(s,e);t.push({name:e,extension:n,declaration:i,operations:r?y:placementOf(i.on),models:r?c:void 0,required:i.required===!0?u:void 0,...i.bound===!0&&{bound:!0},...i.uncacheable===!0&&{uncacheable:!0}})}return i!==void 0&&t.push({name:i.control,extension:n,declaration:Object.freeze({oneOf:Object.freeze(rowsModes(i))}),operations:v,fallback:i.default}),t}function placementOf(e){return e===void 0?g:typeof e==`string`?_[e]:new Set(e)}function rowsModes(e){let[t]=Object.values(e.models);return t===void 0?[e.default]:Object.keys(t)}const b=new WeakSet;function snapshotControlValue(e){if(typeof e!=`object`||!e||!c(e))return e;let t;try{t=captureOf(e,new WeakSet)}catch{return e}if(t===`opaque`)return e;if(t===`fixed`)return b.add(e),e;let n;try{n=structuredClone(e)}catch{return e}return freezeCopy(n)&&b.add(n),n}function captureOf(e,t){if(ArrayBuffer.isView(e))return`opaque`;if(t.has(e))return`fixed`;t.add(e);let n=e instanceof Date||!Object.isFrozen(e)?`copy`:`fixed`,r=Array.isArray(e);for(let i of Reflect.ownKeys(e)){if(r&&i===`length`)continue;let a=Object.getOwnPropertyDescriptor(e,i);if(typeof i==`symbol`||!a.enumerable||!(`value`in a))return`opaque`;let o=a.value;if(typeof o!=`object`||!o)continue;let s=captureOf(o,t);if(s===`opaque`)return`opaque`;s===`copy`&&(n=`copy`)}return n}function freezeCopy(e){if(e instanceof Date)return!1;let t=!0;for(let n of Object.values(e))typeof n==`object`&&n&&!freezeCopy(n)&&(t=!1);return Object.freeze(e),t}function isStableControlValue(e){return typeof e!=`object`||!e||b.has(e)}function admitControls(e,t,n,r,i){if(typeof n!=`object`||!n)return{args:n,controls:void 0};let a;try{a=Reflect.ownKeys(n)}catch(n){throw controlFailure(`The arguments of ${e}.${t} could not be inspected for controls`,e,t,n)}let o=[],s;for(let c of r){let{name:r,required:l}=c,u;c.bound!==!0&&a.includes(r)&&((s??=new Set).add(r),u=readControl(n,c,e,t));let d=u===void 0?i?.[r]??c.fallback:snapshotControlValue(admitControl(c,u,e,t));if(d!==void 0)o.push([r,d]);else if(l===!0||l?.has(e))throw invalidControl(c,e,t,[`is required`])}return{args:s===void 0?n:withoutControls(n,a,s,e,t),controls:o.length===0?void 0:Object.freeze(Object.fromEntries(o))}}function bindControls(e,t,n,r){let i={...r};for(let[r,a]of Object.entries(n)){let n=e.find(e=>e.name===r&&e.extension===t);if(n===void 0)throw new o(`Extension "${t}" binds control "${r}", which it does not declare.`,{meta:{extension:t}});i[r]=snapshotControlValue(admitControl(n,a))}return Object.freeze(i)}function controlsOwnedBy(e,t){let n=[];for(let r of t)e!==void 0&&Object.hasOwn(e,r)&&n.push([r,e[r]]);return Object.freeze(Object.fromEntries(n))}function readControl(e,t,n,r){try{return Reflect.get(e,t.name)}catch(e){throw controlFailure(`Extension "${t.extension}" control "${t.name}" of ${n}.${r} could not be read`,n,r,e)}}function withoutControls(e,t,n,r,i){let a={};try{for(let r of t){if(n.has(r))continue;let t=Object.getOwnPropertyDescriptor(e,r);t&&Object.defineProperty(a,r,t)}}catch(e){throw controlFailure(`The arguments of ${r}.${i} could not be inspected for controls`,r,i,e)}return a}function admitControl(e,r,i,a){let{declaration:o}=e;if(`oneOf`in o){if(o.oneOf.some(e=>e===r))return r;throw invalidControl(e,i,a,[`must be one of ${o.oneOf.map(e=>JSON.stringify(e)).join(`, `)}`])}let s;try{s=o.schema[`~standard`].validate(r)}catch(t){throw isVibORMFailure(t)?t:validatorFailure(e,i,a,`threw`,t)}let c=`malformed`,l=[],u;try{if(n(s)){let e=`then`in s?s.then:void 0;if(t(e))c=`promise`,Reflect.apply(e,s,[void 0,()=>void 0]);else{let e=s.issues;e===void 0?`value`in s&&(c=`value`,u=s.value):Array.isArray(e)&&(c=`issues`,l=e)}}}catch(t){throw validatorFailure(e,i,a,`returned an unreadable result`,t)}switch(c){case`value`:return u;case`issues`:throw invalidControl(e,i,a,issueMessages(l));case`promise`:throw validatorFailure(e,i,a,`returned a promise`,TypeError(`Control validators must return synchronously`));default:throw validatorFailure(e,i,a,`returned a malformed result`,TypeError(`A Standard Schema result has a value or an issue list`))}}function issueMessages(e){let t=[];try{for(let r of e){let e=n(r)?r.message:void 0;t.push(typeof e==`string`?e:`is invalid`)}}catch{return[`is invalid`]}return t.length===0?[`is invalid`]:t}function isVibORMFailure(e){try{return e instanceof i}catch{return!1}}function uncacheableRead(e,t,n,r){let i=e.find(e=>e.uncacheable===!0&&t?.[e.name]!==void 0);return i&&invalidControl(i,n,r,[`is not cacheable: a read that holds it is not served from the cache`])}function invalidControl(e,t,n,r){return new s(n===void 0?{kind:`schema-builder`,builder:`$bind`,path:e.name}:{kind:`operation`,operation:n,model:t},r.map(t=>({path:e.name,message:`Control "${e.name}" ${t}`})),{meta:{model:t,extension:e.extension}})}function validatorFailure(e,t,n,r,i){return controlFailure(`Extension "${e.extension}" control "${e.name}" validator for ${n===void 0?`$bind`:`${t}.${n}`} ${r}`,t,n,i)}function controlFailure(e,t,n,i){return new a(`${e}.`,{cause:r(i),meta:{model:t,operation:n}})}export{setOfficialCacheChainCapability as C,registerOfficialCacheQuery as S,installOfficialCacheRuntime as _,placeControls as a,officialCacheRuntime as b,g as c,isWriteOperation as d,l as f,getOfficialCacheQueryCapability as g,getOfficialCacheChainDefinition as h,isStableControlValue as i,baseOperation as l,getOfficialCacheChainCapability as m,bindControls as n,rowsModes as o,bindOfficialCacheChain as p,controlsOwnedBy as r,uncacheableRead as s,admitControls as t,isReadOperation as u,isCacheManagedExecution as v,registerOfficialCacheChain as x,u as y};
|
|
2
|
-
//# sourceMappingURL=controls-KQ85SWfT.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"controls-KQ85SWfT.mjs","names":[],"sources":["../src/cache/capability.ts","../src/query-engine/routed-operations.ts","../src/extensions/controls.ts"],"sourcesContent":["// The part of the official cache the core client reads on every operation:\n// whether a chain carries the cache, and a handle on the cache runtime. The\n// runtime itself (cache driver, cache flow, result codecs) is installed by\n// `cache()` from `viborm/cache`, so an application that never creates the\n// extension does not load it. A chain can only carry the capability after\n// `cache()` ran, which is what makes `officialCacheRuntime()` total wherever\n// the core asks for it.\n\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n GenericQueryHandler,\n OfficialGenericQueryHandler,\n} from \"@extensions/query\";\nimport { isFunction } from \"@validation/value-guards\";\nimport type { CacheDriver, WaitUntilFn } from \"./driver\";\nimport type { OfficialCacheRuntime } from \"./runtime\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\nexport const OFFICIAL_CACHE_NAME = \"viborm.cache\";\n\n/** The exact official query contribution. It is recognized by identity. */\nexport type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {\n bind(thisArg: unknown): GenericQueryHandler;\n};\n\n/**\n * A mutation's `cache` argument is the cache's declared control (ruling 7):\n * core removes and admits it before request handlers run, through the cache's\n * own parser, so a malformed value is still a `CacheConfigurationError`.\n */\nexport type OfficialCacheControls = {\n readonly cache: {\n readonly schema: StandardSchemaV1<CacheInvalidationOptions>;\n readonly on: \"writes\";\n };\n};\n\n/** The official value accepted by the dedicated `$extends` overload. */\nexport type OfficialCacheExtension = {\n readonly name: typeof OFFICIAL_CACHE_NAME;\n readonly query: OfficialCacheQueryContribution;\n readonly controls: OfficialCacheControls;\n};\n\n/**\n * The cache's one declaration. The chain places it for any definition carrying\n * the cache's query, whatever `controls` that definition spells: the query is\n * the cache's identity, so its control cannot be forged or left out. It lives\n * here, in the part core always loads, and admits through the runtime: a chain\n * carries the cache only after `cache()` installed that runtime.\n */\nexport const officialCacheControls: OfficialCacheControls = Object.freeze({\n cache: Object.freeze({\n schema: Object.freeze({\n \"~standard\": Object.freeze({\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) =>\n Object.freeze({\n value: officialCacheRuntime().admitMutationCacheOptions(value),\n }),\n }),\n }),\n on: \"writes\",\n }),\n});\n\n/**\n * What `cache()` knows before it meets a client: no scope, because the scope\n * partitions on facts (dialect, SQL namespace) that only a concrete driver\n * carries. One definition may be appended to several clients.\n */\nexport interface OfficialCacheDefinitionCapability {\n readonly driver: CacheDriver;\n readonly version: string | number | undefined;\n readonly waitUntil: WaitUntilFn | undefined;\n}\n\n/** The definition once bound to one client's driver, gaining its scope. */\nexport interface OfficialCacheCapability\n extends OfficialCacheDefinitionCapability {\n readonly scope: object;\n}\n\n/**\n * The two driver facts the scope derives from. Structural, so the cache holds\n * no driver reference and no import edge back into `src/drivers`.\n */\nexport interface OfficialCacheBindTarget {\n readonly dialect: string;\n readonly adapter: { readonly namespace?: string | undefined };\n}\n\nconst capabilitiesByQuery = new WeakMap<\n CallableFunction,\n OfficialCacheDefinitionCapability\n>();\nconst definitionsByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheDefinitionCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheCapability\n>();\nlet runtime: OfficialCacheRuntime | undefined;\n\n/** Recognize `query` as the official cache's contribution. `cache()` only. */\nexport function registerOfficialCacheQuery(\n query: CallableFunction,\n capability: OfficialCacheDefinitionCapability,\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n capabilitiesByQuery.set(query, capability);\n}\n\n/** Make the cache runtime reachable; `viborm/cache` does this as it loads. */\nexport function installOfficialCacheRuntime(\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n}\n\n/** The cache runtime; reachable only where a chain carries the cache. */\nexport function officialCacheRuntime(): OfficialCacheRuntime {\n if (runtime === undefined)\n throw new Error(\n \"The official cache runtime is not loaded: import cache() from viborm/cache.\"\n );\n return runtime;\n}\n\nexport function getOfficialCacheQueryCapability(\n query: unknown\n): OfficialCacheDefinitionCapability | undefined {\n return isFunction(query) ? capabilitiesByQuery.get(query) : undefined;\n}\n\n/**\n * The definition carried by this chain, scope or no scope. Generic\n * extension-chain code sees only this: admission, duplicate refusal, and\n * propagation are all decisions about the DEFINITION, and none of them may\n * depend on whether a client has bound it yet.\n */\nexport function getOfficialCacheChainDefinition(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheDefinitionCapability | undefined {\n return chain === undefined ? undefined : definitionsByChain.get(chain);\n}\n\n/** The bound capability: present only after a client composition root bound it. */\nexport function getOfficialCacheChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialCacheChain(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheDefinitionCapability\n): void {\n definitionsByChain.set(chain, capability);\n}\n\n/** Publish the capability the runtime bound for one chain. */\nexport function setOfficialCacheChainCapability(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n\n/**\n * Bind one resolved chain's cache definition to the concrete client driver,\n * deriving the scope that partitions its storage.\n *\n * Called by the client composition root — the one place that holds both the\n * resolved chain and the driver — and only for a chain that carries the\n * official cache, so an ordinary extension costs nothing here.\n */\nexport function bindOfficialCacheChain(\n chain: ResolvedExtensionChain,\n target: OfficialCacheBindTarget\n): void {\n if (definitionsByChain.get(chain) === undefined) return;\n officialCacheRuntime().bindChain(chain, target);\n}\n\n/** Whether an operation runs under the official cache's managed execution. */\nexport function isCacheManagedExecution(\n options: { readonly skipSpan?: boolean } | undefined\n): boolean {\n return options?.skipSpan === true;\n}\n","import type { Operations } from \"@client/types\";\n\n/**\n * The client operation vocabulary, retained at the C-01 cutover.\n *\n * These four names are the only part of the deleted shipped routing module that\n * owners OUTSIDE the engine consume: the client (`isWriteOperation`), the\n * official cache (`isWriteOperation`), the extension surface\n * (`ROUTED_OPERATIONS`) and the query-interception seam (`isReadOperation`).\n * The text below is the deleted `write-engine/routing.ts` definitions verbatim,\n * so no operation changes classification at the cutover.\n */\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** Whether a public operation routes through the engine's read owner. */\nexport function isReadOperation(operation: string): boolean {\n return READ_OPERATIONS.has(operation);\n}\n\n/**\n * The operation names the engine owns a construction path for. Every client\n * operation family is here; a name outside it (there is none on the client path)\n * resolves to `undefined`.\n */\nexport const ROUTED_OPERATIONS: ReadonlySet<string> = new Set([\n ...READ_OPERATIONS,\n \"create\",\n \"update\",\n \"delete\",\n \"upsert\",\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n]);\n\n/** Whether a public operation routes through the engine's write owner. */\nexport function isWriteOperation(operation: string): boolean {\n return ROUTED_OPERATIONS.has(operation) && !isReadOperation(operation);\n}\n\n/**\n * The verb an `…OrThrow` operation shares its whole envelope with: its schema,\n * its admission and its result. Every other verb is its own base.\n */\nexport function baseOperation(\n operation: Operations\n): Exclude<Operations, \"findUniqueOrThrow\" | \"findFirstOrThrow\"> {\n if (operation === \"findUniqueOrThrow\") return \"findUnique\";\n if (operation === \"findFirstOrThrow\") return \"findFirst\";\n return operation;\n}\n","import { isCanonicalKeyData } from \"@cache/key\";\nimport type {\n CacheableOperations,\n MutationOperations,\n Operations,\n} from \"@client/types\";\nimport {\n ClientInitializationError,\n QueryError,\n ValidationError,\n VibORMError,\n} from \"@errors\";\nimport {\n isReadOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ControlLiteral, RuntimeExtensionDefinition } from \"./definition\";\n\n// =============================================================================\n// DEFINITION MEMBERS: plain data, checked by TypeScript only\n// =============================================================================\n\n/** The operations a declared control is accepted on. */\nexport type ControlPlacement =\n | \"reads\"\n | \"writes\"\n | \"all\"\n | readonly Operations[];\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema; `on` names the operations that accept it (every operation\n * when absent). With `required`, a call on one of those operations that does\n * not pass it is refused, on the models the extension names in `rows`,\n * `data` or `deletion` only; an extension that names no model asks for it on\n * every model. With `bound`, it is accepted only from a binding (the client\n * scope's `$bind`), never from a call's arguments: its placement reads no\n * argument, so a call that passes it is refused as passing an unknown key.\n * With `uncacheable`, a read that holds a value of it is never served from\n * the cache: `$withCache` on that read is refused before any statement. A\n * value held in a variable keeps its literal type only with `as const`, as a\n * held enum clause does.\n */\nexport type ControlDeclaration = (\n | { readonly oneOf: readonly (string | number | boolean)[] }\n | { readonly schema: StandardSchemaV1 }\n) & {\n readonly on?: ControlPlacement;\n readonly required?: boolean;\n readonly bound?: boolean;\n readonly uncacheable?: boolean;\n};\n\nexport type ControlsContribution = {\n readonly [name: string]: ControlDeclaration;\n};\n\n/** Constant scalar `where` or `data` fields of one model. */\ntype ScalarFields = { readonly [field: string]: unknown };\n\n/**\n * Which rows an operation sees. `control` names the call argument that picks\n * a mode; every model entry declares the same mode names, `default` among\n * them. `root` filters the call's own candidates, `related` rows reached\n * through a relation; each is a model's `where`, admitted once when the\n * extension is applied, or the name of one of its `verbs` predicates. Where a\n * filter takes a value, `{ control: \"<name>\", path?: \"a.b\" }` takes the value\n * the call passed for that control (or a field of it), `{ now: true }` the\n * call's instant, and `{ $if: … }` tests a call value. An absent value\n * (`null` included) matches nothing where its control is required, and drops\n * its filter where it is not.\n *\n * `verbs` judges, per model, what a call may do to the rows it sees: a mode\n * only narrows them (R8).\n */\nexport type RowsContribution = {\n readonly control: string;\n readonly default: string;\n readonly models: {\n readonly [model: string]: {\n readonly [mode: string]: {\n readonly root?: ScalarFields | string;\n readonly related?: ScalarFields | string;\n };\n };\n };\n readonly verbs?: { readonly [model: string]: RowsVerbs };\n};\n\n/**\n * One model's named predicates, each a `where` admitted once, and the verbs\n * that take them. `read` ANDs with every mode's `root` and `related`; a write\n * takes its verb's beside them: a delete `delete`'s, an update, for each\n * field its data writes, that field's `writes` entry, else `update`'s, and\n * `update`'s when its data writes only stamps. A join row's change is a write\n * of the relation on both rows it links; a row only addressed to reach its\n * children is read. A verb left out matches nothing.\n *\n * The row a write produces is judged too, as a value, against the rows as\n * they stand before the write, inside the statement that writes it (R4): a\n * created row at `place` (a model naming none is not judged on create); an\n * updated row at the predicates that judged its old row, and, for each field\n * its data writes, at that field's `moves` entry, and where it writes the\n * key of an `acyclic` relation (a to-one relation of the model to itself),\n * outside its own subtree. A refused row is written by no statement.\n *\n * `evidence` declares a projection key (`evidence.as`) a `select` or\n * `include` may name at every depth, on reads and on the rows a write\n * returns: per row, whether each of `names` holds there beside `read`, or,\n * `ordered`, the last of them that holds (`null` on a row `read` does not\n * hold). `reads` gates a field on a predicate: the row carries it only where\n * `read` and that predicate hold, a `select` naming it fails on a row\n * without them, and every operand a call writes over it (`where`, `orderBy`,\n * aggregates, `distinct`, unique lookups, relation filters) reads it as\n * absent there. A key or foreign-key field is never gated.\n */\nexport type RowsVerbs = {\n readonly predicates: { readonly [name: string]: ScalarFields };\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n readonly writes?: { readonly [field: string]: string };\n readonly place?: string;\n readonly moves?: { readonly [field: string]: string };\n readonly acyclic?: readonly string[];\n readonly evidence?: {\n readonly as: string;\n readonly names: readonly string[];\n readonly ordered?: boolean;\n };\n readonly reads?: { readonly [field: string]: string };\n};\n\n/**\n * What a delete does on the models named here: an update that stamps `at`\n * with the call's time and writes `assign`, unless the call's controls match\n * `removeWhen`.\n */\nexport type DeletionContribution = {\n readonly removeWhen?: {\n readonly [control: string]: string | number | boolean;\n };\n readonly models: {\n readonly [model: string]: {\n readonly at?: string;\n readonly assign?: ScalarFields;\n };\n };\n};\n\n/**\n * Fields an extension writes on the models named here: `create` on every\n * create of the model, `update` on every update of it, a soft delete's\n * included. A value is a constant, `{ control: \"<name>\", path?: \"a.b\" }` for\n * the value the call passed for that control or a field of it (a call that\n * passed none writes nothing there), `{ now: true }` for the call's instant,\n * or, on `update`, one of the field's update operators (`{ increment: 1 }`). A field is written only where the caller left it\n * out: a call that writes it itself, or writes the relation whose foreign key\n * holds it, keeps its own value there. A create may leave out such a field\n * even where the schema requires it: the call's data is checked with it\n * counted as given. When the model names here are known to the types\n * (written out, or kept by a `const` type parameter, not a plain\n * `string[]`), the extended client's types agree, nested creates included:\n * the field is optional on a create. When two extensions name a field, the\n * later one writes it, and a value the caller writes wins over both.\n */\nexport type DataContribution = {\n readonly models: {\n readonly [model: string]: {\n readonly create?: ScalarFields;\n readonly update?: ScalarFields;\n };\n };\n};\n\n// =============================================================================\n// CONTROL STATE: what a chain's controls add to each (model, operation)\n// =============================================================================\n\n/** Operations that select candidates: where a rows control is accepted. */\ntype CandidateOperations = Exclude<Operations, \"create\" | \"createMany\">;\n\n/** One declared control as the delegates see it. */\nexport interface PlacedControl<\n Value = unknown,\n Models = PropertyKey,\n Placed = Operations,\n> {\n readonly value: Value;\n readonly models: Models;\n readonly operations: Placed;\n}\n\nexport type NoControls = Record<never, never>;\n\ntype ControlValue<Declaration> = Declaration extends {\n readonly oneOf: readonly (infer Value)[];\n}\n ? Value\n : Declaration extends { readonly schema: StandardSchemaV1<infer Input> }\n ? Input\n : never;\n\ntype PlacementOperations<On> = On extends \"reads\"\n ? CacheableOperations\n : On extends \"writes\"\n ? MutationOperations\n : On extends readonly (infer Operation)[]\n ? Operation\n : Operations;\n\n/**\n * `deletion` places the control `removeWhen` names: on the deletes of the\n * models it manages, whatever the declaration's `on` says.\n */\ntype PlaceControl<Name, Declaration, Deletion> = Deletion extends {\n readonly removeWhen: infer RemoveWhen;\n readonly models: infer Managed;\n}\n ? Name extends keyof RemoveWhen\n ? PlacedControl<\n ControlValue<Declaration>,\n keyof Managed,\n \"delete\" | \"deleteMany\"\n >\n : PlaceFreeControl<Declaration>\n : PlaceFreeControl<Declaration>;\n\ntype PlaceFreeControl<Declaration> = PlacedControl<\n ControlValue<Declaration>,\n PropertyKey,\n PlacementOperations<\n Declaration extends { readonly on: infer On } ? On : \"all\"\n >\n>;\n\ntype DeclaredControls<Definition> = Definition extends {\n readonly controls: infer Controls extends ControlsContribution;\n}\n ? {\n readonly [Name in keyof Controls as Controls[Name] extends {\n readonly bound: true;\n }\n ? never\n : Name]: PlaceControl<\n Name,\n Controls[Name],\n Definition extends { readonly deletion: infer Deletion }\n ? Deletion\n : unknown\n >;\n }\n : NoControls;\n\n/** Every model entry declares the same mode names: those are the values. */\ntype RowsModes<Rows extends RowsContribution> =\n | Rows[\"default\"]\n | {\n [Model in keyof Rows[\"models\"]]: keyof Rows[\"models\"][Model];\n }[keyof Rows[\"models\"]];\n\n/** The rows control: every candidate-selecting operation of every model. */\ntype RowsControl<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? {\n readonly [Name in Rows[\"control\"]]: PlacedControl<\n RowsModes<Rows>,\n PropertyKey,\n CandidateOperations\n >;\n }\n : NoControls;\n\n/**\n * The models one definition's `rows` can hide from a relation read: its\n * `models` and `verbs` keys. A to-one relation that targets one of them reads `null` when\n * its target is hidden, so the result types widen it (`result-types.ts`).\n */\nexport type RowsModels<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? Extract<\n | keyof Rows[\"models\"]\n | (Rows extends { readonly verbs: infer Verbs } ? keyof Verbs : never),\n string\n >\n : never;\n\n/** The controls one definition places, keyed by control name. */\nexport type DefinitionControls<Definition> = DeclaredControls<Definition> &\n RowsControl<Definition>;\n\n/** The optional control arguments one (model, operation) accepts. */\nexport type OperationControls<Controls, ModelName, Operation> = {\n readonly [Name in keyof Controls as Controls[Name] extends PlacedControl<\n unknown,\n infer Models,\n infer Placed\n >\n ? ModelName extends Models\n ? Operation extends Placed\n ? Name\n : never\n : never\n : never]?: Controls[Name] extends PlacedControl<infer Value>\n ? Value\n : never;\n};\n\n// =============================================================================\n// DATA STATE: the fields a chain's `data` writes, per model\n// =============================================================================\n\n/**\n * The fields one `data` entry writes on its models' creates: there they may\n * be left out even where the schema requires them. An update's fields need\n * nothing, as every field of an update is optional already.\n */\nexport interface StampedFields<Models = PropertyKey, Fields = PropertyKey> {\n readonly models: Models;\n readonly fields: Fields;\n}\n\ntype CreateStamps<Model, Entry> = \"create\" extends keyof Entry\n ? Entry extends { readonly create?: infer Fields }\n ? StampedFields<Model, keyof NonNullable<Fields>>\n : never\n : never;\n\n/**\n * What one definition's `data` writes on creates: one member per model. A\n * definition whose model names are lost (`{ [model: string]: ... }`, as a\n * recipe called with a plain `string[]` builds) writes nothing the types can\n * name: its required fields stay required in the payloads.\n */\nexport type DefinitionData<Definition> = Definition extends {\n readonly data: { readonly models: infer Models };\n}\n ? string extends keyof Models\n ? never\n : {\n [Model in keyof Models]: CreateStamps<Model, Models[Model]>;\n }[keyof Models]\n : never;\n\n/** The fields a chain writes on every create of one model. */\nexport type StampedFieldNames<Data, ModelName> =\n Data extends StampedFields<infer Models, infer Fields extends PropertyKey>\n ? ModelName extends Models\n ? Fields\n : never\n : never;\n\n// =============================================================================\n// PLACEMENT: where each declared control is accepted\n// =============================================================================\n\n/** Where a control goes when its declaration names a placement. */\nconst PLACEMENTS: Readonly<\n Record<\"reads\" | \"writes\" | \"all\", ReadonlySet<string>>\n> = {\n reads: new Set([...ROUTED_OPERATIONS].filter(isReadOperation)),\n writes: new Set([...ROUTED_OPERATIONS].filter(isWriteOperation)),\n all: ROUTED_OPERATIONS,\n};\n\n/** Every operation that selects candidates: where a `rows` control goes. */\nconst CANDIDATE_OPERATIONS: ReadonlySet<string> = new Set(\n [...ROUTED_OPERATIONS].filter(\n (operation) => operation !== \"create\" && operation !== \"createMany\"\n )\n);\n\n/** Where a `deletion.removeWhen` control goes, on the models it manages. */\nconst DELETE_OPERATIONS: ReadonlySet<string> = new Set([\n \"delete\",\n \"deleteMany\",\n]);\n\n/** One control of a chain: its owner, its placement and how a value is admitted. */\nexport interface ResolvedControl {\n readonly name: string;\n readonly extension: string;\n readonly declaration: ControlDeclaration;\n /** The operations that accept it. */\n readonly operations: ReadonlySet<string>;\n /** The models that accept it; every model when absent. */\n readonly models?: ReadonlySet<string>;\n /**\n * Where a call that does not pass it is refused: on every model that\n * accepts it (`true`), on these models only, or nowhere when absent.\n */\n readonly required?: true | ReadonlySet<string>;\n /** What an absent argument admits: the `rows` control's default mode. */\n readonly fallback?: ControlLiteral;\n /** Accepted only from a binding, never read from the arguments. */\n readonly bound?: true;\n /** A read holding a value of it is not served from the cache. */\n readonly uncacheable?: true;\n}\n\n/**\n * Give every control of one definition its placement. A control\n * `deletion.removeWhen` names goes on the deletes of the models `deletion`\n * manages; the `rows` control on every candidate-selecting operation of every\n * model, its values the mode names; every other control where its own `on`\n * says (every operation without one), on every model. A `required` control\n * is asked for only on the models the definition names in `rows`, `data` or\n * `deletion`, and on every model when it names none.\n */\nexport function placeControls(\n definition: RuntimeExtensionDefinition\n): readonly ResolvedControl[] {\n const placed: ResolvedControl[] = [];\n const { name: extension, controls, rows, deletion, data } = definition;\n const removeWhen = deletion?.removeWhen ?? {};\n const managed = new Set(Object.keys(deletion?.models ?? {}));\n const named = new Set([\n ...managed,\n ...Object.keys(rows?.models ?? {}),\n ...Object.keys(rows?.verbs ?? {}),\n ...Object.keys(data?.models ?? {}),\n ]);\n const requiredOn = named.size === 0 ? true : named;\n for (const [name, declaration] of Object.entries(controls ?? {})) {\n const removes = Object.hasOwn(removeWhen, name);\n placed.push({\n name,\n extension,\n declaration,\n operations: removes ? DELETE_OPERATIONS : placementOf(declaration.on),\n models: removes ? managed : undefined,\n required: declaration.required === true ? requiredOn : undefined,\n ...(declaration.bound === true && { bound: true }),\n ...(declaration.uncacheable === true && { uncacheable: true }),\n });\n }\n if (rows !== undefined) {\n placed.push({\n name: rows.control,\n extension,\n declaration: Object.freeze({ oneOf: Object.freeze(rowsModes(rows)) }),\n operations: CANDIDATE_OPERATIONS,\n fallback: rows.default,\n });\n }\n return placed;\n}\n\nfunction placementOf(on: ControlDeclaration[\"on\"]): ReadonlySet<string> {\n if (on === undefined) return ROUTED_OPERATIONS;\n return typeof on === \"string\" ? PLACEMENTS[on] : new Set<string>(on);\n}\n\n/**\n * The `rows` control's values: the mode names, which every model entry\n * declares alike, or the default alone when no model is named.\n */\nexport function rowsModes(rows: RowsContribution): readonly string[] {\n const [modes] = Object.values(rows.models);\n return modes === undefined ? [rows.default] : Object.keys(modes);\n}\n\n// =============================================================================\n// ADMISSION: one call's controls, removed and validated once\n// =============================================================================\n\n/**\n * The controls one call admitted, by name. A `rows` control is resolved to its\n * mode, so an absent one reads as its default; an absent plain control is not\n * here.\n */\nexport type AdmittedControls = Readonly<Record<string, unknown>>;\n\nexport interface ControlAdmission {\n /** The arguments without their controls; the input itself when none was given. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly controls: AdmittedControls | undefined;\n}\n\n/** The admitted values {@link snapshotControlValue} copied: the stable ones. */\nconst snapshots = new WeakSet<object>();\n\n/**\n * An admitted value as the call holds it from here on. Plain data is copied\n * once and frozen, so every reader of the call's controls (the rows its\n * filters bind, the key its cached read is stored under, its handlers) reads\n * the same value whatever the caller later does to its own. A value already\n * fixed all the way down is kept by identity. A value a copy would change\n * (a non-enumerable or symbol property, which `structuredClone` drops; a\n * getter, whose answer only calling it shows), one that resists inspection,\n * one with no canonical spelling, or one that cannot be copied (a Proxy), is\n * kept as given, as are bytes (an indexed write survives `freeze`); a copy\n * that still holds a `Date` is kept but not stable (`setTime` survives it). In\n * those cases the call binds the value for itself alone and its read is not\n * cached.\n */\nexport function snapshotControlValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n if (!isCanonicalKeyData(value)) return value;\n let capture: ReturnType<typeof captureOf>;\n try {\n capture = captureOf(value, new WeakSet());\n } catch {\n // A Proxy may answer the canonical check and refuse a later reflection.\n return value;\n }\n if (capture === \"opaque\") return value;\n if (capture === \"fixed\") {\n snapshots.add(value);\n return value;\n }\n let copy: object;\n try {\n copy = structuredClone(value);\n } catch {\n return value;\n }\n if (freezeCopy(copy)) snapshots.add(copy);\n return copy;\n}\n\n/**\n * How an admitted value can be held: `fixed` when nothing reachable from it\n * can change (frozen own data properties only, no `Date`), `copy` when a\n * copy reproduces it (enumerable string-keyed data properties), `opaque`\n * when a copy might not (a non-enumerable or symbol property, or a getter,\n * never called here) or would not fix it (bytes).\n */\nfunction captureOf(\n value: object,\n seen: WeakSet<object>\n): \"fixed\" | \"copy\" | \"opaque\" {\n // Bytes are never stable (an indexed write survives `freeze`), and their\n // own properties are one per byte: kept as given, unread.\n if (ArrayBuffer.isView(value)) return \"opaque\";\n if (seen.has(value)) return \"fixed\";\n seen.add(value);\n let capture: \"fixed\" | \"copy\" =\n value instanceof Date || !Object.isFrozen(value) ? \"copy\" : \"fixed\";\n const array = Array.isArray(value);\n for (const key of Reflect.ownKeys(value)) {\n if (array && key === \"length\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (\n typeof key === \"symbol\" ||\n !descriptor.enumerable ||\n !(\"value\" in descriptor)\n )\n return \"opaque\";\n const entry: unknown = descriptor.value;\n if (typeof entry !== \"object\" || entry === null) continue;\n const inner = captureOf(entry, seen);\n if (inner === \"opaque\") return \"opaque\";\n if (inner === \"copy\") capture = \"copy\";\n }\n return capture;\n}\n\n/** Freeze a private copy; answer whether nothing in it can still change. */\nfunction freezeCopy(value: object): boolean {\n if (value instanceof Date) return false;\n let fixed = true;\n for (const entry of Object.values(value))\n if (typeof entry === \"object\" && entry !== null && !freezeCopy(entry))\n fixed = false;\n Object.freeze(value);\n return fixed;\n}\n\n/**\n * Whether a control value is the one admission fixed: a primitive, or plain\n * data {@link snapshotControlValue} copied. Only such a value may key anything that\n * outlives the call (a bound-facts memo, a cache entry).\n */\nexport function isStableControlValue(value: unknown): boolean {\n return typeof value !== \"object\" || value === null || snapshots.has(value);\n}\n\n/**\n * Remove every control placed on this operation from its arguments and admit\n * each once, before any request handler runs. A key naming a control placed\n * elsewhere, or a bound-only one, stays in the arguments, where core\n * validation refuses it as an unknown key. A control the call did not pass\n * takes the value its view binds, if any; without one it is refused here on\n * the models its placement requires it on.\n */\nexport function admitControls(\n model: string,\n operation: Operation,\n input: Record<string, unknown>,\n placed: readonly ResolvedControl[],\n bound?: AdmittedControls\n): ControlAdmission {\n // Arguments that are not an object hold no control: core validation refuses\n // them as it does on a client without controls.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, controls: undefined };\n }\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(input);\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n const admitted: [string, unknown][] = [];\n let given: Set<PropertyKey> | undefined;\n for (const control of placed) {\n const { name, required } = control;\n let raw: unknown;\n if (control.bound !== true && keys.includes(name)) {\n (given ??= new Set()).add(name);\n raw = readControl(input, control, model, operation);\n }\n // A bound value was admitted and fixed once, when its view was bound.\n const value =\n raw === undefined\n ? (bound?.[name] ?? control.fallback)\n : snapshotControlValue(admitControl(control, raw, model, operation));\n if (value !== undefined) admitted.push([name, value]);\n else if (required === true || required?.has(model)) {\n throw invalidControl(control, model, operation, [\"is required\"]);\n }\n }\n return {\n args:\n given === undefined\n ? input\n : withoutControls(input, keys, given, model, operation),\n controls:\n admitted.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(admitted)),\n };\n}\n\n/**\n * The values a view binds after one extension binds its own controls: each\n * admitted once and fixed, over the values the view already binds, a value\n * replacing an earlier one.\n */\nexport function bindControls(\n controls: readonly ResolvedControl[],\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedControls | undefined\n): AdmittedControls {\n const next: Record<string, unknown> = { ...previous };\n for (const [name, raw] of Object.entries(values)) {\n const control = controls.find(\n (candidate) =>\n candidate.name === name && candidate.extension === extension\n );\n if (control === undefined) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" binds control \"${name}\", which it does not declare.`,\n { meta: { extension } }\n );\n }\n next[name] = snapshotControlValue(admitControl(control, raw));\n }\n return Object.freeze(next);\n}\n\n/** One extension's own admitted controls, as its handlers see them. */\nexport function controlsOwnedBy(\n admitted: AdmittedControls | undefined,\n names: readonly string[]\n): AdmittedControls {\n const owned: [string, unknown][] = [];\n for (const name of names) {\n if (admitted !== undefined && Object.hasOwn(admitted, name)) {\n owned.push([name, admitted[name]]);\n }\n }\n return Object.freeze(Object.fromEntries(owned));\n}\n\nfunction readControl(\n input: Record<string, unknown>,\n control: ResolvedControl,\n model: string,\n operation: Operation\n): unknown {\n try {\n return Reflect.get(input, control.name);\n } catch (cause) {\n throw controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" of ${model}.${operation} could not be read`,\n model,\n operation,\n cause\n );\n }\n}\n\n/** The caller's arguments minus the controls, every other descriptor kept. */\nfunction withoutControls(\n input: Record<string, unknown>,\n keys: readonly PropertyKey[],\n controls: ReadonlySet<PropertyKey>,\n model: string,\n operation: Operation\n): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n try {\n for (const key of keys) {\n if (controls.has(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor) Object.defineProperty(args, key, descriptor);\n }\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n return args;\n}\n\n/** One value admitted for a call's (model, operation), or, without them, a binding. */\nfunction admitControl(\n control: ResolvedControl,\n value: unknown,\n model?: string,\n operation?: Operation\n): unknown {\n const { declaration } = control;\n if (\"oneOf\" in declaration) {\n if (declaration.oneOf.some((allowed) => allowed === value)) return value;\n throw invalidControl(control, model, operation, [\n `must be one of ${declaration.oneOf.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n }\n let result: unknown;\n try {\n result = declaration.schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing request transform is.\n if (isVibORMFailure(cause)) throw cause;\n throw validatorFailure(control, model, operation, \"threw\", cause);\n }\n let shape: \"promise\" | \"malformed\" | \"issues\" | \"value\" = \"malformed\";\n let issues: readonly unknown[] = [];\n let admitted: unknown;\n try {\n if (isRecord(result)) {\n const then = \"then\" in result ? result.then : undefined;\n if (isFunction(then)) {\n shape = \"promise\";\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n Reflect.apply(then, result, [undefined, () => undefined]);\n } else {\n const listed = result.issues;\n if (listed !== undefined) {\n if (Array.isArray(listed)) {\n shape = \"issues\";\n issues = listed;\n }\n } else if (\"value\" in result) {\n shape = \"value\";\n admitted = result.value;\n }\n }\n }\n } catch (cause) {\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned an unreadable result\",\n cause\n );\n }\n switch (shape) {\n case \"value\":\n return admitted;\n case \"issues\":\n throw invalidControl(control, model, operation, issueMessages(issues));\n case \"promise\":\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Control validators must return synchronously\")\n );\n default:\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a malformed result\",\n new TypeError(\"A Standard Schema result has a value or an issue list\")\n );\n }\n}\n\n/** Each issue's message; an issue that cannot be read still refuses. */\nfunction issueMessages(issues: readonly unknown[]): string[] {\n const messages: string[] = [];\n try {\n for (const issue of issues) {\n const message = isRecord(issue) ? issue.message : undefined;\n messages.push(typeof message === \"string\" ? message : \"is invalid\");\n }\n } catch {\n return [\"is invalid\"];\n }\n return messages.length === 0 ? [\"is invalid\"] : messages;\n}\n\n/** Contained: `instanceof` on a hostile thrown proxy is itself a throw site. */\nfunction isVibORMFailure(value: unknown): value is VibORMError {\n try {\n return value instanceof VibORMError;\n } catch {\n return false;\n }\n}\n\n/**\n * The refusal of a cached read that holds a value of an `uncacheable`\n * control, or `undefined` when it holds none: such a read is an observation\n * the control's owner does not accept (the cache would serve it after the\n * facts it was judged on changed).\n */\nexport function uncacheableRead(\n controls: readonly ResolvedControl[],\n admitted: AdmittedControls | undefined,\n model: string,\n operation: Operation\n): ValidationError | undefined {\n const held = controls.find(\n (control) =>\n control.uncacheable === true && admitted?.[control.name] !== undefined\n );\n return (\n held &&\n invalidControl(held, model, operation, [\n \"is not cacheable: a read that holds it is not served from the cache\",\n ])\n );\n}\n\nfunction invalidControl(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n operation === undefined\n ? { kind: \"schema-builder\", builder: \"$bind\", path: control.name }\n : { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: control.name,\n message: `Control \"${control.name}\" ${message}`,\n })),\n { meta: { model, extension: control.extension } }\n );\n}\n\nfunction validatorFailure(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n failure: string,\n cause: unknown\n): QueryError {\n return controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" validator for ${operation === undefined ? \"$bind\" : `${model}.${operation}`} ${failure}`,\n model,\n operation,\n cause\n );\n}\n\nfunction controlFailure(\n message: string,\n model: string | undefined,\n operation: Operation | undefined,\n cause: unknown\n): QueryError {\n return new QueryError(`${message}.`, {\n cause: errorCause(cause),\n meta: { model, operation },\n });\n}\n"],"mappings":"kPAmBA,MAAa,EAAsB,eAiCtB,EAA+C,OAAO,OAAO,CACxE,MAAO,OAAO,OAAO,CACnB,OAAQ,OAAO,OAAO,CACpB,YAAa,OAAO,OAAO,CACzB,QAAS,EACT,OAAQ,SACR,SAAW,GACT,OAAO,OAAO,CACZ,MAAO,sBAAsB,CAAC,0BAA0B,EAAM,CAC/D,CAAC,CACL,CAAC,CACH,CAAC,CACF,GAAI,SACL,CAAC,CACH,CAAC,CA4BI,EAAsB,IAAI,QAI1B,EAAqB,IAAI,QAIzB,EAAsB,IAAI,QAIhC,IAAI,EAGJ,SA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EAAU,aAAa,OAE/D,CACN,MAAO,CAAC,aAAa,CAEvB,OAAO,EAAS,SAAW,EAAI,CAAC,aAAa,CAAG,EAIlD,SAAS,gBAAgB,EAAsC,CAC7D,GAAI,CACF,OAAO,aAAiB,OAClB,CACN,MAAO,IAUX,SAAgB,gBACd,EACA,EACA,EACA,EAC6B,CAC7B,IAAM,EAAO,EAAS,KACnB,GACC,EAAQ,cAAgB,IAAQ,IAAW,EAAQ,QAAU,IAAA,GAChE,CACD,OACE,GACA,eAAe,EAAM,EAAO,EAAW,CACrC,sEACD,CAAC,CAIN,SAAS,eACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,IAAc,IAAA,GACV,CAAE,KAAM,iBAAkB,QAAS,QAAS,KAAM,EAAQ,KAAM,CAChE,CAAE,KAAM,YAAa,YAAW,QAAO,CAC3C,EAAS,IAAK,IAAa,CACzB,KAAM,EAAQ,KACd,QAAS,YAAY,EAAQ,KAAK,IAAI,IACvC,EAAE,CACH,CAAE,KAAM,CAAE,QAAO,UAAW,EAAQ,UAAW,CAAE,CAClD,CAGH,SAAS,iBACP,EACA,EACA,EACA,EACA,EACY,CACZ,OAAO,eACL,cAAc,EAAQ,UAAU,aAAa,EAAQ,KAAK,kBAAkB,IAAc,IAAA,GAAY,QAAU,GAAG,EAAM,GAAG,IAAY,GAAG,IAC3I,EACA,EACA,EACD,CAGH,SAAS,eACP,EACA,EACA,EACA,EACY,CACZ,OAAO,IAAI,EAAW,GAAG,EAAQ,GAAI,CACnC,MAAO,EAAW,EAAM,CACxB,KAAM,CAAE,QAAO,YAAW,CAC3B,CAAC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-DyEHMdJg.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function decodeProviderTimestamp(e){let t=c.exec(e);if(!t)return;let n=t[13]?1-Number(t[1]):Number(t[1]),o=Number(t[2]),s=Number(t[3]),l=Number(t[4]),u=Number(t[5]),d=Number(t[6]),f=Number(t[10]??0),p=Number(t[11]??0),m=Number(t[12]??0);if(!(a(n,o,s)&&r(l,u,d))||f>23||p>59||m>59)return;let h=new Date(0);h.setUTCFullYear(n,o-1,s),h.setUTCHours(l,u,d,Number((t[7]??``).padEnd(3,`0`).slice(0,3)));let g=(f*3600+p*60+m)*1e3,_=h.getTime()-(t[9]===`-`?-g:g);return i(_)?new Date(_):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
|
|
2
|
-
//# sourceMappingURL=datetime-physical-codec-BEqQbIP_.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"datetime-physical-codec-BEqQbIP_.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OA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AAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-mapping-C9WgitPi.mjs","names":["providerSettledBeforeCallback","settledOutcome"],"sources":["../src/errors/constraints.ts","../src/errors/record-series-progress.ts","../src/query-engine/types.ts","../src/errors/logged-errors.ts","../src/drivers/shared/transactions.ts","../src/drivers/driver-error-context.ts","../src/drivers/error-mapping.ts"],"sourcesContent":["import { VibORMError, VibORMErrorCode, type VibORMErrorOptions } from \"./base\";\n\n/**\n * Unique constraint violation\n */\nexport class UniqueConstraintError extends VibORMError {\n static override readonly diagnosticName = \"UniqueConstraintError\";\n\n /** Literal discriminant: this class always carries `UNIQUE_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.UNIQUE_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.UNIQUE_CONSTRAINT, options);\n }\n}\n\n/**\n * Foreign key constraint violation\n */\nexport class ForeignKeyError extends VibORMError {\n static override readonly diagnosticName = \"ForeignKeyError\";\n\n /** Literal discriminant: this class always carries `FOREIGN_KEY_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.FOREIGN_KEY_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.FOREIGN_KEY_CONSTRAINT, options);\n }\n}\n\n/**\n * Not-null constraint violation\n */\nexport class NotNullConstraintError extends VibORMError {\n static override readonly diagnosticName = \"NotNullConstraintError\";\n\n /** Literal discriminant: this class always carries `NOT_NULL_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.NOT_NULL_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.NOT_NULL_CONSTRAINT, options);\n }\n}\n\n/**\n * Check constraint violation\n */\nexport class CheckConstraintError extends VibORMError {\n static override readonly diagnosticName = \"CheckConstraintError\";\n\n /** Literal discriminant: this class always carries `CHECK_CONSTRAINT`. */\n declare readonly code: typeof VibORMErrorCode.CHECK_CONSTRAINT;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.CHECK_CONSTRAINT, options);\n }\n}\n\n/**\n * Value too long for the column's declared type (Prisma P2000)\n *\n * Raised where the database enforces a column length: PostgreSQL SQLSTATE 22001\n * (`string_data_right_truncation`) and MySQL errno 1406 (`ER_DATA_TOO_LONG`).\n *\n * **SQLite raises nothing comparable.** SQLite ignores declared type lengths entirely\n * (`VARCHAR(5)` stores any string), so an over-long value is written, not rejected; the only\n * related error, `SQLITE_TOOBIG`, fires at the ~1GB `SQLITE_MAX_LENGTH` limit and means a\n * different thing. Prisma behaves the same way — quaint's SQLite connector has no arm for it,\n * so it falls through to a generic query error rather than P2000\n * (`quaint/src/connector/sqlite/error.rs`). VibORM therefore keeps `QueryError` on SQLite\n * instead of manufacturing a P2000 that the engine cannot honestly promise.\n */\nexport class ValueTooLongError extends VibORMError {\n static override readonly diagnosticName = \"ValueTooLongError\";\n\n /** Literal discriminant: this class always carries `VALUE_TOO_LONG`. */\n declare readonly code: typeof VibORMErrorCode.VALUE_TOO_LONG;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.VALUE_TOO_LONG, options);\n }\n}\n\n/**\n * Type guard for unique constraint errors\n */\nexport function isUniqueConstraintError(\n error: unknown\n): error is UniqueConstraintError {\n return error instanceof UniqueConstraintError;\n}\n\n/**\n * Type guard for foreign key errors\n */\nexport function isForeignKeyError(error: unknown): error is ForeignKeyError {\n return error instanceof ForeignKeyError;\n}\n\n/**\n * Type guard for not-null constraint errors\n */\nexport function isNotNullConstraintError(\n error: unknown\n): error is NotNullConstraintError {\n return error instanceof NotNullConstraintError;\n}\n\n/**\n * Type guard for check constraint errors\n */\nexport function isCheckConstraintError(\n error: unknown\n): error is CheckConstraintError {\n return error instanceof CheckConstraintError;\n}\n\n/**\n * Type guard for value-too-long errors\n */\nexport function isValueTooLongError(\n error: unknown\n): error is ValueTooLongError {\n return error instanceof ValueTooLongError;\n}\n","import { isVibORMError, type VibORMError } from \"./base\";\nimport {\n getTrustedRecordSeriesProgress,\n type RecordSeriesProgress,\n registerTrustedRecordSeriesProgress,\n sanitizeRecordSeriesProgress,\n} from \"./diagnostics\";\nimport { QueryEngineError } from \"./query\";\n\n/**\n * Enrich the owned failure after segment-atomic execution has stopped. The\n * database executor supplies counters only; this errors-layer boundary validates\n * them, updates direct metadata, and updates trusted serialization together.\n */\nexport function attachRecordSeriesProgress<T extends VibORMError>(\n error: T,\n progress: RecordSeriesProgress\n): T;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown {\n const ownedError = isVibORMError(error)\n ? error\n : new QueryEngineError(\n \"Record-series execution failed at a committed-segment boundary.\",\n error instanceof Error ? { cause: error } : undefined\n );\n // One failure crosses one terminal series boundary. If a wrapper encounters\n // the same error again, retain the first trusted observation so public\n // metadata and trusted serialization cannot diverge.\n const trusted = getTrustedRecordSeriesProgress(ownedError);\n const sanitized = trusted ?? sanitizeRecordSeriesProgress(progress);\n if (!sanitized) return error;\n Object.defineProperty(ownedError.meta, \"recordSeriesProgress\", {\n configurable: true,\n enumerable: true,\n value: sanitized,\n writable: true,\n });\n if (!trusted) {\n registerTrustedRecordSeriesProgress(ownedError, sanitized);\n }\n return ownedError;\n}\n\n/** A committed prefix forbids the routed whole-operation retry. */\nexport function hasCommittedRecordSeriesProgress(error: unknown): boolean {\n if (!isVibORMError(error)) return false;\n const progress = getTrustedRecordSeriesProgress(error);\n return (\n (progress?.committedSegments ?? 0) > 0 ||\n progress?.mayHaveCommittedSegment === true\n );\n}\n","/**\n * Query Engine Types\n *\n * Shared types used across the query engine.\n */\n\nimport type { DatabaseAdapter } from \"@adapters\";\nimport type { QueryExecutionContext } from \"@drivers/driver\";\nimport type { QueryResult } from \"@drivers/types\";\nimport type { Model } from \"@schema/model\";\nimport type { RelationCardinality } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type {\n ResolvedRelationIndex,\n ResolvedSlot,\n ResolvedVariantJunctionEdge,\n ResolvedVariantJunctionMember,\n ResolvedVariantRowEdge,\n ResolvedVariantRowMember,\n} from \"@schema/validation/relation-resolution\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\n\n// Re-export errors from unified error hierarchy\nexport {\n NestedWriteError,\n NotFoundError,\n QueryEngineError,\n ValidationError,\n} from \"@errors\";\n// Re-export Sql for convenience\nexport { Sql } from \"@sql\";\n\n// ============================================================\n// BATCH EXECUTION TYPES\n// ============================================================\n\n/** Raw rows/count produced by one mutation result-emulation scope. */\nexport interface MutationQueryResult {\n rows: Record<string, unknown>[];\n rowCount: number;\n}\n\n/**\n * Prepared query ready for batch execution\n */\nexport interface PreparedQuery {\n /** SQL string */\n sql: string;\n /** Query parameters */\n params: unknown[];\n /** Immutable attribution captured when the ORM operation was created. */\n context: QueryExecutionContext;\n}\n\n/**\n * One logical operation expanded into driver-level batch queries.\n */\nexport interface PreparedBatchOperation<T = unknown> {\n queries: PreparedQuery[];\n guards?: PreparedBatchGuard[];\n parseResult: (results: QueryResult<unknown>[]) => T;\n}\n\n/**\n * What a prepared guard publishes when its premise does not hold: the typed\n * failure taxonomy plus the `raceable` bit fixed by the guard's premise class.\n * `batch-error-attribution.ts` is the one algorithm that reads it, and the one\n * place it becomes an `Error`.\n */\nexport interface PreparedGuardFailure {\n readonly kind:\n | \"foreignKey\"\n | \"forbidden\"\n | \"nestedWrite\"\n | \"notFound\"\n | \"query\";\n readonly message: string;\n readonly relation?: string;\n readonly raceable: boolean;\n}\n\n/** Declarative ownership for one assertion query in a prepared operation. */\nexport interface PreparedBatchGuard {\n readonly queryIndex: number;\n readonly premise: \"exists\" | \"notExists\";\n readonly probe: import(\"@sql\").Sql;\n readonly failure: PreparedGuardFailure;\n readonly model: string;\n readonly operation: Operation;\n}\n\n/**\n * Options for engine.prepare()\n */\nexport interface PrepareOptions {\n /** Throw NotFoundError if result is null (for OrThrow variants) */\n throwIfNotFound?: boolean;\n /** Original operation name for error messages */\n originalOperation?: string;\n /**\n * The cache driver manages this execution: the operation completion closes\n * and hands over its cache outcome list.\n */\n skipSpan?: boolean;\n}\n\n/**\n * All supported operations.\n *\n * NOTE — `createManyAndReturn` / `updateManyAndReturn` / `deleteManyAndReturn`\n * are INTERNAL names, not client operations. The public surface has ONE name per\n * bulk family (maintainer decision D-1): `createMany` / `updateMany` /\n * `deleteMany` take an optional `select`, and its presence routes the tree to the\n * row-returning arm. These three tokens name that arm inside the SQL-building\n * substrate (result shape, program lowering, identity helpers); the client never\n * spells them, and they share their family's arg schema.\n */\nexport const OPERATIONS = [\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"create\",\n \"createMany\",\n \"createManyAndReturn\",\n \"update\",\n \"updateMany\",\n \"updateManyAndReturn\",\n \"delete\",\n \"deleteMany\",\n \"deleteManyAndReturn\",\n \"upsert\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n] as const;\n\nexport type Operation = (typeof OPERATIONS)[number];\n\n/** Operations that return BatchPayload { count: number } */\nexport const BATCH_OPERATIONS = [\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n] as const;\nexport type BatchOperation = (typeof BATCH_OPERATIONS)[number];\n\n/** Check if operation is a batch operation */\nexport function isBatchOperation(op: Operation): op is BatchOperation {\n return (BATCH_OPERATIONS as readonly string[]).includes(op);\n}\n\n/** Requested fields inside one aggregate JSON carrier. */\nexport interface ExpectedAggregateResultShape {\n /** Undefined only for the scalar `_count: true` result. */\n fields?: ReadonlySet<string>;\n}\n\n/**\n * One arm of a polymorphic projection that the selection reads\n * (`selectedArm`, result/result-shape.ts); an arm `only` excludes is absent.\n */\nexport interface ExpectedPolymorphicVariantShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n}\n\n/** Exact target-specific result contracts for one polymorphic projection. */\nexport interface ExpectedPolymorphicResultShape {\n /** Which carrier the read emitted: the singular tagged CASE, or the collection document. */\n readonly cardinality: \"one\" | \"many\";\n readonly optional: boolean;\n readonly variants: ReadonlyMap<string, ExpectedPolymorphicVariantShape>;\n}\n\n/** Exact public result contract for one ordinary relation projection. */\nexport interface ExpectedRelationResultShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n readonly cardinality: RelationCardinality;\n readonly optional: boolean;\n /**\n * The admitted recurrence of a recursive slot, the same normalized value\n * execution consumes. `shape` is then the ONE repeated node, and the slot's\n * own key recurs inside every occurrence: absent at a numeric cutoff,\n * present on every occurrence of an exhaustive traversal.\n */\n readonly recurrence?: NormalizedRecurrence;\n}\n\n/** Exact raw columns and nested projections expected for one returned row. */\nexport interface ExpectedResultShape {\n /** Raw statement carrier declared by the compiled operation result. */\n carrier: \"rows\" | \"count\" | \"existence\";\n rawKeys: readonly string[];\n /** Scalar whose selected `_distance` expression produced the private column. */\n readonly distanceScalar?: Scalar;\n relations: ReadonlyMap<string, ExpectedRelationResultShape>;\n polymorphic: ReadonlyMap<string, ExpectedPolymorphicResultShape>;\n aggregates: ReadonlyMap<string, ExpectedAggregateResultShape>;\n relationCounts: ReadonlySet<string>;\n}\n\n/**\n * Minimal SQL-construction state shared by related model scopes.\n *\n * `relations` is the ONE index the composition root resolved, passed by\n * identity: a scope answers every topology question by looking this model's\n * slot up in it, so no scope, model or module holds a second topology view\n * (§8.3, §11.4.10).\n */\nexport interface QueryScope extends ScopeSource {\n readonly model: Model<any>;\n readonly nextAlias: () => string;\n readonly rootAlias: string;\n readonly mutationTable?: string;\n}\n\n/**\n * What a root scope is opened FROM: the dialect and the one resolved index.\n *\n * Both the engine and any existing scope satisfy it, which is what lets the\n * index travel by identity from the composition root to every scope without a\n * wrapper that copies it (§10E.10).\n */\nexport interface ScopeSource {\n readonly adapter: DatabaseAdapter;\n readonly relations: ResolvedRelationIndex;\n}\n\n/**\n * A contextual relation reference: the resolved slot the gate published, plus\n * the two facts a builder ADDRESSES it by.\n *\n * It stores no topology. `name` is the slot's own field key — variant-qualified\n * on a member view, which is what keeps step ids deterministic (§8.3) — and\n * `targetModel`/`cardinality` are projections of the resolved EDGE, taken where\n * the reference is made. There is no declared relation type, no foreign-key\n * field list, no optionality flag and no carrier brand to copy, because\n * `resolved.edge` answers each of those questions itself.\n */\nexport interface RelationRef {\n readonly name: string;\n readonly resolved: ResolvedSlot;\n readonly targetModel: Model<any>;\n readonly cardinality: RelationCardinality;\n}\n\n/** The row-held arm: a private `(type, id)` column pair on the owner's row. */\nexport interface VariantRowCarrierSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantRowEdge;\n /** The public carrier slot spans the edge's complete member collection. */\n readonly member?: never;\n}\n\n/** The collection arm: one member junction table per configured variant. */\nexport interface VariantJunctionCarrierSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantJunctionEdge;\n readonly member?: never;\n}\n\n/**\n * A direct variant relation's carrier slot.\n *\n * Spelled as the UNION of the two arms rather than one shape over the edge\n * union, so that the narrowing guard below SUBTRACTS: a caller that rules out\n * the row-held arm holds the collection arm, with no second test and no cast.\n */\nexport type VariantCarrierSlot =\n | VariantRowCarrierSlot\n | VariantJunctionCarrierSlot;\n\n/**\n * The NARROWING spelling of `carrier.edge.kind === \"variantRowCarrier\"`, for\n * the callers that must pass the CARRIER SLOT itself into a row-held-only slot.\n *\n * It is not a second owner of the question — its body is that one test, and a\n * caller that only needs the answer asks `edge.kind` inline. It exists because\n * the edge is a nested discriminant: testing it narrows the edge reference,\n * never the slot holding it. Same reason, same shape, as\n * `hasPolymorphicMembership` in `relation-data-builder.ts`.\n */\nexport function isVariantRowCarrier(\n carrier: VariantCarrierSlot\n): carrier is VariantRowCarrierSlot {\n return carrier.edge.kind === \"variantRowCarrier\";\n}\n\n/** A bound inverse: one existing member of someone else's row carrier. */\nexport interface VariantRowInverseSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantRowEdge;\n readonly member: ResolvedVariantRowMember;\n}\n\n/** A bound inverse: one existing member of someone else's junction carrier. */\nexport interface VariantJunctionInverseSlot {\n readonly slot: ResolvedSlot[\"slot\"];\n readonly edge: ResolvedVariantJunctionEdge;\n readonly member: ResolvedVariantJunctionMember;\n}\n\n/**\n * The two NARROWING spellings of \"this slot is a bound inverse of that carrier\n * family\", for the callers that must hand the slot's edge and its member to one\n * function together.\n *\n * `edge` is a nested discriminant: testing `edge.kind` narrows the edge alone\n * and leaves `member` the union of both families, which is precisely the pairing\n * these two exist to keep. They are two because the two member records are two\n * types — one predicate returning either would hand its caller the union back.\n */\nexport function isVariantRowInverse(\n resolved: ResolvedSlot\n): resolved is VariantRowInverseSlot {\n return (\n resolved.edge.kind === \"variantRowCarrier\" && resolved.member !== undefined\n );\n}\n\nexport function isVariantJunctionInverse(\n resolved: ResolvedSlot\n): resolved is VariantJunctionInverseSlot {\n return (\n resolved.edge.kind === \"variantJunctionCarrier\" &&\n resolved.member !== undefined\n );\n}\n\n/**\n * One member of a row carrier, selected by a payload's public discriminator.\n *\n * The two objects the gate published, carried together — never a copy of their\n * contents, and never a synthesized relation (§8.3, D9). `ref` is the addressing\n * view the write parts spell error sentences and step ids with.\n */\nexport interface SelectedVariantRow {\n readonly carrier: VariantRowCarrierSlot;\n readonly member: ResolvedVariantRowMember;\n readonly ref: RelationRef;\n}\n\n/** One member of a junction carrier, selected by a payload's discriminator. */\nexport interface SelectedVariantMember {\n readonly carrier: VariantJunctionCarrierSlot;\n readonly member: ResolvedVariantJunctionMember;\n readonly ref: RelationRef;\n}\n\n// ============================================================\n// NARROWER TYPE DEFINITIONS\n// These provide better autocomplete and error messages\n// ============================================================\n\n/**\n * Scalar filter operators for where clauses\n */\nexport interface ScalarFilter<T = unknown> {\n equals?: T | null;\n not?: T | ScalarFilter<T> | null;\n in?: T[];\n notIn?: T[];\n lt?: T;\n lte?: T;\n gt?: T;\n gte?: T;\n}\n\n/**\n * String-specific filter operators\n */\nexport interface StringFilter extends ScalarFilter<string> {\n contains?: string;\n startsWith?: string;\n endsWith?: string;\n mode?: \"default\" | \"insensitive\";\n}\n\n/**\n * Array/list filter operators\n */\nexport interface ArrayFilter<T = unknown> {\n has?: T;\n hasEvery?: T[];\n hasSome?: T[];\n isEmpty?: boolean;\n}\n\n/**\n * Relation filter for to-one relations\n */\nexport interface ToOneRelationFilter {\n is?: WhereInput | null;\n isNot?: WhereInput | null;\n}\n\n/**\n * Relation filter for to-many relations\n */\nexport interface ToManyRelationFilter {\n some?: WhereInput;\n every?: WhereInput;\n none?: WhereInput;\n}\n\n/**\n * Where input for filtering records\n */\nexport interface WhereInput {\n AND?: WhereInput | WhereInput[];\n OR?: WhereInput[];\n NOT?: WhereInput | WhereInput[];\n [field: string]:\n | unknown\n | ScalarFilter\n | StringFilter\n | ArrayFilter\n | ToOneRelationFilter\n | ToManyRelationFilter\n | WhereInput\n | WhereInput[]\n | undefined;\n}\n\n/**\n * Order by direction\n */\nexport type SortOrder = \"asc\" | \"desc\";\n\n/**\n * Order by input for sorting\n */\nexport interface OrderByInput {\n [field: string]: SortOrder | OrderByInput;\n}\n\n/**\n * Select input for field selection\n */\nexport interface SelectInput {\n [field: string]: boolean | SelectInput | IncludeInput;\n}\n\n/**\n * Include input for relation inclusion\n */\nexport interface IncludeInput {\n [relation: string]:\n | boolean\n | {\n select?: SelectInput;\n include?: IncludeInput;\n where?: WhereInput;\n orderBy?: OrderByInput | OrderByInput[];\n take?: number;\n skip?: number;\n };\n}\n\n/**\n * Numeric update operations\n */\nexport interface NumericUpdateOperations<T = number> {\n set?: T;\n increment?: T;\n decrement?: T;\n multiply?: T;\n divide?: T;\n}\n\n/**\n * Array update operations\n */\nexport interface ArrayUpdateOperations<T = unknown> {\n set?: T[];\n push?: T | T[];\n}\n\n/**\n * Update data input\n */\nexport interface UpdateInput {\n [field: string]: unknown | NumericUpdateOperations | ArrayUpdateOperations;\n}\n\n/**\n * Create data input\n */\nexport interface CreateInput {\n [field: string]: unknown;\n}\n\n/**\n * Aggregate filter for HAVING clause\n */\nexport interface AggregateFilter {\n equals?: number;\n not?: number | null;\n gt?: number;\n gte?: number;\n lt?: number;\n lte?: number;\n in?: number[];\n notIn?: number[];\n}\n\n/**\n * Having input for groupBy\n */\nexport interface HavingInput {\n _count?: Record<string, AggregateFilter>;\n _avg?: Record<string, AggregateFilter>;\n _sum?: Record<string, AggregateFilter>;\n _min?: Record<string, AggregateFilter>;\n _max?: Record<string, AggregateFilter>;\n [field: string]:\n | unknown\n | AggregateFilter\n | Record<string, AggregateFilter>\n | undefined;\n}\n","/**\n * Cross-layer record of errors core has already selected for a log.\n *\n * One failure crosses two observers: the driver's statement completion selects\n * the failing *statement* for the error log and the query engine's operation\n * completion selects the failing *operation*. Both would report the same error\n * object, so the statement completion marks what it selected, synchronously,\n * and the operation completion skips anything already marked. Core selects and\n * marks; the official instrumentation extension only formats. The record lives\n * in `src/errors/` so that core has no runtime edge into the extension.\n *\n * ## Why a module-scoped WeakSet, and not the instrumentation context\n *\n * The de-duplication marker does not belong in the instrumentation context: it\n * describes one thrown error, not the client-wide observer configuration, and\n * the same context serves concurrent operations.\n *\n * ## Why not a property on the error\n *\n * The error is handed to the caller. Stamping it (the former\n * `Object.defineProperty(error, \"logged\", …)`) made an internal\n * de-duplication convention part of the public error's shape, and it could not\n * mark a frozen error at all — such an error was logged twice.\n *\n * ## Serverless note\n *\n * `src/instrumentation/AGENTS.md` Rule 3 keeps mutable state out of module\n * scope so nothing survives a request in a reused isolate. A `WeakSet` holds\n * no strong reference: an entry disappears with the error that keyed it, and\n * an error object never outlives the request that threw it. There is nothing\n * here to go stale, and nothing to grow.\n */\n\nconst loggedErrors = new WeakSet<Error>();\n\n/** Record that core has selected this error for a log. */\nexport function markErrorLogged(error: Error): void {\n loggedErrors.add(error);\n}\n\n/** Preserve the report record when package code replaces one failure with its successor. */\nexport function transferLoggedErrorEvidence(\n source: Error,\n successor: Error\n): void {\n if (loggedErrors.has(source)) loggedErrors.add(successor);\n}\n\n/** Whether core has already selected this error for a log. */\nexport function isErrorLogged(error: Error): boolean {\n return loggedErrors.has(error);\n}\n","import { TransactionError } from \"@errors\";\nimport type { TransactionPhaseNotifications } from \"../execution-context\";\n\nexport function nestedTransactionDispatchError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" received nested provider state outside TransactionBoundDriver.`,\n { meta: { driver: driverName, method: \"$transaction\" } }\n );\n}\n\nexport function unsupportedCallbackTransactionError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" does not support callback transactions.`,\n { meta: { driver: driverName, method: \"$transaction(callback)\" } }\n );\n}\n\n// A broken provider lifecycle cannot prove whether its handle remains safe.\nexport class ProviderTransactionContractError extends TransactionError {}\n\ntype LifecycleStep = () => unknown | Promise<unknown>;\n\nexport interface TransactionLifecycle<T> {\n readonly begin: LifecycleStep;\n readonly callback: () => Promise<T>;\n readonly commit: LifecycleStep;\n readonly rollback: LifecycleStep;\n readonly close?: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\nexport interface ProviderManagedTransaction<T, TTransaction> {\n readonly run: (\n callback: (tx: TTransaction) => Promise<T>\n ) => Promise<unknown>;\n readonly callback: (tx: TTransaction) => Promise<T>;\n readonly close: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\ntype ProviderCallbackOutcome<T> =\n | { readonly status: \"pending\" }\n | { readonly status: \"fulfilled\"; readonly value: T }\n | { readonly error: unknown; readonly status: \"rejected\" };\n\n/** Close provider-owned transaction state when its own cleanup/finalization fails. */\nexport async function runProviderManagedTransaction<T, TTransaction>(\n lifecycle: ProviderManagedTransaction<T, TTransaction>\n): Promise<T> {\n let callbackCallCount = 0;\n let callbackOutcome: ProviderCallbackOutcome<T> = {\n status: \"pending\",\n };\n const readCallbackOutcome = (): ProviderCallbackOutcome<T> => callbackOutcome;\n let callbackPromise: Promise<T> | undefined;\n let closeAttempted = false;\n const capturedCloseFailures: unknown[] = [];\n const closeBeforeCallbackDrain = async () => {\n closeAttempted = true;\n try {\n await lifecycle.close();\n } catch (error) {\n capturedCloseFailures.push(error);\n }\n };\n try {\n await lifecycle.run((tx) => {\n callbackCallCount++;\n if (callbackCallCount > 1) {\n throw new ProviderTransactionContractError(\n \"Transaction provider invoked the transaction callback more than once.\"\n );\n }\n callbackPromise = (async () => {\n try {\n const value = await lifecycle.callback(tx);\n lifecycle.phases?.readyToCommit();\n callbackOutcome = { status: \"fulfilled\", value };\n return value;\n } catch (error) {\n callbackOutcome = { status: \"rejected\", error };\n throw error;\n }\n })();\n callbackPromise.catch(() => undefined);\n return callbackPromise;\n });\n } catch (error) {\n const providerSettledBeforeCallback =\n callbackPromise !== undefined &&\n readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n if (\n settledOutcome.status === \"rejected\" &&\n !providerSettledBeforeCallback &&\n error === settledOutcome.error\n ) {\n throw error;\n }\n const primaryFailure =\n settledOutcome.status === \"rejected\" ? settledOutcome.error : error;\n const cleanupFailures: unknown[] = [];\n if (providerSettledBeforeCallback) {\n cleanupFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider settled before the transaction callback settled.\"\n )\n );\n }\n if (\n settledOutcome.status === \"rejected\" &&\n error !== settledOutcome.error\n ) {\n cleanupFailures.push(\n ...readTransactionCleanupFailures(error, settledOutcome.error)\n );\n }\n cleanupFailures.push(...capturedCloseFailures);\n const cleanupSteps = cleanupFailures.map(failureStep);\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n const providerSettledBeforeCallback =\n callbackPromise !== undefined && readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n const contractFailures: TransactionError[] = [];\n if (callbackCallCount !== 1) {\n contractFailures.push(\n new ProviderTransactionContractError(\n callbackCallCount === 0\n ? \"Transaction provider completed without invoking the transaction callback.\"\n : \"Transaction provider invoked the transaction callback more than once.\"\n )\n );\n }\n if (providerSettledBeforeCallback) {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider completed before the transaction callback settled.\"\n )\n );\n }\n if (settledOutcome.status === \"rejected\") {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider resolved after the transaction callback rejected.\"\n )\n );\n }\n if (contractFailures.length > 0) {\n const primaryFailure =\n settledOutcome.status === \"rejected\"\n ? settledOutcome.error\n : contractFailures.shift();\n const cleanupSteps = [\n ...contractFailures.map(failureStep),\n ...capturedCloseFailures.map(failureStep),\n ];\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n if (settledOutcome.status !== \"fulfilled\") {\n return throwAfterCleanup(\n new ProviderTransactionContractError(\n \"Transaction callback outcome was not recorded.\"\n ),\n [lifecycle.close]\n );\n }\n lifecycle.phases?.committed();\n return settledOutcome.value;\n}\n\n/** Run a top-level provider transaction without losing cleanup failures. */\nexport async function runTransactionLifecycle<T>(\n lifecycle: TransactionLifecycle<T>\n): Promise<T> {\n try {\n await lifecycle.begin();\n } catch (error) {\n return throwAfterCleanup(error, lifecycle.close ? [lifecycle.close] : []);\n }\n\n let result: T;\n try {\n result = await lifecycle.callback();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.readyToCommit();\n\n try {\n await lifecycle.commit();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.committed();\n\n if (lifecycle.close) await lifecycle.close();\n return result;\n}\n\nexport const runSavepoint = async <T>(\n executeStatement: (statement: string) => unknown | Promise<unknown>,\n fn: () => Promise<T>\n): Promise<T> => {\n const savepointName = `sp_${crypto.randomUUID().replace(/-/g, \"\")}`;\n await executeStatement(`SAVEPOINT ${savepointName}`);\n\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n\n try {\n await executeStatement(`RELEASE SAVEPOINT ${savepointName}`);\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n return result;\n};\n\nexport function createTransactionCleanupError(\n primaryFailure: unknown,\n cleanupFailures: readonly unknown[]\n): AggregateError {\n return new AggregateError(\n [primaryFailure, ...cleanupFailures],\n readFailureMessage(primaryFailure),\n { cause: primaryFailure }\n );\n}\n\nexport function readTransactionCleanupFailures(\n error: unknown,\n primaryFailure: unknown\n): readonly unknown[] {\n try {\n if (!(error instanceof AggregateError) || error.cause !== primaryFailure) {\n return [error];\n }\n return error.errors[0] === primaryFailure ? error.errors.slice(1) : [error];\n } catch {\n return [error];\n }\n}\n\nasync function throwAfterCleanup(\n primaryFailure: unknown,\n cleanupSteps: readonly LifecycleStep[]\n): Promise<never> {\n const cleanupFailures: unknown[] = [];\n for (const cleanupStep of cleanupSteps) {\n try {\n await cleanupStep();\n } catch (error) {\n cleanupFailures.push(error);\n }\n }\n\n if (cleanupFailures.length > 0) {\n throw createTransactionCleanupError(primaryFailure, cleanupFailures);\n }\n throw primaryFailure;\n}\n\nfunction failureStep(failure: unknown): LifecycleStep {\n return () => {\n throw failure;\n };\n}\n\nfunction readFailureMessage(error: unknown): string {\n try {\n return error instanceof Error && typeof error.message === \"string\"\n ? error.message\n : \"Transaction failed\";\n } catch {\n return \"Transaction failed\";\n }\n}\n","import {\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n getTrustedErrorCause,\n getTrustedErrorDisclosure,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n resolveDiagnosticDisclosure,\n sanitizeErrorMetadata,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValidationError,\n type ValidationErrorSource,\n ValueTooLongError,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport { OPERATIONS, type Operation } from \"@query-engine/types\";\nimport {\n isArrayValue,\n isError,\n isRecord,\n isTrustedCode,\n safeArrayLength,\n safeOwnPropertyDescriptor,\n sanitizeSqlState,\n} from \"../errors/diagnostic-safety\";\nimport { transferLoggedErrorEvidence } from \"../errors/logged-errors\";\nimport {\n readSuppressedFailures,\n withSuppressedFailure,\n} from \"./shared/suppressed-failure\";\nimport { ProviderTransactionContractError } from \"./shared/transactions\";\nimport type { Dialect } from \"./types\";\n\nexport interface DriverErrorShape {\n code?: string | number;\n bodyCode?: string | number;\n errno?: number;\n stringErrno?: string;\n constraint?: string;\n table?: string;\n column?: string;\n constraint_name?: string;\n table_name?: string;\n column_name?: string;\n sqlState?: string;\n sqlstate?: string;\n status?: string | number;\n statusCode?: string | number;\n}\n\nexport interface DriverErrorContext {\n driverName: string;\n /**\n * The SQL family that raised the error, when the normalizing call site knows\n * it. Only numeric provider codes need it: a symbolic name or a message\n * symbol identifies its own provider, but a bare integer does not.\n */\n dialect?: Dialect;\n model?: string;\n operation?: Operation | string;\n correlationId?: string;\n statementIndex?: number;\n query?: string;\n params?: unknown[];\n diagnostics?: DiagnosticDisclosure;\n callsite?: string;\n forceContext?: boolean;\n}\n\nconst EXECUTION_META_KEYS = [\n \"driver\",\n \"model\",\n \"operation\",\n \"correlationId\",\n \"callsite\",\n \"query\",\n \"params\",\n] as const;\nconst MYSQL_SQLSTATE_IN_MESSAGE_PATTERN = /\\(sqlstate ([^)]+)\\)/i;\nconst MYSQL_KEY_IN_MESSAGE_PATTERN = /for key '([^']+)'/;\n\nexport function readProperty(value: object, key: string): unknown {\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport function attachExecutionContext(\n error: VibORMError,\n context: DriverErrorContext\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const mergedMeta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n context.diagnostics\n );\n const forceContext = context.forceContext !== false;\n if (!forceContext) {\n if (\n resolveDiagnosticDisclosure(context.diagnostics).includeCallsite &&\n context.callsite\n )\n mergedMeta.callsite = context.callsite;\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n }\n const additions = sanitizeErrorMetadata(\n buildMeta({}, context, \"\"),\n context.diagnostics\n );\n for (const key of EXECUTION_META_KEYS) {\n Reflect.deleteProperty(mergedMeta, key);\n }\n for (const key of Reflect.ownKeys(additions)) {\n if (typeof key !== \"string\") continue;\n Object.defineProperty(mergedMeta, key, {\n configurable: true,\n enumerable: true,\n value: additions[key],\n writable: true,\n });\n }\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n}\n\n/** Clone one trusted failure with the exact durable write state now known. */\nexport function attachCommitCertainty(\n error: VibORMError,\n commitCertainty: NonNullable<VibORMErrorMeta[\"commitCertainty\"]>\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const diagnostics = getTrustedErrorDisclosure(error);\n const meta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n diagnostics\n );\n meta.commitCertainty = commitCertainty;\n return cloneVibORMError(error, meta, snapshot, diagnostics);\n}\n\nfunction cloneVibORMError(\n error: VibORMError,\n meta: VibORMErrorMeta,\n snapshot: Record<string, unknown>,\n diagnostics: DiagnosticDisclosure | undefined\n): VibORMError {\n // The clone runs only the base constructor under the chosen class.\n // ValidationError owns state that constructor cannot rebuild, so it is\n // rebuilt from its snapshot here; every other class keeps its identity only\n // when it is one VibORM defines without such state.\n let cloneConstructor: unknown = VibORMError;\n if (error instanceof ValidationError) {\n const validationClone = cloneValidationError(error, meta, diagnostics);\n if (validationClone) {\n transferLoggedErrorEvidence(error, validationClone);\n return transferSuppressedFailureEvidence(error, validationClone);\n }\n } else {\n cloneConstructor = getCloneConstructor(error);\n }\n const message =\n typeof snapshot.message === \"string\"\n ? snapshot.message\n : \"VibORM operation failed\";\n const code = isVibORMErrorCode(snapshot.code)\n ? snapshot.code\n : VibORMErrorCode.INTERNAL_ERROR;\n const cause = getTrustedErrorCause(error);\n const options = {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n };\n const newTarget =\n typeof cloneConstructor === \"function\" ? cloneConstructor : VibORMError;\n let candidate: unknown;\n try {\n candidate = Reflect.construct(\n VibORMError,\n [message, code, options],\n newTarget\n );\n } catch {\n candidate = new VibORMError(message, code, options);\n }\n const clonedError =\n candidate instanceof VibORMError\n ? candidate\n : new VibORMError(message, code, options);\n transferLoggedErrorEvidence(error, clonedError);\n return transferSuppressedFailureEvidence(error, clonedError);\n}\n\n/**\n * Carry the evidence a failure retained onto the failure that replaces it, so\n * rebuilding a primary (a clone, a mapped provider error) never drops it.\n */\nexport function transferSuppressedFailureEvidence(\n source: unknown,\n target: VibORMError\n): VibORMError {\n for (const failure of readSuppressedFailures(source)) {\n withSuppressedFailure(target, failure);\n }\n return target;\n}\n\nfunction cloneValidationError(\n error: ValidationError,\n meta: VibORMErrorMeta,\n diagnostics: DiagnosticDisclosure | undefined\n): ValidationError | undefined {\n const serialized = VibORMError.prototype.toJSON.call(error);\n const source = snapshotValidationSource(readProperty(serialized, \"source\"));\n const issues = readProperty(serialized, \"issues\");\n if (!(source && isArrayValue(issues))) return undefined;\n const issueSnapshot = snapshotValidationIssues(issues);\n const cause = getTrustedErrorCause(error);\n return new ValidationError(source, issueSnapshot, {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n });\n}\n\nfunction snapshotValidationSource(\n value: unknown\n): ValidationErrorSource | undefined {\n if (!isRecord(value)) return undefined;\n const kind = readProperty(value, \"kind\");\n if (kind === \"operation\") {\n const operation = readProperty(value, \"operation\");\n const model = readProperty(value, \"model\");\n if (!isOperation(operation)) return undefined;\n return {\n kind,\n operation,\n ...(typeof model === \"string\" ? { model } : {}),\n };\n }\n if (kind === \"registry\") {\n const model = readProperty(value, \"model\");\n const property = readProperty(value, \"property\");\n return {\n kind,\n ...(typeof model === \"string\" ? { model } : {}),\n ...(typeof property === \"string\" ? { property } : {}),\n };\n }\n if (kind === \"schema-builder\") {\n const builder = readProperty(value, \"builder\");\n const path = readProperty(value, \"path\");\n if (!(typeof builder === \"string\" && typeof path === \"string\")) {\n return undefined;\n }\n return { kind, builder, path };\n }\n if (kind === \"json-schema\") {\n const target = readProperty(value, \"target\");\n const schemaType = readProperty(value, \"schemaType\");\n return {\n kind,\n ...(typeof target === \"string\" ? { target } : {}),\n ...(typeof schemaType === \"string\" ? { schemaType } : {}),\n };\n }\n return undefined;\n}\n\nfunction snapshotValidationIssues(value: unknown[]): Array<{\n path: string;\n message: string;\n}> {\n const issues: Array<{ path: string; message: string }> = [];\n const length = Math.min(safeArrayLength(value), 128);\n for (let index = 0; index < length; index += 1) {\n const descriptor = safeOwnPropertyDescriptor(value, String(index));\n if (!(descriptor && \"value\" in descriptor && isRecord(descriptor.value))) {\n continue;\n }\n const path = readProperty(descriptor.value, \"path\");\n const message = readProperty(descriptor.value, \"message\");\n if (typeof path !== \"string\" || typeof message !== \"string\") continue;\n issues.push({ path, message });\n }\n return issues;\n}\n\nfunction isOperation(value: unknown): value is Operation {\n return (\n typeof value === \"string\" &&\n (OPERATIONS as readonly string[]).includes(value)\n );\n}\n\n// Every VibORM error class whose state the base constructor rebuilds, so its\n// identity survives cloning. A class outside it — a caller's subclass, which\n// may own state no clone can reconstruct, or SchemaValidationError with its\n// issues — degrades to the base class rather than a hollow instance that\n// passes \\`instanceof\\` but breaks on its own members. ValidationError is\n// absent on purpose: it is rebuilt from its snapshot.\nconst CLONE_CONSTRUCTORS = [\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValueTooLongError,\n] as const;\n\nfunction getCloneConstructor(error: VibORMError): unknown {\n try {\n const prototype = Object.getPrototypeOf(error);\n if (prototype === ProviderTransactionContractError.prototype)\n return TransactionError;\n return (\n CLONE_CONSTRUCTORS.find((ctor) => ctor.prototype === prototype) ??\n VibORMError\n );\n } catch {\n return VibORMError;\n }\n}\n\n// The code shape rule, not membership in the enum object: reading the enum's\n// values would keep the whole object in every bundle, while member accesses\n// are inlined. The snapshot already passed the same rule when it was taken.\nfunction isVibORMErrorCode(value: unknown): value is VibORMErrorCode {\n return isTrustedCode(value);\n}\n\nexport function buildMeta(\n error: DriverErrorShape,\n context: DriverErrorContext,\n message: string\n): VibORMErrorMeta {\n const meta: VibORMErrorMeta = { driver: context.driverName };\n const disclosure = resolveDiagnosticDisclosure(context.diagnostics);\n\n if (disclosure.includeCallsite && context.callsite)\n meta.callsite = context.callsite;\n if (context.model) meta.model = context.model;\n if (context.operation) meta.operation = context.operation;\n if (context.correlationId) meta.correlationId = context.correlationId;\n if (context.statementIndex !== undefined) {\n meta.statementIndex = context.statementIndex;\n }\n if (disclosure.includeSql && context.query !== undefined) {\n meta.query = context.query;\n }\n if (disclosure.includeParams && context.params !== undefined) {\n meta.params = context.params;\n }\n\n const providerCode = error.code ?? error.bodyCode;\n if (typeof providerCode === \"string\" || typeof providerCode === \"number\") {\n meta.providerCode = providerCode;\n }\n if (typeof error.errno === \"number\") meta.providerErrno = error.errno;\n const sqlState =\n error.sqlState ??\n error.sqlstate ??\n sanitizeSqlState(providerCode) ??\n MYSQL_SQLSTATE_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (typeof sqlState === \"string\") meta.providerSqlState = sqlState;\n const status = error.status ?? error.statusCode;\n if (typeof status === \"string\" || typeof status === \"number\") {\n meta.providerStatus = status;\n }\n\n const constraint = error.constraint ?? error.constraint_name;\n const table = error.table ?? error.table_name;\n const column = error.column ?? error.column_name;\n if (constraint) meta.constraint = constraint;\n if (table) meta.table = table;\n if (column) meta.columns = [column];\n\n if (!meta.constraint) {\n const key = MYSQL_KEY_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (key) {\n const dotIndex = key.indexOf(\".\");\n if (dotIndex === -1) {\n meta.constraint = key;\n } else {\n meta.constraint = key.slice(dotIndex + 1);\n if (!meta.table) meta.table = key.slice(0, dotIndex);\n }\n }\n }\n return meta;\n}\n","import {\n attachRecordSeriesProgress,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n ForeignKeyError,\n getTrustedRecordSeriesProgress,\n isVibORMError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NotNullConstraintError,\n QueryError,\n TransactionError,\n type TransactionErrorCode,\n UniqueConstraintError,\n ValueTooLongError,\n type VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport {\n attachExecutionContext,\n buildMeta,\n type DriverErrorContext,\n type DriverErrorShape,\n readProperty,\n transferSuppressedFailureEvidence,\n} from \"./driver-error-context\";\nimport type { Dialect } from \"./types\";\n\n// Stop at \":\" so D1's \"users.email: SQLITE_CONSTRAINT\" suffix isn't captured\nconst BUN_SQL_STATE_PATTERN = /^[0-9A-Z]{5}$/;\nconst PROVIDER_CONNECTION_CODE_PATTERN =\n /^(?:CONNECTION_(?:CLOSED|DESTROYED|ENDED)$|ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EPIPE$|ERR_POSTGRES_CONNECTION_|08[0-9A-Z]{3}$|57P0[123]$)/;\nconst SQLITE_CONSTRAINT_COLUMNS_PATTERN = /constraint failed: ([^:]+)/;\n// Symbolic BUSY/LOCKED codes are the exact base name or an underscore-delimited\n// extended family member. The delimiter is load-bearing: startsWith accepted\n// unrelated provider codes such as SQLITE_BUSYWORK and SQLITE_LOCKEDNESS.\nconst SQLITE_CONTENTION_FAMILY_PATTERN =\n /^SQLITE_(?:BUSY|LOCKED)(?:_[A-Z0-9]+)+$/;\nconst ASCII_PROVIDER_SYMBOL_PATTERN = /[A-Za-z0-9_]+/g;\n// An extended result code is `base | (sub << 8)`, so the whole family keeps its\n// base in the low byte. That byte alone proves nothing across providers —\n// MySQL errno 1029 also ends in 5 — so numeric recognition needs the dialect.\nconst SQLITE_BASE_CODE_MASK = 0xff;\nconst SQLITE_BUSY_BASE_CODE = 5;\nconst SQLITE_LOCKED_BASE_CODE = 6;\nconst MYSQL_ERRNO_IN_MESSAGE_PATTERN = /\\(errno (\\d+)\\)/;\n// Batch-plan assertions (adapter.assertions) fail on purpose with a\n// dialect-specific trick: division by zero on PG (SQLSTATE 22012), invalid\n// JSON via JSON_EXTRACT/json_extract on MySQL (errno 3141) and SQLite\n// (\"malformed JSON\"). The statements are identifiable by their column alias.\nexport const ASSERTION_MARKER = \"__viborm_assert__\";\n/**\n * A write judging the row it produces (`adapter.assertions.holds`) carries\n * this alias, and fails on its own refusal: the sentinel text its guard\n * names (PostgreSQL, SQLite: in the message) or, on MySQL, the invalid path\n * its sentinel is (errno 3143). Nothing else the statement raises is a\n * refusal, so a caller's division by zero or invalid JSON in it stays the\n * provider's failure (E5.6).\n */\nexport const JUDGEMENT_MARKER = \"__viborm_judged__\";\nconst REFUSAL_SENTINEL = \"__viborm_refused__\";\nconst MYSQL_INVALID_JSON_PATH = 3143;\nconst POSTGRES_DIVISION_BY_ZERO = \"22012\";\nconst MYSQL_INVALID_JSON_TEXT = 3141;\n\n// `json_each(?))` closes a bound member list (SQLite's `literals.list`): JSON\n// text the adapter stringified, which cannot raise \"malformed JSON\".\nconst JSON_ACCESS_SIGNATURE = /json(?!_each\\(\\?\\)\\))|->/i;\n\nconst FOREIGN_ASSERTION_SIGNATURE: Record<Dialect, RegExp> = {\n postgresql: /[/%]/,\n mysql: JSON_ACCESS_SIGNATURE,\n sqlite: JSON_ACCESS_SIGNATURE,\n};\n\n/**\n * Report whether an ordinary statement can raise the same provider error as a\n * batch assertion. Assertion statements carry {@link ASSERTION_MARKER}; all\n * other statements are checked against the executing dialect's failure\n * signature. With an ownership set, assertions outside that set also collide.\n * A conservative match leaves the raw provider error unattributed.\n */\nexport function batchMayContainAssertionCollision(\n statements: readonly { readonly sql: string }[],\n dialect: Dialect,\n ownedAssertions?: ReadonlySet<number>\n): boolean {\n const signature = FOREIGN_ASSERTION_SIGNATURE[dialect];\n for (const [index, statement] of statements.entries()) {\n if (\n statement.sql.includes(ASSERTION_MARKER) ||\n statement.sql.includes(JUDGEMENT_MARKER)\n ) {\n if (ownedAssertions && !ownedAssertions.has(index)) return true;\n continue;\n }\n if (signature.test(statement.sql)) return true;\n }\n return false;\n}\n\nfunction isRefusal(\n code: string | number | undefined,\n errno: number | undefined,\n message: string\n): boolean {\n return (\n message.includes(REFUSAL_SENTINEL) ||\n errno === MYSQL_INVALID_JSON_PATH ||\n code === \"ER_INVALID_JSON_PATH\"\n );\n}\n\nfunction isAssertionFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string\n): boolean {\n return (\n code === POSTGRES_DIVISION_BY_ZERO ||\n code === \"ER_INVALID_JSON_TEXT_IN_PARAM\" ||\n errno === MYSQL_INVALID_JSON_TEXT ||\n message.includes(\"division by zero\") ||\n message.includes(\"malformed JSON\") ||\n message.includes(\"Invalid JSON text\")\n );\n}\n\nfunction isSQLiteContentionResultCode(\n value: string | number | undefined\n): boolean {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n return false;\n }\n // biome-ignore lint/suspicious/noBitwiseOperators: SQLite defines an extended result code as `base | (sub << 8)`.\n const base = value & SQLITE_BASE_CODE_MASK;\n return base === SQLITE_BUSY_BASE_CODE || base === SQLITE_LOCKED_BASE_CODE;\n}\n\nfunction isSQLiteContentionName(value: string): boolean {\n return (\n value === \"SQLITE_BUSY\" ||\n value === \"SQLITE_LOCKED\" ||\n SQLITE_CONTENTION_FAMILY_PATTERN.test(value)\n );\n}\n\n/**\n * Report whether a provider error is SQLite lock contention, across the three\n * shapes drivers use: an extended symbolic code, an extended numeric result\n * code, or a message carrying the symbol (D1, libsql).\n */\nfunction isSQLiteContention(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n dialect: Dialect | undefined\n): boolean {\n if (dialect !== \"sqlite\") return false;\n if (typeof code === \"string\" && isSQLiteContentionName(code)) {\n return true;\n }\n if (\n isSQLiteContentionResultCode(code) ||\n isSQLiteContentionResultCode(errno)\n ) {\n return true;\n }\n return [...message.matchAll(ASCII_PROVIDER_SYMBOL_PATTERN)].some((match) =>\n isSQLiteContentionName(match[0])\n );\n}\n\n/**\n * A recognized failure's class, called with one options shape. `QueryError`\n * is not one: it is the unrecognized fallback, and its `code` family differs.\n */\ntype FailureClass = new (\n message: string,\n options: {\n cause: Error;\n code: TransactionErrorCode | undefined;\n diagnostics: DiagnosticDisclosure | undefined;\n meta: VibORMErrorMeta;\n }\n) => DriverFailure;\n\n/** What one recognized provider failure becomes: class, message, and code when the class has a family. */\ntype FailureConstruction = readonly [\n failure: FailureClass,\n message: string,\n code?: TransactionErrorCode | undefined,\n ...rest: unknown[],\n];\n\ntype ProviderFailure = readonly [\n failure: FailureClass,\n message: string,\n code: TransactionErrorCode | undefined,\n /** PostgreSQL SQLSTATEs and SQLite extended symbolic codes, matched against `code`. */\n providerCodes: readonly unknown[],\n /** MySQL errnos, matched against `errno`. */\n mysqlErrnos: readonly unknown[],\n /** MySQL symbolic names, matched against `code`. */\n mysqlNames: readonly unknown[],\n /** A fragment of the SQLite message that names this failure. */\n sqliteMessage?: string,\n /** Whether that SQLite message lists the failing columns. */\n sqliteColumns?: true,\n];\n\nconst ASSERTION_FAILURE: FailureConstruction = [\n NestedWriteAssertionError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n];\n// SQLite lock refusal is contention, not proof of a deadlock.\nconst SQLITE_CONTENTION_FAILURE: FailureConstruction = [\n TransactionError,\n \"Database is locked\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n];\n\n/**\n * The recognized provider failures. Precedence is the table read three times:\n * every row's provider code first, then every row's MySQL errno or name, then\n * (after SQLite lock contention) every row's SQLite message fragment. Within a\n * pass, the earlier row wins, so a MySQL errno outranks a later row's name.\n */\nconst PROVIDER_FAILURES: readonly ProviderFailure[] = [\n [\n UniqueConstraintError,\n \"Unique constraint violation\",\n undefined,\n [\"23505\", \"SQLITE_CONSTRAINT_UNIQUE\"],\n [1062],\n [\"ER_DUP_ENTRY\"],\n \"UNIQUE constraint failed\",\n true,\n ],\n [\n ForeignKeyError,\n \"Foreign key constraint violation\",\n undefined,\n // 23001 is restrict_violation — a RESTRICT referential action refused the\n // write. Stock PostgreSQL folds it into 23503; pg-wire servers (CockroachDB)\n // raise it as its own SQLSTATE with the same foreign-key metadata.\n [\"23503\", \"23001\", \"SQLITE_CONSTRAINT_FOREIGNKEY\"],\n // 1451 is ER_ROW_IS_REFERENCED_2: the parent row is still referenced.\n [1452, 1451],\n [\"ER_NO_REFERENCED_ROW_2\", \"ER_ROW_IS_REFERENCED_2\"],\n \"FOREIGN KEY constraint failed\",\n ],\n [\n NotNullConstraintError,\n \"Not-null constraint violation\",\n undefined,\n [\"23502\", \"SQLITE_CONSTRAINT_NOTNULL\"],\n [1048],\n [\"ER_BAD_NULL_ERROR\"],\n \"NOT NULL constraint failed\",\n true,\n ],\n [\n CheckConstraintError,\n \"Check constraint violation\",\n undefined,\n [\"23514\", \"SQLITE_CONSTRAINT_CHECK\"],\n [3819],\n [\"ER_CHECK_CONSTRAINT_VIOLATED\"],\n \"CHECK constraint failed\",\n ],\n [\n ValueTooLongError,\n \"Value too long for column type\",\n undefined,\n // 22001 is string_data_right_truncation and MySQL errno 1406 is\n // ER_DATA_TOO_LONG; Prisma maps both to LengthMismatch/P2000\n // (quaint/src/connector/{postgres,mysql}/error.rs). SQLite has no\n // counterpart: it does not enforce declared column lengths, and quaint's\n // SQLite connector leaves SQLITE_TOOBIG unmapped.\n [\"22001\"],\n [1406],\n [\"ER_DATA_TOO_LONG\"],\n ],\n [\n TransactionError,\n \"Transaction serialization failure\",\n VibORMErrorCode.SERIALIZATION_FAILURE,\n [\"40001\"],\n [],\n [],\n ],\n [\n TransactionError,\n \"Database lock is unavailable\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n [\"55P03\"],\n [],\n [],\n ],\n [\n TransactionError,\n \"Transaction deadlock detected\",\n VibORMErrorCode.DEADLOCK,\n [\"40P01\"],\n [1213],\n [\"ER_LOCK_DEADLOCK\"],\n ],\n];\n\n/**\n * Every error class {@link mapProviderError} constructs — the driver layer's failure\n * vocabulary, named so it is visible at the call sites instead of erased to `Error`.\n *\n * The members are disjoint by `code` — each class carries its literal — so this union is a\n * discriminated union: `if (failure.code === VibORMErrorCode.UNIQUE_CONSTRAINT)` selects\n * `UniqueConstraintError`, and an exhaustive `switch` over the codes bottoms out at `never`.\n *\n * `mapProviderError` is annotated with it, which is the point: adding a ninth class to the\n * mapper without adding it here is a compile error, not a silently widened return.\n */\nexport type DriverFailure =\n | ClientInitializationError\n | CheckConstraintError\n | ConnectionError\n | ForeignKeyError\n | NestedWriteAssertionError\n | NotNullConstraintError\n | QueryError\n | TransactionError\n | UniqueConstraintError\n | ValueTooLongError;\n\nfunction isConfigurationFailure(\n code: string | number | undefined,\n errno?: number\n): boolean {\n return (\n [\n \"28P01\",\n \"28000\",\n \"3D000\",\n \"ER_ACCESS_DENIED_ERROR\",\n \"ER_BAD_DB_ERROR\",\n ].includes(String(code)) ||\n errno === 1045 ||\n errno === 1049\n );\n}\n\nfunction isConnectionCapacityFailure(\n code: string | number | undefined,\n errno?: number\n): boolean {\n return (\n code === \"53300\" ||\n code === \"ER_CON_COUNT_ERROR\" ||\n code === \"ER_TOO_MANY_USER_CONNECTIONS\" ||\n errno === 1040 ||\n errno === 1203\n );\n}\n\nfunction configurationFailure(\n cause: Error,\n context: DriverErrorContext,\n meta: VibORMErrorMeta\n): ClientInitializationError {\n return new ClientInitializationError(\n \"Database authentication or configuration failed\",\n { cause, meta, diagnostics: context.diagnostics }\n );\n}\n\nfunction withProviderFailureEvidence<T extends DriverFailure>(\n error: unknown,\n failure: T\n): T {\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * What {@link normalizeDriverError} can hand back.\n *\n * Two arms, and the type is the union of both. A raw provider error is mapped to a\n * {@link DriverFailure}. An error that is ALREADY a VibORM error is passed through with\n * execution context attached — and that arm is honestly `VibORMError`, not `DriverFailure`:\n * the incoming error can be any VibORM error the layers above threw (a `ValidationError`, an\n * engine refusal), `attachExecutionContext` clones it under its own class, and a stateful\n * class it cannot rebuild degrades to the base `VibORMError` (`driver-error-context.ts`).\n * Typing the whole function `DriverFailure` would be a claim this arm cannot keep.\n */\nexport type NormalizedDriverError = DriverFailure | VibORMError;\n\nexport function normalizeDriverError(\n error: unknown,\n context: DriverErrorContext\n): NormalizedDriverError {\n if (isKnownVibORMError(error)) {\n const normalized = attachExecutionContext(error, context);\n const progress = getTrustedRecordSeriesProgress(error);\n return progress\n ? attachRecordSeriesProgress(normalized, progress)\n : normalized;\n }\n return mapProviderError(error, context);\n}\n\n/**\n * Map a raw provider error onto the {@link DriverFailure} vocabulary. Split out of\n * {@link normalizeDriverError} so the constructed union has a return type to be checked\n * against — the passthrough arm above cannot carry that annotation, and a function has one\n * return type. {@link recognizeProviderFailure} decides which failure it is; this is the\n * one place it is constructed.\n */\nfunction mapProviderError(\n error: unknown,\n context: DriverErrorContext\n): DriverFailure {\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n const stringErrno = dbError.stringErrno;\n const bunSqlState =\n context.driverName === \"bun-sql\" &&\n typeof dbError.code === \"string\" &&\n dbError.code.startsWith(\"ERR_POSTGRES\") &&\n BUN_SQL_STATE_PATTERN.test(stringErrno ?? \"\")\n ? stringErrno\n : undefined;\n const code = bunSqlState ?? dbError.sqlstate ?? dbError.code;\n if (bunSqlState) meta.providerCode = bunSqlState;\n if (isConfigurationFailure(code, dbError.errno))\n return withProviderFailureEvidence(\n error,\n configurationFailure(cause, context, meta)\n );\n if (typeof code === \"string\" && PROVIDER_CONNECTION_CODE_PATTERN.test(code)) {\n return withProviderFailureEvidence(\n error,\n new ConnectionError(\"Database connection failed\", {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code:\n code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n })\n );\n }\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n\n const diagnostics = context.diagnostics;\n // SQLSTATEs and MySQL constants name the physical failure, independently of\n // localized provider text. SQLite exposes these categories only in messages.\n const capacity = isConnectionCapacityFailure(code, errno);\n const schemaMismatch =\n code === \"42P01\" ||\n code === \"42703\" ||\n code === \"ER_NO_SUCH_TABLE\" ||\n code === \"ER_BAD_FIELD_ERROR\" ||\n errno === 1146 ||\n errno === 1054 ||\n (context.dialect === \"sqlite\" &&\n (rawMessage.includes(\"no such table:\") ||\n rawMessage.includes(\"no such column:\") ||\n rawMessage.includes(\"has no column named\")));\n const outOfRange =\n code === \"22003\" ||\n code === \"ER_WARN_DATA_OUT_OF_RANGE\" ||\n code === \"ER_DATA_OUT_OF_RANGE\" ||\n errno === 1264 ||\n errno === 1690 ||\n (context.dialect === \"sqlite\" && rawMessage.includes(\"integer overflow\"));\n if (capacity || schemaMismatch || outOfRange)\n return withProviderFailureEvidence(\n error,\n capacity\n ? new ConnectionError(\"Database connection capacity exhausted\", {\n cause,\n diagnostics,\n meta,\n code: VibORMErrorCode.CONNECTION_CAPACITY,\n })\n : new QueryError(\n schemaMismatch\n ? \"Database table or column does not exist\"\n : \"Value exceeds the database numeric range\",\n {\n cause,\n diagnostics,\n meta,\n code: schemaMismatch\n ? VibORMErrorCode.QUERY_SCHEMA_MISMATCH\n : VibORMErrorCode.QUERY_OUT_OF_RANGE,\n }\n )\n );\n if (code === \"57014\" || code === \"ER_LOCK_WAIT_TIMEOUT\" || errno === 1205) {\n return withProviderFailureEvidence(\n error,\n new QueryError(\"Query timed out\", {\n cause,\n diagnostics,\n meta,\n code: VibORMErrorCode.QUERY_TIMEOUT,\n })\n );\n }\n const recognized = recognizeProviderFailure(\n code,\n errno,\n rawMessage,\n meta,\n context\n );\n let failure: DriverFailure;\n if (recognized) {\n const [Failure, message, failureCode] = recognized;\n failure = new Failure(message, {\n cause,\n code: failureCode,\n diagnostics,\n meta,\n });\n } else {\n failure = new QueryError(\"Query execution failed\", {\n cause,\n diagnostics,\n meta,\n });\n }\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * Which failure a raw provider error is. An assertion statement's own failure\n * comes first; then {@link PROVIDER_FAILURES} in its three passes, with SQLite\n * lock contention before the SQLite message pass. Anything else is not\n * recognized.\n */\nfunction recognizeProviderFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n meta: VibORMErrorMeta,\n context: DriverErrorContext\n): FailureConstruction | undefined {\n if (\n (context.query?.includes(JUDGEMENT_MARKER) &&\n isRefusal(code, errno, message)) ||\n (context.query?.includes(ASSERTION_MARKER) &&\n isAssertionFailure(code, errno, message))\n ) {\n return ASSERTION_FAILURE;\n }\n const recognized =\n PROVIDER_FAILURES.find((row) => row[3].includes(code)) ??\n PROVIDER_FAILURES.find(\n (row) => row[4].includes(errno) || row[5].includes(code)\n );\n if (recognized) {\n if (recognized[7] && typeof code === \"string\" && code.startsWith(\"SQLITE_\"))\n attachSQLiteColumns(message, meta);\n return recognized;\n }\n if (isSQLiteContention(code, errno, message, context.dialect)) {\n return SQLITE_CONTENTION_FAILURE;\n }\n return findSQLiteMessageFailure(message, meta);\n}\n\n/**\n * What {@link normalizeDriverConnectionError} can hand back — the connection variant of\n * {@link NormalizedDriverError}. The constructed arm is exactly {@link ConnectionError}; the\n * passthrough arm is `VibORMError` for the same two reasons documented there.\n */\nexport type NormalizedConnectionError = ConnectionError | VibORMError;\n\nexport function normalizeDriverConnectionError(\n error: unknown,\n context: DriverErrorContext,\n message = \"Database connection failed\"\n): NormalizedConnectionError {\n if (isKnownVibORMError(error)) {\n return attachExecutionContext(error, context);\n }\n\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n const code = dbError.sqlstate ?? dbError.code;\n if (isConfigurationFailure(code, errno))\n return withProviderFailureEvidence(\n error,\n configurationFailure(cause, context, meta)\n );\n return withProviderFailureEvidence(\n error,\n new ConnectionError(\n isConnectionCapacityFailure(code, errno)\n ? \"Database connection capacity exhausted\"\n : message,\n {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code: isConnectionCapacityFailure(code, errno)\n ? VibORMErrorCode.CONNECTION_CAPACITY\n : code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n }\n )\n );\n}\n\nfunction isKnownVibORMError(error: unknown): error is VibORMError {\n try {\n return isVibORMError(error);\n } catch {\n return false;\n }\n}\n\nfunction toError(error: unknown): Error {\n try {\n return error instanceof Error ? error : new Error(\"Unknown provider error\");\n } catch {\n return new Error(\"Unknown provider error\");\n }\n}\n\nfunction getErrorMessage(error: Error): string {\n try {\n return typeof error.message === \"string\"\n ? error.message\n : \"Unknown provider error\";\n } catch {\n return \"Unknown provider error\";\n }\n}\n\nfunction readDriverErrorShape(error: unknown): DriverErrorShape {\n if ((typeof error !== \"object\" && typeof error !== \"function\") || !error) {\n return {};\n }\n const body = readProperty(error, \"body\");\n const errno = readProperty(error, \"errno\");\n return {\n code: readStringOrNumber(error, \"code\"),\n bodyCode:\n body && (typeof body === \"object\" || typeof body === \"function\")\n ? readStringOrNumber(body, \"code\")\n : undefined,\n errno: typeof errno === \"number\" ? errno : undefined,\n stringErrno: typeof errno === \"string\" ? errno : undefined,\n constraint: readString(error, \"constraint\"),\n table: readString(error, \"table\"),\n column: readString(error, \"column\"),\n constraint_name: readString(error, \"constraint_name\"),\n table_name: readString(error, \"table_name\"),\n column_name: readString(error, \"column_name\"),\n sqlState: readString(error, \"sqlState\"),\n sqlstate: readString(error, \"sqlstate\"),\n status: readStringOrNumber(error, \"status\"),\n statusCode: readStringOrNumber(error, \"statusCode\"),\n };\n}\n\nfunction readString(value: object, key: string): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readStringOrNumber(\n value: object,\n key: string\n): string | number | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" || typeof member === \"number\"\n ? member\n : undefined;\n}\n\nfunction parseMessageErrno(message: string): number | undefined {\n const match = MYSQL_ERRNO_IN_MESSAGE_PATTERN.exec(message);\n return match?.[1] ? Number(match[1]) : undefined;\n}\n\n/**\n * The first row whose SQLite message fragment the provider message carries, in\n * table order. UNIQUE and NOT NULL messages also name their columns.\n */\nfunction findSQLiteMessageFailure(\n message: string,\n meta: VibORMErrorMeta\n): ProviderFailure | undefined {\n const row = PROVIDER_FAILURES.find(\n (candidate) => candidate[6] && message.includes(candidate[6])\n );\n if (row?.[7]) attachSQLiteColumns(message, meta);\n return row;\n}\n\nfunction attachSQLiteColumns(message: string, meta: VibORMErrorMeta): void {\n const match = SQLITE_CONSTRAINT_COLUMNS_PATTERN.exec(message);\n if (!match?.[1]) return;\n // Accept only an unambiguous identifier list. Quoted dots/commas are leaves,\n // not separators; arbitrary constraint expressions never become column names.\n const identifier = String.raw`(?:\"(?:[^\"]|\"\")*\"|\\`(?:[^\\`]|\\`\\`)*\\`|\\[[^\\]]+\\]|[A-Za-z_][A-Za-z0-9_$]*)`;\n const path = `${identifier}(?:\\\\s*\\\\.\\\\s*${identifier})*`;\n if (!new RegExp(`^\\\\s*${path}(?:\\\\s*,\\\\s*${path})*\\\\s*$`).test(match[1]))\n return;\n const paths = match[1].match(new RegExp(path, \"g\"));\n if (!paths) return;\n const columns: string[] = [];\n const tables = new Set<string>();\n for (const qualified of paths) {\n const parts = qualified.match(new RegExp(identifier, \"g\"));\n if (!parts?.length) return;\n const names = parts.map((part) => {\n if (part.startsWith('\"')) return part.slice(1, -1).replaceAll('\"\"', '\"');\n if (part.startsWith(\"`\")) return part.slice(1, -1).replaceAll(\"``\", \"`\");\n if (part.startsWith(\"[\")) return part.slice(1, -1);\n return part;\n });\n const column = names.pop();\n if (column === undefined) return;\n columns.push(column);\n if (names.length) tables.add(names.join(\".\"));\n }\n meta.columns = columns;\n if (tables.size === 1) meta.table = tables.values().next().value;\n}\n"],"mappings":"oiBAKA,IAAa,sBAAb,cAA2C,CAAY,CACrD,OAAyB,eAAiB,wBAK1C,YAAY,EAAiB,EAA8B,C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AQ,EAAM,IAAK,GACnB,EAAK,WAAW,IAAI,CAAS,EAAK,MAAM,EAAG,GAAG,CAAC,WAAW,KAAM,IAAI,CACpE,EAAK,WAAW,IAAI,CAAS,EAAK,MAAM,EAAG,GAAG,CAAC,WAAW,KAAM,IAAI,CACpE,EAAK,WAAW,IAAI,CAAS,EAAK,MAAM,EAAG,GAAG,CAC3C,EACP,CACI,EAAS,EAAM,KAAK,CAC1B,GAAI,IAAW,IAAA,GAAW,OAC1B,EAAQ,KAAK,EAAO,CAChB,EAAM,QAAQ,EAAO,IAAI,EAAM,KAAK,IAAI,CAAC,CAE/C,EAAK,QAAU,EACX,EAAO,OAAS,IAAG,EAAK,MAAQ,EAAO,QAAQ,CAAC,MAAM,CAAC"}
|
package/dist/every-CcpKWCVo.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./client-BgJ7Faln.mjs";import{n,t as r}from"./libsql-BlSBYwd_.mjs";import{t as i}from"./mysql-DOLHwIM_.mjs";import{t as a}from"./postgres-DQVSTqVm.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i)}export{registerEveryMigrationDriver as t};
|
|
2
|
-
//# sourceMappingURL=every-CcpKWCVo.mjs.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";const r=2**32,words=e=>{let t=new DataView(new ArrayBuffer(e.length*4));for(let[n,r]of e.entries())t.setUint32(n*4,r);return t},i=words([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=new Uint8Array(words([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]).buffer),o=new Uint8Array(32),s=new DataView(o.buffer),c=new DataView(new ArrayBuffer(256)),rotate=(e,t)=>e>>>t|e<<32-t,fold=(e,t)=>{s.setInt32(e,s.getInt32(e)+t|0)};function compress(e,t){for(let n=0;n<16;n++)c.setInt32(n*4,e.getInt32(t+n*4));for(let e=16;e<64;e++){let t=c.getInt32((e-15)*4),n=c.getInt32((e-2)*4),r=rotate(t,7)^rotate(t,18)^t>>>3,i=rotate(n,17)^rotate(n,19)^n>>>10;c.setInt32(e*4,i+c.getInt32((e-7)*4)+r+c.getInt32((e-16)*4)|0)}let n=s.getInt32(0),r=s.getInt32(4),a=s.getInt32(8),o=s.getInt32(12),l=s.getInt32(16),u=s.getInt32(20),d=s.getInt32(24),f=s.getInt32(28);for(let e=0;e<64;e++){let t=rotate(l,6)^rotate(l,11)^rotate(l,25),s=l&u^~l&d,p=f+t+s+i.getInt32(e*4)+c.getInt32(e*4)|0,m=rotate(n,2)^rotate(n,13)^rotate(n,22),h=n&r^n&a^r&a;f=d,d=u,u=l,l=o+p|0,o=a,a=r,r=n,n=p+m+h|0}fold(0,n),fold(4,r),fold(8,a),fold(12,o),fold(16,l),fold(20,u),fold(24,d),fold(28,f)}function sha256(e){o.set(a);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),i=Math.floor(t/64);for(let e=0;e<i;e++)compress(n,e*64);let s=t-i*64,c=new Uint8Array(s>55?128:64);c.set(e.subarray(i*64)),c[s]=128;let l=new DataView(c.buffer),u=t*8;l.setUint32(c.length-8,Math.floor(u/r)),l.setUint32(c.length-4,u%r);for(let e=0;e<c.length;e+=64)compress(l,e);return Uint8Array.from(o)}const l=`sha256`,u={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`},d=/^[0-9a-f]{64}$/,f=new TextEncoder;function isSha256(e){return typeof e==`string`&&d.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){let t=``;for(let n of sha256(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=f.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return f.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{isSha256 as a,utf8Bytes as c,domainHash as i,u as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,l as t};
|
|
2
|
-
//# sourceMappingURL=identity-oQvIe7u8.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identity-oQvIe7u8.mjs","names":[],"sources":["../src/validation/primitives/sha256.ts","../src/migrations/identity.ts"],"sourcesContent":["// biome-ignore-all lint/suspicious/noBitwiseOperators: SHA-256 is 32-bit word\n// arithmetic. Every operator below is part of FIPS 180-4's definition.\n\n/**\n * SHA-256, the hash Migration V1 identity is defined over.\n *\n * FIPS 180-4: 64-byte blocks, a 64-word message schedule, 64 rounds, a 64-bit\n * big-endian bit length after the `0x80` pad. One exported function, no\n * streaming, no options: the caller hands over the complete message and\n * receives the 32-byte digest.\n *\n * It is synchronous on purpose. WebCrypto's `digest` is the platform hash on\n * every runtime, but it returns a promise, and every content-addressed parser\n * in the migration engine hashes inline; `node:crypto` is synchronous but is\n * not on an edge runtime without a compatibility flag.\n *\n * Every word is read and written through a `DataView` that names big-endian,\n * the byte order the standard is written in, so the host's byte order never\n * enters a digest; it is also the one indexed read in this codebase that is not\n * `T | undefined`, as in the SHA3-512 precedent (`./sha3`).\n *\n * The one caller is `migrations/identity`. Nothing else in VibORM may import\n * this module without its own differential proof against a reference.\n */\n\nconst BLOCK_BYTES = 64;\nconst DIGEST_BYTES = 32;\nconst ROUNDS = 64;\n/** A tail of more than this many bytes leaves no room for the pad and length. */\nconst LAST_BLOCK_ROOM = BLOCK_BYTES - 9;\nconst WORD_SPAN = 2 ** 32;\n\nconst words = (values: readonly number[]): DataView => {\n const view = new DataView(new ArrayBuffer(values.length * 4));\n for (const [index, value] of values.entries()) {\n view.setUint32(index * 4, value);\n }\n return view;\n};\n\n/** The first 32 bits of the fractional parts of the first 64 primes' cube roots. */\nconst ROUND_CONSTANTS = words([\n 0x42_8a_2f_98, 0x71_37_44_91, 0xb5_c0_fb_cf, 0xe9_b5_db_a5, 0x39_56_c2_5b,\n 0x59_f1_11_f1, 0x92_3f_82_a4, 0xab_1c_5e_d5, 0xd8_07_aa_98, 0x12_83_5b_01,\n 0x24_31_85_be, 0x55_0c_7d_c3, 0x72_be_5d_74, 0x80_de_b1_fe, 0x9b_dc_06_a7,\n 0xc1_9b_f1_74, 0xe4_9b_69_c1, 0xef_be_47_86, 0x0f_c1_9d_c6, 0x24_0c_a1_cc,\n 0x2d_e9_2c_6f, 0x4a_74_84_aa, 0x5c_b0_a9_dc, 0x76_f9_88_da, 0x98_3e_51_52,\n 0xa8_31_c6_6d, 0xb0_03_27_c8, 0xbf_59_7f_c7, 0xc6_e0_0b_f3, 0xd5_a7_91_47,\n 0x06_ca_63_51, 0x14_29_29_67, 0x27_b7_0a_85, 0x2e_1b_21_38, 0x4d_2c_6d_fc,\n 0x53_38_0d_13, 0x65_0a_73_54, 0x76_6a_0a_bb, 0x81_c2_c9_2e, 0x92_72_2c_85,\n 0xa2_bf_e8_a1, 0xa8_1a_66_4b, 0xc2_4b_8b_70, 0xc7_6c_51_a3, 0xd1_92_e8_19,\n 0xd6_99_06_24, 0xf4_0e_35_85, 0x10_6a_a0_70, 0x19_a4_c1_16, 0x1e_37_6c_08,\n 0x27_48_77_4c, 0x34_b0_bc_b5, 0x39_1c_0c_b3, 0x4e_d8_aa_4a, 0x5b_9c_ca_4f,\n 0x68_2e_6f_f3, 0x74_8f_82_ee, 0x78_a5_63_6f, 0x84_c8_78_14, 0x8c_c7_02_08,\n 0x90_be_ff_fa, 0xa4_50_6c_eb, 0xbe_f9_a3_f7, 0xc6_71_78_f2,\n]);\n\n/** The first 32 bits of the fractional parts of the first 8 primes' square roots. */\nconst INITIAL_HASH = new Uint8Array(\n words([\n 0x6a_09_e6_67, 0xbb_67_ae_85, 0x3c_6e_f3_72, 0xa5_4f_f5_3a, 0x51_0e_52_7f,\n 0x9b_05_68_8c, 0x1f_83_d9_ab, 0x5b_e0_cd_19,\n ]).buffer\n);\n\n/**\n * The running hash and the message schedule, allocated once: `sha256` is\n * synchronous from entry to return, and every entry begins by resetting the\n * hash to its initial value.\n */\nconst hashBytes = new Uint8Array(DIGEST_BYTES);\nconst hash = new DataView(hashBytes.buffer);\nconst schedule = new DataView(new ArrayBuffer(ROUNDS * 4));\n\nconst rotate = (word: number, bits: number): number =>\n (word >>> bits) | (word << (32 - bits));\n\n/** Folds one working variable back into the running hash. */\nconst fold = (at: number, word: number): void => {\n hash.setInt32(at, (hash.getInt32(at) + word) | 0);\n};\n\n/** The compression function over the 64 bytes of `block` at `offset`. */\nfunction compress(block: DataView, offset: number): void {\n for (let t = 0; t < 16; t++) {\n schedule.setInt32(t * 4, block.getInt32(offset + t * 4));\n }\n for (let t = 16; t < ROUNDS; t++) {\n const early = schedule.getInt32((t - 15) * 4);\n const late = schedule.getInt32((t - 2) * 4);\n const sigma0 = rotate(early, 7) ^ rotate(early, 18) ^ (early >>> 3);\n const sigma1 = rotate(late, 17) ^ rotate(late, 19) ^ (late >>> 10);\n schedule.setInt32(\n t * 4,\n (sigma1 +\n schedule.getInt32((t - 7) * 4) +\n sigma0 +\n schedule.getInt32((t - 16) * 4)) |\n 0\n );\n }\n\n let a = hash.getInt32(0);\n let b = hash.getInt32(4);\n let c = hash.getInt32(8);\n let d = hash.getInt32(12);\n let e = hash.getInt32(16);\n let f = hash.getInt32(20);\n let g = hash.getInt32(24);\n let h = hash.getInt32(28);\n for (let t = 0; t < ROUNDS; t++) {\n const sum1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25);\n const choose = (e & f) ^ (~e & g);\n const first =\n (h +\n sum1 +\n choose +\n ROUND_CONSTANTS.getInt32(t * 4) +\n schedule.getInt32(t * 4)) |\n 0;\n const sum0 = rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n h = g;\n g = f;\n f = e;\n e = (d + first) | 0;\n d = c;\n c = b;\n b = a;\n a = (first + sum0 + majority) | 0;\n }\n fold(0, a);\n fold(4, b);\n fold(8, c);\n fold(12, d);\n fold(16, e);\n fold(20, f);\n fold(24, g);\n fold(28, h);\n}\n\n/**\n * The SHA-256 digest of one complete message.\n *\n * Byte-identical to `node:crypto` for every input, which a differential test\n * pins against the FIPS 180-4 known-answer vectors and 10,000 random messages\n * crossing every block and padding boundary.\n */\nexport function sha256(bytes: Uint8Array): Uint8Array {\n hashBytes.set(INITIAL_HASH);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / BLOCK_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n compress(message, block * BLOCK_BYTES);\n }\n\n // The tail, `0x80`, zeros, then the bit length as a 64-bit big-endian word:\n // one block, or two when the tail leaves fewer than nine bytes free.\n const tailLength = length - wholeBlocks * BLOCK_BYTES;\n const tail = new Uint8Array(\n tailLength > LAST_BLOCK_ROOM ? 2 * BLOCK_BYTES : BLOCK_BYTES\n );\n tail.set(bytes.subarray(wholeBlocks * BLOCK_BYTES));\n tail[tailLength] = 0x80;\n const padded = new DataView(tail.buffer);\n const bits = length * 8;\n padded.setUint32(tail.length - 8, Math.floor(bits / WORD_SPAN));\n padded.setUint32(tail.length - 4, bits % WORD_SPAN);\n for (let at = 0; at < tail.length; at += BLOCK_BYTES) {\n compress(padded, at);\n }\n\n return Uint8Array.from(hashBytes);\n}\n","/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"+HAyBA,MAKM,EAAY,GAAK,GAEjB,MAAS,GAAwC,CACrD,IAAM,EAAO,IAAI,SAAS,IAAI,YAAY,EAAO,OAAS,EAAE,CAAC,CAC7D,IAAK,GAAM,CAAC,EAAO,KAAU,EAAO,SAAS,CAC3C,EAAK,UAAU,EAAQ,EAAG,EAAM,CAElC,OAAO,GAIH,EAAkB,MAAM,CAC5B,WAAe,WAAe,WAAe,WAAe,UAC5D,WAAe,WAAe,WAAe,WAAe,UAC5D,UAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,UAAe,UAC5D,UAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,WAAe,WAC5D,UAAe,UAAe,UAAe,UAAe,WAC5D,WAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,UAAe,UAAe,UAC5D,UAAe,UAAe,UAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,WAC9C,CAAC,CAGI,EAAe,IAAI,WACvB,MAAM,CACJ,WAAe,WAAe,WAAe,WAAe,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AiB,SAEjB,EAAc,CACzB,OAAQ,6BACR,SAAU,+BACV,IAAK,0BACL,SAAU,+BACV,WAAY,iCACZ,MAAO,4BACP,KAAM,2BACN,KAAM,2BACN,UAAW,iCACX,MAAO,4BACR,CAIK,EAAQ,iBACR,EAAO,IAAI,YAEjB,SAAgB,SAAS,EAAiC,CACxD,OAAO,OAAO,GAAU,UAAY,EAAM,KAAK,EAAM,CAGvD,SAAgB,YAAY,EAAgB,EAAuB,CACjE,GAAI,CAAC,SAAS,EAAM,CAClB,MAAM,IAAI,EACR,GAAG,EAAM,2CACT,EAAgB,yBACjB,CAEH,OAAO,EAGT,SAAgB,UAAU,EAA2B,CACnD,IAAI,EAAM,GACV,IAAK,IAAM,KAAQ,OAAO,EAAM,CAAE,GAAO,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAC3E,OAAO,EAGT,SAAgB,WAAW,EAAoB,EAA2B,CACxE,IAAM,EAAS,EAAK,OAAO,EAAO,CAC5B,EAAQ,IAAI,WAAW,EAAO,OAAS,EAAI,EAAM,OAAO,CAI9D,OAHA,EAAM,IAAI,EAAQ,EAAE,CACpB,EAAM,EAAO,QAAU,EACvB,EAAM,IAAI,EAAO,EAAO,OAAS,EAAE,CAC5B,UAAU,EAAM,CAGzB,SAAgB,UAAU,EAA0B,CAClD,OAAO,EAAK,OAAO,EAAK,CAW1B,SAAgB,WAAW,EAA2B,CACpD,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,UAAW,GAAM,CAAC,CAAC,OAChE,EACD"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t}from"./validation-BamBwne9.mjs";import{E as n,g as r}from"./geo-point-codec-DyEHMdJg.mjs";import{o as i}from"./sql-Bhxq9arK.mjs";import{a}from"./physical-CAOaNM4R.mjs";import{t as o}from"./geo-area-codec-CbkmFArQ.mjs";import{r as s}from"./adapter-internals-AGgQRu5t.mjs";import{n as ee}from"./result-parsing-8wEK3GY1.mjs";import{r as c}from"./datetime-physical-codec-BEqQbIP_.mjs";import{A as l,C as u,D as d,E as f,M as p,N as te,S as m,T as h,_ as g,a as _,c as v,d as y,f as b,g as x,h as S,i as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as ne,x as P,y as F}from"./standard-sql-CoGqv-iX.mjs";import{n as I}from"./batch-refs-B4zn-FAu.mjs";import{t as L}from"./adapter-namespace-BpMbLKpL.mjs";import{a as R,d as z,f as B,g as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-CkGe2ABs.mjs";const X=te("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>i`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>i`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>i.raw(`9`.repeat(e)),re=i`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=i`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,n)=>i`CAST(${e} AS ${i.raw(`DECIMAL(${t},${n})`)})`,mysqlCoefficient=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`TRUNCATE(${e}, 0)`;return i`(${a} * ${r} + ${decimalCast(i`(${decimalCast(i`(${e} - ${a})`,n+1,n)} * ${r})`,n,0)})`},mysqlLogical=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`MOD(${e}, ${r})`;return i`((${e} - ${a}) / ${r} + ${decimalCast(a,n,0)} * ${z(n)})`},mysqlGuardedDecimalAssignment=(e,t,n,r)=>{let a=mysqlMaximumCoefficient(n.precision),o=mysqlLogical(t,n);return i`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${r} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} <= ${o} - ${a} WHEN ${a} < 0 THEN ${r} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} + ${a})`,n,s)},mysqlDecimalDecrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} >= -${o} + ${a} WHEN ${a} < 0 THEN ${r} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} - ${a})`,n,s)},mysqlDecimalMultiply=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,i`(${r} * ${a})`,Y(n.scale)),n,i`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${r}) <= ${Q.quotient(o,i`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,n)=>{let r=mysqlCoefficient(t,n);return mysqlGuardedDecimalAssignment(e,G(Q,B(i`(${mysqlCoefficient(e,n)} * ${Y(n.scale)})`,r),i`ABS(${r})`),n,i.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,i`SUM(${mysqlCoefficient(e,t)})`,i`COUNT(${e})`),t),asciiCaseFold=e=>{let t=e;for(let e=0;e<26;e++){let n=i.raw(`'${`ABCDEFGHIJKLMNOPQRSTUVWXYZ`[e]}'`),r=i.raw(`'${`abcdefghijklmnopqrstuvwxyz`[e]}'`);t=i`REPLACE(${t}, ${n}, ${r})`}return t},ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?i.raw(String(t)):e},mysqlJsonObject=e=>{if(e.length===0)return i.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`JSON_OBJECT(${i.join(t,`, `)})`},mysqlJsonListValue=e=>i`CAST(${p(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){L(this,e,`mysql`),this.identifiers=b(X,this.namespace),K(this,this.geoPoint),s(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=m();identifiers;literals={...f(),true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t,n)=>i`${n||e.length===10?e:c(e)}`,decimal:(e,t)=>i`CAST(${n(e,t,`text`)} AS ${i.raw(r(`mysql`,t))})`,id:(e,t)=>i`${e}`};operators={..._(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\\\'`,ilike:(e,t)=>i`${asciiCaseFold(e)} LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,notIlike:(e,t)=>i`${asciiCaseFold(e)} NOT LIKE ${asciiCaseFold(t)} ESCAPE '\\\\'`,containsText:(e,t)=>i`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>i`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>i`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,startsWithPrefix:(e,t)=>i`(${e} LIKE ${`${l(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>i`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>i`(${e} IN ${t} AND BINARY ${e} IN ${t})`,...x(),...N(),...P(),...S(this.literals.true,this.literals.false),...y()};expressions={...C(),asciiCaseFold,caseSensitiveText:e=>i`BINARY ${e}`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`CONCAT(${i.join(e,`, `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?i`UNHEX(${e})`:i`CAST(${e} AS CHAR)`,cast:k({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>i`LOWER(HEX(${e}))`};aggregates={...E(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:v(65)};json={equals:(e,t)=>i`${e} = ${t}`,number:e=>e,boolean:e=>i`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:mysqlJsonObject,array:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,emptyArray:()=>i.raw`JSON_ARRAY()`,agg:e=>i`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:mysqlJsonObject,extract:(e,t)=>i`JSON_EXTRACT(${e}, ${j(t)})`,extractText:(e,t)=>i`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${j(t)}))`,numberAtPath:(e,t)=>{let n=j(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let n=j(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS BINARY) END)`},contains:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>i`JSON_EXTRACT(${e}, '$[last]')`,value:e=>i`CAST(${p(e)} AS JSON)`};arrays={literal:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>i`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>i`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>i`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS CHAR)`,length:e=>i`JSON_LENGTH(${e})`,get:(e,t)=>i`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>i`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,n)=>i`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${n})`};orderBy={...w(),...M()};clauses={...h(),limit:e=>i`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>i`OFFSET ${inlineIntegerLiteral(e)}`};set={...F(),increment:(e,t,n)=>n?.decimal?mysqlDecimalIncrement(e,t,n.decimal):i`${e} = ${e} + ${t}`,decrement:(e,t,n)=>n?.decimal?mysqlDecimalDecrement(e,t,n.decimal):i`${e} = ${e} - ${t}`,multiply:(e,t,n)=>n?.decimal?mysqlDecimalMultiply(e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?mysqlDecimalDivide(e,t,n.decimal):n?.integer?i`${e} = TRUNCATE(${e} / ${t}, 0)`:i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=u();subqueries=d(X);noLimitValue=i.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(i`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=A(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:O(X),insertDefault:e=>i`INSERT INTO ${e} () VALUES ()`,...g(),returning:e=>i.empty,onConflict:(e,t,n)=>i`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=i.raw(X(e));return{prefix:i.empty,suffix:i`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \`__viborm_judged__\`${t?i` FROM ${t}`:i``}`};joins={...D(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...T(X)};setOperations=ne(X);capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0};lastInsertId=()=>i.raw`LAST_INSERT_ID()`;#t=I({table:i.raw`\`__viborm_batch_refs\``,batchIdColumn:i.raw`\`batch_id\``,keyColumn:i.raw`\`ref_key\``,valueColumn:i.raw`\`ref_value\``,duplicateValue:i.raw`VALUES(\`ref_value\`)`,createTable:i.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \`__viborm_batch_refs\` (\`batch_id\` VARCHAR(191) NOT NULL, \`ref_key\` VARCHAR(191) NOT NULL, \`ref_value\` TEXT, PRIMARY KEY (\`batch_id\`, \`ref_key\`))`,castValue:e=>i`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>i`ST_Longitude(${e})`,latitude=e=>i`ST_Latitude(${e})`;return{value:(e,t)=>i`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let n=H(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_GeomFromGeoJSON(${R(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>i`ST_Distance_Sphere(${e}, ${t}, ${o})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>a(e,t,`mysql`)?.representation??`text`,parseResult:V,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=ee(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
|
|
2
|
-
//# sourceMappingURL=mysql-adapter-C6c5govr.mjs.map
|