viborm 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-B8XWzCev.mjs} +1 -1
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-B8XWzCev.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DoWlPD2h.mjs} +1 -1
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DoWlPD2h.mjs.map} +1 -1
  7. package/dist/{builder-Df24l2Bd.mjs → builder-DhxaVYP2.mjs} +2 -2
  8. package/dist/{builder-Df24l2Bd.mjs.map → builder-DhxaVYP2.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +1 -1
  18. package/dist/cache.mjs +1 -1
  19. package/dist/cache.mjs.map +1 -1
  20. package/dist/chain-BjJ_M7EE.mjs +2 -0
  21. package/dist/chain-BjJ_M7EE.mjs.map +1 -0
  22. package/dist/cli.mjs +1 -1
  23. package/dist/client-BCgMXn6N.mjs +2 -0
  24. package/dist/client-BCgMXn6N.mjs.map +1 -0
  25. package/dist/{client-70MrTq1E.d.mts → client-Df81J4oB.d.mts} +1 -1
  26. package/dist/{client-DM1UHfYG.mjs → client-q6ccRgdO.mjs} +2 -2
  27. package/dist/{client-DM1UHfYG.mjs.map → client-q6ccRgdO.mjs.map} +1 -1
  28. package/dist/client.d.mts +1 -1
  29. package/dist/client.mjs +1 -1
  30. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  31. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  32. package/dist/config.d.mts +1 -1
  33. package/dist/config.mjs +1 -1
  34. package/dist/d1.d.mts +1 -1
  35. package/dist/d1.mjs +1 -1
  36. package/dist/{driver-CPD0Xxw2.mjs → driver-D6_Ik58x.mjs} +2 -2
  37. package/dist/{driver-CPD0Xxw2.mjs.map → driver-D6_Ik58x.mjs.map} +1 -1
  38. package/dist/{driver-B9fIori_.mjs → driver-Ddt147dK.mjs} +2 -2
  39. package/dist/{driver-B9fIori_.mjs.map → driver-Ddt147dK.mjs.map} +1 -1
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-dpzVDwzu.mjs +2 -0
  43. package/dist/{every-1pKZteeB.mjs.map → every-dpzVDwzu.mjs.map} +1 -1
  44. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  45. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  46. package/dist/{hydration-DsyHNSDS.mjs → hydration-C2uXmJy6.mjs} +2 -2
  47. package/dist/{hydration-DsyHNSDS.mjs.map → hydration-C2uXmJy6.mjs.map} +1 -1
  48. package/dist/{identifier-conversion-DaZ9yNpv.mjs → identifier-conversion-C2pwwFOS.mjs} +2 -2
  49. package/dist/{identifier-conversion-DaZ9yNpv.mjs.map → identifier-conversion-C2pwwFOS.mjs.map} +1 -1
  50. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  51. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  52. package/dist/{index-VsM29vYN.d.mts → index-D4O0Twvs.d.mts} +16 -8
  53. package/dist/index.d.mts +1 -1
  54. package/dist/index.mjs +1 -1
  55. package/dist/instrumentation.d.mts +1 -1
  56. package/dist/instrumentation.mjs +1 -1
  57. package/dist/{key-D_kagnFv.mjs → key-B7vuAYPG.mjs} +2 -2
  58. package/dist/{key-D_kagnFv.mjs.map → key-B7vuAYPG.mjs.map} +1 -1
  59. package/dist/{libsql-DFAoHXrI.mjs → libsql-DUO6vHad.mjs} +2 -2
  60. package/dist/{libsql-DFAoHXrI.mjs.map → libsql-DUO6vHad.mjs.map} +1 -1
  61. package/dist/libsql.d.mts +1 -1
  62. package/dist/libsql.mjs +1 -1
  63. package/dist/{memory-GTWgeDNY.mjs → memory-BApsTkt1.mjs} +2 -2
  64. package/dist/{memory-GTWgeDNY.mjs.map → memory-BApsTkt1.mjs.map} +1 -1
  65. package/dist/migrations/mysql.d.mts +4 -4
  66. package/dist/migrations/mysql.mjs +1 -1
  67. package/dist/migrations/postgres.d.mts +4 -4
  68. package/dist/migrations/postgres.mjs +1 -1
  69. package/dist/migrations/sqlite.d.mts +4 -4
  70. package/dist/migrations/sqlite.mjs +1 -1
  71. package/dist/migrations/storage/durable-object.mjs +1 -1
  72. package/dist/migrations/storage/fs.mjs +1 -1
  73. package/dist/migrations/storage/r2.mjs +1 -1
  74. package/dist/migrations/tenant.d.mts +2 -2
  75. package/dist/migrations/tenant.mjs +1 -1
  76. package/dist/migrations.d.mts +4 -4
  77. package/dist/migrations.mjs +1 -1
  78. package/dist/{mysql-xChEivOe.mjs → mysql-D1GlcktG.mjs} +2 -2
  79. package/dist/{mysql-xChEivOe.mjs.map → mysql-D1GlcktG.mjs.map} +1 -1
  80. package/dist/{mysql-adapter-C6c5govr.mjs → mysql-adapter-ClOoHKpn.mjs} +2 -2
  81. package/dist/{mysql-adapter-C6c5govr.mjs.map → mysql-adapter-ClOoHKpn.mjs.map} +1 -1
  82. package/dist/mysql2.d.mts +1 -1
  83. package/dist/mysql2.mjs +1 -1
  84. package/dist/neon-http.d.mts +1 -1
  85. package/dist/neon-http.mjs +1 -1
  86. package/dist/{object-store-D9mvOHP4.d.mts → object-store-BN64q8Zn.d.mts} +3 -3
  87. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  88. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  89. package/dist/permissions.d.mts +2 -2
  90. package/dist/permissions.mjs +1 -1
  91. package/dist/permissions.mjs.map +1 -1
  92. package/dist/pg.d.mts +1 -1
  93. package/dist/pg.mjs +1 -1
  94. package/dist/pglite.d.mts +1 -1
  95. package/dist/pglite.mjs +1 -1
  96. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-CjvR0Ge2.mjs} +2 -2
  97. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-CjvR0Ge2.mjs.map} +1 -1
  98. package/dist/planetscale.d.mts +1 -1
  99. package/dist/planetscale.mjs +1 -1
  100. package/dist/{planner-C1NzLBge.d.mts → planner-8smxUOt9.d.mts} +1 -1
  101. package/dist/{postgres-BqAxDWTQ.mjs → postgres-Be0jMJWI.mjs} +2 -2
  102. package/dist/{postgres-BqAxDWTQ.mjs.map → postgres-Be0jMJWI.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-CxEit2-v.mjs → postgres-adapter-BoQ4RRwr.mjs} +2 -2
  104. package/dist/{postgres-adapter-CxEit2-v.mjs.map → postgres-adapter-BoQ4RRwr.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-C_Mt8lVC.mjs} +2 -2
  106. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-C_Mt8lVC.mjs.map} +1 -1
  107. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-CYu1dyI_.mjs} +1 -1
  108. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-CYu1dyI_.mjs.map} +1 -1
  109. package/dist/postgres.d.mts +1 -1
  110. package/dist/postgres.mjs +1 -1
  111. package/dist/result-shape-DQc-tDJ5.mjs +2 -0
  112. package/dist/{result-shape-CDgX_vzn.mjs.map → result-shape-DQc-tDJ5.mjs.map} +1 -1
  113. package/dist/rows-JXjhWwyb.mjs +2 -0
  114. package/dist/rows-JXjhWwyb.mjs.map +1 -0
  115. package/dist/{scalar-S8yMvdmx.mjs → scalar-CqqZ6jWd.mjs} +2 -2
  116. package/dist/{scalar-S8yMvdmx.mjs.map → scalar-CqqZ6jWd.mjs.map} +1 -1
  117. package/dist/schema/json.d.mts +1 -1
  118. package/dist/schema/json.mjs +1 -1
  119. package/dist/{schema-9N9jQlVL.mjs → schema-Cv-hhpl5.mjs} +2 -2
  120. package/dist/{schema-9N9jQlVL.mjs.map → schema-Cv-hhpl5.mjs.map} +1 -1
  121. package/dist/{schema-introspection-CyXKReK1.mjs → schema-introspection-B2Rvqgut.mjs} +3 -3
  122. package/dist/{schema-introspection-CyXKReK1.mjs.map → schema-introspection-B2Rvqgut.mjs.map} +1 -1
  123. package/dist/schema.d.mts +1 -1
  124. package/dist/schema.mjs +1 -1
  125. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-BxtETbG9.mjs} +1 -1
  126. package/dist/{select-assembly-CkGe2ABs.mjs.map → select-assembly-BxtETbG9.mjs.map} +1 -1
  127. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  128. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  129. package/dist/sha256-CEYo7k7R.mjs +2 -0
  130. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  131. package/dist/soft-delete.d.mts +1 -1
  132. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  133. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  134. package/dist/{sqlite-adapter-BXAJy3mI.mjs → sqlite-adapter-B_LNxPA0.mjs} +2 -2
  135. package/dist/{sqlite-adapter-BXAJy3mI.mjs.map → sqlite-adapter-B_LNxPA0.mjs.map} +1 -1
  136. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-DIOll4P7.mjs} +1 -1
  137. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-DIOll4P7.mjs.map} +1 -1
  138. package/dist/sqlite3.d.mts +1 -1
  139. package/dist/sqlite3.mjs +1 -1
  140. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-mJt0RHHE.mjs} +1 -1
  141. package/dist/{standard-sql-CoGqv-iX.mjs.map → standard-sql-mJt0RHHE.mjs.map} +1 -1
  142. package/dist/{to-many-C1PuFIpf.mjs → to-many-BSipkSbK.mjs} +2 -2
  143. package/dist/{to-many-C1PuFIpf.mjs.map → to-many-BSipkSbK.mjs.map} +1 -1
  144. package/dist/{utils-CtFUE8UN.mjs → utils-DjXObbUK.mjs} +2 -2
  145. package/dist/{utils-CtFUE8UN.mjs.map → utils-DjXObbUK.mjs.map} +1 -1
  146. package/dist/v-CrJYqdzu.mjs +2 -0
  147. package/dist/v-CrJYqdzu.mjs.map +1 -0
  148. package/dist/validation.d.mts +1 -1
  149. package/dist/validation.mjs +1 -1
  150. package/dist/{validator-DgffZq9C.mjs → validator-BqzpyNmt.mjs} +2 -2
  151. package/dist/{validator-DgffZq9C.mjs.map → validator-BqzpyNmt.mjs.map} +1 -1
  152. package/dist/version-Dus3if78.mjs +2 -0
  153. package/dist/{version-CXuJzC-q.mjs.map → version-Dus3if78.mjs.map} +1 -1
  154. package/package.json +16 -15
  155. package/dist/chain-C7c1YTXD.mjs +0 -2
  156. package/dist/chain-C7c1YTXD.mjs.map +0 -1
  157. package/dist/client-_WKrPNmm.mjs +0 -2
  158. package/dist/client-_WKrPNmm.mjs.map +0 -1
  159. package/dist/controls-Da-efekX.mjs +0 -2
  160. package/dist/controls-Da-efekX.mjs.map +0 -1
  161. package/dist/every-1pKZteeB.mjs +0 -2
  162. package/dist/identity-oQvIe7u8.mjs +0 -2
  163. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  164. package/dist/result-shape-CDgX_vzn.mjs +0 -2
  165. package/dist/v-CYTUI0H5.mjs +0 -2
  166. package/dist/v-CYTUI0H5.mjs.map +0 -1
  167. package/dist/version-CXuJzC-q.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-D_kagnFv.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-Da-efekX.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"controls-Da-efekX.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,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,QAAU,IAAA,GAClD,EAAS,KAAK,OAAO,GAAY,SAAW,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{p as t}from"./client-DM1UHfYG.mjs";import{n,t as r}from"./libsql-DFAoHXrI.mjs";import{t as i}from"./mysql-xChEivOe.mjs";import{t as a}from"./postgres-BqAxDWTQ.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i)}export{registerEveryMigrationDriver as t};
