@hulla/db 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +263 -2
  3. package/THIRD_PARTY_NOTICES.md +850 -0
  4. package/dist/aggregate.d.ts +63 -0
  5. package/dist/aggregate.js +147 -0
  6. package/dist/auth.d.ts +10 -0
  7. package/dist/auth.js +22 -0
  8. package/dist/bindings.d.ts +56 -0
  9. package/dist/bindings.js +277 -0
  10. package/dist/browser.d.ts +12 -0
  11. package/dist/browser.js +24 -0
  12. package/dist/callable.d.ts +48 -0
  13. package/dist/callable.js +142 -0
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +65 -0
  16. package/dist/codec.d.ts +32 -0
  17. package/dist/codec.js +129 -0
  18. package/dist/codegen.d.ts +19 -0
  19. package/dist/codegen.js +275 -0
  20. package/dist/config.d.ts +70 -0
  21. package/dist/config.js +100 -0
  22. package/dist/contracts.d.ts +109 -0
  23. package/dist/contracts.js +1 -0
  24. package/dist/database-builder.d.ts +19 -0
  25. package/dist/database-builder.js +183 -0
  26. package/dist/database.d.ts +69 -0
  27. package/dist/database.js +128 -0
  28. package/dist/declarations.d.ts +91 -0
  29. package/dist/declarations.js +141 -0
  30. package/dist/dev-worker.d.ts +1 -0
  31. package/dist/dev-worker.js +47 -0
  32. package/dist/dev.d.ts +5 -0
  33. package/dist/dev.js +148 -0
  34. package/dist/error.d.ts +20 -0
  35. package/dist/error.js +82 -0
  36. package/dist/fields.d.ts +36 -0
  37. package/dist/fields.js +63 -0
  38. package/dist/filters.d.ts +93 -0
  39. package/dist/filters.js +220 -0
  40. package/dist/function-shapes.d.ts +7 -0
  41. package/dist/function-shapes.js +150 -0
  42. package/dist/handles.d.ts +27 -0
  43. package/dist/handles.js +387 -0
  44. package/dist/http/protocol.d.ts +64 -0
  45. package/dist/http/protocol.js +77 -0
  46. package/dist/http/sse.d.ts +7 -0
  47. package/dist/http/sse.js +70 -0
  48. package/dist/http.d.ts +44 -0
  49. package/dist/http.js +911 -0
  50. package/dist/index.d.ts +6 -0
  51. package/dist/index.js +1 -0
  52. package/dist/internal/client.d.ts +6 -0
  53. package/dist/internal/client.js +5 -0
  54. package/dist/json-value.d.ts +21 -0
  55. package/dist/json-value.js +79 -0
  56. package/dist/names.d.ts +2 -0
  57. package/dist/names.js +10 -0
  58. package/dist/native.d.ts +3 -0
  59. package/dist/native.js +42 -0
  60. package/dist/notifications.d.ts +8 -0
  61. package/dist/notifications.js +70 -0
  62. package/dist/optimistic.d.ts +46 -0
  63. package/dist/optimistic.js +140 -0
  64. package/dist/page.d.ts +11 -0
  65. package/dist/page.js +1 -0
  66. package/dist/pagination.d.ts +17 -0
  67. package/dist/pagination.js +262 -0
  68. package/dist/project-codegen.d.ts +2 -0
  69. package/dist/project-codegen.js +68 -0
  70. package/dist/projection.d.ts +19 -0
  71. package/dist/projection.js +31 -0
  72. package/dist/runtime-conditions.d.ts +2 -0
  73. package/dist/runtime-conditions.js +10 -0
  74. package/dist/runtime.d.ts +13 -0
  75. package/dist/runtime.js +47 -0
  76. package/dist/schema-codegen.d.ts +16 -0
  77. package/dist/schema-codegen.js +212 -0
  78. package/dist/schema-contract.d.ts +4 -0
  79. package/dist/schema-contract.js +42 -0
  80. package/dist/schema.d.ts +356 -0
  81. package/dist/schema.js +720 -0
  82. package/dist/server-database.d.ts +14 -0
  83. package/dist/server-database.js +386 -0
  84. package/dist/server.d.ts +7 -0
  85. package/dist/server.js +1 -0
  86. package/dist/service.d.ts +13 -0
  87. package/dist/service.js +206 -0
  88. package/dist/sql-check.d.ts +28 -0
  89. package/dist/sql-check.js +59 -0
  90. package/dist/validation.d.ts +43 -0
  91. package/dist/validation.js +21 -0
  92. package/dist/worker-codegen.d.ts +3 -0
  93. package/dist/worker-codegen.js +44 -0
  94. package/dist/worker.d.ts +9 -0
  95. package/dist/worker.js +92 -0
  96. package/dist/write-expression.d.ts +72 -0
  97. package/dist/write-expression.js +122 -0
  98. package/dist/zod.d.ts +28 -0
  99. package/dist/zod.js +102 -0
  100. package/licenses/allocator-api2-0.2.21/LICENSE-APACHE +176 -0
  101. package/licenses/allocator-api2-0.2.21/LICENSE-MIT +23 -0
  102. package/licenses/async-trait-0.1.92/LICENSE-APACHE +176 -0
  103. package/licenses/async-trait-0.1.92/LICENSE-MIT +23 -0
  104. package/licenses/atomic-waker-1.1.2/LICENSE-APACHE +201 -0
  105. package/licenses/atomic-waker-1.1.2/LICENSE-MIT +23 -0
  106. package/licenses/atomic-waker-1.1.2/LICENSE-THIRD-PARTY +45 -0
  107. package/licenses/axum-0.8.9/LICENSE +25 -0
  108. package/licenses/axum-core-0.5.6/LICENSE +27 -0
  109. package/licenses/base64-0.22.1/LICENSE-APACHE +201 -0
  110. package/licenses/base64-0.22.1/LICENSE-MIT +21 -0
  111. package/licenses/bitflags-2.13.2/LICENSE-APACHE +201 -0
  112. package/licenses/bitflags-2.13.2/LICENSE-MIT +25 -0
  113. package/licenses/block-buffer-0.12.1/LICENSE-APACHE +201 -0
  114. package/licenses/block-buffer-0.12.1/LICENSE-MIT +25 -0
  115. package/licenses/byteorder-1.5.0/COPYING +3 -0
  116. package/licenses/byteorder-1.5.0/LICENSE-MIT +21 -0
  117. package/licenses/bytes-1.12.1/LICENSE +25 -0
  118. package/licenses/cc-1.6.0/LICENSE-APACHE +201 -0
  119. package/licenses/cc-1.6.0/LICENSE-MIT +25 -0
  120. package/licenses/cfg-if-1.0.5/LICENSE-APACHE +201 -0
  121. package/licenses/cfg-if-1.0.5/LICENSE-MIT +25 -0
  122. package/licenses/chacha20-0.10.2/LICENSE-APACHE +201 -0
  123. package/licenses/chacha20-0.10.2/LICENSE-MIT +25 -0
  124. package/licenses/cmov-0.5.4/LICENSE-APACHE +202 -0
  125. package/licenses/cmov-0.5.4/LICENSE-MIT +25 -0
  126. package/licenses/const-oid-0.10.2/LICENSE-APACHE +201 -0
  127. package/licenses/const-oid-0.10.2/LICENSE-MIT +25 -0
  128. package/licenses/const-oid-0.9.6/LICENSE-APACHE +201 -0
  129. package/licenses/const-oid-0.9.6/LICENSE-MIT +25 -0
  130. package/licenses/cpufeatures-0.3.1/LICENSE-APACHE +201 -0
  131. package/licenses/cpufeatures-0.3.1/LICENSE-MIT +25 -0
  132. package/licenses/crypto-common-0.2.2/LICENSE-APACHE +201 -0
  133. package/licenses/crypto-common-0.2.2/LICENSE-MIT +25 -0
  134. package/licenses/ctutils-0.4.2/LICENSE-APACHE +202 -0
  135. package/licenses/ctutils-0.4.2/LICENSE-MIT +25 -0
  136. package/licenses/der-0.7.10/LICENSE-APACHE +201 -0
  137. package/licenses/der-0.7.10/LICENSE-MIT +25 -0
  138. package/licenses/der_derive-0.7.3/LICENSE-APACHE +201 -0
  139. package/licenses/der_derive-0.7.3/LICENSE-MIT +25 -0
  140. package/licenses/deranged-0.5.8/LICENSE-Apache +202 -0
  141. package/licenses/deranged-0.5.8/LICENSE-MIT +19 -0
  142. package/licenses/digest-0.11.3/LICENSE-APACHE +201 -0
  143. package/licenses/digest-0.11.3/LICENSE-MIT +26 -0
  144. package/licenses/equivalent-1.0.3/LICENSE-APACHE +201 -0
  145. package/licenses/equivalent-1.0.3/LICENSE-MIT +25 -0
  146. package/licenses/errno-0.3.14/LICENSE-APACHE +201 -0
  147. package/licenses/errno-0.3.14/LICENSE-MIT +25 -0
  148. package/licenses/fallible-iterator-0.2.0/LICENSE-APACHE +202 -0
  149. package/licenses/fallible-iterator-0.2.0/LICENSE-MIT +19 -0
  150. package/licenses/find-msvc-tools-0.1.14/LICENSE-APACHE +201 -0
  151. package/licenses/find-msvc-tools-0.1.14/LICENSE-MIT +25 -0
  152. package/licenses/flagset-0.4.7/LICENSE +202 -0
  153. package/licenses/foldhash-0.2.0/LICENSE +19 -0
  154. package/licenses/futures-channel-0.3.34/LICENSE-APACHE +202 -0
  155. package/licenses/futures-channel-0.3.34/LICENSE-MIT +26 -0
  156. package/licenses/futures-core-0.3.34/LICENSE-APACHE +202 -0
  157. package/licenses/futures-core-0.3.34/LICENSE-MIT +26 -0
  158. package/licenses/futures-sink-0.3.34/LICENSE-APACHE +202 -0
  159. package/licenses/futures-sink-0.3.34/LICENSE-MIT +26 -0
  160. package/licenses/futures-task-0.3.34/LICENSE-APACHE +202 -0
  161. package/licenses/futures-task-0.3.34/LICENSE-MIT +26 -0
  162. package/licenses/futures-util-0.3.34/LICENSE-APACHE +202 -0
  163. package/licenses/futures-util-0.3.34/LICENSE-MIT +26 -0
  164. package/licenses/getrandom-0.2.17/LICENSE-APACHE +201 -0
  165. package/licenses/getrandom-0.2.17/LICENSE-MIT +26 -0
  166. package/licenses/getrandom-0.4.3/LICENSE-APACHE +201 -0
  167. package/licenses/getrandom-0.4.3/LICENSE-MIT +26 -0
  168. package/licenses/hashbrown-0.17.1/LICENSE-APACHE +201 -0
  169. package/licenses/hashbrown-0.17.1/LICENSE-MIT +25 -0
  170. package/licenses/hmac-0.13.0/LICENSE-APACHE +201 -0
  171. package/licenses/hmac-0.13.0/LICENSE-MIT +25 -0
  172. package/licenses/http-1.5.0/LICENSE-APACHE +201 -0
  173. package/licenses/http-1.5.0/LICENSE-MIT +25 -0
  174. package/licenses/http-body-1.1.0/LICENSE +25 -0
  175. package/licenses/http-body-util-0.1.5/LICENSE +25 -0
  176. package/licenses/httparse-1.10.1/LICENSE-APACHE +201 -0
  177. package/licenses/httparse-1.10.1/LICENSE-MIT +20 -0
  178. package/licenses/httpdate-1.0.3/LICENSE-APACHE +201 -0
  179. package/licenses/httpdate-1.0.3/LICENSE-MIT +19 -0
  180. package/licenses/hybrid-array-0.4.15/LICENSE-APACHE +201 -0
  181. package/licenses/hybrid-array-0.4.15/LICENSE-MIT +25 -0
  182. package/licenses/hyper-1.11.1/LICENSE +19 -0
  183. package/licenses/hyper-util-0.1.21/LICENSE +19 -0
  184. package/licenses/itoa-1.0.18/LICENSE-APACHE +176 -0
  185. package/licenses/itoa-1.0.18/LICENSE-MIT +23 -0
  186. package/licenses/libc-0.2.189/LICENSE-APACHE +176 -0
  187. package/licenses/libc-0.2.189/LICENSE-MIT +25 -0
  188. package/licenses/lock_api-0.4.14/LICENSE-APACHE +201 -0
  189. package/licenses/lock_api-0.4.14/LICENSE-MIT +25 -0
  190. package/licenses/log-0.4.34/LICENSE-APACHE +201 -0
  191. package/licenses/log-0.4.34/LICENSE-MIT +25 -0
  192. package/licenses/matchit-0.8.4/LICENSE +21 -0
  193. package/licenses/matchit-0.8.4/LICENSE.httprouter +29 -0
  194. package/licenses/md-5-0.11.0/LICENSE-APACHE +201 -0
  195. package/licenses/md-5-0.11.0/LICENSE-MIT +28 -0
  196. package/licenses/memchr-2.8.3/COPYING +3 -0
  197. package/licenses/memchr-2.8.3/LICENSE-MIT +21 -0
  198. package/licenses/mime-0.3.17/LICENSE-APACHE +201 -0
  199. package/licenses/mime-0.3.17/LICENSE-MIT +20 -0
  200. package/licenses/mio-1.2.3/LICENSE +19 -0
  201. package/licenses/num-conv-0.2.2/LICENSE-Apache +177 -0
  202. package/licenses/num-conv-0.2.2/LICENSE-MIT +19 -0
  203. package/licenses/objc2-core-foundation-0.3.2/LICENSE.md +34 -0
  204. package/licenses/objc2-system-configuration-0.3.2/LICENSE.md +34 -0
  205. package/licenses/once_cell-1.21.4/LICENSE-APACHE +201 -0
  206. package/licenses/once_cell-1.21.4/LICENSE-MIT +23 -0
  207. package/licenses/parking_lot-0.12.5/LICENSE-APACHE +201 -0
  208. package/licenses/parking_lot-0.12.5/LICENSE-MIT +25 -0
  209. package/licenses/parking_lot_core-0.9.12/LICENSE-APACHE +201 -0
  210. package/licenses/parking_lot_core-0.9.12/LICENSE-MIT +25 -0
  211. package/licenses/percent-encoding-2.3.2/LICENSE-APACHE +201 -0
  212. package/licenses/percent-encoding-2.3.2/LICENSE-MIT +25 -0
  213. package/licenses/phf-0.13.1/LICENSE +20 -0
  214. package/licenses/phf_shared-0.13.1/LICENSE +20 -0
  215. package/licenses/pin-project-lite-0.2.17/LICENSE-APACHE +177 -0
  216. package/licenses/pin-project-lite-0.2.17/LICENSE-MIT +23 -0
  217. package/licenses/postgres-protocol-0.6.12/LICENSE-APACHE +201 -0
  218. package/licenses/postgres-protocol-0.6.12/LICENSE-MIT +22 -0
  219. package/licenses/postgres-types-0.2.14/LICENSE-APACHE +201 -0
  220. package/licenses/postgres-types-0.2.14/LICENSE-MIT +22 -0
  221. package/licenses/powerfmt-0.2.1/LICENSE-Apache +202 -0
  222. package/licenses/powerfmt-0.2.1/LICENSE-MIT +19 -0
  223. package/licenses/proc-macro2-1.0.107/LICENSE-APACHE +176 -0
  224. package/licenses/proc-macro2-1.0.107/LICENSE-MIT +23 -0
  225. package/licenses/quote-1.0.47/LICENSE-APACHE +176 -0
  226. package/licenses/quote-1.0.47/LICENSE-MIT +23 -0
  227. package/licenses/rand-0.10.3/COPYRIGHT +12 -0
  228. package/licenses/rand-0.10.3/LICENSE-APACHE +176 -0
  229. package/licenses/rand-0.10.3/LICENSE-MIT +26 -0
  230. package/licenses/rand_core-0.10.1/COPYRIGHT +9 -0
  231. package/licenses/rand_core-0.10.1/LICENSE-APACHE +187 -0
  232. package/licenses/rand_core-0.10.1/LICENSE-MIT +25 -0
  233. package/licenses/ring-0.17.14/LICENSE +9 -0
  234. package/licenses/ring-0.17.14/LICENSE-BoringSSL +272 -0
  235. package/licenses/ring-0.17.14/LICENSE-other-bits +13 -0
  236. package/licenses/ring-0.17.14/src/polyfill/once_cell/LICENSE-APACHE +201 -0
  237. package/licenses/ring-0.17.14/src/polyfill/once_cell/LICENSE-MIT +23 -0
  238. package/licenses/ring-0.17.14/third_party/fiat/LICENSE +15 -0
  239. package/licenses/rquickjs-0.14.0/LICENSE +22 -0
  240. package/licenses/rquickjs-core-0.14.0/LICENSE +22 -0
  241. package/licenses/rquickjs-sys-0.14.0/quickjs/LICENSE +24 -0
  242. package/licenses/rquickjs-sys-0.14.0/vendor/wasi-libc/NOTICE.md +26 -0
  243. package/licenses/rustls-0.23.46/LICENSE-APACHE +201 -0
  244. package/licenses/rustls-0.23.46/LICENSE-ISC +15 -0
  245. package/licenses/rustls-0.23.46/LICENSE-MIT +25 -0
  246. package/licenses/rustls-pki-types-1.15.1/LICENSE-APACHE +201 -0
  247. package/licenses/rustls-pki-types-1.15.1/LICENSE-MIT +25 -0
  248. package/licenses/rustls-webpki-0.103.15/LICENSE +19 -0
  249. package/licenses/scopeguard-1.2.0/LICENSE-APACHE +201 -0
  250. package/licenses/scopeguard-1.2.0/LICENSE-MIT +25 -0
  251. package/licenses/serde-1.0.229/LICENSE-APACHE +176 -0
  252. package/licenses/serde-1.0.229/LICENSE-MIT +23 -0
  253. package/licenses/serde_core-1.0.229/LICENSE-APACHE +176 -0
  254. package/licenses/serde_core-1.0.229/LICENSE-MIT +23 -0
  255. package/licenses/serde_derive-1.0.229/LICENSE-APACHE +176 -0
  256. package/licenses/serde_derive-1.0.229/LICENSE-MIT +23 -0
  257. package/licenses/serde_json-1.0.151/LICENSE-APACHE +176 -0
  258. package/licenses/serde_json-1.0.151/LICENSE-MIT +23 -0
  259. package/licenses/serde_path_to_error-0.1.20/LICENSE-APACHE +176 -0
  260. package/licenses/serde_path_to_error-0.1.20/LICENSE-MIT +23 -0
  261. package/licenses/sha2-0.11.0/LICENSE-APACHE +201 -0
  262. package/licenses/sha2-0.11.0/LICENSE-MIT +28 -0
  263. package/licenses/shlex-2.0.1/LICENSE-APACHE +13 -0
  264. package/licenses/shlex-2.0.1/LICENSE-MIT +21 -0
  265. package/licenses/signal-hook-registry-1.4.8/LICENSE-APACHE +201 -0
  266. package/licenses/signal-hook-registry-1.4.8/LICENSE-MIT +25 -0
  267. package/licenses/siphasher-1.0.4/COPYING +7 -0
  268. package/licenses/siphasher-1.0.4/LICENSE-APACHE +202 -0
  269. package/licenses/siphasher-1.0.4/LICENSE-MIT +17 -0
  270. package/licenses/slab-0.4.12/LICENSE +25 -0
  271. package/licenses/smallvec-1.16.2/LICENSE-APACHE +201 -0
  272. package/licenses/smallvec-1.16.2/LICENSE-MIT +25 -0
  273. package/licenses/socket2-0.6.5/LICENSE-APACHE +201 -0
  274. package/licenses/socket2-0.6.5/LICENSE-MIT +25 -0
  275. package/licenses/spki-0.7.3/LICENSE-APACHE +201 -0
  276. package/licenses/spki-0.7.3/LICENSE-MIT +25 -0
  277. package/licenses/stringprep-0.1.5/LICENSE-APACHE +202 -0
  278. package/licenses/stringprep-0.1.5/LICENSE-MIT +19 -0
  279. package/licenses/subtle-2.6.1/LICENSE +29 -0
  280. package/licenses/syn-2.0.119/LICENSE-APACHE +176 -0
  281. package/licenses/syn-2.0.119/LICENSE-MIT +23 -0
  282. package/licenses/syn-3.0.6/LICENSE-APACHE +176 -0
  283. package/licenses/syn-3.0.6/LICENSE-MIT +23 -0
  284. package/licenses/sync_wrapper-1.0.2/LICENSE +177 -0
  285. package/licenses/time-0.3.55/LICENSE-Apache +177 -0
  286. package/licenses/time-0.3.55/LICENSE-MIT +19 -0
  287. package/licenses/time-core-0.1.9/LICENSE-Apache +177 -0
  288. package/licenses/time-core-0.1.9/LICENSE-MIT +19 -0
  289. package/licenses/time-macros-0.2.32/LICENSE-Apache +177 -0
  290. package/licenses/time-macros-0.2.32/LICENSE-MIT +19 -0
  291. package/licenses/tinyvec-1.13.3/LICENSE-APACHE.md +202 -0
  292. package/licenses/tinyvec-1.13.3/LICENSE-MIT.md +5 -0
  293. package/licenses/tinyvec-1.13.3/LICENSE-ZLIB.md +11 -0
  294. package/licenses/tokio-1.53.1/LICENSE +21 -0
  295. package/licenses/tokio-macros-2.7.2/LICENSE +22 -0
  296. package/licenses/tokio-postgres-0.7.18/LICENSE-APACHE +201 -0
  297. package/licenses/tokio-postgres-0.7.18/LICENSE-MIT +22 -0
  298. package/licenses/tokio-postgres-rustls-0.14.0/LICENSE +21 -0
  299. package/licenses/tokio-rustls-0.26.6/LICENSE-APACHE +201 -0
  300. package/licenses/tokio-rustls-0.26.6/LICENSE-MIT +25 -0
  301. package/licenses/tokio-util-0.7.19/LICENSE +21 -0
  302. package/licenses/tower-0.5.3/LICENSE +25 -0
  303. package/licenses/tower-layer-0.3.3/LICENSE +25 -0
  304. package/licenses/tower-service-0.3.3/LICENSE +25 -0
  305. package/licenses/typenum-1.20.1/LICENSE +1 -0
  306. package/licenses/typenum-1.20.1/LICENSE-APACHE +201 -0
  307. package/licenses/typenum-1.20.1/LICENSE-MIT +21 -0
  308. package/licenses/unicode-bidi-0.3.18/COPYRIGHT +8 -0
  309. package/licenses/unicode-bidi-0.3.18/LICENSE-APACHE +201 -0
  310. package/licenses/unicode-bidi-0.3.18/LICENSE-MIT +25 -0
  311. package/licenses/unicode-ident-1.0.26/LICENSE-APACHE +176 -0
  312. package/licenses/unicode-ident-1.0.26/LICENSE-MIT +23 -0
  313. package/licenses/unicode-ident-1.0.26/LICENSE-UNICODE +39 -0
  314. package/licenses/unicode-normalization-0.1.25/COPYRIGHT +7 -0
  315. package/licenses/unicode-normalization-0.1.25/LICENSE-APACHE +201 -0
  316. package/licenses/unicode-normalization-0.1.25/LICENSE-MIT +25 -0
  317. package/licenses/unicode-properties-0.1.4/COPYRIGHT +7 -0
  318. package/licenses/unicode-properties-0.1.4/LICENSE-APACHE +201 -0
  319. package/licenses/unicode-properties-0.1.4/LICENSE-MIT +25 -0
  320. package/licenses/untrusted-0.9.0/LICENSE.txt +13 -0
  321. package/licenses/uuid-1.26.1/LICENSE-APACHE +201 -0
  322. package/licenses/uuid-1.26.1/LICENSE-MIT +26 -0
  323. package/licenses/webpki-roots-1.0.9/LICENSE +61 -0
  324. package/licenses/whoami-2.1.3/LICENSE_APACHE +176 -0
  325. package/licenses/whoami-2.1.3/LICENSE_BOOST +23 -0
  326. package/licenses/whoami-2.1.3/LICENSE_MIT +19 -0
  327. package/licenses/x509-cert-0.2.5/LICENSE-APACHE +201 -0
  328. package/licenses/x509-cert-0.2.5/LICENSE-MIT +25 -0
  329. package/licenses/zeroize-1.9.1/LICENSE-APACHE +202 -0
  330. package/licenses/zeroize-1.9.1/LICENSE-MIT +25 -0
  331. package/licenses/zmij-1.0.23/LICENSE-MIT +23 -0
  332. package/native/darwin-arm64/hulladb-bridge +0 -0
  333. package/native/darwin-arm64/hulladb-js +0 -0
  334. package/native/darwin-arm64/hulladb-service +0 -0
  335. package/native/linux-x64/hulladb-bridge +0 -0
  336. package/native/linux-x64/hulladb-js +0 -0
  337. package/native/linux-x64/hulladb-service +0 -0
  338. package/package.json +90 -4
