viborm 1.2.4 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-s1ySUuMb.mjs +2 -0
- package/dist/builder-s1ySUuMb.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-7qiFSE8J.mjs +2 -0
- package/dist/chain-7qiFSE8J.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/client-6YgGlXzN.mjs +2 -0
- package/dist/client-6YgGlXzN.mjs.map +1 -0
- package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-BgJ7Faln.mjs +49 -0
- package/dist/{client-B3VWFhv_.mjs.map → client-BgJ7Faln.mjs.map} +1 -1
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-KQ85SWfT.mjs +2 -0
- package/dist/controls-KQ85SWfT.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-vn-9CN0y.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-vn-9CN0y.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-CcpKWCVo.mjs +2 -0
- package/dist/{every-o-Nu9Em8.mjs.map → every-CcpKWCVo.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-BsPZI4jE.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-BsPZI4jE.mjs.map} +1 -1
- package/dist/identifier-conversion-BneQiLxQ.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-BneQiLxQ.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D9LtHxVK.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D9LtHxVK.mjs.map} +1 -1
- package/dist/{libsql-Drp-zaxq.mjs → libsql-BlSBYwd_.mjs} +3 -3
- package/dist/{libsql-Drp-zaxq.mjs.map → libsql-BlSBYwd_.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-CDTUZQWL.mjs → memory-C0k-_S_n.mjs} +2 -2
- package/dist/{memory-CDTUZQWL.mjs.map → memory-C0k-_S_n.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-D7zC03yD.mjs → mysql-DOLHwIM_.mjs} +6 -6
- package/dist/{mysql-D7zC03yD.mjs.map → mysql-DOLHwIM_.mjs.map} +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-Dv-QnnbD.mjs → postgres-DQVSTqVm.mjs} +4 -4
- package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-DQVSTqVm.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-B6yWtnx_.mjs +2 -0
- package/dist/result-shape-B6yWtnx_.mjs.map +1 -0
- package/dist/scalar-CpEwuJvn.mjs +4 -0
- package/dist/scalar-CpEwuJvn.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-BnzGHn7k.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-BnzGHn7k.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-DZsdP6bi.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-DZsdP6bi.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C5RMZl05.mjs +2 -0
- package/dist/to-many-C5RMZl05.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-C3r4gO3Y.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-C3r4gO3Y.mjs.map} +1 -1
- package/dist/v-DtLdBQYg.mjs +2 -0
- package/dist/v-DtLdBQYg.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-CVSrhn0u.mjs +2 -0
- package/dist/validator-CVSrhn0u.mjs.map +1 -0
- package/dist/version-C8QLCt1n.mjs +2 -0
- package/dist/{version-nt0parEY.mjs.map → version-C8QLCt1n.mjs.map} +1 -1
- package/package.json +36 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B3VWFhv_.mjs +0 -49
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-o-Nu9Em8.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-nt0parEY.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
package/dist/client.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as Schema,
|
|
2
|
-
export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type CountResultType, type ExtendedClient, type ExtensionCacheState, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedControl, type RawOperation, type RelationLinks, type Schema, type StatementContext, type StatementHandler, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, defineExtension, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
|
|
1
|
+
import { A as Schema, Bt as CountResultType, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Ht as InferSelectInclude, I as Links, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Qt as StatementHandler, Rt as AggregateResultType, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Ut as defaultOmit, Vt as GroupByResultType, Wn as IndexDefinition, Xt as defineExtension, Y as VibSchema, Yt as ClientExtension, Zt as StatementContext, _ as ObservationCompletion, _n as UnwrapPendingOperation, dr as ObjectSchema, gn as PendingOperation, in as ExtensionResultConsumerState, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as ExtensionCacheState, on as RawOperation, qt as PlacedControl, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation, zt as BatchPayload } from "./index-VsM29vYN.mjs";
|
|
2
|
+
export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type ClientTypeState, type CountResultType, type ExtendedClient, type ExtensionCacheState, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedControl, type RawOperation, type RelationLinks, type Schema, type StatementContext, type StatementHandler, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, defineExtension, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
|
package/dist/client.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as e,o as t}from"./chain-7qiFSE8J.mjs";import{d as n,m as r}from"./result-shape-B6yWtnx_.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-DZsdP6bi.mjs";export{n as PendingOperation,e as defaultOmit,t as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{n as e}from"./chunk-BuuaeEvq.mjs";const t={now:()=>Date.now(),setTimeout(e,t){let n=setTimeout(e,t);return{cancel:()=>clearTimeout(n),unref:()=>{typeof n.unref==`function`&&n.unref()}}}};export{t};
|
|
2
|
-
//# sourceMappingURL=clock-
|
|
2
|
+
//# sourceMappingURL=clock-C24RcpwO.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clock-
|
|
1
|
+
{"version":3,"file":"clock-C24RcpwO.mjs","names":[],"sources":["../src/clock.ts"],"sourcesContent":["/**\n * The time seam.\n *\n * Two subsystems decide things by reading the wall clock and arming timers:\n * cache freshness (TTL, and the stale window SWR serves from) and the\n * transaction `timeout` / `maxWait` bounds. Both are behavior worth testing,\n * and testing either through the host clock means sleeping — which buys a slow\n * suite and a timing race, not a proof.\n *\n * So both take their time from a `Clock`. The default is the host's own, and\n * nothing here is public API: the override exists so a test can advance time\n * instead of waiting for it. Driver-internal timers are deliberately out of\n * scope — they belong to the database client, not to us.\n */\n\n/**\n * A timer armed by a `Clock`. The handle owns its own cancellation, so a call\n * site never reaches for a host timer function to undo what a clock started.\n */\nexport interface ClockTimer {\n /** Cancel the pending callback. Safe to call after it has already fired. */\n cancel(): void;\n /**\n * Release the host's hold on the event loop, where the host has one to\n * release. Node timers do; a virtual clock has nothing to release and says\n * so by omitting this.\n */\n unref?(): void;\n}\n\n/** The reading of time and the arming of timers, as one injectable thing. */\nexport interface Clock {\n /** Milliseconds since the epoch, exactly as `Date.now()` reports them. */\n now(): number;\n /** Arm `callback` to run `ms` from now. Cancel through the returned handle. */\n setTimeout(callback: () => void, ms: number): ClockTimer;\n}\n\n/** The host clock: `Date.now` and the global timer functions. The default. */\nexport const systemClock: Clock = {\n now: () => Date.now(),\n setTimeout(callback: () => void, ms: number): ClockTimer {\n const timer = setTimeout(callback, ms);\n return {\n cancel: () => clearTimeout(timer),\n // Hosts that are not Node (browsers, some edge runtimes) hand back a\n // number with no `unref`. Asking is cheaper than assuming.\n unref: () => {\n if (typeof timer.unref === \"function\") timer.unref();\n },\n };\n },\n};\n"],"mappings":"yCAuCA,MAAa,EAAqB,CAChC,QAAW,KAAK,KAAK,CACrB,WAAW,EAAsB,EAAwB,CACvD,IAAM,EAAQ,WAAW,EAAU,EAAG,CACtC,MAAO,CACL,WAAc,aAAa,EAAM,CAGjC,UAAa,CACP,OAAO,EAAM,OAAU,YAAY,EAAM,OAAO,EAEvD,EAEJ"}
|
package/dist/config.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as ResolveCallback, t as MigrationClient } from "./planner-
|
|
2
|
-
import { n as MigrationStorageWriter } from "./contract-
|
|
1
|
+
import { i as ResolveCallback, t as MigrationClient } from "./planner-C1NzLBge.mjs";
|
|
2
|
+
import { n as MigrationStorageWriter } from "./contract-Dw0FR78e.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/cli/utils.d.ts
|
|
5
5
|
|
package/dist/config.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./utils-
|
|
1
|
+
import{t as e}from"./utils-C3r4gO3Y.mjs";export{e as defineConfig};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{b as r,t as i}from"./base-D3m1S7Uc.mjs";import{p as a,r as o,t as s}from"./validation-BamBwne9.mjs";import{a as c}from"./key-D9LtHxVK.mjs";const l=`viborm.cache`,u=Object.freeze({cache:Object.freeze({schema:Object.freeze({"~standard":Object.freeze({version:1,vendor:`viborm`,validate:e=>Object.freeze({value:officialCacheRuntime().admitMutationCacheOptions(e)})})}),on:`writes`})}),d=new WeakMap,f=new WeakMap,p=new WeakMap;let m;function registerOfficialCacheQuery(e,t,n){m=n,d.set(e,t)}function installOfficialCacheRuntime(e){m=e}function officialCacheRuntime(){if(m===void 0)throw Error(`The official cache runtime is not loaded: import cache() from viborm/cache.`);return m}function getOfficialCacheQueryCapability(e){return t(e)?d.get(e):void 0}function getOfficialCacheChainDefinition(e){return e===void 0?void 0:f.get(e)}function getOfficialCacheChainCapability(e){return e===void 0?void 0:p.get(e)}function registerOfficialCacheChain(e,t){f.set(e,t)}function setOfficialCacheChainCapability(e,t){p.set(e,t)}function bindOfficialCacheChain(e,t){f.get(e)!==void 0&&officialCacheRuntime().bindChain(e,t)}function isCacheManagedExecution(e){return e?.skipSpan===!0}const h=new Set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function isReadOperation(e){return h.has(e)}const g=new Set([...h,`create`,`update`,`delete`,`upsert`,`createMany`,`updateMany`,`deleteMany`]);function isWriteOperation(e){return g.has(e)&&!isReadOperation(e)}function baseOperation(e){return e===`findUniqueOrThrow`?`findUnique`:e===`findFirstOrThrow`?`findFirst`:e}const _={reads:new Set([...g].filter(isReadOperation)),writes:new Set([...g].filter(isWriteOperation)),all:g},v=new Set([...g].filter(e=>e!==`create`&&e!==`createMany`)),y=new Set([`delete`,`deleteMany`]);function placeControls(e){let t=[],{name:n,controls:r,rows:i,deletion:a,data:o}=e,s=a?.removeWhen??{},c=new Set(Object.keys(a?.models??{})),l=new Set([...c,...Object.keys(i?.models??{}),...Object.keys(i?.verbs??{}),...Object.keys(o?.models??{})]),u=l.size===0?!0:l;for(let[e,i]of Object.entries(r??{})){let r=Object.hasOwn(s,e);t.push({name:e,extension:n,declaration:i,operations:r?y:placementOf(i.on),models:r?c:void 0,required:i.required===!0?u:void 0,...i.bound===!0&&{bound:!0},...i.uncacheable===!0&&{uncacheable:!0}})}return i!==void 0&&t.push({name:i.control,extension:n,declaration:Object.freeze({oneOf:Object.freeze(rowsModes(i))}),operations:v,fallback:i.default}),t}function placementOf(e){return e===void 0?g:typeof e==`string`?_[e]:new Set(e)}function rowsModes(e){let[t]=Object.values(e.models);return t===void 0?[e.default]:Object.keys(t)}const b=new WeakSet;function snapshotControlValue(e){if(typeof e!=`object`||!e||!c(e))return e;let t;try{t=captureOf(e,new WeakSet)}catch{return e}if(t===`opaque`)return e;if(t===`fixed`)return b.add(e),e;let n;try{n=structuredClone(e)}catch{return e}return freezeCopy(n)&&b.add(n),n}function captureOf(e,t){if(ArrayBuffer.isView(e))return`opaque`;if(t.has(e))return`fixed`;t.add(e);let n=e instanceof Date||!Object.isFrozen(e)?`copy`:`fixed`,r=Array.isArray(e);for(let i of Reflect.ownKeys(e)){if(r&&i===`length`)continue;let a=Object.getOwnPropertyDescriptor(e,i);if(typeof i==`symbol`||!a.enumerable||!(`value`in a))return`opaque`;let o=a.value;if(typeof o!=`object`||!o)continue;let s=captureOf(o,t);if(s===`opaque`)return`opaque`;s===`copy`&&(n=`copy`)}return n}function freezeCopy(e){if(e instanceof Date)return!1;let t=!0;for(let n of Object.values(e))typeof n==`object`&&n&&!freezeCopy(n)&&(t=!1);return Object.freeze(e),t}function isStableControlValue(e){return typeof e!=`object`||!e||b.has(e)}function admitControls(e,t,n,r,i){if(typeof n!=`object`||!n)return{args:n,controls:void 0};let a;try{a=Reflect.ownKeys(n)}catch(n){throw controlFailure(`The arguments of ${e}.${t} could not be inspected for controls`,e,t,n)}let o=[],s;for(let c of r){let{name:r,required:l}=c,u;c.bound!==!0&&a.includes(r)&&((s??=new Set).add(r),u=readControl(n,c,e,t));let d=u===void 0?i?.[r]??c.fallback:snapshotControlValue(admitControl(c,u,e,t));if(d!==void 0)o.push([r,d]);else if(l===!0||l?.has(e))throw invalidControl(c,e,t,[`is required`])}return{args:s===void 0?n:withoutControls(n,a,s,e,t),controls:o.length===0?void 0:Object.freeze(Object.fromEntries(o))}}function bindControls(e,t,n,r){let i={...r};for(let[r,a]of Object.entries(n)){let n=e.find(e=>e.name===r&&e.extension===t);if(n===void 0)throw new o(`Extension "${t}" binds control "${r}", which it does not declare.`,{meta:{extension:t}});i[r]=snapshotControlValue(admitControl(n,a))}return Object.freeze(i)}function controlsOwnedBy(e,t){let n=[];for(let r of t)e!==void 0&&Object.hasOwn(e,r)&&n.push([r,e[r]]);return Object.freeze(Object.fromEntries(n))}function readControl(e,t,n,r){try{return Reflect.get(e,t.name)}catch(e){throw controlFailure(`Extension "${t.extension}" control "${t.name}" of ${n}.${r} could not be read`,n,r,e)}}function withoutControls(e,t,n,r,i){let a={};try{for(let r of t){if(n.has(r))continue;let t=Object.getOwnPropertyDescriptor(e,r);t&&Object.defineProperty(a,r,t)}}catch(e){throw controlFailure(`The arguments of ${r}.${i} could not be inspected for controls`,r,i,e)}return a}function admitControl(e,r,i,a){let{declaration:o}=e;if(`oneOf`in o){if(o.oneOf.some(e=>e===r))return r;throw invalidControl(e,i,a,[`must be one of ${o.oneOf.map(e=>JSON.stringify(e)).join(`, `)}`])}let s;try{s=o.schema[`~standard`].validate(r)}catch(t){throw isVibORMFailure(t)?t:validatorFailure(e,i,a,`threw`,t)}let c=`malformed`,l=[],u;try{if(n(s)){let e=`then`in s?s.then:void 0;if(t(e))c=`promise`,Reflect.apply(e,s,[void 0,()=>void 0]);else{let e=s.issues;e===void 0?`value`in s&&(c=`value`,u=s.value):Array.isArray(e)&&(c=`issues`,l=e)}}}catch(t){throw validatorFailure(e,i,a,`returned an unreadable result`,t)}switch(c){case`value`:return u;case`issues`:throw invalidControl(e,i,a,issueMessages(l));case`promise`:throw validatorFailure(e,i,a,`returned a promise`,TypeError(`Control validators must return synchronously`));default:throw validatorFailure(e,i,a,`returned a malformed result`,TypeError(`A Standard Schema result has a value or an issue list`))}}function issueMessages(e){let t=[];try{for(let r of e){let e=n(r)?r.message:void 0;t.push(typeof e==`string`?e:`is invalid`)}}catch{return[`is invalid`]}return t.length===0?[`is invalid`]:t}function isVibORMFailure(e){try{return e instanceof i}catch{return!1}}function uncacheableRead(e,t,n,r){let i=e.find(e=>e.uncacheable===!0&&t?.[e.name]!==void 0);return i&&invalidControl(i,n,r,[`is not cacheable: a read that holds it is not served from the cache`])}function invalidControl(e,t,n,r){return new s(n===void 0?{kind:`schema-builder`,builder:`$bind`,path:e.name}:{kind:`operation`,operation:n,model:t},r.map(t=>({path:e.name,message:`Control "${e.name}" ${t}`})),{meta:{model:t,extension:e.extension}})}function validatorFailure(e,t,n,r,i){return controlFailure(`Extension "${e.extension}" control "${e.name}" validator for ${n===void 0?`$bind`:`${t}.${n}`} ${r}`,t,n,i)}function controlFailure(e,t,n,i){return new a(`${e}.`,{cause:r(i),meta:{model:t,operation:n}})}export{setOfficialCacheChainCapability as C,registerOfficialCacheQuery as S,installOfficialCacheRuntime as _,placeControls as a,officialCacheRuntime as b,g as c,isWriteOperation as d,l as f,getOfficialCacheQueryCapability as g,getOfficialCacheChainDefinition as h,isStableControlValue as i,baseOperation as l,getOfficialCacheChainCapability as m,bindControls as n,rowsModes as o,bindOfficialCacheChain as p,controlsOwnedBy as r,uncacheableRead as s,admitControls as t,isReadOperation as u,isCacheManagedExecution as v,registerOfficialCacheChain as x,u as y};
|
|
2
|
+
//# sourceMappingURL=controls-KQ85SWfT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"controls-KQ85SWfT.mjs","names":[],"sources":["../src/cache/capability.ts","../src/query-engine/routed-operations.ts","../src/extensions/controls.ts"],"sourcesContent":["// The part of the official cache the core client reads on every operation:\n// whether a chain carries the cache, and a handle on the cache runtime. The\n// runtime itself (cache driver, cache flow, result codecs) is installed by\n// `cache()` from `viborm/cache`, so an application that never creates the\n// extension does not load it. A chain can only carry the capability after\n// `cache()` ran, which is what makes `officialCacheRuntime()` total wherever\n// the core asks for it.\n\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n GenericQueryHandler,\n OfficialGenericQueryHandler,\n} from \"@extensions/query\";\nimport { isFunction } from \"@validation/value-guards\";\nimport type { CacheDriver, WaitUntilFn } from \"./driver\";\nimport type { OfficialCacheRuntime } from \"./runtime\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\nexport const OFFICIAL_CACHE_NAME = \"viborm.cache\";\n\n/** The exact official query contribution. It is recognized by identity. */\nexport type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {\n bind(thisArg: unknown): GenericQueryHandler;\n};\n\n/**\n * A mutation's `cache` argument is the cache's declared control (ruling 7):\n * core removes and admits it before request handlers run, through the cache's\n * own parser, so a malformed value is still a `CacheConfigurationError`.\n */\nexport type OfficialCacheControls = {\n readonly cache: {\n readonly schema: StandardSchemaV1<CacheInvalidationOptions>;\n readonly on: \"writes\";\n };\n};\n\n/** The official value accepted by the dedicated `$extends` overload. */\nexport type OfficialCacheExtension = {\n readonly name: typeof OFFICIAL_CACHE_NAME;\n readonly query: OfficialCacheQueryContribution;\n readonly controls: OfficialCacheControls;\n};\n\n/**\n * The cache's one declaration. The chain places it for any definition carrying\n * the cache's query, whatever `controls` that definition spells: the query is\n * the cache's identity, so its control cannot be forged or left out. It lives\n * here, in the part core always loads, and admits through the runtime: a chain\n * carries the cache only after `cache()` installed that runtime.\n */\nexport const officialCacheControls: OfficialCacheControls = Object.freeze({\n cache: Object.freeze({\n schema: Object.freeze({\n \"~standard\": Object.freeze({\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) =>\n Object.freeze({\n value: officialCacheRuntime().admitMutationCacheOptions(value),\n }),\n }),\n }),\n on: \"writes\",\n }),\n});\n\n/**\n * What `cache()` knows before it meets a client: no scope, because the scope\n * partitions on facts (dialect, SQL namespace) that only a concrete driver\n * carries. One definition may be appended to several clients.\n */\nexport interface OfficialCacheDefinitionCapability {\n readonly driver: CacheDriver;\n readonly version: string | number | undefined;\n readonly waitUntil: WaitUntilFn | undefined;\n}\n\n/** The definition once bound to one client's driver, gaining its scope. */\nexport interface OfficialCacheCapability\n extends OfficialCacheDefinitionCapability {\n readonly scope: object;\n}\n\n/**\n * The two driver facts the scope derives from. Structural, so the cache holds\n * no driver reference and no import edge back into `src/drivers`.\n */\nexport interface OfficialCacheBindTarget {\n readonly dialect: string;\n readonly adapter: { readonly namespace?: string | undefined };\n}\n\nconst capabilitiesByQuery = new WeakMap<\n CallableFunction,\n OfficialCacheDefinitionCapability\n>();\nconst definitionsByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheDefinitionCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheCapability\n>();\nlet runtime: OfficialCacheRuntime | undefined;\n\n/** Recognize `query` as the official cache's contribution. `cache()` only. */\nexport function registerOfficialCacheQuery(\n query: CallableFunction,\n capability: OfficialCacheDefinitionCapability,\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n capabilitiesByQuery.set(query, capability);\n}\n\n/** Make the cache runtime reachable; `viborm/cache` does this as it loads. */\nexport function installOfficialCacheRuntime(\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n}\n\n/** The cache runtime; reachable only where a chain carries the cache. */\nexport function officialCacheRuntime(): OfficialCacheRuntime {\n if (runtime === undefined)\n throw new Error(\n \"The official cache runtime is not loaded: import cache() from viborm/cache.\"\n );\n return runtime;\n}\n\nexport function getOfficialCacheQueryCapability(\n query: unknown\n): OfficialCacheDefinitionCapability | undefined {\n return isFunction(query) ? capabilitiesByQuery.get(query) : undefined;\n}\n\n/**\n * The definition carried by this chain, scope or no scope. Generic\n * extension-chain code sees only this: admission, duplicate refusal, and\n * propagation are all decisions about the DEFINITION, and none of them may\n * depend on whether a client has bound it yet.\n */\nexport function getOfficialCacheChainDefinition(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheDefinitionCapability | undefined {\n return chain === undefined ? undefined : definitionsByChain.get(chain);\n}\n\n/** The bound capability: present only after a client composition root bound it. */\nexport function getOfficialCacheChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialCacheChain(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheDefinitionCapability\n): void {\n definitionsByChain.set(chain, capability);\n}\n\n/** Publish the capability the runtime bound for one chain. */\nexport function setOfficialCacheChainCapability(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n\n/**\n * Bind one resolved chain's cache definition to the concrete client driver,\n * deriving the scope that partitions its storage.\n *\n * Called by the client composition root — the one place that holds both the\n * resolved chain and the driver — and only for a chain that carries the\n * official cache, so an ordinary extension costs nothing here.\n */\nexport function bindOfficialCacheChain(\n chain: ResolvedExtensionChain,\n target: OfficialCacheBindTarget\n): void {\n if (definitionsByChain.get(chain) === undefined) return;\n officialCacheRuntime().bindChain(chain, target);\n}\n\n/** Whether an operation runs under the official cache's managed execution. */\nexport function isCacheManagedExecution(\n options: { readonly skipSpan?: boolean } | undefined\n): boolean {\n return options?.skipSpan === true;\n}\n","import type { Operations } from \"@client/types\";\n\n/**\n * The client operation vocabulary, retained at the C-01 cutover.\n *\n * These four names are the only part of the deleted shipped routing module that\n * owners OUTSIDE the engine consume: the client (`isWriteOperation`), the\n * official cache (`isWriteOperation`), the extension surface\n * (`ROUTED_OPERATIONS`) and the query-interception seam (`isReadOperation`).\n * The text below is the deleted `write-engine/routing.ts` definitions verbatim,\n * so no operation changes classification at the cutover.\n */\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** Whether a public operation routes through the engine's read owner. */\nexport function isReadOperation(operation: string): boolean {\n return READ_OPERATIONS.has(operation);\n}\n\n/**\n * The operation names the engine owns a construction path for. Every client\n * operation family is here; a name outside it (there is none on the client path)\n * resolves to `undefined`.\n */\nexport const ROUTED_OPERATIONS: ReadonlySet<string> = new Set([\n ...READ_OPERATIONS,\n \"create\",\n \"update\",\n \"delete\",\n \"upsert\",\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n]);\n\n/** Whether a public operation routes through the engine's write owner. */\nexport function isWriteOperation(operation: string): boolean {\n return ROUTED_OPERATIONS.has(operation) && !isReadOperation(operation);\n}\n\n/**\n * The verb an `…OrThrow` operation shares its whole envelope with: its schema,\n * its admission and its result. Every other verb is its own base.\n */\nexport function baseOperation(\n operation: Operations\n): Exclude<Operations, \"findUniqueOrThrow\" | \"findFirstOrThrow\"> {\n if (operation === \"findUniqueOrThrow\") return \"findUnique\";\n if (operation === \"findFirstOrThrow\") return \"findFirst\";\n return operation;\n}\n","import { isCanonicalKeyData } from \"@cache/key\";\nimport type {\n CacheableOperations,\n MutationOperations,\n Operations,\n} from \"@client/types\";\nimport {\n ClientInitializationError,\n QueryError,\n ValidationError,\n VibORMError,\n} from \"@errors\";\nimport {\n isReadOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ControlLiteral, RuntimeExtensionDefinition } from \"./definition\";\n\n// =============================================================================\n// DEFINITION MEMBERS: plain data, checked by TypeScript only\n// =============================================================================\n\n/** The operations a declared control is accepted on. */\nexport type ControlPlacement =\n | \"reads\"\n | \"writes\"\n | \"all\"\n | readonly Operations[];\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema; `on` names the operations that accept it (every operation\n * when absent). With `required`, a call on one of those operations that does\n * not pass it is refused, on the models the extension names in `rows`,\n * `data` or `deletion` only; an extension that names no model asks for it on\n * every model. With `bound`, it is accepted only from a binding (the client\n * scope's `$bind`), never from a call's arguments: its placement reads no\n * argument, so a call that passes it is refused as passing an unknown key.\n * With `uncacheable`, a read that holds a value of it is never served from\n * the cache: `$withCache` on that read is refused before any statement. A\n * value held in a variable keeps its literal type only with `as const`, as a\n * held enum clause does.\n */\nexport type ControlDeclaration = (\n | { readonly oneOf: readonly (string | number | boolean)[] }\n | { readonly schema: StandardSchemaV1 }\n) & {\n readonly on?: ControlPlacement;\n readonly required?: boolean;\n readonly bound?: boolean;\n readonly uncacheable?: boolean;\n};\n\nexport type ControlsContribution = {\n readonly [name: string]: ControlDeclaration;\n};\n\n/** Constant scalar `where` or `data` fields of one model. */\ntype ScalarFields = { readonly [field: string]: unknown };\n\n/**\n * Which rows an operation sees. `control` names the call argument that picks\n * a mode; every model entry declares the same mode names, `default` among\n * them. `root` filters the call's own candidates, `related` rows reached\n * through a relation; each is a model's `where`, admitted once when the\n * extension is applied, or the name of one of its `verbs` predicates. Where a\n * filter takes a value, `{ control: \"<name>\", path?: \"a.b\" }` takes the value\n * the call passed for that control (or a field of it), `{ now: true }` the\n * call's instant, and `{ $if: … }` tests a call value. An absent value\n * (`null` included) matches nothing where its control is required, and drops\n * its filter where it is not.\n *\n * `verbs` judges, per model, what a call may do to the rows it sees: a mode\n * only narrows them (R8).\n */\nexport type RowsContribution = {\n readonly control: string;\n readonly default: string;\n readonly models: {\n readonly [model: string]: {\n readonly [mode: string]: {\n readonly root?: ScalarFields | string;\n readonly related?: ScalarFields | string;\n };\n };\n };\n readonly verbs?: { readonly [model: string]: RowsVerbs };\n};\n\n/**\n * One model's named predicates, each a `where` admitted once, and the verbs\n * that take them. `read` ANDs with every mode's `root` and `related`; a write\n * takes its verb's beside them: a delete `delete`'s, an update, for each\n * field its data writes, that field's `writes` entry, else `update`'s, and\n * `update`'s when its data writes only stamps. A join row's change is a write\n * of the relation on both rows it links; a row only addressed to reach its\n * children is read. A verb left out matches nothing.\n *\n * The row a write produces is judged too, as a value, against the rows as\n * they stand before the write, inside the statement that writes it (R4): a\n * created row at `place` (a model naming none is not judged on create); an\n * updated row at the predicates that judged its old row, and, for each field\n * its data writes, at that field's `moves` entry, and where it writes the\n * key of an `acyclic` relation (a to-one relation of the model to itself),\n * outside its own subtree. A refused row is written by no statement.\n *\n * `evidence` declares a projection key (`evidence.as`) a `select` or\n * `include` may name at every depth, on reads and on the rows a write\n * returns: per row, whether each of `names` holds there beside `read`, or,\n * `ordered`, the last of them that holds (`null` on a row `read` does not\n * hold). `reads` gates a field on a predicate: the row carries it only where\n * `read` and that predicate hold, a `select` naming it fails on a row\n * without them, and every operand a call writes over it (`where`, `orderBy`,\n * aggregates, `distinct`, unique lookups, relation filters) reads it as\n * absent there. A key or foreign-key field is never gated.\n */\nexport type RowsVerbs = {\n readonly predicates: { readonly [name: string]: ScalarFields };\n readonly read?: string;\n readonly update?: string;\n readonly delete?: string;\n readonly writes?: { readonly [field: string]: string };\n readonly place?: string;\n readonly moves?: { readonly [field: string]: string };\n readonly acyclic?: readonly string[];\n readonly evidence?: {\n readonly as: string;\n readonly names: readonly string[];\n readonly ordered?: boolean;\n };\n readonly reads?: { readonly [field: string]: string };\n};\n\n/**\n * What a delete does on the models named here: an update that stamps `at`\n * with the call's time and writes `assign`, unless the call's controls match\n * `removeWhen`.\n */\nexport type DeletionContribution = {\n readonly removeWhen?: {\n readonly [control: string]: string | number | boolean;\n };\n readonly models: {\n readonly [model: string]: {\n readonly at?: string;\n readonly assign?: ScalarFields;\n };\n };\n};\n\n/**\n * Fields an extension writes on the models named here: `create` on every\n * create of the model, `update` on every update of it, a soft delete's\n * included. A value is a constant, `{ control: \"<name>\", path?: \"a.b\" }` for\n * the value the call passed for that control or a field of it (a call that\n * passed none writes nothing there), `{ now: true }` for the call's instant,\n * or, on `update`, one of the field's update operators (`{ increment: 1 }`). A field is written only where the caller left it\n * out: a call that writes it itself, or writes the relation whose foreign key\n * holds it, keeps its own value there. A create may leave out such a field\n * even where the schema requires it: the call's data is checked with it\n * counted as given. When the model names here are known to the types\n * (written out, or kept by a `const` type parameter, not a plain\n * `string[]`), the extended client's types agree, nested creates included:\n * the field is optional on a create. When two extensions name a field, the\n * later one writes it, and a value the caller writes wins over both.\n */\nexport type DataContribution = {\n readonly models: {\n readonly [model: string]: {\n readonly create?: ScalarFields;\n readonly update?: ScalarFields;\n };\n };\n};\n\n// =============================================================================\n// CONTROL STATE: what a chain's controls add to each (model, operation)\n// =============================================================================\n\n/** Operations that select candidates: where a rows control is accepted. */\ntype CandidateOperations = Exclude<Operations, \"create\" | \"createMany\">;\n\n/** One declared control as the delegates see it. */\nexport interface PlacedControl<\n Value = unknown,\n Models = PropertyKey,\n Placed = Operations,\n> {\n readonly value: Value;\n readonly models: Models;\n readonly operations: Placed;\n}\n\nexport type NoControls = Record<never, never>;\n\ntype ControlValue<Declaration> = Declaration extends {\n readonly oneOf: readonly (infer Value)[];\n}\n ? Value\n : Declaration extends { readonly schema: StandardSchemaV1<infer Input> }\n ? Input\n : never;\n\ntype PlacementOperations<On> = On extends \"reads\"\n ? CacheableOperations\n : On extends \"writes\"\n ? MutationOperations\n : On extends readonly (infer Operation)[]\n ? Operation\n : Operations;\n\n/**\n * `deletion` places the control `removeWhen` names: on the deletes of the\n * models it manages, whatever the declaration's `on` says.\n */\ntype PlaceControl<Name, Declaration, Deletion> = Deletion extends {\n readonly removeWhen: infer RemoveWhen;\n readonly models: infer Managed;\n}\n ? Name extends keyof RemoveWhen\n ? PlacedControl<\n ControlValue<Declaration>,\n keyof Managed,\n \"delete\" | \"deleteMany\"\n >\n : PlaceFreeControl<Declaration>\n : PlaceFreeControl<Declaration>;\n\ntype PlaceFreeControl<Declaration> = PlacedControl<\n ControlValue<Declaration>,\n PropertyKey,\n PlacementOperations<\n Declaration extends { readonly on: infer On } ? On : \"all\"\n >\n>;\n\ntype DeclaredControls<Definition> = Definition extends {\n readonly controls: infer Controls extends ControlsContribution;\n}\n ? {\n readonly [Name in keyof Controls as Controls[Name] extends {\n readonly bound: true;\n }\n ? never\n : Name]: PlaceControl<\n Name,\n Controls[Name],\n Definition extends { readonly deletion: infer Deletion }\n ? Deletion\n : unknown\n >;\n }\n : NoControls;\n\n/** Every model entry declares the same mode names: those are the values. */\ntype RowsModes<Rows extends RowsContribution> =\n | Rows[\"default\"]\n | {\n [Model in keyof Rows[\"models\"]]: keyof Rows[\"models\"][Model];\n }[keyof Rows[\"models\"]];\n\n/** The rows control: every candidate-selecting operation of every model. */\ntype RowsControl<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? {\n readonly [Name in Rows[\"control\"]]: PlacedControl<\n RowsModes<Rows>,\n PropertyKey,\n CandidateOperations\n >;\n }\n : NoControls;\n\n/**\n * The models one definition's `rows` can hide from a relation read: its\n * `models` and `verbs` keys. A to-one relation that targets one of them reads `null` when\n * its target is hidden, so the result types widen it (`result-types.ts`).\n */\nexport type RowsModels<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? Extract<\n | keyof Rows[\"models\"]\n | (Rows extends { readonly verbs: infer Verbs } ? keyof Verbs : never),\n string\n >\n : never;\n\n/** The controls one definition places, keyed by control name. */\nexport type DefinitionControls<Definition> = DeclaredControls<Definition> &\n RowsControl<Definition>;\n\n/** The optional control arguments one (model, operation) accepts. */\nexport type OperationControls<Controls, ModelName, Operation> = {\n readonly [Name in keyof Controls as Controls[Name] extends PlacedControl<\n unknown,\n infer Models,\n infer Placed\n >\n ? ModelName extends Models\n ? Operation extends Placed\n ? Name\n : never\n : never\n : never]?: Controls[Name] extends PlacedControl<infer Value>\n ? Value\n : never;\n};\n\n// =============================================================================\n// DATA STATE: the fields a chain's `data` writes, per model\n// =============================================================================\n\n/**\n * The fields one `data` entry writes on its models' creates: there they may\n * be left out even where the schema requires them. An update's fields need\n * nothing, as every field of an update is optional already.\n */\nexport interface StampedFields<Models = PropertyKey, Fields = PropertyKey> {\n readonly models: Models;\n readonly fields: Fields;\n}\n\ntype CreateStamps<Model, Entry> = \"create\" extends keyof Entry\n ? Entry extends { readonly create?: infer Fields }\n ? StampedFields<Model, keyof NonNullable<Fields>>\n : never\n : never;\n\n/**\n * What one definition's `data` writes on creates: one member per model. A\n * definition whose model names are lost (`{ [model: string]: ... }`, as a\n * recipe called with a plain `string[]` builds) writes nothing the types can\n * name: its required fields stay required in the payloads.\n */\nexport type DefinitionData<Definition> = Definition extends {\n readonly data: { readonly models: infer Models };\n}\n ? string extends keyof Models\n ? never\n : {\n [Model in keyof Models]: CreateStamps<Model, Models[Model]>;\n }[keyof Models]\n : never;\n\n/** The fields a chain writes on every create of one model. */\nexport type StampedFieldNames<Data, ModelName> =\n Data extends StampedFields<infer Models, infer Fields extends PropertyKey>\n ? ModelName extends Models\n ? Fields\n : never\n : never;\n\n// =============================================================================\n// PLACEMENT: where each declared control is accepted\n// =============================================================================\n\n/** Where a control goes when its declaration names a placement. */\nconst PLACEMENTS: Readonly<\n Record<\"reads\" | \"writes\" | \"all\", ReadonlySet<string>>\n> = {\n reads: new Set([...ROUTED_OPERATIONS].filter(isReadOperation)),\n writes: new Set([...ROUTED_OPERATIONS].filter(isWriteOperation)),\n all: ROUTED_OPERATIONS,\n};\n\n/** Every operation that selects candidates: where a `rows` control goes. */\nconst CANDIDATE_OPERATIONS: ReadonlySet<string> = new Set(\n [...ROUTED_OPERATIONS].filter(\n (operation) => operation !== \"create\" && operation !== \"createMany\"\n )\n);\n\n/** Where a `deletion.removeWhen` control goes, on the models it manages. */\nconst DELETE_OPERATIONS: ReadonlySet<string> = new Set([\n \"delete\",\n \"deleteMany\",\n]);\n\n/** One control of a chain: its owner, its placement and how a value is admitted. */\nexport interface ResolvedControl {\n readonly name: string;\n readonly extension: string;\n readonly declaration: ControlDeclaration;\n /** The operations that accept it. */\n readonly operations: ReadonlySet<string>;\n /** The models that accept it; every model when absent. */\n readonly models?: ReadonlySet<string>;\n /**\n * Where a call that does not pass it is refused: on every model that\n * accepts it (`true`), on these models only, or nowhere when absent.\n */\n readonly required?: true | ReadonlySet<string>;\n /** What an absent argument admits: the `rows` control's default mode. */\n readonly fallback?: ControlLiteral;\n /** Accepted only from a binding, never read from the arguments. */\n readonly bound?: true;\n /** A read holding a value of it is not served from the cache. */\n readonly uncacheable?: true;\n}\n\n/**\n * Give every control of one definition its placement. A control\n * `deletion.removeWhen` names goes on the deletes of the models `deletion`\n * manages; the `rows` control on every candidate-selecting operation of every\n * model, its values the mode names; every other control where its own `on`\n * says (every operation without one), on every model. A `required` control\n * is asked for only on the models the definition names in `rows`, `data` or\n * `deletion`, and on every model when it names none.\n */\nexport function placeControls(\n definition: RuntimeExtensionDefinition\n): readonly ResolvedControl[] {\n const placed: ResolvedControl[] = [];\n const { name: extension, controls, rows, deletion, data } = definition;\n const removeWhen = deletion?.removeWhen ?? {};\n const managed = new Set(Object.keys(deletion?.models ?? {}));\n const named = new Set([\n ...managed,\n ...Object.keys(rows?.models ?? {}),\n ...Object.keys(rows?.verbs ?? {}),\n ...Object.keys(data?.models ?? {}),\n ]);\n const requiredOn = named.size === 0 ? true : named;\n for (const [name, declaration] of Object.entries(controls ?? {})) {\n const removes = Object.hasOwn(removeWhen, name);\n placed.push({\n name,\n extension,\n declaration,\n operations: removes ? DELETE_OPERATIONS : placementOf(declaration.on),\n models: removes ? managed : undefined,\n required: declaration.required === true ? requiredOn : undefined,\n ...(declaration.bound === true && { bound: true }),\n ...(declaration.uncacheable === true && { uncacheable: true }),\n });\n }\n if (rows !== undefined) {\n placed.push({\n name: rows.control,\n extension,\n declaration: Object.freeze({ oneOf: Object.freeze(rowsModes(rows)) }),\n operations: CANDIDATE_OPERATIONS,\n fallback: rows.default,\n });\n }\n return placed;\n}\n\nfunction placementOf(on: ControlDeclaration[\"on\"]): ReadonlySet<string> {\n if (on === undefined) return ROUTED_OPERATIONS;\n return typeof on === \"string\" ? PLACEMENTS[on] : new Set<string>(on);\n}\n\n/**\n * The `rows` control's values: the mode names, which every model entry\n * declares alike, or the default alone when no model is named.\n */\nexport function rowsModes(rows: RowsContribution): readonly string[] {\n const [modes] = Object.values(rows.models);\n return modes === undefined ? [rows.default] : Object.keys(modes);\n}\n\n// =============================================================================\n// ADMISSION: one call's controls, removed and validated once\n// =============================================================================\n\n/**\n * The controls one call admitted, by name. A `rows` control is resolved to its\n * mode, so an absent one reads as its default; an absent plain control is not\n * here.\n */\nexport type AdmittedControls = Readonly<Record<string, unknown>>;\n\nexport interface ControlAdmission {\n /** The arguments without their controls; the input itself when none was given. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly controls: AdmittedControls | undefined;\n}\n\n/** The admitted values {@link snapshotControlValue} copied: the stable ones. */\nconst snapshots = new WeakSet<object>();\n\n/**\n * An admitted value as the call holds it from here on. Plain data is copied\n * once and frozen, so every reader of the call's controls (the rows its\n * filters bind, the key its cached read is stored under, its handlers) reads\n * the same value whatever the caller later does to its own. A value already\n * fixed all the way down is kept by identity. A value a copy would change\n * (a non-enumerable or symbol property, which `structuredClone` drops; a\n * getter, whose answer only calling it shows), one that resists inspection,\n * one with no canonical spelling, or one that cannot be copied (a Proxy), is\n * kept as given, as are bytes (an indexed write survives `freeze`); a copy\n * that still holds a `Date` is kept but not stable (`setTime` survives it). In\n * those cases the call binds the value for itself alone and its read is not\n * cached.\n */\nexport function snapshotControlValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n if (!isCanonicalKeyData(value)) return value;\n let capture: ReturnType<typeof captureOf>;\n try {\n capture = captureOf(value, new WeakSet());\n } catch {\n // A Proxy may answer the canonical check and refuse a later reflection.\n return value;\n }\n if (capture === \"opaque\") return value;\n if (capture === \"fixed\") {\n snapshots.add(value);\n return value;\n }\n let copy: object;\n try {\n copy = structuredClone(value);\n } catch {\n return value;\n }\n if (freezeCopy(copy)) snapshots.add(copy);\n return copy;\n}\n\n/**\n * How an admitted value can be held: `fixed` when nothing reachable from it\n * can change (frozen own data properties only, no `Date`), `copy` when a\n * copy reproduces it (enumerable string-keyed data properties), `opaque`\n * when a copy might not (a non-enumerable or symbol property, or a getter,\n * never called here) or would not fix it (bytes).\n */\nfunction captureOf(\n value: object,\n seen: WeakSet<object>\n): \"fixed\" | \"copy\" | \"opaque\" {\n // Bytes are never stable (an indexed write survives `freeze`), and their\n // own properties are one per byte: kept as given, unread.\n if (ArrayBuffer.isView(value)) return \"opaque\";\n if (seen.has(value)) return \"fixed\";\n seen.add(value);\n let capture: \"fixed\" | \"copy\" =\n value instanceof Date || !Object.isFrozen(value) ? \"copy\" : \"fixed\";\n const array = Array.isArray(value);\n for (const key of Reflect.ownKeys(value)) {\n if (array && key === \"length\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (\n typeof key === \"symbol\" ||\n !descriptor.enumerable ||\n !(\"value\" in descriptor)\n )\n return \"opaque\";\n const entry: unknown = descriptor.value;\n if (typeof entry !== \"object\" || entry === null) continue;\n const inner = captureOf(entry, seen);\n if (inner === \"opaque\") return \"opaque\";\n if (inner === \"copy\") capture = \"copy\";\n }\n return capture;\n}\n\n/** Freeze a private copy; answer whether nothing in it can still change. */\nfunction freezeCopy(value: object): boolean {\n if (value instanceof Date) return false;\n let fixed = true;\n for (const entry of Object.values(value))\n if (typeof entry === \"object\" && entry !== null && !freezeCopy(entry))\n fixed = false;\n Object.freeze(value);\n return fixed;\n}\n\n/**\n * Whether a control value is the one admission fixed: a primitive, or plain\n * data {@link snapshotControlValue} copied. Only such a value may key anything that\n * outlives the call (a bound-facts memo, a cache entry).\n */\nexport function isStableControlValue(value: unknown): boolean {\n return typeof value !== \"object\" || value === null || snapshots.has(value);\n}\n\n/**\n * Remove every control placed on this operation from its arguments and admit\n * each once, before any request handler runs. A key naming a control placed\n * elsewhere, or a bound-only one, stays in the arguments, where core\n * validation refuses it as an unknown key. A control the call did not pass\n * takes the value its view binds, if any; without one it is refused here on\n * the models its placement requires it on.\n */\nexport function admitControls(\n model: string,\n operation: Operation,\n input: Record<string, unknown>,\n placed: readonly ResolvedControl[],\n bound?: AdmittedControls\n): ControlAdmission {\n // Arguments that are not an object hold no control: core validation refuses\n // them as it does on a client without controls.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, controls: undefined };\n }\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(input);\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n const admitted: [string, unknown][] = [];\n let given: Set<PropertyKey> | undefined;\n for (const control of placed) {\n const { name, required } = control;\n let raw: unknown;\n if (control.bound !== true && keys.includes(name)) {\n (given ??= new Set()).add(name);\n raw = readControl(input, control, model, operation);\n }\n // A bound value was admitted and fixed once, when its view was bound.\n const value =\n raw === undefined\n ? (bound?.[name] ?? control.fallback)\n : snapshotControlValue(admitControl(control, raw, model, operation));\n if (value !== undefined) admitted.push([name, value]);\n else if (required === true || required?.has(model)) {\n throw invalidControl(control, model, operation, [\"is required\"]);\n }\n }\n return {\n args:\n given === undefined\n ? input\n : withoutControls(input, keys, given, model, operation),\n controls:\n admitted.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(admitted)),\n };\n}\n\n/**\n * The values a view binds after one extension binds its own controls: each\n * admitted once and fixed, over the values the view already binds, a value\n * replacing an earlier one.\n */\nexport function bindControls(\n controls: readonly ResolvedControl[],\n extension: string,\n values: Readonly<Record<string, unknown>>,\n previous: AdmittedControls | undefined\n): AdmittedControls {\n const next: Record<string, unknown> = { ...previous };\n for (const [name, raw] of Object.entries(values)) {\n const control = controls.find(\n (candidate) =>\n candidate.name === name && candidate.extension === extension\n );\n if (control === undefined) {\n throw new ClientInitializationError(\n `Extension \"${extension}\" binds control \"${name}\", which it does not declare.`,\n { meta: { extension } }\n );\n }\n next[name] = snapshotControlValue(admitControl(control, raw));\n }\n return Object.freeze(next);\n}\n\n/** One extension's own admitted controls, as its handlers see them. */\nexport function controlsOwnedBy(\n admitted: AdmittedControls | undefined,\n names: readonly string[]\n): AdmittedControls {\n const owned: [string, unknown][] = [];\n for (const name of names) {\n if (admitted !== undefined && Object.hasOwn(admitted, name)) {\n owned.push([name, admitted[name]]);\n }\n }\n return Object.freeze(Object.fromEntries(owned));\n}\n\nfunction readControl(\n input: Record<string, unknown>,\n control: ResolvedControl,\n model: string,\n operation: Operation\n): unknown {\n try {\n return Reflect.get(input, control.name);\n } catch (cause) {\n throw controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" of ${model}.${operation} could not be read`,\n model,\n operation,\n cause\n );\n }\n}\n\n/** The caller's arguments minus the controls, every other descriptor kept. */\nfunction withoutControls(\n input: Record<string, unknown>,\n keys: readonly PropertyKey[],\n controls: ReadonlySet<PropertyKey>,\n model: string,\n operation: Operation\n): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n try {\n for (const key of keys) {\n if (controls.has(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor) Object.defineProperty(args, key, descriptor);\n }\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n return args;\n}\n\n/** One value admitted for a call's (model, operation), or, without them, a binding. */\nfunction admitControl(\n control: ResolvedControl,\n value: unknown,\n model?: string,\n operation?: Operation\n): unknown {\n const { declaration } = control;\n if (\"oneOf\" in declaration) {\n if (declaration.oneOf.some((allowed) => allowed === value)) return value;\n throw invalidControl(control, model, operation, [\n `must be one of ${declaration.oneOf.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n }\n let result: unknown;\n try {\n result = declaration.schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing request transform is.\n if (isVibORMFailure(cause)) throw cause;\n throw validatorFailure(control, model, operation, \"threw\", cause);\n }\n let shape: \"promise\" | \"malformed\" | \"issues\" | \"value\" = \"malformed\";\n let issues: readonly unknown[] = [];\n let admitted: unknown;\n try {\n if (isRecord(result)) {\n const then = \"then\" in result ? result.then : undefined;\n if (isFunction(then)) {\n shape = \"promise\";\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n Reflect.apply(then, result, [undefined, () => undefined]);\n } else {\n const listed = result.issues;\n if (listed !== undefined) {\n if (Array.isArray(listed)) {\n shape = \"issues\";\n issues = listed;\n }\n } else if (\"value\" in result) {\n shape = \"value\";\n admitted = result.value;\n }\n }\n }\n } catch (cause) {\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned an unreadable result\",\n cause\n );\n }\n switch (shape) {\n case \"value\":\n return admitted;\n case \"issues\":\n throw invalidControl(control, model, operation, issueMessages(issues));\n case \"promise\":\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Control validators must return synchronously\")\n );\n default:\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a malformed result\",\n new TypeError(\"A Standard Schema result has a value or an issue list\")\n );\n }\n}\n\n/** Each issue's message; an issue that cannot be read still refuses. */\nfunction issueMessages(issues: readonly unknown[]): string[] {\n const messages: string[] = [];\n try {\n for (const issue of issues) {\n const message = isRecord(issue) ? issue.message : undefined;\n messages.push(typeof message === \"string\" ? message : \"is invalid\");\n }\n } catch {\n return [\"is invalid\"];\n }\n return messages.length === 0 ? [\"is invalid\"] : messages;\n}\n\n/** Contained: `instanceof` on a hostile thrown proxy is itself a throw site. */\nfunction isVibORMFailure(value: unknown): value is VibORMError {\n try {\n return value instanceof VibORMError;\n } catch {\n return false;\n }\n}\n\n/**\n * The refusal of a cached read that holds a value of an `uncacheable`\n * control, or `undefined` when it holds none: such a read is an observation\n * the control's owner does not accept (the cache would serve it after the\n * facts it was judged on changed).\n */\nexport function uncacheableRead(\n controls: readonly ResolvedControl[],\n admitted: AdmittedControls | undefined,\n model: string,\n operation: Operation\n): ValidationError | undefined {\n const held = controls.find(\n (control) =>\n control.uncacheable === true && admitted?.[control.name] !== undefined\n );\n return (\n held &&\n invalidControl(held, model, operation, [\n \"is not cacheable: a read that holds it is not served from the cache\",\n ])\n );\n}\n\nfunction invalidControl(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n operation === undefined\n ? { kind: \"schema-builder\", builder: \"$bind\", path: control.name }\n : { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: control.name,\n message: `Control \"${control.name}\" ${message}`,\n })),\n { meta: { model, extension: control.extension } }\n );\n}\n\nfunction validatorFailure(\n control: ResolvedControl,\n model: string | undefined,\n operation: Operation | undefined,\n failure: string,\n cause: unknown\n): QueryError {\n return controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" validator for ${operation === undefined ? \"$bind\" : `${model}.${operation}`} ${failure}`,\n model,\n operation,\n cause\n );\n}\n\nfunction controlFailure(\n message: string,\n model: string | undefined,\n operation: Operation | undefined,\n cause: unknown\n): QueryError {\n return new QueryError(`${message}.`, {\n cause: errorCause(cause),\n meta: { model, operation },\n });\n}\n"],"mappings":"kPAmBA,MAAa,EAAsB,eAiCtB,EAA+C,OAAO,OAAO,CACxE,MAAO,OAAO,OAAO,CACnB,OAAQ,OAAO,OAAO,CACpB,YAAa,OAAO,OAAO,CACzB,QAAS,EACT,OAAQ,SACR,SAAW,GACT,OAAO,OAAO,CACZ,MAAO,sBAAsB,CAAC,0BAA0B,EAAM,CAC/D,CAAC,CACL,CAAC,CACH,CAAC,CACF,GAAI,SACL,CAAC,CACH,CAAC,CA4BI,EAAsB,IAAI,QAI1B,EAAqB,IAAI,QAIzB,EAAsB,IAAI,QAIhC,IAAI,EAGJ,SAAgB,2BACd,EACA,EACA,EACM,CACN,EAAU,EACV,EAAoB,IAAI,EAAO,EAAW,CAI5C,SAAgB,4BACd,EACM,CACN,EAAU,EAIZ,SAAgB,sBAA6C,CAC3D,GAAI,IAAY,IAAA,GACd,MAAU,MACR,8EACD,CACH,OAAO,EAGT,SAAgB,gCACd,EAC+C,CAC/C,OAAO,EAAW,EAAM,CAAG,EAAoB,IAAI,EAAM,CAAG,IAAA,GAS9D,SAAgB,gCACd,EAC+C,CAC/C,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAmB,IAAI,EAAM,CAIxE,SAAgB,gCACd,EACqC,CACrC,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAoB,IAAI,EAAM,CAGzE,SAAgB,2BACd,EACA,EACM,CACN,EAAmB,IAAI,EAAO,EAAW,CAI3C,SAAgB,gCACd,EACA,EACM,CACN,EAAoB,IAAI,EAAO,EAAW,CAW5C,SAAgB,uBACd,EACA,EACM,CACF,EAAmB,IAAI,EAAM,GAAK,IAAA,IACtC,sBAAsB,CAAC,UAAU,EAA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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 +1,2 @@
|
|
|
1
1
|
import{n as e}from"./chunk-BuuaeEvq.mjs";function currentTemporalValue(e){let t=new Date().toISOString();return e===`date`?t.slice(0,10):e===`time`?t.slice(11,19):t}export{currentTemporalValue as t};
|
|
2
|
-
//# sourceMappingURL=current-
|
|
2
|
+
//# sourceMappingURL=current-oXcxSCBQ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"current-
|
|
1
|
+
{"version":3,"file":"current-oXcxSCBQ.mjs","names":[],"sources":["../src/schema/scalars/datetime/current.ts"],"sourcesContent":["/** The wall-clock value shared by temporal `now` and `updatedAt` generators. */\nexport type TemporalKind = \"datetime\" | \"date\" | \"time\";\n\n/**\n * Read the host wall clock once and spell it in one temporal scalar's logical\n * input language.\n */\nexport function currentTemporalValue(kind: TemporalKind): string {\n const timestamp = new Date().toISOString();\n if (kind === \"date\") return timestamp.slice(0, 10);\n if (kind === \"time\") return timestamp.slice(11, 19);\n return timestamp;\n}\n"],"mappings":"yCAOA,SAAgB,qBAAqB,EAA4B,CAC/D,IAAM,EAAY,IAAI,MAAM,CAAC,aAAa,CAG1C,OAFI,IAAS,OAAe,EAAU,MAAM,EAAG,GAAG,CAC9C,IAAS,OAAe,EAAU,MAAM,GAAI,GAAG,CAC5C"}
|
package/dist/d1.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Schema,
|
|
1
|
+
import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
|
|
2
2
|
import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
|
|
3
3
|
|
|
4
4
|
//#region src/drivers/d1/index.d.ts
|
package/dist/d1.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-qfEejeOX.mjs";import{m as r}from"./error-mapping-C9WgitPi.mjs";import{p as i}from"./validation-BamBwne9.mjs";import{a,n as o,r as s}from"./client-6YgGlXzN.mjs";import{c,t as l}from"./driver-B9fIori_.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-D_cypcyW.mjs";import{t as p}from"./sql-statement-tokens-CFi1y3bK.mjs";import{t as m}from"./sqlite-adapter-BXAJy3mI.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,t){if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,n){return this.executeTypedStatement(e,n,async(e,n,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,n,r,i);return t(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(n).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
|
|
2
2
|
//# sourceMappingURL=d1.mjs.map
|
package/dist/d1.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });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M,KAAK,0BACT,EACA,EAAM,IACN,KAAK,6BAA6B,EAAM,CACxC,EACA,GACD,EAKL,IAAM,EAAmB,MAAM,EAAO,MAAS,EAAW,CAG1D,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,kBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,IAAM,EAA+B,EAAE,CACvC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,OAAQ,GAAS,EAAG,CACtD,IAAM,EAAQ,EAAQ,GACtB,GAAI,CAAC,EACH,MAAM,kBACJ,EACA,oDAAoD,IACrD,CAEH,EAAW,KACT,kBACE,EAAQ,GACR,EAAM,IACN,EAAM,SAAW,EACjB,GACD,CACF,CAEH,OAAO,IAQX,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,YAAa,EAIrB,OAAO,EAA6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
|
|
1
|
+
{"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`. D1 compiles\n // with an expression depth of 100 (\"Expression tree is too large\"):\n // relation filters nest as derived tables and conjunctions as balanced\n // trees (d1-permissions-verbs W-W3, W-W7). D1 refuses a statement over 100 KB: a\n // relation body a statement repeats is stated once (d1-permissions-placement\n // W-P10's update form).\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n deepExpressions: false,\n sharedRelationBodies: true,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\n}\n"],"mappings":"idAOA,MAAM,EAAe,IAAI,IAAI,CAAC,UAAW,SAAU,SAAS,CAAC,CACvD,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,UACA,SACA,QACA,SACA,SACA,SACA,OACA,MACA,UACA,UACA,WACA,YACA,SACD,CAAC,CACI,EAAwB,IAAI,IAAI,CACpC,sBACA,qBACA,eACA,2BACA,qBACA,qBACA,4BACD,CAAC,CACI,EAAyB,IAAI,IAAI,CAAC,WAAW,CA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AAG,EAAQ,EAAQ,OAAQ,GAAS,EAAG,CACtD,IAAM,EAAQ,EAAQ,GACtB,GAAI,CAAC,EACH,MAAM,kBACJ,EACA,oDAAoD,IACrD,CAEH,EAAW,KACT,kBACE,EAAQ,GACR,EAAM,IACN,EAAM,SAAW,EACjB,GACD,CACF,CAEH,OAAO,IAQX,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,YAAa,EAIrB,OAAO,EAA6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-
|
|
2
|
-
//# sourceMappingURL=datetime-physical-codec-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-DyEHMdJg.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function decodeProviderTimestamp(e){let t=c.exec(e);if(!t)return;let n=t[13]?1-Number(t[1]):Number(t[1]),o=Number(t[2]),s=Number(t[3]),l=Number(t[4]),u=Number(t[5]),d=Number(t[6]),f=Number(t[10]??0),p=Number(t[11]??0),m=Number(t[12]??0);if(!(a(n,o,s)&&r(l,u,d))||f>23||p>59||m>59)return;let h=new Date(0);h.setUTCFullYear(n,o-1,s),h.setUTCHours(l,u,d,Number((t[7]??``).padEnd(3,`0`).slice(0,3)));let g=(f*3600+p*60+m)*1e3,_=h.getTime()-(t[9]===`-`?-g:g);return i(_)?new Date(_):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
|
|
2
|
+
//# sourceMappingURL=datetime-physical-codec-BEqQbIP_.mjs.map
|
package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datetime-physical-codec-
|
|
1
|
+
{"version":3,"file":"datetime-physical-codec-BEqQbIP_.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,uBACd,EACA,EACiB,CACjB,GAAI,IAAS,OAAQ,OAAO,EAC5B,IAAM,EAAoB,KAAK,MAAM,EAAI,CACzC,OAAO,IAAS,cACZ,EACA,EAAoB,EAAuB,EAcjD,SAAgB,uBACd,EACA,EACkB,CAClB,IAAM,EAAW,eAAe,EAAM,CACtC,GAAI,IAAa,IAAA,GAAW,OAC5B,IAAM,EACJ,IAAS,cACL,EACA,KAAK,OAAO,EAAW,GAAyB,EAAqB,CACtE,KAAkB,EAAkB,CACzC,OAAO,IAAI,KAAK,EAAkB,CAGpC,MAAM,EACJ,mIAGF,SAAgB,wBAAwB,EAAiC,CACvE,IAAM,EAAQ,EAAe,KAAK,EAAM,CACxC,GAAI,CAAC,EAAO,OACZ,IAAM,EAAO,EAAM,IAAM,EAAI,OAAO,EAAM,GAAG,CAAG,OAAO,EAAM,GAAG,CAC1D,EAAQ,OAAO,EAAM,GAAG,CACxB,EAAM,OAAO,EAAM,GAAG,CACtB,EAAO,OAAO,EAAM,GAAG,CACvB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAa,OAAO,EAAM,KAAO,EAAE,CACnC,EAAe,OAAO,EAAM,KAAO,EAAE,CACrC,EAAe,OAAO,EAAM,KAAO,EAAE,CAC3C,GACE,EACE,EAAwB,EAAM,EAAO,EAAI,EACzC,EAAgB,EAAM,EAAQ,EAAO,GAEvC,EAAa,IACb,EAAe,IACf,EAAe,GAEf,OACF,IAAM,EAAS,IAAI,KAAK,EAAE,CAE1B,EAAO,eAAe,EAAM,EAAQ,EAAG,EAAI,CAC3C,EAAO,YACL,EACA,EACA,EACA,QAAQ,EAAM,IAAM,IAAI,OAAO,EAAG,IAAI,CAAC,MAAM,EAAG,EAAE,CAAC,CACpD,CACD,IAAM,GAAU,EAAa,KAAO,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{_ as r,d as i,f as a,g as o,h as s,i as c,l,n as u,p as d,r as f,t as p}from"./bind-parameter-capacity-qfEejeOX.mjs";import{S as m,b as h,i as g,m as _,n as v,s as y,t as b}from"./base-D3m1S7Uc.mjs";import{c as x,f as S,g as C,m as w,n as T,o as E,r as D,s as O,u as ee}from"./error-mapping-C9WgitPi.mjs";import{i as k,m as A,p as j,r as M}from"./validation-BamBwne9.mjs";import{n as N}from"./transaction-4dfqals6.mjs";import{r as P,t as F}from"./sql-Bhxq9arK.mjs";import{a as I,r as te,t as ne}from"./observation-Co72iCd1.mjs";import{n as L}from"./suppressed-failure-Bdo2aK81.mjs";import{a as R,c as z,o as B,t as V}from"./execution-context-rJXTRVrJ.mjs";import{t as H}from"./clock-C24RcpwO.mjs";import{t as U}from"./settle-CS_k6Ztm.mjs";function applyStatementTransforms(e,n,r,i){if(i===void 0||i.length===0)return e;let a=e;for(let e of i){let i=Object.freeze({statement:a,model:n,operation:r}),o;try{o=Reflect.apply(e.handler,void 0,[i])}catch(t){throw statementTransformFailure(e.extension,n,r,`threw`,normalizeThrown(t))}try{if(P(o)){let e=Reflect.get(o,`toStatement`);if(!t(e))throw TypeError(`Statement transform returned a Sql value without a callable toStatement method`);if(typeof Reflect.apply(e,o,[`?`])!=`string`)throw TypeError(`Statement transform returned a Sql value whose toStatement method did not return a string`);a=o;continue}}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let s;try{s=isThenable(o)}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let c=s?`returned a promise or thenable`:`returned a non-Sql value`;throw statementTransformFailure(e.extension,n,r,c,TypeError(`Statement transform ${c}`))}return a}function isThenable(e){return n(e)||t(e)?t(Reflect.get(e,`then`)):!1}function normalizeThrown(e){return m(e)?e:Error(`Statement transform threw a non-Error value`)}function normalizeUnreadableReturn(e){return m(e)?e:Error(`Statement transform returned an unreadable value`)}function statementTransformFailure(e,t,n,r,i){return new j(`Extension "${e}" statement handler for ${t===void 0?n:`${t}.${n}`} ${r}.`,{cause:i,meta:{method:`statement`,model:t,operation:n}})}var NumberedSql=class extends F{#e;#t;constructor(e,t){super([``],[]);let n=e.strings,r=[],i=new Map,a=n[0];for(let[o,s]of e.values.entries()){let e=s instanceof Date?`date:${s.getTime()}`:s===null||typeof s!=`object`&&typeof s!=`function`?`${typeof s}:${String(s)}`:s,c=i.get(e);c===void 0&&(c=r.push(s),i.set(e,c)),a+=`${t}${c}${n[o+1]}`}this.#e=a,this.#t=r}get values(){return this.#t}toStatement(){return this.#e}};const W=Symbol(`viborm.batchDiagnosticParams`),G=[];Object.freeze(G);function snapshotDiagnosticParameters(e){let t=_(e,{includeParams:!0,includeSql:!0});return Object.freeze(t),t}function findUniqueExecutionContextIndex(e,t){if(!g(e))return t.length===1?0:void 0;let n=readTrustedErrorExecutionContext(e);if(!n?.correlationId)return t.length===1?0:void 0;let r;for(let e=0;e<t.length;e+=1){let i=t[e]?.context;if(i&&i.correlationId===n.correlationId&&i.model===n.model&&i.operation===n.operation){if(r!==void 0)return;r=e}}return r}function findUniqueErrorLogDetails(e,t){if(!t)return;let n=findUniqueExecutionContextIndex(e,t);return n===void 0?void 0:t[n]}function getErrorExecutionContext(e,t){return g(e)?z(readTrustedErrorExecutionContext(e),t,t.operation):t}function readTrustedErrorExecutionContext(e){let t=b.prototype.toJSON.call(e).meta;if(n(t))return{model:typeof t.model==`string`?t.model:void 0,operation:typeof t.operation==`string`?t.operation:void 0,correlationId:typeof t.correlationId==`string`?t.correlationId:void 0}}var SavepointQueue=class{queue=[];head=0;processing=!1;enqueue(e,t){return new Promise((n,r)=>{let i=!1,a;t&&(a=setTimeout(()=>{i=!0,r(t.onMaxWaitExceeded())},t.maxWaitMs)),this.queue.push(async()=>{if(a&&clearTimeout(a),!i)try{n(await e())}catch(e){r(e)}}),this.scheduleFlush()})}run(e,t){if(this.processing)return this.enqueue(e,t);this.processing=!0;let n=e(),release=()=>this.flush();return n.then(release,release),n}scheduleFlush(){this.processing||(this.processing=!0,queueMicrotask(()=>this.flush()))}async flush(){for(;this.head<this.queue.length;){let e=this.queue[this.head++];e&&await e()}this.queue=[],this.head=0,this.processing=!1}};function readOptionOnce(e,t){try{return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}catch(e){throw new M(`The "${t}" option could not be read.`,{cause:h(e)})}}function resolveNamespaceOption(e){let t=readOptionOnce(e,`namespace`);if(t===void 0||typeof t==`string`)return t;throw new M(`The "namespace" option must be a string; received type "${typeof t}".`)}function resolveAttestationOption(e,t,n){let r=readOptionOnce(e,t);if(r!==void 0){if(r===n)return n;throw new M(`The "${t}" option admits only "${n}".`)}}function resolveMigrationNamespaceAttestationOption(e){return resolveAttestationOption(e,`migrationNamespaceAttestation`,`non-redirecting`)}function resolveMigrationSessionAttestationOption(e){return resolveAttestationOption(e,`migrationSessionAttestation`,`dedicated-session`)}function refuseEmptyDatabaseUrl(e,t,n){if(!(n||t.databaseUrl||!Object.hasOwn(t,`databaseUrl`)))throw new M(`Driver "${e}" was given an empty databaseUrl and no host; set the URL or name the host in options.`,{meta:{driver:e,operation:`configuration`}})}function systemRootAsVerifyFull(e){let t;try{t=new URL(e)}catch{return e}return t.searchParams.get(`sslrootcert`)===`system`?(t.searchParams.delete(`sslrootcert`),t.searchParams.set(`sslmode`,`verify-full`),t.href):e}function defineImmutableDriverFact(e,t,n){Object.defineProperty(e,t,{value:n,writable:!1,enumerable:!0,configurable:!1})}const K={schema:!0,skipSchemaValidation:!0};function refuseUnknownDriverConfigKeys(e,t,n,r={}){for(let i of Object.keys(e)){if(Object.hasOwn(K,i)||Object.hasOwn(n,i))continue;let e=Object.hasOwn(r,i)?r[i]:void 0,a=[...Object.keys(K),...Object.keys(n)];throw new M(`viborm/${t} does not accept "${i}"; ${e??`it accepts ${a.join(`, `)}`}.`,{meta:{driver:t,operation:`configuration`}})}}const q=Object.freeze({execute:(e,t)=>t()}),J=Object.freeze({execute:e=>e()});function createDeferredDispatch(){let e,t=new Promise(t=>{e=t}),n=!1,settleDispatch=t=>{n||(n=!0,e?.(t))},execute=(e,t)=>{let n,r,i=new Promise((e,t)=>{n=e,r=t}),a=!1,start=()=>{if(a)return;a=!0;let e;try{e=t()}catch(e){r?.(e);return}e.then(n,r)};return settleDispatch(e(start)),i};return Object.freeze({dispatch:t,execute,settleSkipped:()=>settleDispatch(void 0)})}var Y=class DriverInstrumentationBase{supportsTransactions=!0;supportsBatch=!1;supportsOrderedCommittedSegments=!1;maxBindParametersPerStatement=void 0;driverName;result;client=null;inTransaction=!1;serializeTransactions=!1;connectionQueue=new SavepointQueue;initPromise=null;closeRetryClient=null;isDisconnecting=!1;transactionPoisonError;boundContext;transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`this driver has not declared an isolation-level contract`,timeout:!1,timeoutReason:`this driver has not declared a timeout contract`,maxWait:`unsupported`,maxWaitReason:`this driver has not declared a maxWait contract`}}constructor(e,t,n={},r){defineImmutableDriverFact(this,`dialect`,e),this.driverName=t,this.boundContext=z(n),defineImmutableDriverFact(this,`migrationNamespaceAttestation`,r)}get numbersPlaceholders(){return!0}applyTrustedStatementTransforms(e,t,n){let r=(B(t)??B(this.boundContext))?.statement,i=e;if(r!==void 0&&r.length>0){let a=this.resolveExecutionContext(t,n);i=applyStatementTransforms(e,a.model,a.operation??n,r)}let a=u(this.maxBindParametersPerStatement);return a!==void 0&&i.values.length>a&&this.dialect!==`mysql`&&this.numbersPlaceholders&&(i=new NumberedSql(i,this.dialect===`postgresql`?`$`:`?`)),p(i,this.driverName,a,`operation`),i}hasTrustedObservers(e){return((B(e)??B(this.boundContext))?.observe.length??0)>0}observeTrustedStatement(e,t,n){let r=B(e)?.observe;if(r===void 0||r.length===0)return t(void 0);let i=this.createOfficialStatementExecutionGate(e);return I(r,e.operation,e.model,()=>t(i),n,i?.readFacts)}observeTrustedDriverLifecycle(e,t,n,r,i){let a=B(t)?.observe;if(a===void 0||a.length===0)return r(void 0);let o=readOfficialCapability(t),s=o?.observesLifecycle===!0&&o.wants(n)?this.createOfficialDriverLifecycleExecutionGate(t,n):void 0;return te(e,a,t.operation,()=>r(s),i,s?.readFacts)}materializeTrustedBatchQuery(e,t){let n=i(e);if(n===void 0)return e;let r=this.applyTrustedStatementTransforms(n,t,`executeBatch`);return{sql:this.buildStatement(r),params:l(r.values,t),...e.context===void 0?{}:{context:e.context}}}observeTrustedBatchStatements(e,t,n,r){let i=B(t)?.observe;if(i===void 0||i.length===0)return n(e.map(e=>this.materializeTrustedBatchQuery(e,e.context??t)),void 0);let a=this.createOfficialStatementExecutionGate(t),o=!1,s=[],startAt=c=>{for(let n=c;n<e.length;n+=1){let c=e[n];if(c===void 0)continue;let l=c.context??t,u=o?void 0:a?.readFacts;return o=!0,I(i,l.operation,l.model,()=>(s.push(this.materializeTrustedBatchQuery(c,l)),startAt(n+1)),r,u)}return n(s,a)};return startAt(0)}createOfficialStatementExecutionGate(e){let t=readOfficialCapability(e);if(t?.observesLifecycle!==!0||!(t.wants(`statement`)||t.wants(`query-log`)||t.wants(`error-log`)))return;let n=createDeferredDispatch(),r,i=Object.freeze({kind:`statement`,dispatch:n.dispatch,complete:e=>{if(r===void 0){n.settleSkipped();return}let t=e.status===`failure`&&e.failure instanceof Error?e.failure:void 0;if(e.status===`failure`&&t===void 0)return;let i=t===void 0||r.forceErrorContext?void 0:findUniqueErrorLogDetails(t,r.members),a=i?.context??(t===void 0||r.forceErrorContext?r.context:getErrorExecutionContext(t,r.context)),o=readOfficialCapability(a);if(o===void 0)return;let s=o.wants(t===void 0?`query-log`:`error-log`);if(s||t&&o.wants(`statement`))return t!==void 0&&s&&C(t),Object.freeze({kind:`statement`,endedAt:Date.now(),capability:o,...s?{}:{skipLog:!0},context:a,sql:i?.sql??r.sql,params:i?.params??r.params,...t===void 0?{}:{failure:t}})}});return Object.freeze({readFacts:()=>i,execute:(e,t)=>n.execute(t=>(r=Object.freeze({...e,driver:this,startedAt:Date.now(),start:t}),r),t)})}createOfficialDriverLifecycleExecutionGate(e,t){let n=createDeferredDispatch(),r=Object.freeze({kind:`driver-lifecycle`,dispatch:n.dispatch,complete:e=>(n.settleSkipped(),e.status===`failure`&&e.failure instanceof Error?Object.freeze({kind:`driver-lifecycle`,failure:e.failure}):void 0)});return Object.freeze({readFacts:()=>r,execute:r=>n.execute(n=>Object.freeze({driver:this,context:e,boundary:t,start:n}),r)})}buildStatement(e){switch(this.dialect){case`postgresql`:return e.toStatement(`$n`);case`sqlite`:case`mysql`:return e.toStatement(`?`);default:return e.toStatement()}}getBatchDiagnosticParameters(e){try{let t=Reflect.get(e,W);return Array.isArray(t)?t:this.getDiagnosticParameters(e.params??[],e.context)}catch{return this.getDiagnosticParameters(e.params??[],e.context)}}getDiagnosticParameters(e,t,n){return this.canDiscloseParameters(t)||n!==void 0&&n!==t&&this.canDiscloseParameters(n)?snapshotDiagnosticParameters(e):G}connectedClient(){if(!(this.getClient!==DriverInstrumentationBase.prototype.getClient||this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null))return this.client??void 0}async getClient(e={}){if(this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null)throw this.unavailableClientError(e);return this.client?this.client:await this.initializeClient(e)}unavailableClientError(e){return this.transactionPoisonError?new N(`Driver "${this.driverName}" is unavailable after transaction cleanup failed.`,{cause:this.transactionPoisonError,meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId}}):this.connectionClosedError(this.isDisconnecting?`Database connection is closing`:`Database connection cleanup is incomplete`,e)}connectionClosedError(e,t){return new k(e,{code:v.CONNECTION_CLOSED,diagnostics:this.getErrorDisclosure(t),meta:{driver:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId}})}async initializeClient(e){this.initPromise||=Promise.resolve().then(()=>this.initClient()).then(e=>(this.client=e,e));try{return await this.initPromise}catch(t){throw T(t,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:R(e),diagnostics:this.getErrorDisclosure(e)})}}normalizeStatementFailure(e,t,n,r,i){return D(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,callsite:R(r),query:t,params:n,diagnostics:this.getErrorDisclosure(r),forceContext:i})}async executeNormalizedStatement(e,t,n,r,i){try{return await r()}catch(r){throw this.normalizeStatementFailure(r,e,t,n,i)}}resolveExecutionContext(e,t){return z(e,this.boundContext,t)}canDiscloseParameters(e){let t=readOfficialCapability(e);return t!==void 0&&(t.diagnostics.includeParams===!0||t.wants(`parameters`))}getErrorDisclosure(e){return readOfficialCapability(e)?.diagnostics??y}};function readOfficialCapability(e){return ne(B(e))}const X=[`ReadUncommitted`,`ReadCommitted`,`RepeatableRead`,`Serializable`],methodForForm=e=>e===`batch`?`$transaction([...])`:`$transaction(callback)`;function invalidTransactionOptions(e,t){return new N(e,{code:v.INVALID_TRANSACTION_INPUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function refuseTransactionOption(e,t,n){return new A(`Driver "${n.driverName}" cannot honor the "${e}" transaction option on ${methodForForm(n.form)}: ${t}`,{meta:{driver:n.driverName,method:methodForForm(n.form)}})}function transactionTimeoutError(e,t){return new N(`Transaction on driver "${t.driverName}" exceeded its timeout of ${e}ms and was rolled back.`,{code:v.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function transactionMaxWaitError(e,t){return new N(`Transaction on driver "${t.driverName}" waited longer than maxWait (${e}ms) for a transaction slot and never started.`,{code:v.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}const isIsolationLevel=e=>X.includes(e);function readDurationOption(e,t,n){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw invalidTransactionOptions(`Transaction option "${t}" must be a positive finite number of milliseconds.`,n);return e}function parseTransactionOptions(e,t){if(e===void 0)return;if(!n(e))throw invalidTransactionOptions(`Transaction options must be an object.`,t);let r=t.form===`batch`?[`isolationLevel`]:[`isolationLevel`,`timeout`,`maxWait`];for(let n of Reflect.ownKeys(e))if(!(typeof n==`string`&&r.includes(n)))throw t.form===`batch`&&(n===`timeout`||n===`maxWait`)?invalidTransactionOptions(`Transaction option "${n}" is not available on $transaction([...]): an array of operations has no interactive window to bound. Use the callback form.`,t):invalidTransactionOptions(`Unknown transaction option "${String(n)}". Supported options are ${r.map(e=>`"${e}"`).join(`, `)}.`,t);let i={};if(e.isolationLevel!==void 0){if(!isIsolationLevel(e.isolationLevel))throw invalidTransactionOptions(`Unknown isolation level ${JSON.stringify(e.isolationLevel)}. Supported levels are ${X.map(e=>`"${e}"`).join(`, `)}.`,t);i.isolationLevel=e.isolationLevel}return e.timeout!==void 0&&(i.timeout=readDurationOption(e.timeout,`timeout`,t)),e.maxWait!==void 0&&(i.maxWait=readDurationOption(e.maxWait,`maxWait`,t)),i}const re={ReadUncommitted:`READ UNCOMMITTED`,ReadCommitted:`READ COMMITTED`,RepeatableRead:`REPEATABLE READ`,Serializable:`SERIALIZABLE`};function isolationLevelStatement(e){return`SET TRANSACTION ISOLATION LEVEL ${re[e]}`}function resolveIsolationLevel(e,t,n){switch(t.isolationLevel){case`provider`:return{placement:`provider`};case`post-begin`:case`pre-begin`:return{placement:t.isolationLevel,statement:isolationLevelStatement(e)};case`serializable-only`:if(e===`Serializable`)return{placement:`serializable-only`};throw refuseTransactionOption(`isolationLevel`,`${e} is not available — ${t.isolationLevelReason??`this driver offers Serializable only`}.`,n);default:throw refuseTransactionOption(`isolationLevel`,t.isolationLevelReason??`this driver does not open a transaction that can be configured`,n)}}function resolveTransactionPlan(e,t,n){if(!e||e.isolationLevel===void 0&&e.timeout===void 0&&e.maxWait===void 0)return;let r=`unsupported`,i;if(e.isolationLevel!==void 0){let a=resolveIsolationLevel(e.isolationLevel,t,n);r=a.placement,i=a.statement}if(e.timeout!==void 0&&!t.timeout)throw refuseTransactionOption(`timeout`,t.timeoutReason??`this driver does not run an interactive callback that could be interrupted`,n);if(e.maxWait!==void 0&&t.maxWait===`unsupported`)throw refuseTransactionOption(`maxWait`,t.maxWaitReason??`this driver has no transaction-slot wait that VibORM can bound`,n);let a={};return r===`pre-begin`&&e.isolationLevel!==void 0&&(a.isolationLevel=e.isolationLevel),t.maxWait===`acquisition`&&e.maxWait!==void 0&&(a.maxWaitMs=e.maxWait),{...e.isolationLevel===void 0?{}:{isolationLevel:e.isolationLevel},...i===void 0?{}:{isolationStatement:i},isolationPlacement:r,...e.timeout===void 0?{}:{timeoutMs:e.timeout},...e.maxWait===void 0?{}:{maxWaitMs:e.maxWait},maxWaitMode:t.maxWait,...Object.keys(a).length===0?{}:{driverOptions:a}}}async function runWithTransactionTimeout(e,t,n,r=H){return U(e(),t,()=>transactionTimeoutError(t,n),void 0,r)}async function acquireWithMaxWait(e,t,n,r,i=H){let a=e();return n===void 0?a:U(a,n,()=>transactionMaxWaitError(n,r),e=>{try{t(e)}catch{}},i)}const Z=new WeakMap;let Q,$;function physicalConnectionQueue(e){let t=Z.get(e);return t||(t=new SavepointQueue,Z.set(e,t)),t}function isConnectionScope(e){let t=Q?.getStore();return t!==void 0&&t.queue===e&&t.active}function connectionQueueWait(e,t){let n=e??(Q===null?5e3:void 0);return n===void 0?void 0:{maxWaitMs:n,onMaxWaitExceeded:()=>transactionMaxWaitError(n,t)}}async function withConnectionScope(e,t){if($??=import(`node:async_hooks`).then(({AsyncLocalStorage:e})=>{Q=new e}).catch(()=>{Q=null}),await $,Q===null)return t();if(!Q)throw Error(`Connection scope failed to initialize`);let n={queue:e,active:!0};return Q.run(n,async()=>{try{return await t()}finally{n.active=!1}})}function prepareAtomicBatch(e,t,n,r){let i=[],a=e.map(e=>{let r=e.params,a=z(e.context,t,`executeBatch`),c=r?l(r,a):void 0;c&&Object.freeze(c);let u={sql:e.sql,...c?{params:c}:{},context:a};s(e)&&(u=o(u)),d(e,u,c??[]);let f=n(c??[],a);return i.push(f),Object.defineProperty(u,W,{configurable:!1,enumerable:!1,value:f,writable:!1}),Object.freeze(u)}),c=a.map((e,n)=>({context:e.context??t,params:i[n]??G,sql:e.sql})),u=r?i:G;return r&&Object.freeze(u),{queries:a,diagnosticParams:u,members:c}}function toTransactionOperationError(e){return e instanceof Error?e:new N(`Transaction operation failed`,{cause:Error(`A transaction operation rejected without an Error`)})}function normalizeTransactionLifecycleError(e,t){try{if(!(e instanceof AggregateError))return t(e);let n=e.cause;return e.errors[0]===n?x(t(n),e.errors.slice(1).map(e=>t(e))):t(e)}catch{return t(e)}}function withoutTimeout(e){if(!e)return e;let{timeout:t,...n}=e;return n}var DriverTransactionBase=class extends Y{runTransactionBody(e){return e()}assertBaseOperationAllowedDuringTransaction(e){if(isConnectionScope(this.connectionQueue))throw this.transactionBoundError(e)}transactionBoundError(e){return new N(`Driver "${this.driverName}" cannot use the originating client while its single connection is transaction-bound. Use the transaction client supplied to the callback.`,{meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,method:`$transaction(callback)`}})}async runConnectionTransactionLease(e){return withConnectionScope(this.connectionQueue,e)}resolveTransactionOptions(e,t){let n={driverName:this.driverName,form:t};return resolveTransactionPlan(parseTransactionOptions(e,n),this.transactionOptionSupport(),n)}assertTransactionOptionsSupported(e,t){this.resolveTransactionOptions(e,t)}readPostBeginIsolationStatement(e){if(e?.isolationPlacement===`post-begin`)return e.isolationStatement}_execute(e,t){return this.executeTypedStatement(e,t,this.executeNormalizedProvider)}async executeNormalizedProvider(e,t,n,r,i=!1){let a=i?await this.executeRaw(e,t,n,r):await this.execute(e,t,n,r);return c(a,{provider:this.driverName,operation:r.operation??(i?`executeRaw`:`execute`)}),a}async executeTypedStatement(e,t,n){let r=this.resolveExecutionContext(t,`execute`),i=this.hasTrustedObservers(r),a=i?void 0:this.applyTrustedStatementTransforms(e,r,`execute`);return this.dispatchStatement(r,i,t=>{try{return a??=this.applyTrustedStatementTransforms(e,r,`execute`),this.sendStatement(this.buildStatement(a),a.values,r,n,t)}catch(e){return Promise.reject(e)}})}dispatchStatement(e,t,n){let r=t?()=>this.observeTrustedStatement(e,n):n;return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(e),this.connectionQueue.run(r,connectionQueueWait(void 0,{driverName:this.driverName,form:`callback`}))):r()}async sendStatement(e,t,n,r,i=q){let a=l(t,n),o=this.getDiagnosticParameters(a,n),s=this.connectedClient()??await this.getClient(n);return i.execute({context:n,forceErrorContext:!0,params:o,sql:e},()=>this.executeNormalizedStatement(e,o,n,()=>r.call(this,s,e,a,n),!0))}_prepare(e,t){let n=new F([...e.strings],[...e.values]),r={sql:this.buildStatement(n),params:[...n.values]};return a(r,n),r}async _executeRaw(e,t,n){let r=this.resolveExecutionContext(n,`executeRaw`);return this.dispatchStatement(r,this.hasTrustedObservers(r),n=>this.sendStatement(e,t??[],r,(e,t,n)=>this.executeNormalizedProvider(e,t,n,r,!0),n))}runProviderTransactionCore(e,t,n,r=J){let i=Symbol(`noCallbackFailure`),a=i,o=t?.timeoutMs===void 0?e:n=>runWithTransactionTimeout(()=>e(n),t.timeoutMs,{driverName:this.driverName,form:`callback`}),trackedCallback=async e=>{try{return await o(e)}catch(e){throw a=e,e}},s=this.readPostBeginIsolationStatement(t),providerCallback=async e=>(s&&await this.executeRaw(e,s,void 0,{...n,operation:`transaction`}),trackedCallback(e)),runTransaction=async()=>{let e=await this.getClient(n);try{return await this.transaction(e,providerCallback,n,t?.driverOptions)}catch(e){let normalizeTransactionFailure=e=>D(e,{driverName:this.driverName,dialect:this.dialect,model:n.model,operation:n.operation,correlationId:n.correlationId,diagnostics:this.getErrorDisclosure(n)});if(a!==i){if(e===a)throw e;let t=ee(e,a).map(normalizeTransactionFailure),n=x(a,t);throw this.transactionCleanupFailed(n),n}let t=normalizeTransactionLifecycleError(e,normalizeTransactionFailure);throw(this.inTransaction||e instanceof O||e instanceof AggregateError&&e.errors[0]===e.cause&&e.errors.length>1)&&this.transactionCleanupFailed(t),t}};return r.execute(runTransaction)}observeTransactionLifecycle(e,t,n){let r=e===`transaction`?{phase:`pending`}:void 0,i=r?V(t,{readyToCommit:()=>{r.phase=`ready`},committed:()=>{r.phase=`committed`}}):t;return this.observeTrustedDriverLifecycle(e,t,e,async e=>{let t=await n(i,e);return r&&(r.phase=`committed`),t},r===void 0?void 0:()=>r.phase===`pending`?void 0:{commitCertainty:r.phase===`committed`?`committed`:`may-have-committed`})}async _transaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`);if(!this.supportsTransactions)throw w(this.driverName);let i=this.resolveExecutionContext(n,`transaction`),a=this.serializeTransactions&&!this.inTransaction;a&&this.assertBaseOperationAllowedDuringTransaction(i);let o=connectionQueueWait(r?.maxWaitMode===`queue`?r.maxWaitMs:void 0,{driverName:this.driverName,form:`callback`}),executeTransaction=(t,n)=>{let run=()=>this.runProviderTransactionCore(e,r,t,n);return a?this.connectionQueue.enqueue(()=>this.runConnectionTransactionLease(run),o):run()};return this.hasTrustedObservers(i)?this.observeTransactionLifecycle(`transaction`,i,executeTransaction):executeTransaction(i)}async withTransaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`),i=this.resolveExecutionContext(n,`transaction`),a=r?.timeoutMs,o=a===void 0?t:withoutTimeout(t),s;return this._transaction(async t=>{s=this.createTransactionBoundDriver(t,i);let n=s,scopedBody=()=>this.runTransactionBody(()=>e(n)),runBody=()=>a===void 0?scopedBody():runWithTransactionTimeout(scopedBody,a,{driverName:this.driverName,form:`callback`});try{let e=await runBody();return s.closeTransactionScope(),await s.waitForActiveOperations(),s.assertTransactionCommittable(),e}catch(e){s.closeTransactionScope(e),await s.waitForActiveOperations();let t=s.getTransactionFailure();throw t&&t!==e?L(e,t):e}},o,i)}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=[];try{for(let[n,r]of t.entries()){if(!r)continue;let t=r.context?this.resolveExecutionContext(r.context,r.context.operation??`executeBatch`):a,i=r,c=this.getBatchDiagnosticParameters(r),normalizeFailure=e=>D(e,{driverName:this.driverName,dialect:this.dialect,model:t.model,operation:t.operation,correlationId:t.correlationId,statementIndex:n,query:i.sql,params:c,diagnostics:this.getErrorDisclosure(t),forceContext:!0});o.push(await new Promise((n,a)=>{let o,l,u=new Promise((e,t)=>{o=e,l=t}),d=this.observeTrustedStatement(t,(a=q)=>{i=this.materializeTrustedBatchQuery(r,t),c=this.getBatchDiagnosticParameters(i);let{sql:f,params:p}=i,m=s(i);return n({execute:async()=>{try{o(await a.execute({context:t,forceErrorContext:!0,params:c,sql:f},()=>this.executeNormalizedStatement(f,c,t,()=>m?this.executeRaw(e,f,p,t):this.execute(e,f,p??[],t),!0)))}catch(e){l(normalizeFailure(e))}return d},cancel:e=>(l(e),d)}),u});d.catch(a)}).catch(e=>{throw normalizeFailure(e)}))}let n=[];for(let e of o)n.push(await e.execute());return n}catch(e){throw await Promise.allSettled(o.map(t=>t.cancel(e))),e}}async _executeBatch(e,t,n,r){if(this.resolveTransactionOptions(t,`batch`),e.length===0)return[];if(!(this.supportsBatch||this.supportsTransactions))throw new N(`Driver "${this.driverName}" supports neither transactions nor atomic batch execution.`,{meta:{driver:this.driverName,method:`$transaction([...])`}});let i=this.resolveExecutionContext(n,`executeBatch`),a={provider:this.driverName,operation:i.operation??`executeBatch`};if(this.supportsBatch){if(r&&!this.supportsOrderedCommittedSegments)throw new N(`Driver '${this.driverName}' cannot acknowledge ordered committed segments.`);let executeNativeBatch=async(n=e,o=q)=>{let{queries:s,diagnosticParams:c,members:l}=prepareAtomicBatch(n,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),u=s.map(e=>e.sql).join(`; `),d=await this.getClient(i),executeProvider=async()=>{try{let e=await this.executeBatch(d,s,i,r,t);return f(e,s.length,a),e}catch(e){let t=findUniqueExecutionContextIndex(e,s),n=t===void 0?void 0:s[t],r=n?.context??i;throw D(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,statementIndex:n?t:void 0,query:n?n.sql:u,params:n?this.getBatchDiagnosticParameters(n):c,diagnostics:this.getErrorDisclosure(r),forceContext:!0})}};return o.execute({context:i,forceErrorContext:!1,members:l,params:c,sql:u},()=>this.executeNormalizedStatement(u,c,i,executeProvider,!1))},submitNativeBatch=()=>this.observeTrustedBatchStatements(e,i,executeNativeBatch);return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(i),this.connectionQueue.enqueue(submitNativeBatch,connectionQueueWait(void 0,{driverName:this.driverName,form:`batch`}))):submitNativeBatch()}let{queries:o}=prepareAtomicBatch(e,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),runSequentialBatch=async e=>{let t=await this.executeBatch(e,o,i);return f(t,o.length,a),t};return this.inTransaction?runSequentialBatch(await this.getClient(i)):this._transaction(runSequentialBatch,t,i)}transactionCleanupFailed(e){this.transactionPoisonError??=e}};function observePromiseRejection(e,t){return new ie(e,t)}var ie=class RejectionObservedPromise{[Symbol.toStringTag]=`Promise`;onRejectionObserved;promise;constructor(e,t){this.promise=e,this.onRejectionObserved=t}then(e,t){return t&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.then(e,t),this.onRejectionObserved)}catch(e){return e&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.catch(e),this.onRejectionObserved)}finally(e){return new RejectionObservedPromise(this.promise.finally(e),this.onRejectionObserved)}};const ae=Object.freeze({foreignKeys:`pragma`,reservedTablePrefixes:`none`,exclusion:`database-write-lock`});var Driver=class extends DriverTransactionBase{createTransactionBoundDriver(e,t){return new oe(this,e,t)}_connect(e){return this.runConnectionLifecycle(`connect`,e,(e,t)=>t.execute(async()=>{await this.getClient(e)}))}_disconnect(e){return this.runConnectionLifecycle(`disconnect`,e,async(e,t)=>{if(this.isDisconnecting)throw this.connectionClosedError(`Database connection is closing`,e);this.isDisconnecting=!0;let doDisconnect=async()=>{if(this.initPromise)try{await this.initPromise}catch{}let t=this.closeRetryClient??this.client;if(!t){this.transactionPoisonError=void 0;return}try{await this.closeClient(t)}catch(n){throw this.closeRetryClient=t,this.client===t&&(this.client=null),this.initPromise=null,T(n,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,diagnostics:this.getErrorDisclosure(e)},`Database disconnection failed`)}},n=t.execute(doDisconnect);try{await n,this.client=null,this.initPromise=null,this.closeRetryClient=null,this.transactionPoisonError=void 0}finally{this.isDisconnecting=!1}})}async runConnectionLifecycle(e,t,n){let r=this.resolveExecutionContext(t,e),run=(e=J)=>n(r,e),i=this.serializeTransactions&&!this.inTransaction;return i&&this.assertBaseOperationAllowedDuringTransaction(r),this.hasTrustedObservers(r)?this.observeTrustedDriverLifecycle(`connection`,r,e,i?e=>this.connectionQueue.enqueue(()=>run(e)):run):i?this.connectionQueue.enqueue(run):run()}async disconnect(){return this._disconnect()}};function disposeDriver(){return this.disconnect()}r!==void 0&&Object.defineProperty(Driver.prototype,r,{configurable:!0,writable:!0,enumerable:!1,value:disposeDriver});var oe=class TransactionBoundDriver extends Driver{baseDriver;parentTransactionDriver;tx;scopeQueue=new SavepointQueue;activeOperations=new Set;nestedTransactionObservations=new Set;transactionClosed=!1;signalScopeClosed;scopeClosed;isSavepointActive=!1;hasAdmittedWithTransactionDispatch=!1;rollbackOnlyError;result;inTransaction=!0;supportsTransactions;supportsBatch;supportsOrderedCommittedSegments;maxBindParametersPerStatement;constructor(e,t,n){super(e.dialect,e.driverName,n,e.migrationNamespaceAttestation);let resolveClosed=()=>void 0;this.scopeClosed=new Promise(e=>{resolveClosed=e}),this.signalScopeClosed=resolveClosed,this.baseDriver=e,this.parentTransactionDriver=e instanceof TransactionBoundDriver?e:void 0,this.tx=t,defineImmutableDriverFact(this,`adapter`,e.adapter),this.result=e.result,this.supportsTransactions=e.supportsTransactions,this.supportsBatch=e.supportsBatch,this.supportsOrderedCommittedSegments=e.supportsOrderedCommittedSegments,this.maxBindParametersPerStatement=e.maxBindParametersPerStatement}async getClient(e){return this.tx}closeTransactionScope(...e){this.transactionClosed=!0,e.length>0&&this.signalScopeClosed(e[0]);for(let e of this.nestedTransactionObservations)e.failure&&!e.isRejectionObserved&&this.markCurrentScopeRollbackOnly(e.failure)}runTransactionBody(e){return Promise.race([e(),this.scopeClosed.then(e=>{throw e})])}async waitForActiveOperations(){for(;this.activeOperations.size>0;)await Promise.allSettled([...this.activeOperations])}getTransactionFailure(){return this.parentTransactionDriver?.getTransactionFailure()??this.rollbackOnlyError}assertTransactionCommittable(){if(this.parentTransactionDriver?.assertTransactionCommittable(),this.rollbackOnlyError)throw this.rollbackOnlyError}markCurrentScopeRollbackOnly(e){this.rollbackOnlyError??=e}markRootTransactionRollbackOnly(e){if(this.parentTransactionDriver){this.parentTransactionDriver.markRootTransactionRollbackOnly(e);return}this.rollbackOnlyError??=e}assertRollbackOnlyUsable(){let e=this.getTransactionFailure();if(e)throw L(E(e,new N(`Transaction for driver "${this.driverName}" is rollback-only after an earlier failure; no further statements can execute.`,{cause:e,meta:{driver:this.driverName,method:`$transaction`}})),e)}assertTransactionOpen(){if(this.parentTransactionDriver?.assertTransactionOpen(),this.assertRollbackOnlyUsable(),this.transactionClosed)throw new N(`Transaction for driver "${this.driverName}" is no longer active.`,{meta:{driver:this.driverName,method:`$transaction`}})}getActiveSavepointUseError(e){if(this.isSavepointActive)return new N(`Transaction scope for driver "${this.driverName}" cannot be used while its nested transaction is active. At every nesting level, use the transaction client supplied to that callback.`,{meta:{driver:this.driverName,method:e}})}enqueueScopeOperation(e){return this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable();try{return await e()}catch(e){throw this.markCurrentScopeRollbackOnly(toTransactionOperationError(e)),e}})}trackTransactionOperation(e,t){let n=t?void 0:{isRejectionObserved:!1};n&&this.nestedTransactionObservations.add(n);let r=Promise.resolve().then(()=>(this.assertTransactionOpen(),e()));return this.activeOperations.add(r),r.then(()=>{this.activeOperations.delete(r)},e=>{this.activeOperations.delete(r);let t=toTransactionOperationError(e);if(n){n.failure=t,this.transactionClosed&&!n.isRejectionObserved&&this.markCurrentScopeRollbackOnly(t);return}this.markCurrentScopeRollbackOnly(t)}).catch(()=>void 0),n?observePromiseRejection(r,()=>{n.isRejectionObserved=!0}):r}scoped(e,t){let n=this.getActiveSavepointUseError(e);return n?Promise.reject(n):this.trackTransactionOperation(()=>this.enqueueScopeOperation(t),!0)}_execute(e,t){return this.scoped(`execute`,()=>super._execute(e,t))}_executeRaw(e,t,n){return this.scoped(`executeRaw`,()=>super._executeRaw(e,t,n))}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`a nested transaction runs as a SAVEPOINT inside the outer transaction, whose isolation level is already fixed and cannot be changed mid-transaction — set it on the outermost $transaction`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`a nested transaction reuses the outer transaction's connection, so there is no transaction slot to wait for`}}resolveNestedOptions(e,t){try{return this.resolveTransactionOptions(e,t)}catch(e){return toTransactionOperationError(e)}}_executeBatch(e,t,n,r){let i=this.resolveNestedOptions(t,`batch`);return i instanceof Error?Promise.reject(i):e.length===0?Promise.resolve([]):this.scoped(`$transaction([...])`,()=>super._executeBatch(e,t,n,r))}_transaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.hasAdmittedWithTransactionDispatch;if(!i){let e=this.getActiveSavepointUseError(`$transaction(callback)`);if(e)return Promise.reject(e);try{this.assertTransactionOpen()}catch(e){return Promise.reject(e)}}let a=this.resolveExecutionContext(n,`transaction`),o=this.hasTrustedObservers(a),executeTransaction=(t=J)=>this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable(),this.isSavepointActive=!0;try{return await this.runProviderTransactionCore(e,r,a,t)}finally{this.isSavepointActive=!1}}),s=o?()=>this.observeTransactionLifecycle(`savepoint`,a,(e,t)=>executeTransaction(t)):void 0;return i?s?s():executeTransaction():this.trackTransactionOperation(s??executeTransaction,!1)}withTransaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.getActiveSavepointUseError(`$transaction(callback)`);return i?Promise.reject(i):this.trackTransactionOperation(()=>{this.hasAdmittedWithTransactionDispatch=!0;try{return super.withTransaction(e,t,n)}finally{this.hasAdmittedWithTransactionDispatch=!1}},!1)}initClient(){throw Error(`TransactionBoundDriver does not initialize clients`)}closeClient(){return Promise.resolve()}execute(e,t,n,r){return this.baseDriver.execute(e,t,n,r)}executeRaw(e,t,n,r){return this.baseDriver.executeRaw(e,t,n,r)}async transaction(e,t,n){return this.assertTransactionCommittable(),S(e=>this.baseDriver.executeRaw(this.tx,e,void 0,n??{}),()=>t(this.tx))}transactionCleanupFailed(e){this.markRootTransactionRollbackOnly(e)}async disconnect(){}};export{isolationLevelStatement as a,refuseUnknownDriverConfigKeys as c,resolveNamespaceOption as d,systemRootAsVerifyFull as f,acquireWithMaxWait as i,resolveMigrationNamespaceAttestationOption as l,ae as n,defineImmutableDriverFact as o,physicalConnectionQueue as r,refuseEmptyDatabaseUrl as s,Driver as t,resolveMigrationSessionAttestationOption as u};
|
|
2
|
+
//# sourceMappingURL=driver-B9fIori_.mjs.map
|