2
- //# sourceMappingURL=every-1pKZteeB.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,G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,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{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{b as r,c as i,r as a,t as o,u as s,v as c}from"./controls-Da-efekX.mjs";import{a as l,i as u,p as d,r as f}from"./chain-C7c1YTXD.mjs";import{S as p,t as m}from"./base-D3m1S7Uc.mjs";import{a as h,h as g,r as _}from"./error-mapping-C9WgitPi.mjs";import{d as v,f as y,p as b,y as x}from"./validation-BamBwne9.mjs";import{t as S}from"./transaction-4dfqals6.mjs";import{t as C}from"./sql-Bhxq9arK.mjs";import{o as w,s as T}from"./builder-Df24l2Bd.mjs";import{t as E}from"./types-C5Oxz9yp.mjs";import{i as D,t as O}from"./observation-Co72iCd1.mjs";import{a as k,o as A,r as j}from"./execution-context-rJXTRVrJ.mjs";import{n as M}from"./transaction-operation-CU1zlxiG.mjs";import{t as N}from"./result-parsing-8wEK3GY1.mjs";const P=new WeakMap,F=new WeakMap;function executePreparedQuery(e,t,n,r,i,a,o){return(e===void 0||t===void 0||t.length===0)&&o===void 0?n():!r&&o===void 0&&e!==void 0&&t!==void 0&&t.length>0?runCompiledQueryInterceptors(e,t,n,discardReadWriteOutcomeRegistration,a?.readCommitCertainty,a?.reportAdmissionFailure):executeInterceptedQuery(e,t,n,r,i,a,o)}function discardReadWriteOutcomeRegistration(){}async function executeInterceptedQuery(e,t,n,r,i,a,o){let s=o===void 0?[]:[o];o!==void 0&&i?.stage(o);let captureWriteOutcome=e=>{s.push(e),i?.stage(e)},c=0,l,u=!1,publish=async e=>{if(i){if(s.length===0||u)return;u=!0,i.confirm(s);return}c+=1,l=e,s.length!==0&&await publishWriteOutcomes(s,{certainty:e})},d=Object.freeze({committed:()=>publish(`committed`),mayHaveCommitted:()=>publish(`may-have-committed`)}),executeChild=async()=>{try{let e=await n(d);return r&&(i!==void 0||c===0)&&await publish(`committed`),e}catch(e){throw i&&!u&&i.discard(s),e}};try{return e===void 0||t===void 0||t.length===0?await executeChild():await runCompiledQueryInterceptors(e,t,executeChild,captureWriteOutcome,()=>l??a?.readCommitCertainty?.(),a?.reportAdmissionFailure)}catch(e){throw i&&!u&&i.discard(s),e}}function runCompiledQueryInterceptors(e,t,n,r,i,a){return t===void 0||t.length===0?n():runInterceptorAt(e,t,0,n,r,i,a)}function runInterceptorAt(e,t,n,r,i,a,o){let s=t[n];return s===void 0?r():runOneInterceptor(e,s,()=>runInterceptorAt(e,t,n+1,r,i,a,o),i,a,o)}async function runOneInterceptor(e,n,r,i,a,o){let s=!0,c,l=!1,u=!0,d,recordProtocolFailure=t=>{if(d)return d;let r=interceptorError(n.extension,e,t);return d=r,o?.(r),r},proceed=()=>{if(!s)throw recordProtocolFailure(`called proceed more than once`);if(l)throw recordProtocolFailure(`called proceed after its handler settled`);u=!1,s=!1;let e=startChild(r);return c=settle(e),e},onWriteOutcome=e=>{if(!t(e))throw recordProtocolFailure(`registered a non-function write-outcome listener`);if(!u||l)throw recordProtocolFailure(`registered a write-outcome listener after proceed`);i(Object.freeze({extension:n.extension,listener:e}))},f=exposeHandlerContext(e,proceed,onWriteOutcome,n.controls),p;try{p=Promise.resolve(Reflect.apply(n.handler,void 0,[f]))}catch(e){p=Promise.reject(e)}let m=await settle(p);l=!0,u=!1;let h=m.status===`fulfilled`?m:{...m,failure:d!==void 0&&m.reason===d?d:interceptorFailure(n.extension,e,m.reason,a?.())};if(c!==void 0&&h.status===`rejected`&&h.reason!==d&&o?.(h.failure),c===void 0){if(d)throw d;if(h.status===`rejected`)throw h.failure;if(requiresProceed(e))throw interceptorError(n.extension,e,`completed without proceed`);return h.value}let g=await c;if(g.status===`rejected`){let e=selectExtensionFailures(d,h,g);throw e?retainSuppressedFailures(g.reason,e):g.reason}let _=selectExtensionFailures(d,h,g);return _&&throwExtensionFailures(_),h.value}function selectExtensionFailures(e,t,n){if(e&&n.status===`rejected`&&n.reason===e)return;if(t.status!==`rejected`||e!==void 0&&t.reason===e||n.status===`rejected`&&t.reason===n.reason)return e?[e]:void 0;let r=t.failure;return e?[e,r]:[r]}function exposeHandlerContext(e,t,n,r){return Object.freeze({mode:e.mode,kind:e.kind,model:e.model,operation:e.operation,input:e.input,...e.kind===`model`&&r!==void 0?{controls:a(e.controls,r)}:{},proceed:t,onWriteOutcome:n})}function startChild(e){try{return Promise.resolve(e())}catch(e){return Promise.reject(e)}}async function settle(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function requiresProceed(e){return e.mode===`array`||e.kind!==`model`||!s(e.operation)}function interceptorFailure(e,t,n,r){return p(n)?n:interceptorError(e,t,`failed`,Error(`Query interceptor rejected with a non-Error value`),r)}function interceptorError(e,t,n,r,i){let a=`Extension "${e}" query handler for ${describeOperation(t)} ${n}.`,o={method:`query`,model:t.model,operation:String(t.operation),...i===void 0?{}:{commitCertainty:i}};return r?new b(a,{cause:r,meta:o}):new b(a,{meta:o})}function describeOperation(e){return e.kind===`model`?`${e.model}.${e.operation}`:e.operation}function throwExtensionFailures(e){let t=e[0];throw e.length===1?t:AggregateError(e,`Query interceptor protocol and handler both failed.`,{cause:t})}function retainSuppressedFailures(e,t){let n=AggregateError([e,...t],`Query execution and extension post-work both failed.`,{cause:e});return P.set(n,e),n}function decomposeQueryCoordinationFailure(e){if(!(e instanceof AggregateError)||!P.has(e))return;let t=P.get(e);if(!(e.cause!==t||e.errors[0]!==t))return Object.freeze({child:t,postWork:Object.freeze(e.errors.slice(1))})}var TransactionWriteOutcomes=class{#e=[];stage(e){for(let t of this.#e)if(t.registration===e)return;this.#e.push({registration:e,state:`pending`})}confirm(e){this.#t(e,`confirmed`)}discard(e){this.#t(e,`discarded`)}discardAll(){for(let e of this.#e)e.state=`discarded`}promoteTo(e){for(let t of this.#e)t.state===`confirmed`&&e.#e.push({...t}),t.state=`discarded`}publishCommitted(){return this.publish(`committed`)}async publish(e){let t=[];for(let e of this.#e)e.state===`confirmed`&&t.push(e.registration),e.state=`discarded`;await publishWriteOutcomes(t,{certainty:e})}#t(e,t){for(let n of this.#e)n.state===`pending`&&e.includes(n.registration)&&(n.state=t)}};async function publishWriteOutcomes(e,t){let n;for(let r of e)try{await r.listener(t)}catch(e){let i=p(e)?e:void 0,a=r.failurePolicy===`boundary-owned`&&i!==void 0?i:new b(`Extension "${r.extension}" write-outcome listener failed after ${t.certainty}.`,{cause:i??Error(`Write-outcome listener rejected with a non-Error value`),meta:{method:`onWriteOutcome`,commitCertainty:t.certainty}});(n??=[]).push(a)}if(n===void 0)return;let[r]=n;if(n.length===1)throw r;let i=AggregateError(n,`Multiple extension write-outcome listeners failed.`,{cause:r});throw F.set(i,n),i}function decomposeWriteOutcomePublicationFailure(e){return e instanceof AggregateError?F.get(e)??[e]:[e]}function createOperationExecutionContext(e,t,n){let r=O(n)?.diagnostics?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return j({model:e,operation:t},createCorrelationId,n,r)}function createPendingOperationContext(e,t,n,r,i){return Object.freeze({clientId:n,scopeId:r,attribution:createOperationExecutionContext(e,t,i)})}function withOperationErrorContext(e,t){let n=k(e);if(n===void 0)return t();let r=O(A(e))?.diagnostics,annotate=t=>{throw t instanceof m?h(t,{forceContext:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:n,diagnostics:r}):t};try{return t().catch(annotate)}catch(e){return Promise.reject().catch(()=>annotate(e))}}function createPendingOperationInstrumentationFacts(e,t,n,r,i,a,o){return createOperationInstrumentationFacts(e,t,n,r,i,a,o)}function createRawOperationInstrumentationFacts(e,t,n){return createOperationInstrumentationFacts(e,t,void 0,n,n,void 0,!1)}function createOperationInstrumentationFacts(e,t,n,i,a,o,s){let c=O(A(t));if(c?.observesLifecycle===!0)return()=>Object.freeze({kind:`operation`,context:t,identity:d(e),model:n,requestedOperation:i,operation:a,collection:o,complete(e){let n=s?r().readCacheExecutionOutcomes(t):void 0,{failure:i}=e,a=e.status===`failure`&&c.wants(`error-log`)&&isUnloggedError(i)?i:void 0,o=e.status===`failure`&&i instanceof Error&&c.wants(`operation`)?i:void 0;if(!(n===void 0&&a===void 0&&o===void 0))return Object.freeze({kind:`operation`,endedAt:Date.now(),...n===void 0?{}:{readCacheOutcomes:n},...(a??o)===void 0?{}:{failure:a??o},...a===void 0?{skipLog:!0}:{}})}})}async function observeTransactionBatchPhase(e,t,n){let r=O(A(e))?.diagnostics;try{return await n()}catch(n){throw _(n,{driverName:t.driverName,dialect:t.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:k(e),diagnostics:r,forceContext:!0})}}function createCorrelationId(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function isUnloggedError(e){return e instanceof Error&&!g(e)}function captureExecution(e){try{return e()}catch(e){return Promise.reject(e)}}var PendingExecution=class{#e=null;#t=null;#n=!1;#r;#i;constructor(e,t){this.#r=e,this.#i=t}executeDefault(e){if(this.#t!==null&&this.#t!==`default`)throw v.alreadyExecutedWithDriver(this.#r,this.#i);return this.#e||=(this.#t=`default`,captureExecution(e)),this.#e}executeWith(e,t){if(this.#n)throw v.alreadyExecutedWithDriver(this.#r,this.#i);if(this.#t===`default`)throw v.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null&&this.#t!==e)throw v.differentDriverConflict(this.#r,this.#i);return this.#e||=(this.#t=e,captureExecution(t)),this.#e}reserveWith(e){if(this.#t===`default`)throw v.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null)throw this.#t===e?v.alreadyExecutedWithDriver(this.#r,this.#i):v.differentDriverConflict(this.#r,this.#i);this.#t=e,this.#n=!0}executeReserved(e){return this.#e||=captureExecution(e),this.#e}};const I=Object.freeze({accessor:opaqueInspectionValue(`accessor`),function:opaqueInspectionValue(`function`),unsupported:opaqueInspectionValue(`unsupported`)}),L=Object.getOwnPropertyDescriptor(C.prototype,`strings`)?.get,R=Object.getOwnPropertyDescriptor(C.prototype,`values`)?.get;function opaqueInspectionValue(e){let t=Object.create(null);return t.opaque=e,Object.freeze(t)}function snapshotQueryInput(e){return snapshotOwn(e,new Map,!1)}function snapshotOwn(e,t,n){let r=n?[]:Object.create(null);t.set(e,r);let i;try{i=Reflect.ownKeys(e)}catch{return t.set(e,I.unsupported),I.unsupported}for(let a of i){let i;try{i=Object.getOwnPropertyDescriptor(e,a)}catch{return t.set(e,I.unsupported),I.unsupported}if(i!==void 0){if(n&&a===`length`){Object.defineProperty(r,a,i);continue}i.enumerable&&Object.defineProperty(r,a,{configurable:!1,enumerable:!0,value:`value`in i?snapshotValue(i.value,t):I.accessor,writable:!1})}}return Object.freeze(r)}function snapshotValue(e,t){if(typeof e==`function`)return I.function;if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);try{if(Array.isArray(e))return snapshotOwn(e,t,!0);let r=Object.getPrototypeOf(e);if(r===C.prototype&&e instanceof C)return snapshotSql(e,t);if(r===Date.prototype&&e instanceof Date){let n=Object.freeze(new Date(Date.prototype.getTime.call(e)));return t.set(e,n),n}if(e instanceof Uint8Array){let n=new Uint8Array(e);return t.set(e,n),n}if(r===ArrayBuffer.prototype&&e instanceof ArrayBuffer){let n=e.slice(0);return t.set(e,n),n}if(r===Map.prototype&&e instanceof Map){let n=new Map;return t.set(e,n),Map.prototype.forEach.call(e,(e,r)=>{n.set(snapshotValue(r,t),snapshotValue(e,t))}),n}if(r===Set.prototype&&e instanceof Set){let n=new Set;return t.set(e,n),Set.prototype.forEach.call(e,e=>{n.add(snapshotValue(e,t))}),n}if(ArrayBuffer.isView(e)){let n=structuredClone(e);return t.set(e,n),n}if((r===Object.prototype||r===null)&&n(e))return snapshotOwn(e,t,!1)}catch{}return t.set(e,I.unsupported),I.unsupported}function snapshotSql(e,t){if(!(L&&R))throw TypeError(`Sql inspection getters are unavailable`);let n=Reflect.apply(L,e,[]),r=Reflect.apply(R,e,[]),i=Array(n.length);for(let e=0;e<n.length;e+=1){let t=Object.getOwnPropertyDescriptor(n,e);if(!(t&&`value`in t&&typeof t.value==`string`))throw TypeError(`Sql inspection strings are not plain data values`);i[e]=t.value}let a=Array(r.length),o=new C(i,a);t.set(e,o);for(let e=0;e<r.length;e+=1){let n=Object.getOwnPropertyDescriptor(r,e);a[e]=n&&`value`in n?snapshotValue(n.value,t):I.accessor}o.toStatement(`?`),o.toStatement(`$n`),o.toStatement(`:n`);for(let e of Reflect.ownKeys(o)){let t=Reflect.get(o,e);typeof t==`object`&&t&&Object.freeze(t)}return Object.freeze(o),o}const z=Symbol.for(`viborm.pendingOperation`);let attachPendingCacheExecutionFriend,readPendingCacheResultFriend;function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,r;try{await e()}catch(e){n=!0,r=e}try{await t()}catch(e){throw n?x(r,e,`Write publication callbacks both failed.`):e}if(n)throw r}}const B=Object.freeze({});let createPendingOperationFriend,V;var H=class PendingOperation{[Symbol.toStringTag]=`Promise`;[z]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=!1;#p;#m;#h;#g;#_;#v=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(B,e,t,n,r,i,void 0,void 0,a===void 0?void 0:{prepare:a,status:`pending`},void 0,o),attachPendingCacheExecutionFriend=(e,t)=>e.#F(t),readPendingCacheResultFriend=e=>({get args(){return e.cacheKeyArgs()},get controls(){return e.#y(),e.#l?.controls},get codec(){return e.#T()},executionContext:e.#e.attribution}),V=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,requiresInterception:e=>{let t=String(e.#o.originalOperation),n=u(e.#t.extensionChain,`request`,e.#i,t),r=n!==void 0&&n.length>0&&(e.#t.extensionChain?.observe.length??0)>0,i=u(e.#t.extensionChain,`query`,e.#i,t);return r||i!==void 0&&i.length>0||e.#u!==void 0},prepareAdmission:(e,t=`input`)=>{e.#C(),t===`plan`&&e.#S()},stagePackageWriteOutcomes:(e,t)=>{let n=e.#b();n!==void 0&&t.stage(n)},startInterception:(e,t,n,r)=>{let i=String(e.#o.originalOperation),a=u(e.#t.extensionChain,`query`,e.#i,i),o=e.#C(),c=e.#b();return(a===void 0||a.length===0)&&c===void 0?t():executePreparedQuery(a===void 0||a.length===0?void 0:e.#w(`array`,o),a,t,!s(i),n,r,c)},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#M(t,n?.committed,n?.mayHaveCommitted)),isWrite:e=>!s(String(e.#o.originalOperation)),hasObservation:e=>(e.#t.extensionChain?.observe.length??0)>0,observe:(e,t,n)=>{let r=e.#t.extensionChain?.observe;return r===void 0||r.length===0?t():D(r,String(e.#o.originalOperation),e.#i,t,n,e.#D())},reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observe;return n===void 0||n.length===0?e.#s.executeWith(t,()=>e.#M(t)):e.#s.executeWith(t,()=>D(n,String(e.#o.originalOperation),e.#i,()=>e.#M(t),()=>e.#m===void 0?void 0:{commitCertainty:e.#m},e.#D()))},prepare:e=>e.#S()?.queries[0],prepareBatch:e=>e.#x().prepareBatch(e.#e.attribution),parseResult:(e,t)=>{let n=e.#S();if(!n)throw new y(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);return n.parseResult([t])},observeBatchPhase:(e,t,n)=>observeTransactionBatchPhase(e.#e.attribution,t,n)}),M(PendingOperation.prototype,e=>#e in e,V),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,i,a,o,s,c,l,u){if(e!==B)throw new S;this.#t=t,this.#n=n,this.#r=i,this.#c=s,this.#l=c,this.#u=u,this.#p=l,this.#h=t.route;let d=r.endsWith(`OrThrow`);this.#a=d?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new PendingExecution(this.#i,this.#a),this.#o=Object.freeze({...a,throwIfNotFound:d||a?.throwIfNotFound,originalOperation:a?.originalOperation??r}),this.#e=o??createPendingOperationContext(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),Object.freeze(this)}#y(){let e=this.#l;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=f(this.#t.extensionChain,this.#i,String(this.#o.originalOperation)),n=t.length===0?void 0:o(this.#i,this.#a,this.#r,t,this.#t.bound),r=e.prepare(n?.args??this.#r,n?.controls);return e.args=r,e.controls=n?.controls,e.status=`success`,r}catch(t){throw e.error=t,e.status=`failure`,t}}#b(){return this.#f?this.#d:(this.#d=this.#u?.(this.#e.attribution,this.#l?.controls),this.#f=!0,this.#d)}#x(){let e=this.#p?.routed;if(e)return e;if(this.#g)return this.#g;if(!i.has(this.#a))throw new y(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...i].sort().join(`, `)}.`);let t=this.#y(),n=this.#t.extensionChain?.callRows,r=this.#h.operation(this.#n,String(this.#o.originalOperation),t,n&&l(n,this.#i,this.#l?.controls));return this.#g=r,this.#p&&(this.#p.routed=r),r}#S(){if(this.#v)return this.#_;let e=this.#x().prepareSingle(this.#e.attribution);return this.#_=e?.queries.length===1?e:void 0,this.#v=!0,this.#_}#C(){return this.#x().preparedArgs}#w(e,t){let n=this.#l?.controls;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),input:snapshotQueryInput(t),...n===void 0?{}:{controls:n}})}#T(){return this.#x().cacheResultCodec()}#E(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observe;return e===void 0||e.length===0?this.#O():D(e,String(this.#o.originalOperation),this.#i,()=>this.#O(),()=>this.#m===void 0?void 0:{commitCertainty:this.#m},this.#D())})}#D(){return createPendingOperationInstrumentationFacts(this.#t.driver,this.#e.attribution,this.#i,String(this.#o.originalOperation),String(this.#a),this.#n[`~`].names.sql??this.#i,c(this.#o))}#O(e,t,n){return withOperationErrorContext(this.#e.attribution,()=>this.#k(e,t,n))}#k(e,t,n){let r=this.#j(`committed`),i=this.#j(`may-have-committed`),a=String(this.#o.originalOperation),o=u(this.#t.extensionChain,`query`,this.#i,a);return(o===void 0||o.length===0)&&this.#u===void 0?this.#M(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#A(o,a,r,i,e,t,n)}#A(e,t,n,r,i,a,o){let c;try{c=this.#C()}catch(e){return Promise.reject(e)}let l=this.#b();return(e===void 0||e.length===0)&&l===void 0?this.#M(i,combineWriteNotifications(a,n),combineWriteNotifications(o,r)):executePreparedQuery(e===void 0||e.length===0?void 0:this.#w(this.#t.transactionWriteOutcomes?`transaction`:`direct`,c),e,e=>this.#M(i,combineWriteNotifications(a,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(o,combineWriteNotifications(e?.mayHaveCommitted,r))),!s(t),this.#t.transactionWriteOutcomes,void 0,l)}#j(e){if(!(this.#t.transactionWriteOutcomes!==void 0||(this.#t.extensionChain?.observe.length??0)===0))return async()=>{(e===`committed`||this.#m===void 0)&&(this.#m=e)}}#M(e,t,n){return this.#c?this.#c(e,t,n):this.#N(e,t,n)}#N(e,t,n){let r;try{r=this.#x()}catch(e){return Promise.reject(e)}return r.execute({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!s(String(this.#o.originalOperation)),writeMayBeVisible:n})}getArgs(){return this.#r}cacheKeyArgs(){let e=this.#P();if(!e)throw new y(`Operation '${this.#a}' on model '${this.#i}' exposes no validated payload to key a cache entry on.`);return e}#P(){if(s(this.#a))return this.#x().preparedArgs}buildStatement(){return this.#x().buildStatement()}#F(e){let t=this.#p??={routed:this.#g},deferredExecution=(t,n,r)=>e((e,i,a)=>this.#M(e??t,combineWriteNotifications(i,n),combineWriteNotifications(a,r)),t);return new PendingOperation(B,this.#t,this.#n,this.#a,this.#r,this.#o,this.#e,deferredExecution,this.#l,t,this.#u)}then(e,t){return this.#E().then(e,t)}catch(e){return this.#E().catch(e)}finally(e){return this.#E().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function attachPendingCacheExecution(e,t){return attachPendingCacheExecutionFriend(e,t)}function readPendingCacheResult(e){return readPendingCacheResultFriend(e)}function isPendingOperation(e){return typeof e==`object`&&!!e&&z in e&&e[z]===!0}const U=`0viborm_distance`,W=`0viborm_relation_counts`,G=`0viborm_empty_row`,gateResultKey=e=>`0viborm_gate:${e}`,K=`0viborm_cursor_`,q=`0viborm_orphans`;function getAggregateResultKey(e){return`0viborm_aggregate:${e.slice(1)}`}function getAggregateResultName(e){switch(e){case`0viborm_aggregate:count`:return`_count`;case`0viborm_aggregate:avg`:return`_avg`;case`0viborm_aggregate:sum`:return`_sum`;case`0viborm_aggregate:min`:return`_min`;case`0viborm_aggregate:max`:return`_max`;default:return}}function getGroupByFields(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[];if(new Set(t).size!==t.length)throw new y(`GroupBy operation does not allow duplicate fields in 'by'`);return t}const J=new Set([`findFirst`,`findMany`,`findUnique`,`create`,`createManyAndReturn`,`update`,`updateManyAndReturn`,`delete`,`deleteManyAndReturn`,`upsert`]),Y=`Distance select supports only one _distance field per select.`;function selectedArm(e,t,r){let i=n(e)?e:void 0;if(!t)return getOwnValue(i,r)??!0;let a=getOwnValue(i,`only`);if(Array.isArray(a)&&!a.includes(r))return;let o=getOwnValue(i,`variants`);return(n(o)?getOwnValue(o,r):void 0)??!0}const X=[`_count`,`_avg`,`_sum`,`_min`,`_max`];function getOwnValue(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function createShape(e,t=new Map,n=new Map,r=new Set,i=new Map,a){if(new Set(e).size!==e.length)throw new y(`The requested result shape contains colliding output columns.`);return{carrier:`rows`,rawKeys:e,...a?{distanceScalar:a}:{},relations:t,polymorphic:i,aggregates:n,relationCounts:r}}function selectedEntries(e){return n(e)?Object.entries(e).filter(([,e])=>e!==!1&&e!==void 0):[]}function getNestedSelection(e){if(!n(e))return{};let t={},r=getOwnValue(e,`select`),i=getOwnValue(e,`include`);return n(r)&&(t.select=r),n(i)&&(t.include=i),t}function buildModelShape(e,t,r){let i=[],a=new Map,o=new Map,s=e[`~`].state.scalars,c=e[`~`].state.relations,l=getOwnValue(t,`select`),u=getOwnValue(t,`include`),d=n(l)?l:void 0,f=n(u)?u:void 0,p=!1,m;if(d)for(let[e,t]of Object.entries(d)){let r=getOwnValue(s,e);if(r){if(t===!0){i.push(e);continue}if(n(t)&&Object.hasOwn(t,`_distance`)){if(p)throw new y(Y);p=!0,m=r,i.push(U)}}}else for(let t of T(e))i.push(t);addSelectedRelations(e,c,d,i,a,r),addSelectedPolymorphicRelations(e,d,i,o,r),addSelectedRelations(e,c,f,i,a,r),addSelectedPolymorphicRelations(e,f,i,o,r);let h=[getOwnValue(d,`_count`),getOwnValue(f,`_count`)],g=new Set;for(let e of h){if(!n(e))continue;let t=getOwnValue(e,`select`);if(n(t))for(let[e]of selectedEntries(t)){let t=getOwnValue(c,e);if(!t)continue;let n=t[`~`].state;E(n)&&n.cardinality!==`many`||g.add(e)}}return g.size>0&&i.push(W),i.length===0&&i.push(G),createShape(i,a,new Map,g,o,m)}function admittedRecurrence(e){if(n(e))return getOwnValue(e,`recurse`)}function addSelectedRelations(e,t,n,r,i,a){for(let[o,s]of selectedEntries(n)){let n=getOwnValue(t,o);if(!n||E(n[`~`].state))continue;let c=n[`~`].settleTarget();r.push(o);let l=buildModelShape(c,getNestedSelection(s),a),u=a.get(e)?.get(o),d=admittedRecurrence(s);i.set(o,{model:c,shape:l,cardinality:n[`~`].state.cardinality,optional:u!==void 0&&w(u),...d?{recurrence:d}:{}})}}function addSelectedPolymorphicRelations(e,t,n,r,i){let a=e[`~`].state.relations;for(let[o,s]of selectedEntries(t)){let t=getOwnValue(a,o);if(!t)continue;let c=t[`~`].state;if(!E(c))continue;let l=c.cardinality===`many`,u=new Map;for(let e of Object.keys(c.target.entries)){let n=selectedArm(s,l,e);if(n===void 0)continue;let r=t[`~`].settleTarget(e);u.set(e,{model:r,shape:buildModelShape(r,getNestedSelection(n),i)})}n.push(o);let d=i.get(e)?.get(o);r.set(o,{cardinality:c.cardinality,optional:d!==void 0&&w(d),variants:u})}}function buildAggregateShape(e,t=[]){let n=[...t],r=new Set(t),i=new Map;for(let t of X){let a=getOwnValue(e,t);if(a===void 0||a===!1)continue;let o;if(!(t===`_count`&&a===!0)){let e=selectedEntries(a);if(e.length===0)continue;o=new Set(e.map(([e])=>e))}if(r.has(t))throw new y(`GroupBy cannot return both grouped scalar '${t}' and aggregate '${t}' in one result.`);let s=getAggregateResultKey(t);n.push(s),r.add(t),i.set(s,{...o?{fields:o}:{}})}return createShape(n,new Map,i)}function buildCountShape(e){let t=selectedEntries(getOwnValue(e,`select`)).map(([e])=>e);return{...createShape(t.length===0?[N]:t),carrier:`count`}}function buildExpectedResultShape(e,t,n,r){if(t===`count`)return buildCountShape(n);if(t===`exist`)return{...createShape([N]),carrier:`existence`};if(t===`aggregate`)return buildAggregateShape(n);if(t===`groupBy`)return buildAggregateShape(n,getGroupByFields(getOwnValue(n,`by`)));if(J.has(t))return buildModelShape(e,n,r)}export{decomposeQueryCoordinationFailure as C,TransactionWriteOutcomes as S,executePreparedQuery as T,PendingExecution as _,U as a,observeTransactionBatchPhase as b,W as c,H as d,attachPendingCacheExecution as f,snapshotQueryInput as g,readPendingCacheResult as h,K as i,gateResultKey as l,isPendingOperation as m,buildExpectedResultShape as n,G as o,createPendingOperation as p,selectedArm as r,q as s,Y as t,getAggregateResultName as u,createOperationExecutionContext as v,decomposeWriteOutcomePublicationFailure as w,withOperationErrorContext as x,createRawOperationInstrumentationFacts as y};
2
- //# sourceMappingURL=result-shape-CDgX_vzn.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,c as n,i as r,n as i,o as a,r as o,s}from"./value-guards-CK9guf2Z.mjs";import{t as c}from"./validation-BamBwne9.mjs";import{$ as l,I as u,L as ee,N as te,P as d,Pt as f,Q as p,R as m,X as h,Y as g,Z as _,a as ne,d as re,f as v,i as ie,jt as y,nt as ae,o as oe,p as b,r as se,rt as x,tt as ce,z as S}from"./geo-point-codec-DyEHMdJg.mjs";import{o as le,r as C}from"./sql-Bhxq9arK.mjs";const w=Symbol.for(`viborm.field-ref`);function isFieldRef(e){if(typeof e!=`object`||!e)return!1;let t=e[w];return typeof t==`object`&&!!t}function fieldRefPayload(e){return e[w]}function formatFieldRef(e){let t=fieldRefPayload(e);return`${t.model}.${t.field}`}function createFieldRef(e,t,n,r){return Object.freeze({[w]:Object.freeze({model:e,field:t,type:n,list:r})})}const UNKNOWN_FIELD=(e,t,n)=>Error(`Unknown scalar field "${t}" on model '${e}'. Known fields: ${n.join(`, `)}.`);function createModelFieldRefs(e,t){let n=new Map,r=t[`~`].state.scalars,i=Object.keys(r).filter(e=>r[e][`~`].state.type!==`point`),a=new Set(i);return new Proxy(Object.create(null),{get(t,o){if(typeof o!=`string`)return;let s=n.get(o);if(s)return s;let c=a.has(o)?r[o]:void 0;if(!c)throw UNKNOWN_FIELD(e,o,i);let l=c[`~`].state,u=createFieldRef(e,o,l.type,l.array);return n.set(o,u),u},has:(e,t)=>typeof t==`string`&&a.has(t),ownKeys:()=>i,getOwnPropertyDescriptor:(e,t)=>typeof t==`string`&&a.has(t)?{enumerable:!0,configurable:!0}:void 0})}const T=Symbol.for(`viborm.json-null`);var JsonNullSentinel=class{[T];kind;constructor(e){this[T]=e,this.kind=e,Object.freeze(this)}toString(){return this.kind}toJSON(){return`viborm.json-null:${this.kind}`}};const ue=new JsonNullSentinel(`DbNull`),E=new JsonNullSentinel(`JsonNull`),de=new JsonNullSentinel(`AnyNull`),fe=new Set([`DbNull`,`JsonNull`,`AnyNull`]);function isJsonNullSentinel(e){if(typeof e!=`object`||!e)return!1;let t=e[T];return typeof t==`string`&&fe.has(t)}function jsonNullKindOf(e){return isJsonNullSentinel(e)?e.kind:void 0}function refuseRelationInput(e,t,n,r){throw new c({kind:`schema-builder`,builder:e,path:t},[{path:t,message:n}],r===void 0?void 0:{cause:r})}function isPlainRecord(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function declaredKeys(e){return Object.keys(e)}function hasExactKeys(e,t){return e.length===t.length&&t.every(t=>e.includes(t))}function readCallerProperty(e,t,n,r){try{return Reflect.get(t,n)}catch(t){refuseRelationInput(e,r,`Could not read relation input '${r}'`,normalizeThrown(t,`Reading relation input '${r}' threw a non-Error value`))}}function normalizeRelationName(e,t){return(typeof t!=`string`||t.length===0)&&refuseRelationInput(e,`name`,`A relation name must be a non-empty string`),t}function normalizeReferentialAction(e,t){if(t===`cascade`||t===`setNull`||t===`restrict`||t===`noAction`)return t;refuseRelationInput(`s.toOne`,e,`A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'`)}function normalizeJunctionAction(e,t){if(t===`cascade`||t===`restrict`||t===`noAction`)return t;refuseRelationInput(`s.toMany`,e,`A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member`)}function normalizeJunctionActions(e,t){if(typeof t!=`object`||!t){let n=normalizeJunctionAction(e,t);return Object.freeze({source:n,target:n})}isPlainRecord(t)&&hasExactKeys(declaredKeys(t),[`source`,`target`])||refuseRelationInput(`s.toMany`,e,`A junction '${e}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`);let side=n=>normalizeJunctionAction(`${e}.${n}`,readCallerProperty(`s.toMany`,t,n,`${e}.${n}`));return Object.freeze({source:side(`source`),target:side(`target`)})}function normalizeJunctionToken(e,t){return f(t)||refuseRelationInput(`s.toMany`,e,`Junction '${e}' must be a valid schema identifier`),t}function normalizeFieldTuple(e,t,n){let[r,...i]=n;return r===void 0&&refuseRelationInput(e,t,`'${t}' requires at least one field key`),new Set(n).size!==n.length&&refuseRelationInput(e,t,`'${t}' cannot repeat a field key in one foreign-key tuple`),[r,...i]}function createTargetSettlement(e){let t=new Map;return n=>{let r=n??``,i=t.get(r);if(i===void 0&&(i=settleTargetOnce(e,n),t.set(r,i)),i.settled===`value`)return i.value;throw i.error}}function settleTargetOnce(e,t){let n=e(t);if(typeof n!=`function`)return{settled:`error`,error:Error(`Relation target getter is not a function`)};try{return{settled:`value`,value:n()}}catch(e){return{settled:`error`,error:normalizeThrown(e,`Relation target getter threw a non-Error value`)}}}function normalizeThrown(e,t){if(e instanceof Error)return e;let n;try{n=typeof e==`symbol`?e.toString():String(e)}catch{n=`<unrenderable non-Error value>`}return Error(`${t}: ${n}`)}function array(e){let t=e[`~standard`].validate,n=_(`array`,e=>ae(e,t));return n.item=e,n}const D=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Uint8Array`})])}),O=Object.getPrototypeOf(Uint8Array.prototype);function localBufferPrototype(){try{let e=Reflect.get(globalThis,`Buffer`);if(typeof e!=`function`)return;let t=Reflect.get(e,`prototype`);if(typeof t==`object`&&t&&Object.getPrototypeOf(t)===Uint8Array.prototype)return t}catch{return}}const k=localBufferPrototype();function hasOwnViewMetadata(e){return Object.getOwnPropertyDescriptor(e,`buffer`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteOffset`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteLength`)!==void 0}function hasTrustedLocalPrototype(e){let t=Object.getPrototypeOf(e);return(t===Uint8Array.prototype||t===k)&&!hasOwnViewMetadata(e)}function validateBlob(e){try{if(!n(e))return D;let t=Reflect.get(O,`buffer`,e),r=Reflect.get(O,`byteOffset`,e),i=Reflect.get(O,`byteLength`,e),a=hasTrustedLocalPrototype(e),o=new Uint8Array(t,r,i);return l(a?e:o)}catch{return D}}function blob(e){return h(`blob`,validateBlob,e)}const A=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected boolean`})])});function validateBoolean(e){return i(e)?l(e):A}function boolean(e){return h(`boolean`,validateBoolean,e)}const j=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Date`})])}),M=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected valid Date`})])});function validateDate(e){if(!o(e))return j;let t=Date.prototype.getTime.call(e);return Number.isNaN(t)?M:e instanceof Date?l(e):l(new Date(t))}function date(e){return h(`date`,validateDate,e)}const N=Object.freeze({issues:Object.freeze([Object.freeze({message:d})])});function validateDecimal(e){let t=u(e);return t===void 0?N:l(t)}function buildDecimalValueValidator(e){let t=e?.schema,n=e?.decimal,validate=validateDecimal;if(t!==void 0){let e=t[`~standard`].validate,n=validate;validate=t=>{let r=n(t);if(r.issues)return r;let i=e(te(r.value));if(`then`in i)return y(i),p(`Async schemas are not supported`);if(i.issues)return ce(i.issues);let a=ee(i.value);return a===void 0?p(`Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type`):l(a)}}if(n!==void 0){let e=validate;validate=t=>{let r=e(t);if(r.issues)return r;let i=m(r.value,n.precision,n.scale);return i===void 0?r:p(i)}}return validate}function decimal(e){let t=e===void 0?void 0:{...e,schema:void 0};return h(`decimal`,buildDecimalValueValidator(e),t)}function enum_(e,t){let n=new Set(e),baseValidate=t=>s(t)&&n.has(t)?l(t):{issues:[{message:`Expected one of: ${e.join(` | `)}`}]};return h(`enum`,baseValidate,t,{values:e})}function getNestedValue(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function declaresPath(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:getNestedValue(e,t.slice(0,n));return a(r)&&t.slice(n+1)in r}function entriesFromObject(e,t){let n={};for(let r of Object.keys(e)){let i=getNestedValue(e[r],t);i!==void 0&&(n[r]=i)}return Object.keys(e).length>0&&Object.keys(n).length===0&&refuseUnmatchedPath(e,t),n}function fromObject(e,t,n){return S(entriesFromObject(e,t),n)}function refuseUnmatchedPath(e,t){if(!Object.values(e).some(e=>declaresPath(e,t)))throw new c({kind:`schema-builder`,builder:`fromObject`,path:t},[{path:t,message:`fromObject path "${t}" did not match any entries in the source object`}])}const P=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-](\d{2}):(\d{2}))$/,F=/^(\d{4})-(\d{2})-(\d{2})$/,I=/^\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/,L=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string or Date`})])}),R=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)`})])}),z=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date in ISO timestamp`})])});function validateIsoTimestamp(e){if(o(e))return v(Date.prototype.getTime.call(e))?l(Date.prototype.toISOString.call(e)):z;if(!s(e))return L;let t=P.exec(e);return t?!(b(Number(t[1]),Number(t[2]),Number(t[3]))&&re(Number(t[4]),Number(t[5]),Number(t[6])))||Number(t[7]??0)>23||Number(t[8]??0)>59||!v(Date.parse(e))?z:l(new Date(e).toISOString()):R}function isoTimestamp(e){return h(`iso_timestamp`,validateIsoTimestamp,e)}const B=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO date format (YYYY-MM-DD)`})])}),V=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date`})])});function validateIsoDate(e){if(o(e))return v(Date.prototype.getTime.call(e))?l(Date.prototype.toISOString.call(e).slice(0,10)):V;if(!s(e))return L;let t=F.exec(e);return t?b(Number(t[1]),Number(t[2]),Number(t[3]))?l(e):V:B}function isoDate(e){return h(`iso_date`,validateIsoDate,e)}const pe=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO time format (HH:mm:ss)`})])}),H=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid time`})])});function validateIsoTime(e){if(o(e))return Number.isNaN(Date.prototype.getTime.call(e))?H:l(Date.prototype.toISOString.call(e).split(`T`)[1].replace(`Z`,``));if(!s(e))return L;if(!I.test(e))return pe;let t=e.split(`:`),n=Number(t[0]),r=Number(t[1]),i=Math.trunc(Number(t[2]));return n<0||n>23||r<0||r>59||i<0||i>59?H:l(e.padEnd(12,e.includes(`.`)?`0`:`.000`))}function isoTime(e){return h(`iso_time`,validateIsoTime,e)}const me=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected JSON-compatible value`})])}),U=Symbol(`invalid JSON`);function normalizeJson(e,n=new WeakMap){if(e===null||s(e)||i(e))return e;if(t(e))return Number.isFinite(e)?e:U;if(!(a(e)||Array.isArray(e))||isFieldRef(e))return U;let r=n.get(e);if(r!==void 0)return r;if(n.set(e,U),Array.isArray(e)){let t=[];for(let r of e){let e=r===void 0?null:normalizeJson(r,n);if(e===U)return U;t.push(e)}return n.set(e,t),t}let o=Object.getPrototypeOf(e);if(o!==null&&o!==Object.prototype)return U;let c={};for(let t of Object.keys(e)){let r=e[t];if(r===void 0)continue;let i=normalizeJson(r,n);if(i===U)return U;Object.defineProperty(c,t,{value:i,enumerable:!0,configurable:!0,writable:!0})}return n.set(e,c),c}function validateJson(e){let t=normalizeJson(e);return t===U?me:l(t)}function json(e){return h(`json`,validateJson,e)}const W=[`DbNull`,`JsonNull`,`AnyNull`];function listKinds(e){return e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} or ${e.at(-1)}`}function refuseSentinel(e,t,n){return p(`${W.filter(e=>!t.includes(e)).length===W.length?`JSON null sentinels are not supported in ${n}`:`${e.kind} is not supported in ${n}; that slot accepts ${listKinds(t)}`}.`)}function checkSentinel(e,t,n){return t.includes(e.kind)?l(e):refuseSentinel(e,t,n)}function copyOptionality(e,t,n){e.allowed=n,e.wrapped=t,e.acceptsUndefined=t.acceptsUndefined===!0}function jsonNullOr(e,t,n){let r=_(`json_null_or`,r=>isJsonNullSentinel(r)?checkSentinel(r,e,n):x(t,r));return copyOptionality(r,t,e),r}function jsonWrite(e,t,n,r){let i=_(`json_write`,i=>{if(isJsonNullSentinel(i))return checkSentinel(i,e,n);if(i===null)return p(r);let a=x(t,i);return!a.issues&&a.value===null&&i!==void 0?checkSentinel(E,e,n):a});return copyOptionality(i,t,e),i}function lazy(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return new Proxy({},{get(e,t,n){let i=resolve(),a=Reflect.get(i,t,n);return r(a)?a.bind(i):a},has(e,t){return Reflect.has(resolve(),t)},ownKeys(e){return Reflect.ownKeys(resolve())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(resolve(),t)},getPrototypeOf(e){return Reflect.getPrototypeOf(resolve())}})}function lazyRef(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return{type:`lazyRef`,get wrapped(){return resolve()},get entries(){return resolve().entries},"~standard":{version:1,vendor:`viborm`,validate:e=>resolve()[`~standard`].validate(e),get jsonSchema(){return resolve()[`~standard`].jsonSchema}}}}function literal(e,t){let n=e===null?`null`:String(e),r=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected literal: ${n}`})])}),baseValidate=t=>t===e?l(t):r;return h(`literal`,baseValidate,t,{value:e})}function nullable(e){let t=e[`~standard`].validate,n=_(`nullable`,e=>e===null?l(null):t(e));return n.wrapped=e,n}function maybeNullable(e,t){return t?nullable(e):e}function omit(e,t){return S(e.entries,{...e.options||{},omit:t})}let G=0,K=!0;function withoutFilterDepthBound(e){let t=K;K=!1;try{return e()}finally{K=t}}function limitFilterDepth(e){let t=e[`~standard`].validate;return Object.defineProperty(e[`~standard`],`validate`,{value:e=>{if(K&&G>=16)return p(`Filter nesting exceeds 16 levels`);G++;try{return t(e)}finally{G--}}}),e}const q=new WeakSet,J=new WeakSet;let Y;function valueNodeOf(e){if(typeof e==`object`&&e&&q.has(e))return e;let t=Y?.value(e);return t!==void 0&&q.add(t),t}function valueNodeOr(e){let t=_(`value_node_or`,t=>{let n=valueNodeOf(t);return n===void 0?x(e,t):l(n)});return Object.assign(t,{wrapped:e,acceptsUndefined:e.acceptsUndefined===!0}),t}function conditionNodeOr(e){let t=e[`~standard`],n=t.validate;return Object.defineProperty(t,`validate`,{value:e=>{if(typeof e==`object`&&e&&J.has(e))return l(e);if(!(Y&&a(e)&&Object.hasOwn(e,`$if`)))return n(e);let{$if:t,...r}=e,i=Y.condition(t);return typeof i==`string`?p(i,[`$if`]):(J.add(i),Object.keys(r).length===0?l(i):n({AND:[r,i]}))}}),e}function admittingDomainPredicate(e,t){let n=Y;Y=e;try{return withoutFilterDepthBound(t)}finally{Y=n}}function writtenDepth(e){let t=_(`written_depth`,t=>Y&&(t===!0||typeof t==`object`&&t&&t.depth===void 0)?p(`A row predicate's recurse must write its depth (false, or a number)`):x(e,t));return Object.assign(t,{wrapped:e,acceptsUndefined:e.acceptsUndefined===!0}),t}let X;const Z=new WeakMap;function runInOperandScope(e,t){let n=X;X=e;try{return t()}finally{X=n}}function scopeOperands(e,t){let n=e[`~standard`],r=n.validate;return n.validate=e=>runInOperandScope(t,()=>r(e)),limitFilterDepth(e)}function currentContext(){let e=X;if(!e)return;let t=Z.get(e);if(t)return t;let n={fields:createModelFieldRefs(e[`~`].names.ts??`unknown`,e),sql:le};return Z.set(e,n),n}const Q="A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)";function describe$1(e){return e===null?`null`:Array.isArray(e)?`an array`:`a value of type '${typeof e}'`}e(describe$1,`describe`);function resolveCallback(e,t){let n=currentContext();if(!n)return p(`A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.`);let i;try{i=e(n)}catch(e){return p(`Filter callback threw: ${e instanceof Error?e.message:String(e)}`)}return isFieldRef(i)?checkRef(i,t):C(i)?l(i):a(i)&&r(i.then)?(y(i),p(`${Q}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`)):p(`${Q}; it returned ${describe$1(i)}.`)}function comparisonOperand(e,t){let n=_(`comparison_operand`,n=>{let i=valueNodeOf(n);return i===void 0?r(n)?resolveCallback(n,e):isFieldRef(n)?checkRef(n,e):C(n)?l(n):x(t,n):l(i)});return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function fieldRefOr(e,t){let n=_(`field_ref_or`,n=>{let r=valueNodeOf(n);return r===void 0?isFieldRef(n)?checkRef(n,e):x(t,n):l(r)});return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function closeOperands(e,t,n){let r=e[`~standard`],i={"~standard":{version:r.version,vendor:r.vendor,validate:r.validate}},a=_(`no_field_ref`,e=>{let r=findOpaqueOperand(e,n);if(r)return p(`${r} is not supported in ${t}.`);let a=x(i,e);if(a.issues)return a;let o=findOpaqueOperand(a.value,n);return o?p(`${o} is not supported in ${t}.`):a});return a.wrapped=e,a.acceptsUndefined=e.acceptsUndefined??!1,a}function noFieldRef(e,t){return closeOperands(e,t,!1)}function noOperandExpression(e,t){return closeOperands(e,t,!0)}function findOpaqueOperand(e,t){let n=new WeakSet,r=[e];for(;r.length>0;){let e=r.pop();if(t&&typeof e==`function`)return`A filter callback`;if(!(typeof e!=`object`||!e)){if(isFieldRef(e)){let t=fieldRefPayload(e);return`Field reference '${t.model}.${t.field}'`}if(t&&C(e))return`An SQL fragment`;if(!n.has(e)&&(n.add(e),!(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))){if(Array.isArray(e)){for(let t of e)r.push(t);continue}for(let t of Object.keys(e))r.push(e[t])}}}}function checkRef(e,t){let n=fieldRefPayload(e);return n.list?p(`Field reference '${n.model}.${n.field}' is a list field; list fields cannot be used as a comparison operand.`):n.type===t?l(e):p(`Field reference '${n.model}.${n.field}' is of type '${n.type}', but a '${t}' operand is required here.`)}function transform(e){return{type:`transform`,transform:e}}function pipe(e,...t){let n=_(`pipe`,n=>{let r=x(e,n);if(r.issues)return r;let i=r.value;for(let e of t)if(e.type===`transform`)try{i=e.transform(i)}catch(e){return p(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}return l(i)});return n.schema=e,n.actions=t,n}function point(e){return h(`point`,se,e)}function record(e,t){let n=_(`record`,n=>{if(!a(n))return p(`Expected object, received ${Array.isArray(n)?`array`:typeof n}`);let r={};for(let[i,a]of Object.entries(n)){let n=x(e,i);if(n.issues)return p(`Invalid key "${i}": ${n.issues[0].message}`,[i]);let o=x(t,a);if(o.issues){let e=o.issues[0],t=e.path?[i].concat(e.path):[i];return p(e.message,t)}r[n.value]=o.value}return l(r)});return n.key=e,n.value=t,n}function entriesFromKeys(e,t){let n={};for(let r of e)n[r]=t;return n}function fromKeys(e,t,n){return S(entriesFromKeys(e,t),n)}function refused(e){return _(`refused`,()=>p(e))}function coerce(e,t){let n=_(`transform`,n=>{let r=x(e,n);if(r.issues)return{issues:r.issues};try{return l(t(r.value))}catch(e){return p(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}});return n.wrapped=e,n.acceptsUndefined=e.acceptsUndefined===!0,n}const he=coerce,shorthandFilter=e=>coerce(e,e=>({equals:e})),shorthandUpdate=e=>coerce(e,e=>({set:e})),shorthandArray=e=>coerce(e,e=>[e]),ge=Object.freeze([Object.freeze({message:`Async schemas are not supported`})]);function tagsOf(e){let t,n=new Map;for(let r of e){let{type:e,entries:i,options:a}=r;if(e!==`object`||!i||a?.array===!0)return;t??=Object.keys(i).find(e=>isLiteral(i[e]));let o=t===void 0?void 0:i[t];if(!(isLiteral(o)&&o.acceptsUndefined!==!0)||n.has(o.value)||a?.omit?.includes(t))return;n.set(o.value,r[`~standard`].validate)}return t===void 0||n.size<2?void 0:{key:t,members:n}}function isLiteral(e){return a(e)&&e.type===`literal`}function settled(e){return`then`in e?(y(e),{issues:ge}):e}function describe({message:e,path:t}){return t?.length?`${t.join(`.`)}: ${e}`:e}function union(e){let t=e.map(e=>e[`~standard`].validate),n=null,r=_(`union`,r=>{n===null&&(n=tagsOf(e));let i=n&&a(r)&&n.members.get(r[n.key]);if(i)return settled(i(r));let o,s=-1,c;for(let e of t){let t=settled(e(r));if(!t.issues)return t;let{issues:n}=t,i=n[0].path?.length??0;if(i>s)o=n,s=i,c=void 0;else if(i===s){let e=describe(n[0]);c??=[describe(o[0])],c.includes(e)||c.push(e)}}return c&&c.length>1?p(c.join(`, or `)):o?{issues:o}:p(`Expected no value: the union has no member`)});return r.options=e,r}const singleOrArray=e=>union([coerce(e,e=>[e]),array(e)]),_e=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string`})])});function validateString(e){return s(e)?l(e):_e}function string(e){return h(`string`,validateString,e)}const ve=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected array of numbers`})])});function createVectorValidator(e){let n=e===void 0?null:Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected vector of ${e} dimensions`})])});return r=>{if(!Array.isArray(r))return ve;let i=r.length;for(let e=0;e<i;e++)if(!(t(r[e])&&Number.isFinite(r[e])))return p(`Expected finite number at index ${e}`);return n&&i!==e?n:l(r)}}function vector(e,t){return h(`vector`,createVectorValidator(e),t,{dimensions:e})}const $={string,number:oe,integer:ne,boolean,bigint:g,decimal,literal,enum:enum_,json,date,isoTimestamp,isoDate,isoTime,blob,vector,point,array,nullable,maybeNullable,optional:ie,object:S,omit,fromObject,union,pipe,transformAction:transform,record,fromKeys,coerce,map:he,lazy,lazyRef,singleOrArray,shorthandFilter,shorthandUpdate,shorthandArray,comparisonOperand,fieldRefOr,noFieldRef,noOperandExpression,jsonNullOr,jsonWrite,refused};var ye=$;export{jsonNullKindOf as A,readCallerProperty as C,E as D,ue as E,fieldRefPayload as M,formatFieldRef as N,JsonNullSentinel as O,isFieldRef as P,normalizeRelationName as S,de as T,isPlainRecord as _,admittingDomainPredicate as a,normalizeJunctionToken as b,writtenDepth as c,validateIsoTime as d,validateIsoTimestamp as f,hasExactKeys as g,declaredKeys as h,scopeOperands as i,createModelFieldRefs as j,isJsonNullSentinel as k,limitFilterDepth as l,createTargetSettlement as m,ye as n,conditionNodeOr as o,entriesFromObject as p,entriesFromKeys as r,valueNodeOr as s,$ as t,validateIsoDate as u,normalizeFieldTuple as v,refuseRelationInput as w,normalizeReferentialAction as x,normalizeJunctionActions as y};
2
- //# sourceMappingURL=v-CYTUI0H5.mjs.map