@@ -0,0 +1,59 @@
1
+ const fieldBrand = Symbol('SQL check field');
2
+ const checkBrand = Symbol('SQL check expression');
3
+ function literal(value) {
4
+ if (value === null || typeof value === 'boolean')
5
+ return value;
6
+ if (typeof value === 'string' && !/[\uD800-\uDFFF]/u.test(value) && !value.includes('\0'))
7
+ return value;
8
+ if (typeof value === 'number' && Number.isFinite(value))
9
+ return value === 0 ? 0 : value;
10
+ if (typeof value === 'bigint' && value >= -(1n << 63n) && value < (1n << 63n))
11
+ return value;
12
+ throw new TypeError('SQL check interpolations require a field, expression or finite scalar literal');
13
+ }
14
+ /** Trusted SQL expression text; interpolated fields and values are quoted separately. */
15
+ export function sql(parts, ...values) {
16
+ if (!Array.isArray(parts) || !Array.isArray(parts.raw) || parts.length !== values.length + 1)
17
+ throw new TypeError('Use sql as a tagged template');
18
+ const text = [parts[0]];
19
+ const operands = [];
20
+ for (let index = 0; index < values.length; index++) {
21
+ const value = values[index];
22
+ if (value !== null && typeof value === 'object' && checkBrand in value) {
23
+ text[text.length - 1] += value.parts[0];
24
+ value.operands.forEach((operand, part) => { operands.push(operand); text.push(value.parts[part + 1]); });
25
+ text[text.length - 1] += parts[index + 1];
26
+ }
27
+ else {
28
+ operands.push(Object.freeze(value !== null && typeof value === 'object' && fieldBrand in value
29
+ ? { field: value[fieldBrand] } : { value: literal(value) }));
30
+ text.push(parts[index + 1]);
31
+ }
32
+ }
33
+ if (text.some(part => typeof part !== 'string' || /\0|;|--|\/\*|\*\//.test(part)))
34
+ throw new TypeError('SQL checks accept one expression without statement separators or comments');
35
+ return Object.freeze({ [checkBrand]: true, parts: Object.freeze(text), operands: Object.freeze(operands) });
36
+ }
37
+ export function compileChecks(callback, fields, _primaryKey) {
38
+ if (callback === undefined)
39
+ return Object.freeze([]);
40
+ if (typeof callback !== 'function')
41
+ throw new TypeError('Table checks must be a callback');
42
+ const columns = Object.freeze(Object.fromEntries(fields.map(name => [name, Object.freeze({ [fieldBrand]: name })])));
43
+ const checks = callback(columns);
44
+ if (!checks || typeof checks !== 'object' || ![Object.prototype, null].includes(Object.getPrototypeOf(checks)))
45
+ throw new TypeError('Table checks must return a plain record of SQL expressions');
46
+ return Object.freeze(Reflect.ownKeys(checks).map(name => {
47
+ if (typeof name !== 'string' || !name || name.includes('\0') || /[\uD800-\uDFFF]/u.test(name))
48
+ throw new TypeError('SQL checks require valid nonempty names');
49
+ const property = Object.getOwnPropertyDescriptor(checks, name);
50
+ if (!property.enumerable || !('value' in property) || !property.value || property.value[checkBrand] !== true)
51
+ throw new TypeError('Table checks must contain SQL expressions without accessors');
52
+ const expression = property.value;
53
+ if (expression.operands.some(operand => 'field' in operand && !fields.includes(operand.field)))
54
+ throw new TypeError('SQL checks can only reference fields of their own table');
55
+ if (!expression.parts.some(part => part.trim()) && !expression.operands.length)
56
+ throw new TypeError('SQL checks cannot be empty');
57
+ return Object.freeze({ name, parts: expression.parts, operands: expression.operands });
58
+ }));
59
+ }
@@ -0,0 +1,43 @@
1
+ /** Database field parsing contract; function declarations use StandardSchema instead. */
2
+ export interface Validator<T> {
3
+ parse(value: unknown): T;
4
+ }
5
+ /** Structurally compatible subset of Standard Schema v1 (standardschema.dev).
6
+ * Applications supply their own validator library; the SDK has no validator dependency. */
7
+ export interface StandardSchema<I = unknown, O = I> {
8
+ readonly "~standard": {
9
+ readonly version: 1;
10
+ readonly vendor: string;
11
+ readonly types?: {
12
+ readonly input: I;
13
+ readonly output: O;
14
+ } | undefined;
15
+ readonly validate: (value: unknown, options?: {
16
+ readonly libraryOptions?: Record<string, unknown> | undefined;
17
+ } | undefined) => {
18
+ readonly value: O;
19
+ readonly issues?: undefined;
20
+ } | {
21
+ readonly issues: readonly {
22
+ readonly message: string;
23
+ readonly path?: readonly (PropertyKey | {
24
+ readonly key: PropertyKey;
25
+ })[] | undefined;
26
+ }[];
27
+ } | Promise<{
28
+ readonly value: O;
29
+ readonly issues?: undefined;
30
+ } | {
31
+ readonly issues: readonly {
32
+ readonly message: string;
33
+ readonly path?: readonly (PropertyKey | {
34
+ readonly key: PropertyKey;
35
+ })[] | undefined;
36
+ }[];
37
+ }>;
38
+ };
39
+ }
40
+ export type SchemaInput<S extends StandardSchema> = NonNullable<S["~standard"]["types"]>["input"];
41
+ export type SchemaOutput<S extends StandardSchema> = NonNullable<S["~standard"]["types"]>["output"];
42
+ export declare function assertStandardSchema(value: unknown): asserts value is StandardSchema;
43
+ export declare function validateSchema(schema: StandardSchema, value: unknown, label: "Input" | "Output"): Promise<unknown>;
@@ -0,0 +1,21 @@
1
+ export function assertStandardSchema(value) {
2
+ if ((typeof value !== "object" && typeof value !== "function") || value === null)
3
+ throw new TypeError("Expected a Standard Schema validator");
4
+ const properties = value["~standard"];
5
+ if (!properties || properties.version !== 1 || typeof properties.vendor !== "string" || typeof properties.validate !== "function") {
6
+ throw new TypeError("Expected a Standard Schema v1 validator");
7
+ }
8
+ }
9
+ export async function validateSchema(schema, value, label) {
10
+ const result = await schema["~standard"].validate(value);
11
+ if (typeof result !== "object" || result === null)
12
+ throw new TypeError("Invalid Standard Schema validation result");
13
+ if (result.issues !== undefined) {
14
+ if (!Array.isArray(result.issues) || result.issues.some(issue => typeof issue?.message !== "string"))
15
+ throw new TypeError("Invalid Standard Schema issues");
16
+ throw new TypeError(result.issues.map(issue => issue.message).join("; ") || `${label} validation failed`);
17
+ }
18
+ if (!Object.hasOwn(result, "value"))
19
+ throw new TypeError("Invalid Standard Schema validation result");
20
+ return result.value;
21
+ }
@@ -0,0 +1,3 @@
1
+ export declare const workerBundleHeader = "// Generated restricted worker by @hulla/db. Do not edit.\n";
2
+ /** Build trusted source into one portable script. The execution engine has no loader. */
3
+ export declare function compileWorker(entrypoint: string): Promise<string>;
@@ -0,0 +1,44 @@
1
+ import { builtinModules } from "node:module";
2
+ import { runtimeExportConditions } from "./runtime-conditions.js";
3
+ export const workerBundleHeader = "// Generated restricted worker by @hulla/db. Do not edit.\n";
4
+ const escapePattern = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
+ const forbiddenImports = new RegExp(`^(?:[a-zA-Z][\\w+.-]*:|bun(?:/|$)|(?:${builtinModules.map(escapePattern).join("|")})$)|\\.(?:node|so|dylib)$`);
6
+ function unsupportedImport(path, importer) {
7
+ return new Error(`Unsupported declaration import ${JSON.stringify(path)} in ${importer}. Queries and mutations support bundled computation/validation code; move server I/O to ordinary server code.`);
8
+ }
9
+ /** Build trusted source into one portable script. The execution engine has no loader. */
10
+ export async function compileWorker(entrypoint) {
11
+ const build = await Bun.build({
12
+ conditions: runtimeExportConditions(),
13
+ entrypoints: [entrypoint], target: "browser", format: "iife", throw: false, metafile: true,
14
+ plugins: [{
15
+ name: "hulla-declaration-capabilities",
16
+ setup(builder) {
17
+ // Leave ordinary resolution to Bun. A wildcard onResolve callback can
18
+ // corrupt reexported namespace bindings in Bun 1.4, including Zod's.
19
+ builder.onResolve({ filter: forbiddenImports }, args => {
20
+ throw unsupportedImport(args.path, args.importer);
21
+ });
22
+ },
23
+ }],
24
+ });
25
+ if (!build.success)
26
+ throw new Error(`Cannot bundle database declarations:\n${build.logs.map(log => log.message).join("\n")}`);
27
+ if (build.outputs.length !== 1 || !build.metafile)
28
+ throw new Error("Database declarations must compile to one self-contained script");
29
+ // Inspect dynamic imports without intercepting library namespace resolution.
30
+ // Bun labels tree-shaken relative imports as external in input metadata, even
31
+ // when nothing is external in the emitted bundle. Check the output below for
32
+ // surviving external imports. The native runtime also denies dynamic imports.
33
+ for (const [importer, input] of Object.entries(build.metafile.inputs)) {
34
+ for (const dependency of input.imports) {
35
+ if (dependency.kind === "dynamic-import") {
36
+ throw unsupportedImport(dependency.original ?? dependency.path, importer);
37
+ }
38
+ }
39
+ }
40
+ if (Object.values(build.metafile.outputs).some(output => output.imports.length !== 0)) {
41
+ throw new Error("Database declarations must compile to one self-contained script");
42
+ }
43
+ return workerBundleHeader + await build.outputs[0].text();
44
+ }
@@ -0,0 +1,9 @@
1
+ import type { SchemaDefinition } from "./schema.ts";
2
+ export interface WorkerApplication {
3
+ readonly schema: SchemaDefinition;
4
+ readonly modules: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
5
+ }
6
+ /** Install one portable application in a fresh restricted native JavaScript realm.
7
+ * Native code owns capabilities, transaction lifetime, and execution budgets.
8
+ */
9
+ export declare function installWorker(application: WorkerApplication): void;
package/dist/worker.js ADDED
@@ -0,0 +1,92 @@
1
+ import { valueCodec } from "./codec.js";
2
+ import { transactionDatabase } from "./database.js";
3
+ import { executeDefinition, isFunctionDefinition } from "./declarations.js";
4
+ import { schemaDescriptor } from "./schema-contract.js";
5
+ import { DatabaseError } from "./error.js";
6
+ /** Compare JSON contracts independently of object property insertion order. */
7
+ function sameContract(left, right, depth = 0) {
8
+ if (depth > 128)
9
+ return false;
10
+ if (left === right)
11
+ return true;
12
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null)
13
+ return false;
14
+ if (Array.isArray(left) !== Array.isArray(right))
15
+ return false;
16
+ const leftKeys = Object.keys(left), rightKeys = Object.keys(right);
17
+ if (leftKeys.length !== rightKeys.length)
18
+ return false;
19
+ return leftKeys.every(key => Object.hasOwn(right, key)
20
+ && sameContract(left[key], right[key], depth + 1));
21
+ }
22
+ /** Install one portable application in a fresh restricted native JavaScript realm.
23
+ * Native code owns capabilities, transaction lifetime, and execution budgets.
24
+ */
25
+ export function installWorker(application) {
26
+ const nativeRequest = globalThis.__hullaDb;
27
+ if (typeof nativeRequest !== "function")
28
+ throw new Error("The native database bridge is unavailable");
29
+ const contract = schemaDescriptor(application.schema);
30
+ const execute = async (invocation) => {
31
+ let active = true, pending = 0;
32
+ let tail = Promise.resolve();
33
+ const request = (operation, validate) => {
34
+ if (!active)
35
+ return Promise.reject(new Error("Transaction context has expired"));
36
+ pending++;
37
+ const result = tail.then(async () => {
38
+ if (!active)
39
+ throw new Error("Transaction context has expired");
40
+ const response = JSON.parse(await nativeRequest(JSON.stringify(operation)));
41
+ validate?.(response);
42
+ return response;
43
+ }).finally(() => { pending--; });
44
+ // Calls share one native transaction. A failed request poisons this chain
45
+ // even when application code catches the individual operation's error.
46
+ tail = result;
47
+ void result.catch(() => { });
48
+ return result;
49
+ };
50
+ try {
51
+ if (!sameContract(contract, invocation.schema))
52
+ throw new Error("schema_mismatch");
53
+ const name = invocation.name;
54
+ if (typeof name !== "string")
55
+ throw new TypeError("Invalid function name");
56
+ const separator = name.lastIndexOf(".");
57
+ if (separator < 1)
58
+ throw new TypeError("Invalid function name");
59
+ const moduleName = name.slice(0, separator), exportName = name.slice(separator + 1);
60
+ const module = Object.hasOwn(application.modules, moduleName) ? application.modules[moduleName] : undefined;
61
+ const definition = module && Object.hasOwn(module, exportName) ? module[exportName] : undefined;
62
+ if (!isFunctionDefinition(definition) || definition.kind !== invocation.kind)
63
+ throw new TypeError("Function kind/name mismatch");
64
+ const argument = valueCodec(invocation.input_shape).decode(invocation.input);
65
+ const db = transactionDatabase(application.schema, definition.kind === "mutation", request);
66
+ const result = await executeDefinition(definition, Object.freeze({ db, identity: invocation.identity }), argument);
67
+ // Result codecs and JSON serialization can invoke application getters. They
68
+ // must never acquire a database capability after the handler has returned.
69
+ active = false;
70
+ if (pending)
71
+ throw new Error("Await all database operations before returning");
72
+ await tail;
73
+ return JSON.stringify(valueCodec(invocation.result_shape).encode(result));
74
+ }
75
+ catch (error) {
76
+ if (error instanceof DatabaseError) {
77
+ // Revalidate declared fields; never serialize stack/cause or an overridden toJSON.
78
+ const payload = JSON.stringify(new DatabaseError({ code: error.code, message: error.message, ...(error.details === undefined ? {} : { details: error.details }) }).toJSON());
79
+ const failure = new Error("application_error");
80
+ Object.defineProperty(failure, "application", { value: payload });
81
+ throw failure;
82
+ }
83
+ const code = error instanceof Error && error.message === "schema_mismatch" ? "schema_mismatch"
84
+ : error instanceof TypeError ? "invalid_request" : "handler_failed";
85
+ throw new Error(code);
86
+ }
87
+ finally {
88
+ active = false;
89
+ }
90
+ };
91
+ Object.defineProperty(globalThis, "__hullaExecute", { value: execute, writable: false, configurable: false });
92
+ }
@@ -0,0 +1,72 @@
1
+ import type { CompiledTable, TableShape } from "./schema.ts";
2
+ declare const expressionType: unique symbol;
3
+ declare const storedExpressionType: unique symbol;
4
+ declare const policyType: unique symbol;
5
+ export interface WriteValue<V, B = V> {
6
+ readonly [expressionType]: V;
7
+ readonly [storedExpressionType]: B;
8
+ }
9
+ export type WriteReference<V, B = V, Stored = B> = WriteValue<V, Stored> & (NonNullable<B> extends number | bigint ? {
10
+ add(value: NonNullable<B> | WriteValue<unknown, NonNullable<Stored>>): WriteReference<V, B, Stored>;
11
+ add(value: WriteValue<unknown, NonNullable<Stored> | null>): WriteReference<NonNullable<V> | null, NonNullable<B> | null, NonNullable<Stored> | null>;
12
+ } : {});
13
+ export type WriteReferences<R, B = R, Stored = B> = {
14
+ readonly [K in keyof R]: WriteReference<R[K], K extends keyof B ? B[K] : R[K], K extends keyof Stored ? Stored[K] : R[K]>;
15
+ };
16
+ export type WritePatch<P, B = P> = {
17
+ [K in keyof P]?: P[K] | (Exclude<P[K], undefined> extends never ? never : WriteValue<unknown, Exclude<K extends keyof B ? B[K] : P[K], undefined>>);
18
+ };
19
+ export type UpdateInput<R, P, B = R, Stored = B> = P | ((current: WriteReferences<R, B, Stored>) => WritePatch<P, Stored>);
20
+ export interface ConflictPolicy<Skip extends boolean = boolean> {
21
+ readonly [policyType]: Skip;
22
+ }
23
+ export interface ConflictTarget<R, P, B = R, Stored = B> {
24
+ skip(): ConflictPolicy<true>;
25
+ update(patch: WritePatch<P, Stored> | ((rows: {
26
+ readonly current: WriteReferences<R, B, Stored>;
27
+ readonly incoming: WriteReferences<R, B, Stored>;
28
+ }) => WritePatch<P, Stored>)): ConflictPolicy<false>;
29
+ }
30
+ export interface ConflictSelector<R, P, Targets extends readonly string[], B = R, Stored = B> {
31
+ on(...fields: Targets): ConflictTarget<R, P, B, Stored>;
32
+ }
33
+ type Primary<D extends TableShape> = D["options"] extends {
34
+ readonly primaryKey: infer K extends string;
35
+ } ? readonly [K] : readonly ["id"];
36
+ type Unique<D extends TableShape> = D["options"] extends {
37
+ readonly unique: infer U;
38
+ } ? {
39
+ [K in keyof U]: U[K] extends {
40
+ readonly fields: infer F extends readonly string[];
41
+ } ? F : never;
42
+ }[keyof U] : never;
43
+ export type ConflictTargets<D extends TableShape> = Primary<D> | Unique<D>;
44
+ export type RowExpectation = number | ((count: number) => boolean);
45
+ export type WriteExpression = {
46
+ readonly kind: "value";
47
+ readonly value: unknown;
48
+ } | {
49
+ readonly kind: "field";
50
+ readonly source: "current" | "incoming";
51
+ readonly field: string;
52
+ } | {
53
+ readonly kind: "add";
54
+ readonly left: WriteExpression;
55
+ readonly right: WriteExpression;
56
+ };
57
+ export interface CompiledConflict {
58
+ readonly fields: readonly string[];
59
+ readonly action: {
60
+ readonly kind: "skip";
61
+ } | {
62
+ readonly kind: "update";
63
+ readonly values: Readonly<Record<string, WriteExpression>>;
64
+ };
65
+ }
66
+ /** A row expectation is evaluated by the transaction transport before commit. */
67
+ export declare function rowExpectation(input: unknown): (result: unknown) => void;
68
+ export declare function writeCompiler(table: CompiledTable): {
69
+ update(input: unknown): Record<string, WriteExpression>;
70
+ conflict(callback: unknown): CompiledConflict;
71
+ };
72
+ export {};
@@ -0,0 +1,122 @@
1
+ import { DatabaseError } from "./error.js";
2
+ const expressionType = Symbol("write expression type");
3
+ const storedExpressionType = Symbol("write expression storage type");
4
+ const expressionTokens = new WeakSet();
5
+ const policyType = Symbol("conflict policy type");
6
+ /** A row expectation is evaluated by the transaction transport before commit. */
7
+ export function rowExpectation(input) {
8
+ if (typeof input !== "function" && (!Number.isSafeInteger(input) || input < 0))
9
+ throw new TypeError("Expected a nonnegative safe row count or synchronous predicate");
10
+ return result => {
11
+ const count = result === null ? 0 : Array.isArray(result) ? result.length : 1;
12
+ const accepted = typeof input === "function" ? input(count) : count === input;
13
+ if (typeof accepted !== "boolean") {
14
+ // Observe a rejected promise from an accidentally async callback without accepting it.
15
+ if (accepted && typeof accepted.then === "function")
16
+ Promise.resolve(accepted).catch(() => { });
17
+ throw new TypeError("Row expectations must return a synchronous boolean");
18
+ }
19
+ if (!accepted)
20
+ throw new DatabaseError({ code: "row_expectation_failed", message: `Affected-row expectation failed (${count} rows)` });
21
+ };
22
+ }
23
+ export function writeCompiler(table) {
24
+ const nodes = new WeakMap();
25
+ function references(source, scope) {
26
+ return Object.freeze(Object.fromEntries(Object.entries(table.fields).map(([name, field]) => [name,
27
+ reference({ kind: "field", source, field: name }, field, scope, 0, 1),
28
+ ])));
29
+ }
30
+ function reference(node, field, scope, depth, size, nullable = field.allowsNull) {
31
+ const value = Object.create(null);
32
+ if (field.scalar === "int64" || field.scalar === "float64") {
33
+ value.add = (right) => {
34
+ const operand = expression(right, field, scope, true, true);
35
+ if (Math.max(depth, operand.depth) + 1 > 64)
36
+ throw new TypeError("Write expression nesting exceeds budget");
37
+ if (size + operand.size + 1 > 1024)
38
+ throw new TypeError("Write expression size exceeds budget");
39
+ return reference(Object.freeze({ kind: "add", left: node, right: operand.node }), field, scope, Math.max(depth, operand.depth) + 1, size + operand.size + 1, nullable || operand.nullable);
40
+ };
41
+ }
42
+ nodes.set(value, { node, field, scope, depth, size, nullable });
43
+ expressionTokens.add(value);
44
+ return Object.freeze(value);
45
+ }
46
+ function expression(value, field, scope, allowNullReference = false, arithmetic = false) {
47
+ const meta = typeof value === "object" && value !== null ? nodes.get(value) : undefined;
48
+ if (meta) {
49
+ if (meta.scope !== scope)
50
+ throw new TypeError("Write expressions belong to their declaration callback");
51
+ if (meta.field.scalar !== field.scalar || meta.field.precision !== field.precision || (meta.nullable && !field.allowsNull && !allowNullReference))
52
+ throw new TypeError("Incompatible write expression assignment");
53
+ return meta;
54
+ }
55
+ if (typeof value === "object" && value !== null && expressionTokens.has(value))
56
+ throw new TypeError("Write expressions belong to their declaration callback");
57
+ let parsed;
58
+ if (arithmetic) {
59
+ if (field.scalar === "int64" && field.mode !== "bigint") {
60
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
61
+ throw new TypeError("int64 arithmetic requires a safe integer in number mode");
62
+ value = BigInt(value);
63
+ }
64
+ parsed = field.storage(value);
65
+ }
66
+ else
67
+ parsed = field.encode(value);
68
+ return { node: Object.freeze({ kind: "value", value: typeof parsed === "bigint" ? parsed.toString() : parsed }), field, scope, depth: 0, size: 1, nullable: parsed === null };
69
+ }
70
+ function patch(input, scope) {
71
+ if (typeof input !== "object" || input === null || Array.isArray(input) || ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
72
+ throw new TypeError("Expected a write patch object");
73
+ let size = 0;
74
+ return Object.freeze(Object.fromEntries(Object.entries(input).flatMap(([name, value]) => {
75
+ if (!Object.hasOwn(table.fields, name))
76
+ throw new TypeError(`Unknown field ${table.name}.${name}`);
77
+ if (name === table.primaryKey)
78
+ throw new TypeError("Cannot update a primary key");
79
+ if (value === undefined)
80
+ return [];
81
+ const item = expression(value, table.fields[name], scope);
82
+ size += item.size;
83
+ if (size > 1024)
84
+ throw new TypeError("Write expression size exceeds budget");
85
+ return [[name, item.node]];
86
+ })));
87
+ }
88
+ return {
89
+ update(input) {
90
+ const scope = {};
91
+ return patch(typeof input === "function" ? input(references("current", scope)) : input, scope);
92
+ },
93
+ conflict(callback) {
94
+ if (typeof callback !== "function")
95
+ throw new TypeError("OnConflict requires a policy callback");
96
+ const scope = {};
97
+ const policies = new WeakMap();
98
+ const on = (...fields) => {
99
+ if (!fields.length || fields.some(field => typeof field !== "string") || new Set(fields).size !== fields.length)
100
+ throw new TypeError("Expected a complete primary or unique conflict key");
101
+ const eligible = [[table.primaryKey], ...Object.values(table.unique).map(key => key.fields)];
102
+ if (!eligible.some(key => key.length === fields.length && key.every(field => fields.includes(field))))
103
+ throw new TypeError("Conflict target must be a complete primary or unique key");
104
+ const target = Object.freeze([...fields]);
105
+ const policy = (action) => {
106
+ const token = Object.freeze(Object.create(null));
107
+ policies.set(token, Object.freeze({ fields: target, action: Object.freeze(action) }));
108
+ return token;
109
+ };
110
+ return Object.freeze({
111
+ skip: () => policy({ kind: "skip" }),
112
+ update: (input) => policy({ kind: "update", values: patch(typeof input === "function" ? input(Object.freeze({ current: references("current", scope), incoming: references("incoming", scope) })) : input, scope) }),
113
+ });
114
+ };
115
+ const result = callback(Object.freeze({ on }));
116
+ const selected = typeof result === "object" && result !== null ? policies.get(result) : undefined;
117
+ if (!selected)
118
+ throw new TypeError("Return a conflict policy from this callback");
119
+ return selected;
120
+ },
121
+ };
122
+ }
package/dist/zod.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { z } from "zod";
2
+ import { type TableDefinition } from "./schema.ts";
3
+ type Narrow<S extends z.ZodType, T> = S & z.ZodType<T, T>;
4
+ type Native<T> = 0 extends 1 & T ? z.ZodType<T> : [T] extends [Date] ? Narrow<z.ZodDate, T> : [T] extends [string] ? Narrow<z.ZodString, T> : [T] extends [number] ? Narrow<z.ZodNumber, T> : [T] extends [bigint] ? Narrow<z.ZodBigInt, T> : [T] extends [boolean] ? Narrow<z.ZodBoolean, T> : [T] extends [readonly (infer Item)[]] ? z.ZodArray<Schema<Item>> : z.ZodType<T>;
5
+ type NullableSchema<T> = null extends T ? z.ZodNullable<Native<Exclude<T, null>>> : Native<T>;
6
+ type Schema<T> = undefined extends T ? z.ZodOptional<NullableSchema<Exclude<T, undefined>>> : NullableSchema<T>;
7
+ type Present<T> = {
8
+ [K in keyof T as [Exclude<T[K], undefined>] extends [never] ? never : K]: T[K];
9
+ };
10
+ type Select<D extends TableDefinition> = Present<D["$inferSelect"]>;
11
+ type Insert<D extends TableDefinition> = Present<D["$inferInsert"]>;
12
+ type Update<D extends TableDefinition> = Present<D["$inferUpdate"]>;
13
+ type FieldSchema<D extends TableDefinition, K, T> = K extends keyof D["fields"] ? D["fields"][K]["customCodec"] extends true ? z.ZodType<Exclude<T, null | undefined>> : Native<Exclude<T, null | undefined>> : Native<Exclude<T, null | undefined>>;
14
+ type Refinements<D extends TableDefinition, T> = {
15
+ [K in keyof T]?: (schema: FieldSchema<D, K, T[K]>) => z.ZodType;
16
+ };
17
+ type NullableWrapped<T, S extends z.ZodType> = null extends T ? z.ZodNullable<S> : S;
18
+ type Wrapped<T, S extends z.ZodType> = undefined extends T ? z.ZodOptional<NullableWrapped<T, S>> : NullableWrapped<T, S>;
19
+ type Refined<D extends TableDefinition, T, R> = {
20
+ -readonly [K in keyof T]-?: K extends keyof R ? R[K] extends (schema: never) => infer S ? S extends z.ZodType ? Wrapped<T[K], S> : Wrapped<T[K], FieldSchema<D, K, T[K]>> : Wrapped<T[K], FieldSchema<D, K, T[K]>> : Wrapped<T[K], FieldSchema<D, K, T[K]>>;
21
+ };
22
+ /** Native Zod object for a complete application row, including its primary key. */
23
+ export declare function createSelectSchema<D extends TableDefinition, R extends Refinements<D, Select<D>> = {}>(table: D, refinements?: R & Refinements<D, Select<D>>): z.ZodObject<Refined<D, Select<D>, R>>;
24
+ /** Defaults and generated keys become optional; no database defaults are applied. */
25
+ export declare function createInsertSchema<D extends TableDefinition, R extends Refinements<D, Insert<D>> = {}>(table: D, refinements?: R & Refinements<D, Insert<D>>): z.ZodObject<Refined<D, Insert<D>, R>>;
26
+ /** Partial assignment schema with the immutable primary key excluded. */
27
+ export declare function createUpdateSchema<D extends TableDefinition, R extends Refinements<D, Update<D>> = {}>(table: D, refinements?: R & Refinements<D, Update<D>>): z.ZodObject<Refined<D, Update<D>, R>>;
28
+ export {};
package/dist/zod.js ADDED
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ import { compiledTableForDefinition, jsonValidatorForShape, v, } from "./schema.js";
3
+ /** Native Zod object for a complete application row, including its primary key. */
4
+ export function createSelectSchema(table, refinements) {
5
+ return tableSchema(table, "select", refinements);
6
+ }
7
+ /** Defaults and generated keys become optional; no database defaults are applied. */
8
+ export function createInsertSchema(table, refinements) {
9
+ return tableSchema(table, "insert", refinements);
10
+ }
11
+ /** Partial assignment schema with the immutable primary key excluded. */
12
+ export function createUpdateSchema(table, refinements) {
13
+ return tableSchema(table, "update", refinements);
14
+ }
15
+ function valid(parse, value) {
16
+ try {
17
+ parse(value);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ function jsonSchema(shape) {
25
+ const validator = jsonValidatorForShape(shape);
26
+ if (validator?.customCodec)
27
+ return z.custom(value => valid(value => validator.parse(value), value), "Invalid application JSON value");
28
+ switch (shape.kind) {
29
+ case "string": return z.string();
30
+ case "number": return z.number();
31
+ case "boolean": return z.boolean();
32
+ case "nullable": return jsonSchema(shape.inner).nullable();
33
+ case "array": return z.array(jsonSchema(shape.item));
34
+ case "object": return z.strictObject(Object.fromEntries(Object.entries(shape.fields).map(([key, field]) => [key, field.optional ? jsonSchema(field.shape).optional() : jsonSchema(field.shape)])));
35
+ case "any": return z.json();
36
+ }
37
+ }
38
+ function fieldSchema(field) {
39
+ let schema;
40
+ if (field.customCodec)
41
+ schema = z.custom();
42
+ else
43
+ switch (field.scalar) {
44
+ case "string":
45
+ schema = z.string();
46
+ break;
47
+ case "uuid":
48
+ schema = z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
49
+ break;
50
+ case "float64":
51
+ schema = z.number();
52
+ break;
53
+ case "int64":
54
+ schema = field.mode === "bigint" ? z.bigint() : z.number().int().min(Number.MIN_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
55
+ break;
56
+ case "boolean":
57
+ schema = z.boolean();
58
+ break;
59
+ case "date":
60
+ case "timestamp":
61
+ case "localTimestamp":
62
+ schema = field.mode === "date" ? z.date() : z.string();
63
+ break;
64
+ case "json":
65
+ schema = jsonSchema(field.jsonShape ?? { kind: "any" });
66
+ break;
67
+ }
68
+ return schema;
69
+ }
70
+ function tableSchema(table, operation, refinements = {}) {
71
+ const compiled = compiledTableForDefinition(table);
72
+ if (!compiled && Object.values(table.fields).some(field => typeof field.target === "string"))
73
+ throw new TypeError("Call defineSchema before adapting a table with string v.id references");
74
+ const key = table.options.primaryKey ?? "id";
75
+ const fields = { ...table.fields, ...(Object.hasOwn(table.fields, key) ? {} : { [key]: v.uuid() }), ...compiled?.fields };
76
+ const generation = table.options.keyGeneration ?? (fields[key]?.scalar === "uuid" ? "uuidV7" : "none");
77
+ const shape = {};
78
+ for (const [name, field] of Object.entries(fields)) {
79
+ if ((operation === "update" && name === key) || (operation === "insert" && name === key && table.options.insertKeyPolicy === "generatedOnly"))
80
+ continue;
81
+ let schema = fieldSchema(field);
82
+ const refine = Object.getOwnPropertyDescriptor(refinements, name);
83
+ if (refine) {
84
+ if (!("value" in refine) || typeof refine.value !== "function")
85
+ throw new TypeError(`Expected a Zod refinement callback for ${name}`);
86
+ schema = refine.value(schema);
87
+ if (!(schema instanceof z.ZodType))
88
+ throw new TypeError(`Refinement for ${name} must return a Zod schema`);
89
+ }
90
+ if (field.allowsNull)
91
+ schema = schema.nullable();
92
+ // Validate storage constraints/codecs without changing the accepted value.
93
+ schema = schema.refine(value => valid(value => field.parse(value), value), "Value violates its database field definition");
94
+ if (operation === "update" || (operation === "insert" && (field.hasDefault || (name === key && generation !== "none"))))
95
+ schema = schema.optional();
96
+ shape[name] = schema;
97
+ }
98
+ for (const name of Object.keys(refinements))
99
+ if (!Object.hasOwn(shape, name))
100
+ throw new TypeError(`Cannot refine excluded or unknown field ${name}`);
101
+ return z.strictObject(shape);
102
+ }