viborm 1.16.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
- package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
- package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
- package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
- package/dist/adapters.d.mts +50 -94
- package/dist/adapters.mjs +1 -1
- package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
- package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
- package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
- package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
- package/dist/auto-names-GpcDfhaw.mjs +2 -0
- package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
- package/dist/batch-refs-BuICt2tu.mjs +2 -0
- package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
- package/dist/better-auth.d.mts +1 -1
- package/dist/better-auth.mjs +2 -2
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/call-D2E7dPCd.mjs +2 -0
- package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-Cq_VcF43.d.mts +183 -0
- package/dist/client-DkNRAOuH.mjs +2 -0
- package/dist/client-DkNRAOuH.mjs.map +1 -0
- package/dist/{planner-C-zjj19U.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
- package/dist/client-rIiFOn1W.mjs +9 -0
- package/dist/client-rIiFOn1W.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
- package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
- package/dist/{object-store-C4qmW7xf.d.mts → conformance-C1JveA8y.d.mts} +5 -60
- package/dist/conformance-C4JYA0JG.mjs +2 -0
- package/dist/conformance-C4JYA0JG.mjs.map +1 -0
- package/dist/contract-BBone8RD.mjs +2 -0
- package/dist/contract-BBone8RD.mjs.map +1 -0
- package/dist/coordination-BxMskOgi.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{database-adapter-BMjJiBFm.d.mts → database-adapter-cW0nmWM6.d.mts} +1 -1
- package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
- package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
- package/dist/datetime-values-D_G6m5_o.mjs +2 -0
- package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
- package/dist/decimal-D4DRlT2y.mjs +2 -0
- package/dist/decimal-D4DRlT2y.mjs.map +1 -0
- package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
- package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
- package/dist/{document-CHaVF7Vn.d.mts → document-B8ClXlb7.d.mts} +1 -1
- package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
- package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
- package/dist/{driver-BvTixv-m.d.mts → driver-KgGMnfz8.d.mts} +1 -1
- package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
- package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
- package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
- package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/error-mapping-B9rSvgG9.mjs +1 -1
- package/dist/every-tAZuZ50K.mjs +2 -0
- package/dist/{every-JpbiHdMb.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +1 -1
- package/dist/{exports-DYnTfvQo.d.mts → exports-reE3GioL.d.mts} +1 -1
- package/dist/extension-Bf4vO5mp.mjs +2 -0
- package/dist/extension-Bf4vO5mp.mjs.map +1 -0
- package/dist/facts-Bjnzv3j-.mjs +2 -0
- package/dist/facts-Bjnzv3j-.mjs.map +1 -0
- package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
- package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
- package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
- package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
- package/dist/geo-point-DCV0eO1p.mjs +2 -0
- package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
- package/dist/id-domain-Cj6MnMxg.mjs +2 -0
- package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
- package/dist/identifier-BdLx66pi.mjs +2 -0
- package/dist/identifier-BdLx66pi.mjs.map +1 -0
- package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
- package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
- package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
- package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
- package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
- package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
- package/dist/index.d.mts +2 -2
- 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/introspect-dyBpdr2L.mjs +2 -0
- package/dist/{introspect-q3Rf_Xv8.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
- package/dist/json-DvvrTWUw.mjs +2 -0
- package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
- package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
- package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
- package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
- package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
- package/dist/judge-words-CqNdnbou.mjs +2 -0
- package/dist/judge-words-CqNdnbou.mjs.map +1 -0
- package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
- package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
- package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
- package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
- package/dist/keys-o4Pl6Vsg.mjs +2 -0
- package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
- package/dist/libsql-C0iMZifz.mjs +3 -0
- package/dist/libsql-C0iMZifz.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/light-reLULeHN.mjs +2 -0
- package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
- package/dist/memory-DtTuFo-h.mjs +2 -0
- package/dist/memory-DtTuFo-h.mjs.map +1 -0
- package/dist/methods-part-Dsi0DBNU.mjs +2 -0
- package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
- package/dist/migrations/mysql/runtime.d.mts +7 -0
- package/dist/migrations/mysql/runtime.mjs +2 -0
- package/dist/migrations/mysql/runtime.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +7 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/mysql.mjs.map +1 -1
- package/dist/migrations/postgres/runtime.d.mts +7 -0
- package/dist/migrations/postgres/runtime.mjs +2 -0
- package/dist/migrations/postgres/runtime.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +7 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/postgres.mjs.map +1 -1
- package/dist/migrations/snowflake.d.mts +7 -5
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/snowflake.mjs.map +1 -1
- package/dist/migrations/sqlite/runtime.d.mts +7 -0
- package/dist/migrations/sqlite/runtime.mjs +2 -0
- package/dist/migrations/sqlite/runtime.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +7 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/sqlite.mjs.map +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/surrealdb.d.mts +7 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/surrealdb.mjs.map +1 -1
- package/dist/migrations/tenant.d.mts +4 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations.d.mts +7 -5
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/model-ByktcCGW.mjs +2 -0
- package/dist/model-ByktcCGW.mjs.map +1 -0
- package/dist/mysql-DPYi1p_g.mjs +4 -0
- package/dist/mysql-DPYi1p_g.mjs.map +1 -0
- package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
- package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
- package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
- package/dist/native-types-BUkcVedc.mjs +2 -0
- package/dist/native-types-BUkcVedc.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +1 -1
- package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
- package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
- package/dist/object-store-j4kgh61D.d.mts +59 -0
- package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
- package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/ordering.mjs +2 -2
- package/dist/pending-operation-B5o-zhES.mjs +2 -0
- package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +2 -2
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
- package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
- package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
- package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/postgres-CEGFOi8D.mjs +27 -0
- package/dist/postgres-CEGFOi8D.mjs.map +1 -0
- package/dist/postgres-adapter-B-im38AE.mjs +2 -0
- package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
- package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
- package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
- package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
- package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
- package/dist/postgres.d.mts +2 -2
- package/dist/postgres.mjs +1 -1
- package/dist/provider-limits-DvcCUw7l.mjs +2 -0
- package/dist/provider-limits-DvcCUw7l.mjs.map +1 -0
- package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
- package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
- package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
- package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
- package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
- package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
- package/dist/query-DSEMPA7r.mjs +2 -0
- package/dist/query-DSEMPA7r.mjs.map +1 -0
- package/dist/query-backend-CzwVfrQ6.mjs +2 -0
- package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
- package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
- package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
- package/dist/raw-B8cNef_V.mjs +2 -0
- package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
- package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
- package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
- package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
- package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
- package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
- package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
- package/dist/rule-words-ojG0-vSf.mjs +2 -0
- package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
- package/dist/runtime-BAqlANG_.mjs +10 -0
- package/dist/runtime-BAqlANG_.mjs.map +1 -0
- package/dist/runtime-D0oaIS1E.mjs +2 -0
- package/dist/runtime-D0oaIS1E.mjs.map +1 -0
- package/dist/runtime-Dfkv59_p.mjs +15 -0
- package/dist/runtime-Dfkv59_p.mjs.map +1 -0
- package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
- package/dist/runtime-client-xeiXA_1m.mjs +2 -0
- package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
- package/dist/scalar-BTYxpiP_.mjs +4 -0
- package/dist/scalar-BTYxpiP_.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-BzkBJTF-.mjs +2 -0
- package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
- package/dist/schema-D7MyYTjA.mjs +2 -0
- package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
- package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
- package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
- package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
- package/dist/serializer-CIhcZMxs.mjs +7 -0
- package/dist/serializer-CIhcZMxs.mjs.map +1 -0
- package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
- package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
- package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
- package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
- package/dist/snowflake-C1dqbche.mjs +2 -0
- package/dist/{snowflake-BfF8xwfP.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
- package/dist/snowflake.d.mts +2 -2
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
- package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
- package/dist/sql-AHN2niBz.mjs +2 -0
- package/dist/{sql-Bu63iAfT.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
- package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
- package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
- package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
- package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
- package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
- package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
- package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
- package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
- package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
- package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
- package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
- package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-AyDLKSEQ.mjs +2 -0
- package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
- package/dist/time-step-BIdl2Iy7.mjs +2 -0
- package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
- package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
- package/dist/type-mapping-BYre7JQ1.mjs +3 -0
- package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
- package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
- package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
- package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
- package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
- package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
- package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
- package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
- package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
- package/dist/utils-DYrxwV_M.mjs +2 -0
- package/dist/utils-DYrxwV_M.mjs.map +1 -0
- package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
- package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
- package/dist/validation-CEnhYqhl.mjs +2 -0
- package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-CISkL46K.mjs +2 -0
- package/dist/validator-CISkL46K.mjs.map +1 -0
- package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
- package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
- package/dist/{client-Dlz3-2JC.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
- package/dist/version-nEOMCWfV.mjs +2 -0
- package/dist/{version-0BDwfy7C.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
- package/dist/view-CmLQ0I6x.mjs +2 -0
- package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
- package/dist/write-sinks-BhwgQn_5.mjs +2 -0
- package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
- package/package.json +27 -2
- package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
- package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
- package/dist/call-0bd_B9Vp.mjs +0 -2
- package/dist/client-D7sWgUt2.mjs +0 -2
- package/dist/client-D7sWgUt2.mjs.map +0 -1
- package/dist/client-DEfFqv4S.mjs +0 -9
- package/dist/client-DEfFqv4S.mjs.map +0 -1
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
- package/dist/every-JpbiHdMb.mjs +0 -2
- package/dist/extension-Dh1ddrlA.mjs +0 -2
- package/dist/extension-Dh1ddrlA.mjs.map +0 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
- package/dist/id-domain-Cg65TLZ-.mjs +0 -2
- package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
- package/dist/introspect-q3Rf_Xv8.mjs +0 -2
- package/dist/json-CsAdz9pg.mjs +0 -2
- package/dist/judge-words-k5GCc4cV.mjs +0 -2
- package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
- package/dist/keys-DZdKAd4n.mjs +0 -2
- package/dist/libsql-DEZ0uhK2.mjs +0 -3
- package/dist/libsql-DEZ0uhK2.mjs.map +0 -1
- package/dist/light-D2wNSbzY.mjs +0 -2
- package/dist/memory-BaGWNdvk.mjs +0 -2
- package/dist/memory-BaGWNdvk.mjs.map +0 -1
- package/dist/methods-part-BaNx3o7b.mjs +0 -2
- package/dist/model-Dtd37Sky.mjs +0 -2
- package/dist/model-Dtd37Sky.mjs.map +0 -1
- package/dist/mysql-BFPF8xyv.mjs +0 -9
- package/dist/mysql-BFPF8xyv.mjs.map +0 -1
- package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
- package/dist/native-types-1ewJXVks.mjs +0 -2
- package/dist/native-types-1ewJXVks.mjs.map +0 -1
- package/dist/pending-operation-D4gUKMxD.mjs +0 -2
- package/dist/postgres-DQQE2ys_.mjs +0 -34
- package/dist/postgres-DQQE2ys_.mjs.map +0 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
- package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +0 -2
- package/dist/provider-limits-Bcsz0EJv.mjs.map +0 -1
- package/dist/query-BTb6iakn.mjs +0 -2
- package/dist/query-BTb6iakn.mjs.map +0 -1
- package/dist/query-backend-TisPjCPF.mjs +0 -2
- package/dist/raw-DqEb71JZ.mjs +0 -2
- package/dist/rule-words-DMbQuvD2.mjs +0 -2
- package/dist/scalar-Dm9brvAU.mjs +0 -4
- package/dist/scalar-Dm9brvAU.mjs.map +0 -1
- package/dist/schema-DDkAUfOb.mjs +0 -2
- package/dist/schema-DqR_Kcje.mjs +0 -2
- package/dist/serializer-ettLu5xG.mjs +0 -33
- package/dist/serializer-ettLu5xG.mjs.map +0 -1
- package/dist/snowflake-BfF8xwfP.mjs +0 -2
- package/dist/sql-Bu63iAfT.mjs +0 -2
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
- package/dist/surrealql-DY74AUeD.mjs +0 -2
- package/dist/surrealql-DY74AUeD.mjs.map +0 -1
- package/dist/time-step-DJaIhpAz.mjs +0 -2
- package/dist/time-step-DJaIhpAz.mjs.map +0 -1
- package/dist/validation-BHjx13zG.mjs +0 -2
- package/dist/validator-DMzH5Tz0.mjs +0 -2
- package/dist/validator-DMzH5Tz0.mjs.map +0 -1
- package/dist/version-0BDwfy7C.mjs +0 -2
- package/dist/view-CHgjF2BO.mjs +0 -2
- package/dist/write-sinks-Bei5vFHP.mjs +0 -2
- /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
- /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
- /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"datetime-values-D_G6m5_o.mjs","names":[],"sources":["../src/validation/primitives/decimal-value.ts","../src/validation/primitives/decimal-codec.ts","../src/validation/primitives/datetime-values.ts"],"sourcesContent":["/**\n * The exact decimal VALUE type, its accepted spelling, and the text-level\n * arithmetic the field codec needs.\n *\n * A `Decimal` is an immutable signed `BigInt` coefficient and a non-negative\n * scale, `coefficient x 10^-scale`: no NaN, no infinity, no exponent, no\n * statics and no configuration. The constructor and every result strip\n * insignificant fraction zeros and zero is `(0n, 0)`, so `toString()` IS the\n * canonical private text every identity owner keys on.\n *\n * `admitDecimal` is the one admission rule (a string through the grammar,\n * anything else through the brand). The brand is the `#c` private field only\n * the constructor installs, so `canonicalDecimalText` answers `undefined` for\n * `Object.create(Decimal.prototype)`, a look-alike object or a `Proxy`, and no\n * boundary above has to snapshot a foreign representation.\n *\n * The published TYPE is an interface and the published VALUE a const holding\n * the class: result types map every leaf through `Prettify`, a mapped type\n * drops private fields, and a class type would stop being assignable to\n * `Decimal`. The const's declared type keeps the two in step.\n */\n\n/**\n * The accepted literal grammar: optional sign, decimal digits, at most one dot,\n * at least one digit overall. Deliberately NO exponent — `1e3` is a float\n * spelling, and admitting it would mean admitting `1e400` and the rounding\n * question that comes with it. Deliberately no whitespace, no `NaN`, no\n * `Infinity`: none of them name an exact decimal.\n */\nconst DECIMAL_LITERAL_REGEX = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\n\nconst LEADING_ZEROS_REGEX = /^0+/;\nconst TRAILING_ZEROS_REGEX = /0+$/;\nconst LEADING_SIGN_REGEX = /^[+-]/;\n\n/**\n * Reduce a valid decimal literal to its ONE canonical spelling: no leading `+`,\n * no insignificant leading or trailing zeros, no bare `-0`, no dangling dot.\n *\n * Canonicalization is not cosmetic. It is the private logical representation\n * every identity owner keys on — cursors, row keys, cache keys, race pins, link\n * folds — so two Decimal instances naming the same number are the same key, and\n * `\"1.10\"` and `\"1.1\"` are the same value on every dialect.\n */\nfunction canonicalizeLiteral(literal: string): string {\n const [rawInteger = \"\", rawFraction = \"\"] = literal\n .replace(LEADING_SIGN_REGEX, \"\")\n .split(\".\");\n const whole = rawInteger.replace(LEADING_ZEROS_REGEX, \"\") || \"0\";\n const fraction = rawFraction.replace(TRAILING_ZEROS_REGEX, \"\");\n if (whole === \"0\" && fraction === \"\") return \"0\";\n return `${literal.startsWith(\"-\") ? \"-\" : \"\"}${whole}${fraction === \"\" ? \"\" : `.${fraction}`}`;\n}\n\n/**\n * The canonical text of a `Decimal | string`, or `undefined` when the value\n * names no exact decimal: THE admission rule.\n *\n * The constructor reads a string through it, and the field (`v.decimal()`),\n * the engine binders and the cache encoder read every value through it, so\n * what `s.decimal()` accepts and what `new Decimal()` accepts cannot drift\n * apart. A `Decimal` answers through the brand, never through its shape.\n */\nexport function admitDecimal(value: unknown): string | undefined {\n if (typeof value !== \"string\") return canonicalDecimalText(value);\n return DECIMAL_LITERAL_REGEX.test(value)\n ? canonicalizeLiteral(value)\n : undefined;\n}\n\n/**\n * The two PRIMITIVE forms of an exact decimal a caller may hand the value type:\n * a spelling, or a whole coefficient. Both name an exact decimal; a JavaScript\n * number names a double, so it is not one of them.\n */\nexport type DecimalPrimitive = string | bigint;\n\n/**\n * How a quotient resolves a value exactly between two representable ones.\n *\n * Two modes, each with a caller: `\"half-up\"` is what an application reading a\n * money column expects and what every VibORM release so far has produced;\n * `\"half-even\"` is what the SQL engines do, so a caller reconciling against a\n * server-side division can ask for the server's answer. There is no third mode\n * because there is no third caller.\n */\nexport type DecimalRounding = \"half-up\" | \"half-even\";\n\nconst TEN = 10n;\n\n/** `10^power`, the scale shift both alignment and rounding are spelled with. */\nfunction shift(power: number): bigint {\n return TEN ** BigInt(power);\n}\n\n/**\n * Round `numerator / denominator` to an integer, both taken as non-negative.\n *\n * `\"half-up\"` sends a tie away from zero, which is the sign the caller's\n * coefficient carries separately; `\"half-even\"` sends it to the even neighbour.\n */\nfunction roundQuotient(\n numerator: bigint,\n denominator: bigint,\n rounding: DecimalRounding\n): bigint {\n const quotient = numerator / denominator;\n const doubled = (numerator % denominator) * 2n;\n if (doubled > denominator) return quotient + 1n;\n if (doubled < denominator) return quotient;\n return rounding === \"half-up\" || quotient % 2n !== 0n\n ? quotient + 1n\n : quotient;\n}\n\n/** The accepted spelling, named once for both refusal sentences below. */\nconst DECIMAL_SPELLING = \"decimal string (no exponent/number)\";\n\n/**\n * The FIELD boundary's refusal: `v.decimal()` returns it as its issue message\n * wherever `admitDecimal` answers `undefined`.\n */\nexport const DECIMAL_INPUT_REFUSAL = `Expected Decimal or ${DECIMAL_SPELLING}`;\n\n/**\n * The constructor's refusal. It names one more member than the field's,\n * because the value type also takes a whole `bigint` coefficient, and it shares\n * the grammar and the spelling clause with it.\n */\nexport const DECIMAL_CONSTRUCTOR_REFUSAL = `Expected Decimal, bigint, or ${DECIMAL_SPELLING}`;\n\n/**\n * Write one normalized coefficient and scale as canonical text: the integer\n * digits, a point only when there are fraction digits, and a sign only on a\n * value below zero. The one canonical rendering — `toString` and the seam the\n * codec reads both come here, so no caller can be shown a second spelling;\n * `toFixed` shares its point placement.\n */\nfunction renderParts(coefficient: bigint, scale: number): string {\n const negative = coefficient < 0n;\n return placePoint(\n negative,\n (negative ? -coefficient : coefficient).toString(),\n scale\n );\n}\n\n/** Unsigned digits with the point `fractionDigits` from the right, and a sign. */\nfunction placePoint(\n negative: boolean,\n digits: string,\n fractionDigits: number\n): string {\n const sign = negative ? \"-\" : \"\";\n if (fractionDigits === 0) return `${sign}${digits}`;\n const padded = digits.padStart(fractionDigits + 1, \"0\");\n const point = padded.length - fractionDigits;\n return `${sign}${padded.slice(0, point)}.${padded.slice(point)}`;\n}\n\n/**\n * Write a coefficient and scale with exactly `fractionDigits` fraction digits,\n * rounding half away from zero: `toFixed`.\n */\nfunction renderFixed(\n coefficient: bigint,\n scale: number,\n fractionDigits: number\n): string {\n const negative = coefficient < 0n;\n const rounded = roundQuotient(\n (negative ? -coefficient : coefficient) * shift(fractionDigits),\n shift(scale),\n \"half-up\"\n ).toString();\n // A negative value keeps its sign even when every digit it rounded to is a\n // zero: `-0.004` to two places is `-0.00`, which says the value was below\n // zero and too small to show. Zero itself is never negative, so there is no\n // second rule to apply.\n return placePoint(negative, rounded, fractionDigits);\n}\n\n/**\n * Read already-canonical text straight into a coefficient and a scale.\n *\n * Canonical text carries no `+`, no insignificant zero and no bare `-0`, so\n * what comes out needs no normalization — which is what lets the codec hand\n * over a spelling it has already validated without paying for the grammar a\n * second time.\n */\nfunction partsOfCanonical(canonical: string): [bigint, number] {\n const point = canonical.indexOf(\".\");\n if (point === -1) return [BigInt(canonical), 0];\n const scale = canonical.length - point - 1;\n return [\n BigInt(canonical.slice(0, point) + canonical.slice(point + 1)),\n scale,\n ];\n}\n\n/**\n * The exact decimal VALUE.\n *\n * Immutable: every operation returns a new instance and none of them mutates\n * the receiver. Every binary operation accepts the same\n * `Decimal | DecimalPrimitive` the constructor does, so there is one admission\n * grammar for the whole type.\n *\n * This is an INTERFACE, and {@link Decimal} below is the const that holds the\n * class implementing it. They carry the same name on purpose — a caller writes\n * `Decimal` for both — and the const's declared type is what keeps them in\n * step: a method added to one side and not the other stops compiling.\n *\n * @example\n * new Decimal(\"19.99\").times(\"3\").toString(); // \"59.97\"\n * new Decimal(\"1\").div(\"3\", 5).toString(); // \"0.33333\"\n */\nexport interface Decimal {\n /** Immutable canonical text retained by deep equality and structured cloning. */\n readonly value: string;\n /** This value plus `other`, exactly. */\n plus(other: Decimal | DecimalPrimitive): Decimal;\n /** This value minus `other`, exactly. */\n minus(other: Decimal | DecimalPrimitive): Decimal;\n /** This value times `other`, exactly: coefficients multiply, scales add. */\n times(other: Decimal | DecimalPrimitive): Decimal;\n /**\n * This value divided by `other`, to `fractionDigits` fraction digits.\n *\n * A quotient is the one operation with no exact answer, so it is the one that\n * asks: how many digits, and what happens to a tie.\n *\n * @throws {RangeError} when `other` is zero.\n */\n div(\n other: Decimal | DecimalPrimitive,\n fractionDigits?: number,\n rounding?: DecimalRounding\n ): Decimal;\n /** `-1`, `0` or `1` as this value is below, equal to, or above `other`. */\n cmp(other: Decimal | DecimalPrimitive): -1 | 0 | 1;\n /** Whether this value and `other` are the same number. */\n eq(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is below `other`. */\n lt(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is below `other` or the same number. */\n lte(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is above `other`. */\n gt(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is above `other` or the same number. */\n gte(other: Decimal | DecimalPrimitive): boolean;\n /** This value without its sign. */\n abs(): Decimal;\n /** This value with its sign flipped. Zero has no sign to flip. */\n neg(): Decimal;\n /**\n * The canonical text of this value: no exponent, ever, and no insignificant\n * zero, so two instances naming the same number spell it the same way.\n */\n toString(): string;\n /**\n * This value with exactly `fractionDigits` fraction digits, rounding half\n * away from zero. With no argument it is {@link Decimal.toString}: the whole\n * value, in normal notation, rounded nowhere.\n */\n toFixed(fractionDigits?: number): string;\n /**\n * This value as a JavaScript number, which is a double: the conversion is\n * exact only for values a double can hold, and is the caller's decision.\n */\n toNumber(): number;\n /** The canonical text, so `` `${value}` `` and `+value` read the number. */\n valueOf(): string;\n /** The canonical text, so `JSON.stringify` writes the number, not `{}`. */\n toJSON(): string;\n}\n\n/**\n * The two module-private readers of a Decimal's private fields, captured from\n * inside the class body.\n *\n * Captured rather than declared `static` so the published constructor carries\n * no static property at all: `Object.getOwnPropertyNames(Decimal)` is\n * `length`, `name`, `prototype` and nothing else, which is the \"no\n * configuration, in either direction\" promise made literal.\n */\nlet owns: (value: unknown) => value is ExactDecimal;\nlet textOf: (value: ExactDecimal) => string;\n\n/**\n * The class, and the only place a `#c` is installed.\n *\n * Named for what it is rather than `Decimal`, which the interface above already\n * takes: it is not a wrapper AROUND a decimal, it IS the exact decimal, and a\n * class named `DecimalValue`/`DecimalWrapper` beside a `Decimal` is exactly the\n * second-owner shape the language census refuses.\n *\n * Module-private: what the package exports is {@link Decimal} below, whose\n * declared type carries ONE construct signature — the public grammar. The\n * two-argument form here is the internal seam a coefficient at a non-zero\n * scale arrives through; TypeScript outside this module cannot spell it, but\n * untyped JavaScript reaches it (`new Decimal(123n, 2)` is 1.23) and the\n * scale is not checked there.\n */\nclass ExactDecimal implements Decimal {\n readonly #c: bigint;\n readonly #scale: number;\n readonly value: string;\n\n constructor(value: Decimal | DecimalPrimitive, scale?: number) {\n // A `bigint` is a coefficient: a public one is a whole number (scale 0),\n // and the internal seam passes its scale. Normalized here so every result\n // in this file is normalized in one place.\n let text: string;\n if (typeof value === \"bigint\") {\n let coefficient = value;\n let places = scale ?? 0;\n while (places > 0 && coefficient % TEN === 0n) {\n coefficient /= TEN;\n places--;\n }\n this.#c = coefficient;\n this.#scale = coefficient === 0n ? 0 : places;\n text = renderParts(this.#c, this.#scale);\n } else if (owns(value)) {\n // The BRAND, not `instanceof`: a prototype is forgeable and a private field\n // is not, so a value that only wears the prototype falls through to the\n // refusal below instead of failing on a field it does not have.\n this.#c = value.#c;\n this.#scale = value.#scale;\n text = value.value;\n } else {\n const canonical = admitDecimal(value);\n if (canonical === undefined) {\n throw new TypeError(DECIMAL_CONSTRUCTOR_REFUSAL);\n }\n const [coefficient, places] = partsOfCanonical(canonical);\n this.#c = coefficient;\n this.#scale = places;\n text = canonical;\n }\n this.value = text;\n Object.defineProperty(this, \"value\", {\n writable: false,\n configurable: false,\n });\n }\n\n static {\n owns = (value: unknown): value is ExactDecimal =>\n typeof value === \"object\" && value !== null && #c in value;\n textOf = (value) => value.value;\n }\n\n /** The coefficient this value would carry at `scale`, which is never less. */\n #at(scale: number): bigint {\n return this.#c * shift(scale - this.#scale);\n }\n\n #align(other: Decimal | DecimalPrimitive): [bigint, bigint, number] {\n const rhs = new ExactDecimal(other);\n const scale = Math.max(this.#scale, rhs.#scale);\n return [this.#at(scale), rhs.#at(scale), scale];\n }\n\n plus(other: Decimal | DecimalPrimitive): Decimal {\n const [left, right, scale] = this.#align(other);\n return new ExactDecimal(left + right, scale);\n }\n\n minus(other: Decimal | DecimalPrimitive): Decimal {\n const [left, right, scale] = this.#align(other);\n return new ExactDecimal(left - right, scale);\n }\n\n times(other: Decimal | DecimalPrimitive): Decimal {\n const factor = new ExactDecimal(other);\n return new ExactDecimal(this.#c * factor.#c, this.#scale + factor.#scale);\n }\n\n div(\n other: Decimal | DecimalPrimitive,\n fractionDigits = 20,\n rounding: DecimalRounding = \"half-up\"\n ): Decimal {\n const divisor = new ExactDecimal(other);\n if (divisor.#c === 0n) throw new RangeError(\"Division by zero\");\n const numerator = this.#c * shift(divisor.#scale + fractionDigits);\n const denominator = divisor.#c * shift(this.#scale);\n const negative = numerator < 0n !== denominator < 0n;\n const magnitude = roundQuotient(\n numerator < 0n ? -numerator : numerator,\n denominator < 0n ? -denominator : denominator,\n rounding\n );\n return new ExactDecimal(negative ? -magnitude : magnitude, fractionDigits);\n }\n\n cmp(other: Decimal | DecimalPrimitive): -1 | 0 | 1 {\n const [left, right] = this.#align(other);\n return left < right ? -1 : left > right ? 1 : 0;\n }\n\n eq(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === 0;\n }\n\n lt(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === -1;\n }\n\n lte(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) !== 1;\n }\n\n gt(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === 1;\n }\n\n gte(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) !== -1;\n }\n\n abs(): Decimal {\n return new ExactDecimal(this.#c < 0n ? -this.#c : this.#c, this.#scale);\n }\n\n neg(): Decimal {\n return new ExactDecimal(-this.#c, this.#scale);\n }\n\n toString(): string {\n return renderParts(this.#c, this.#scale);\n }\n\n toFixed(fractionDigits?: number): string {\n return fractionDigits === undefined\n ? this.toString()\n : renderFixed(this.#c, this.#scale, fractionDigits);\n }\n\n toNumber(): number {\n return Number(this.toString());\n }\n\n valueOf(): string {\n return this.toString();\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `Decimal(\"${this.value}\")`;\n }\n}\n\n/**\n * The public constructor, carrying the one grammar a caller may spell.\n *\n * The same object as the class, so `instanceof` and `Object.create(\n * Decimal.prototype)` behave exactly as they would for a plain class\n * declaration — only the internal two-argument construction is hidden, and the\n * instance TYPE stays free of private fields so a mapped result type keeps it.\n */\nexport const Decimal: {\n /**\n * @param value a `Decimal` to copy, an exact decimal string, or a whole\n * `bigint`.\n * @throws {TypeError} for every other value, including every JavaScript\n * number, a string outside the accepted grammar, and a value of any other\n * type.\n */\n new (value: Decimal | DecimalPrimitive): Decimal;\n readonly prototype: Decimal;\n} = ExactDecimal;\n\n/**\n * Construct one Decimal from text this module's own grammar already admitted.\n *\n * The decode half of every result, cache and default boundary. The codec has\n * established the spelling before calling, so re-testing it here would make the\n * grammar two owners deep; a caller that has NOT established it uses the\n * ordinary constructor, which is the only other way in.\n */\nexport function fromCanonical(canonical: string): Decimal {\n const [coefficient, scale] = partsOfCanonical(canonical);\n return new ExactDecimal(coefficient, scale);\n}\n\n/**\n * The canonical text of a value that IS one of ours, or `undefined`.\n *\n * The whole value boundary, in one function: the private field is installed by\n * the constructor and by nothing else, so answering at all is a witness of\n * CONSTRUCTION rather than a reading of a shape — `undefined` for\n * `Object.create(Decimal.prototype)`, for a plain object carrying the same\n * keys, for a `Proxy` around a real one, and for every other value there is.\n *\n * The text is read from the fields, deliberately NOT through `value.toString()`:\n * the prototype is an object an application can write to, and a codec that\n * rendered through it would be rendering whatever the application put there.\n * The fields are reachable from inside the class body and from nowhere else, so\n * this is the only rendering no caller can move — and it shares `renderParts`\n * with the prototype method, so there is still one spelling.\n */\nexport function canonicalDecimalText(value: unknown): string | undefined {\n return owns(value) ? textOf(value) : undefined;\n}\n\n/**\n * The Decimal `coefficient x 10^-scale`: the decode seam for an unscaled\n * integer a provider stored, normalized by the constructor like every result.\n */\nexport function fromCoefficient(coefficient: bigint, scale: number): Decimal {\n return new ExactDecimal(coefficient, scale);\n}\n\n/**\n * The unscaled integer coefficient of canonical text at `scale`, which is never\n * less than the text's own: `logical x 10^scale`, exact because it is the\n * value's own `BigInt` shifted, never a JavaScript multiplication.\n */\nexport function toCoefficient(canonical: string, scale: number): string {\n const [coefficient, own] = partsOfCanonical(canonical);\n return (coefficient * shift(scale - own)).toString();\n}\n\n/**\n * Why canonical text is outside the domain `{ precision, scale }`, or\n * `undefined` when it fits: the one owner of both refusal sentences.\n *\n * Fitting is a DOMAIN question, not a spelling one: `\"1.2\"` at scale 5 fits and\n * stays `\"1.2\"`. Only digits past `scale`, or an unscaled coefficient wider\n * than `precision`, are outside, and both are refused rather than rounded.\n *\n * Read from the TEXT, in one pass and with no allocation: a declared scale may\n * be as large as `Number.MAX_SAFE_INTEGER` before a provider bounds it, and a\n * field refuses an over-long literal before any `BigInt` is built.\n */\nexport function domainRefusal(\n canonical: string,\n precision: number,\n scale: number\n): string | undefined {\n const point = canonical.indexOf(\".\");\n const fractionDigits = point === -1 ? 0 : canonical.length - point - 1;\n if (fractionDigits > scale) {\n return `'${canonical}' exceeds scale ${scale} (${fractionDigits} fractional digits)`;\n }\n const start = canonical.startsWith(\"-\") ? 1 : 0;\n let digits: number;\n if (canonical[start] !== \"0\") {\n // Canonical text has no leading zero, so every integer digit counts.\n digits = (point === -1 ? canonical.length : point) - start + scale;\n } else {\n // A zero integer part: the coefficient starts at the first non-zero\n // fraction digit, and zero itself has none.\n let first = point + 1;\n while (canonical[first] === \"0\") first++;\n digits = point === -1 ? 0 : scale - (first - point - 1);\n }\n if (digits > precision) {\n return `'${canonical}' exceeds precision ${precision} (${digits} digits)`;\n }\n return undefined;\n}\n","/**\n * The field-aware decimal codec: the descriptor type, the two physical\n * vocabularies a column crosses through, the provider decode grammars and\n * their domain limits, the two DDL renderings, the widened-sum decode and the\n * JSON list container. The value and its arithmetic are `decimal-value.ts`'s;\n * a value whose `canonicalDecimalText` answers was built by its constructor,\n * so there is nothing here to snapshot or defend against.\n */\n\nimport { isString } from \"../value-guards\";\nimport {\n admitDecimal,\n canonicalDecimalText,\n type Decimal,\n domainRefusal,\n fromCanonical,\n fromCoefficient,\n toCoefficient,\n} from \"./decimal-value\";\n\n// =============================================================================\n// THE DOMAIN\n// =============================================================================\n\n/**\n * The fixed-decimal domain: multiples of `10^-scale` whose unscaled coefficient\n * has at most `precision` digits. Frozen once by `s.decimal` and carried by\n * reference through every modifier.\n */\nexport interface DecimalDescriptor {\n readonly precision: number;\n readonly scale: number;\n}\n\n/** Whether two optional descriptor references declare the same value domain. */\nexport function sameDecimalDescriptor(\n left: DecimalDescriptor | undefined,\n right: DecimalDescriptor | undefined\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return left.precision === right.precision && left.scale === right.scale;\n}\n\n/**\n * The two exact physical vocabularies a decimal field can cross through.\n *\n * The active adapter selects one; this codec alone interprets it. The value\n * cannot select its own vocabulary because `\"120\"` is logical 120 as native\n * decimal text and logical 1.2 as a scale-2 coefficient.\n */\nexport type DecimalPhysicalRepresentation = \"text\" | \"coefficient\";\n\n/**\n * The codec's names for four value-module seams: the admission rule\n * (`admitDecimal`), the brand reader (`canonicalDecimalText`), the\n * grammar-skipping decode seam (`fromCanonical`) and the coefficient at a\n * scale (`toCoefficient`). Each is the same function, not a wrapper around it.\n * They are the names every other module reaches: the language census lets only\n * this codec and the root entry import a construction seam from the value\n * module at runtime, so `primitives/decimal.ts`, the engine's binders, result\n * parser and cache, and the migration readers build and admit through here.\n */\nexport const canonicalizeDecimal = admitDecimal;\nexport const canonicalizeMaterializedDecimal = canonicalDecimalText;\nexport const toDecimal = fromCanonical;\nexport const logicalToCoefficient = toCoefficient;\n\n// =============================================================================\n// THE COEFFICIENT VOCABULARY\n// =============================================================================\n\n/**\n * The one physical coefficient spelling: `0`, or an optional minus and digits\n * with no leading zero. `BigInt` alone would also read `\" 1 \"`, `\"0x10\"` and\n * `\"\"`, so a provider value crosses this before it becomes a number.\n */\nconst COEFFICIENT_REGEX = /^(?:0|-?[1-9]\\d*)$/;\n\n/**\n * Decode one untrusted unscaled coefficient at `scale`, or `undefined` when it\n * is outside the vocabulary or wider than `precision` digits. The length is\n * bounded before the `BigInt` is built.\n */\nfunction decodeCoefficient(\n value: unknown,\n scale: number,\n precision?: number\n): Decimal | undefined {\n if (!(isString(value) && COEFFICIENT_REGEX.test(value))) return undefined;\n const digits = value.startsWith(\"-\") ? value.length - 1 : value.length;\n if (precision !== undefined && digits > precision) return undefined;\n return fromCoefficient(BigInt(value), scale);\n}\n\n/** The canonical text of a decoded coefficient, or `undefined`. */\nfunction decodeCoefficientText(\n value: unknown,\n scale: number,\n precision?: number\n): string | undefined {\n const decoded = decodeCoefficient(value, scale, precision);\n return decoded === undefined ? undefined : canonicalDecimalText(decoded);\n}\n\n// =============================================================================\n// PROVIDER TEXT DECODE\n// =============================================================================\n\n/** Physical decimal text emitted by PostgreSQL/MySQL: optional minus, no leading zero, optional fraction. */\nconst PROVIDER_TEXT_REGEX = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/;\n\nfunction decodeProviderText(\n value: unknown,\n scale: number,\n precision = Number.POSITIVE_INFINITY\n): string | undefined {\n if (!(isString(value) && PROVIDER_TEXT_REGEX.test(value))) return undefined;\n const canonical = admitDecimal(value)!;\n return domainRefusal(canonical, precision, scale) === undefined\n ? canonical\n : undefined;\n}\n\n/**\n * Decode one scalar field value read back as native decimal text, or\n * `undefined` when the provider returned something outside the field's declared\n * domain or outside the physical vocabulary the adapter promised.\n *\n * The PostgreSQL/MySQL scalar-read half of the codec: a column declared\n * `NUMERIC(p,s)` cannot answer with more than `s` fractional digits or more\n * than `p` coefficient digits, so a value that does is a column the schema no\n * longer describes rather than a number to widen the field for.\n */\nexport function decodeFieldScalar(\n text: unknown,\n descriptor: DecimalDescriptor\n): string | undefined {\n return decodeProviderText(text, descriptor.scale, descriptor.precision);\n}\n\n/**\n * Decode an aggregate SUM, which keeps the field's SCALE but is deliberately\n * NOT held to its precision: adding a million `precision: 10` rows produces a\n * legitimate answer wider than any single column. `undefined` means the\n * provider returned something that is not an exact decimal at this scale.\n */\nexport function decodeWidenedSum(\n value: unknown,\n scale: number\n): string | undefined {\n return decodeProviderText(value, scale);\n}\n\n// =============================================================================\n// PROVIDER PHYSICAL REPRESENTATION\n// =============================================================================\n\nfunction encodePhysicalDecimalAtScale(\n canonical: string,\n scale: number,\n representation: DecimalPhysicalRepresentation\n): string {\n return representation === \"coefficient\"\n ? toCoefficient(canonical, scale)\n : canonical;\n}\n\n/**\n * Encode one trusted canonical logical value in the vocabulary selected by the\n * active adapter. SQL construction remains with that adapter.\n */\nexport function encodePhysicalDecimal(\n canonical: string,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string {\n return encodePhysicalDecimalAtScale(\n canonical,\n descriptor.scale,\n representation\n );\n}\n\nfunction decodePhysical(\n value: unknown,\n scale: number,\n representation: DecimalPhysicalRepresentation,\n precision?: number\n): string | undefined {\n return representation === \"text\"\n ? decodeProviderText(value, scale, precision)\n : decodeCoefficientText(value, scale, precision);\n}\n\nfunction materializePhysical(\n value: unknown,\n scale: number,\n representation: DecimalPhysicalRepresentation,\n precision?: number\n): Decimal | undefined {\n if (representation === \"coefficient\") {\n return decodeCoefficient(value, scale, precision);\n }\n const canonical = decodeProviderText(value, scale, precision);\n return canonical === undefined ? undefined : fromCanonical(canonical);\n}\n\n/**\n * Decode one untrusted provider scalar into canonical private logical text.\n */\nexport function decodePhysicalDecimal(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string | undefined {\n return decodePhysical(\n value,\n descriptor.scale,\n representation,\n descriptor.precision\n );\n}\n\n/**\n * Decode one ordinary scalar directly into its one fresh public Decimal.\n */\nexport function materializePhysicalDecimal(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): Decimal | undefined {\n return materializePhysical(\n value,\n descriptor.scale,\n representation,\n descriptor.precision\n );\n}\n\n/**\n * Encode the ordered input members that the adapter will place in its native\n * array or JSON-backed coefficient container. Canonicalization stays inside\n * the codec so the caller does not need a second list pass or conversion owner.\n */\nexport function encodePhysicalDecimalListMembers(\n values: readonly unknown[],\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string[] | undefined {\n const members = new Array<string>(values.length);\n for (const [index, value] of values.entries()) {\n const canonical = admitDecimal(value);\n if (canonical === undefined) return undefined;\n members[index] = encodePhysicalDecimalAtScale(\n canonical,\n descriptor.scale,\n representation\n );\n }\n return members;\n}\n\n/**\n * Decode one provider list into canonical private logical members. Text means\n * a native array of exact decimal strings; coefficient means one JSON text\n * container of coefficient strings.\n */\nexport function decodePhysicalDecimalList(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string[] | undefined {\n if (representation === \"coefficient\") {\n return decodeDecimalListContainer(\n value,\n descriptor.scale,\n descriptor.precision\n );\n }\n try {\n if (!Array.isArray(value)) return undefined;\n const length = value.length;\n if (!Number.isSafeInteger(length) || length < 0) return undefined;\n const members = new Array<string>(length);\n for (let index = 0; index < length; index++) {\n if (!Object.hasOwn(value, index)) return undefined;\n const canonical = decodeFieldScalar(value[index], descriptor);\n if (canonical === undefined) return undefined;\n members[index] = canonical;\n }\n return members;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decode an exact SUM while retaining only the declared scale. The field\n * precision is deliberately not applied because sums widen.\n */\nexport function decodePhysicalWidenedSum(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string | undefined {\n return decodePhysical(value, descriptor.scale, representation);\n}\n\n/** Decode one widened SUM directly into its one fresh public Decimal. */\nexport function materializePhysicalWidenedSum(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): Decimal | undefined {\n return materializePhysical(value, descriptor.scale, representation);\n}\n\n// =============================================================================\n// THE TWO DDL RENDERINGS\n// =============================================================================\n\n/** The dialects that spell a fixed decimal, in `NativeType[\"db\"]` vocabulary. */\nexport type DecimalDialect = \"pg\" | \"mysql\" | \"sqlite\";\n\n// =============================================================================\n// PROVIDER PHYSICAL LIMITS\n// =============================================================================\n\n/**\n * What each provider can physically store, as one table (plan 3.1).\n *\n * PostgreSQL's `NUMERIC(p,s)` tops out at 1000 digits. MySQL's `DECIMAL(p,s)`\n * tops out at 65 digits with at most 30 after the point, and exact coefficient\n * arithmetic additionally needs `precision + scale <= 65`. SQLite's bound is not\n * a storage limit at all — it stores the unscaled coefficient in an int64 — but\n * the requirement of the one-statement multiply/divide: `precision + scale <=\n * 18` is what makes every in-range rounded result computable without\n * overflowing the intermediate, and 18 digits is also the widest literal\n * SQLite's own parser reads as an integer rather than as a REAL, which is what\n * the descriptor's range CHECK is written in.\n *\n * A descriptor is syntactically valid at model construction regardless: a\n * schema valid for PostgreSQL stays a valid model graph, and only BINDING it to\n * a provider that cannot store it fails.\n */\nconst PROVIDER_LIMITS: Record<\n DecimalDialect,\n { readonly precision: number; readonly scale: number; readonly sum?: number }\n> = {\n pg: { precision: 1000, scale: 1000 },\n mysql: { precision: 65, scale: 30, sum: 65 },\n sqlite: { precision: 18, scale: 18, sum: 18 },\n};\n\n/**\n * Why this provider cannot store this descriptor, or `undefined` when it can:\n * one sentence per failing bound, naming the descriptor, the provider and the\n * limit — the caller adds the field. Read by the schema bind boundary\n * (`provider-limits.ts`) before any provider I/O, and by the migration layer.\n */\nexport function describeProviderLimitRefusal(\n dialect: DecimalDialect,\n descriptor: DecimalDescriptor\n): string | undefined {\n const limit = PROVIDER_LIMITS[dialect];\n const { precision, scale } = descriptor;\n const named = describeDecimalDomain(descriptor);\n return precision > limit.precision\n ? `${named} exceeds max precision ${limit.precision}`\n : scale > limit.scale\n ? `${named} exceeds max scale ${limit.scale}`\n : limit.sum !== undefined && precision + scale > limit.sum\n ? `${named} requires precision + scale <= ${limit.sum}`\n : undefined;\n}\n\n/**\n * The physical column type for this descriptor.\n *\n * SQLite has no exact decimal type — `DECIMAL(10,5)` is only a NUMERIC-affinity\n * spelling whose numbers it ignores — so it stores the signed integer\n * coefficient and the migration driver adds the range check that makes the\n * declared precision real.\n *\n * No space after the comma, on every dialect: the emitted text is compared by\n * the differ, so one descriptor has one spelling.\n */\nexport function decimalColumnType(\n dialect: DecimalDialect,\n { precision, scale }: DecimalDescriptor\n): string {\n return dialect === \"sqlite\"\n ? \"INTEGER\"\n : `${dialect === \"pg\" ? \"NUMERIC\" : \"DECIMAL\"}(${precision},${scale})`;\n}\n\n/**\n * The DDL literal for a default. PostgreSQL and MySQL take the value padded to\n * `scale` fraction digits, because that is what MySQL reads back from\n * `information_schema`: canonical `1.2` on a scale-5 column would read back as\n * `1.20000` and the differ would see a change on every push. SQLite takes the\n * coefficient, the same integer the column stores.\n *\n * The text is padded, never rounded: PostgreSQL introspection hands back\n * catalog text the column's scale never touched (`DEFAULT 1.005` on\n * `NUMERIC(10,2)` stays `1.005`), and the differ compares what the DDL\n * declared. A scale-0 column keeps the integer part.\n */\nexport function decimalDefaultText(\n dialect: DecimalDialect,\n canonical: string,\n descriptor: DecimalDescriptor\n): string {\n const { scale } = descriptor;\n if (dialect === \"sqlite\") return toCoefficient(canonical, scale);\n const point = canonical.indexOf(\".\");\n if (scale === 0) return point === -1 ? canonical : canonical.slice(0, point);\n if (point === -1) return `${canonical}.${\"0\".repeat(scale)}`;\n return canonical.padEnd(point + 1 + scale, \"0\");\n}\n\n/**\n * The physical value of one trusted literal decimal-list default.\n *\n * PostgreSQL owns a native numeric array, so every logical member is padded to\n * the declared scale just like a scalar DDL default. MySQL and the SQLite\n * family own coefficient-string JSON containers, exactly like their runtime\n * list writes. This codec renders the VALUE only; migration drivers still own\n * string quoting and provider expression syntax.\n */\nexport function decimalListDefaultText(\n dialect: DecimalDialect,\n canonicals: readonly string[],\n descriptor: DecimalDescriptor\n): string {\n if (dialect !== \"pg\") {\n return encodeDecimalListContainer(canonicals, descriptor.scale);\n }\n return `{${canonicals.map((c) => decimalDefaultText(\"pg\", c, descriptor)).join(\",\")}}`;\n}\n\n// =============================================================================\n// THE JSON LIST CONTAINER\n// =============================================================================\n\nexport function encodeDecimalListContainer(\n canonicals: readonly string[],\n scale: number\n): string {\n return JSON.stringify(canonicals.map((c) => toCoefficient(c, scale)));\n}\n\n/**\n * The canonical logical members of a physical list container, or `undefined`\n * when the container is not one this codec wrote: malformed JSON, a non-array\n * top level, a numeric token, `null`, or a member outside the coefficient\n * grammar. Order and multiplicity are preserved exactly.\n */\nexport function decodeDecimalListContainer(\n container: unknown,\n scale: number,\n precision?: number\n): string[] | undefined {\n if (!isString(container)) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(container);\n } catch {\n return undefined;\n }\n if (!Array.isArray(parsed)) return undefined;\n const members = new Array<string>(parsed.length);\n for (const [index, member] of parsed.entries()) {\n const canonical = decodeCoefficientText(member, scale, precision);\n if (canonical === undefined) return undefined;\n members[index] = canonical;\n }\n return members;\n}\n\n/** Domain diagnostics and catalog admission share the value descriptor owner. */\nexport function describeDecimalDomain(descriptor: DecimalDescriptor): string {\n return `precision ${descriptor.precision}, scale ${descriptor.scale}`;\n}\n\nconst STORED_DECIMAL_INTEGER = /^-?\\d+$/;\nexport function readStoredDecimalDescriptor(\n precisionValue: unknown,\n scaleValue: unknown,\n dialect: DecimalDialect\n): DecimalDescriptor | undefined {\n const precision = readStoredDecimalInteger(precisionValue);\n const scale = readStoredDecimalInteger(scaleValue);\n if (\n precision === undefined ||\n scale === undefined ||\n precision <= 0 ||\n scale < 0 ||\n scale > precision\n )\n return undefined;\n const descriptor = { precision, scale };\n return describeProviderLimitRefusal(dialect, descriptor) === undefined\n ? descriptor\n : undefined;\n}\n\nfunction readStoredDecimalInteger(value: unknown): number | undefined {\n const parsed =\n typeof value === \"number\"\n ? value\n : isString(value) && STORED_DECIMAL_INTEGER.test(value)\n ? Number(value)\n : Number.NaN;\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n","/**\n * The one logical instant domain of a VibORM DateTime value.\n *\n * Four-digit ISO years are not only an input spelling. They bound every\n * public DateTime instant, including a `Date` input and a provider value read\n * back through a numeric physical representation.\n */\n\nexport const MIN_DATETIME_EPOCH_MILLISECONDS = -62_167_219_200_000;\nexport const MAX_DATETIME_EPOCH_MILLISECONDS = 253_402_300_799_999;\n\n/** Whether one number names a whole millisecond in the public DateTime domain. */\nexport function isDateTimeInstant(epochMilliseconds: number): boolean {\n return (\n Number.isInteger(epochMilliseconds) &&\n epochMilliseconds >= MIN_DATETIME_EPOCH_MILLISECONDS &&\n epochMilliseconds <= MAX_DATETIME_EPOCH_MILLISECONDS\n );\n}\n\n/** Whether three numeric components name one real proleptic-Gregorian date. */\nexport function isGregorianCalendarDate(\n year: number,\n month: number,\n day: number\n): boolean {\n const hasIntegerComponents =\n Number.isInteger(year) && Number.isInteger(month) && Number.isInteger(day);\n if (!hasIntegerComponents || month < 1 || month > 12 || day < 1) {\n return false;\n }\n let daysInMonth = 31;\n if (month === 2) {\n daysInMonth = isLeapYear(year) ? 29 : 28;\n } else if (month === 4 || month === 6 || month === 9 || month === 11) {\n daysInMonth = 30;\n }\n return day <= daysInMonth;\n}\n\n/** Whether three numeric components name one clock time without leap seconds. */\nexport function isDateTimeClock(\n hour: number,\n minute: number,\n second: number\n): boolean {\n return (\n Number.isInteger(hour) &&\n Number.isInteger(minute) &&\n Number.isInteger(second) &&\n hour >= 0 &&\n hour <= 23 &&\n minute >= 0 &&\n minute <= 59 &&\n second >= 0 &&\n second <= 59\n );\n}\n\nfunction isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n"],"mappings":"gDA6BA,MAAM,EAAwB,iCAExB,EAAsB,MACtB,EAAuB,MACvB,EAAqB,QAW3B,SAAS,EAAoB,EAAyB,CACpD,GAAM,CAAC,EAAa,GAAI,EAAc,IAAM,EACzC,QAAQ,EAAoB,GAAE,CAC9B,MAAM,IAAI,CACP,EAAQ,EAAW,QAAQ,EAAqB,GAAG,EAAI,IACvD,EAAW,EAAY,QAAQ,EAAsB,GAAG,CAE9D,OADI,IAAU,KAAO,IAAa,GAAW,IACtC,GAAG,EAAQ,WAAW,IAAI,CAAG,IAAM,KAAK,IAAQ,IAAa,GAAK,GAAK,IAAI,MAYpF,SAAgB,EAAa,EAAoC,CAE/D,OADI,OAAO,GAAU,SACd,EAAsB,KAAK,EAAK,CACnC,EAAoB,EAAK,CACzB,IAAA,GAHkC,EAAqB,EAAM,CAwBnE,MAAM,EAAM,IAGZ,SAAS,EAAM,EAAuB,CACpC,OAAO,GAAO,OAAO,EAAM,CAS7B,SAAS,EACP,EACA,EACA,EACQ,CACR,IAAM,EAAW,EAAY,EACvB,EAAW,EAAY,EAAe,GAG5C,OAFI,EAAU,EAAoB,EAAW,GACzC,EAAU,EAAoB,EAC3B,IAAa,WAAa,EAAW,IAAO,GAC/C,EAAW,GACX,EAIN,MAAM,EAAmB,sCAMZ,EAAwB,uBAAuB,IAO/C,GAA8B,gCAAgC,IAS3E,SAAS,EAAY,EAAqB,EAAuB,CAC/D,IAAM,EAAW,EAAc,GAC/B,OAAO,EACL,GACC,EAAW,CAAC,EAAc,GAAa,UAAU,CAClD,EACD,CAIH,SAAS,EACP,EACA,EACA,EACQ,CACR,IAAM,EAAO,EAAW,IAAM,GAC9B,GAAI,IAAmB,EAAG,M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AAS,EAAM,EAAI,GAAuB,KAAK,EAAM,CACnD,OAAO,EAAM,CACb,IACR,OAAO,OAAO,cAAc,EAAO,CAAG,EAAS,IAAA,GC1fjD,MAAa,EAAkC,aAClC,EAAkC,eAG/C,SAAgB,GAAkB,EAAoC,CACpE,OACE,OAAO,UAAU,EAAkB,EACnC,GAAqB,GACrB,GAAqB,EAKzB,SAAgB,GACd,EACA,EACA,EACS,CAGT,GAAI,EADF,OAAO,UAAU,EAAK,EAAI,OAAO,UAAU,EAAM,EAAI,OAAO,UAAU,EAAI,GAC/C,EAAQ,GAAK,EAAQ,IAAM,EAAM,EAC5D,MAAO,GAET,IAAI,EAAc,GAMlB,OALI,IAAU,EACZ,EAAc,GAAW,EAAK,CAAG,GAAK,IAC7B,IAAU,GAAK,IAAU,GAAK,IAAU,GAAK,IAAU,MAChE,EAAc,IAET,GAAO,EAIhB,SAAgB,GACd,EACA,EACA,EACS,CACT,OACE,OAAO,UAAU,EAAK,EACtB,OAAO,UAAU,EAAO,EACxB,OAAO,UAAU,EAAO,EACxB,GAAQ,GACR,GAAQ,IACR,GAAU,GACV,GAAU,IACV,GAAU,GACV,GAAU,GAId,SAAS,GAAW,EAAuB,CACzC,OAAO,EAAO,GAAM,IAAM,EAAO,KAAQ,GAAK,EAAO,KAAQ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./migrations-DIUltjr3.mjs";import{b as t,s as n,x as r}from"./datetime-values-D_G6m5_o.mjs";import{E as i}from"./push-fingerprint-CegYVFFp.mjs";function a(e,t){return t.precision-t.scale<e.precision-e.scale||t.scale<e.scale}function o(e,t){return t.decimal===void 0?!1:!r(e.decimal,t.decimal)||e.type.toUpperCase()!==t.type.toUpperCase()}function s(e,t){return e.decimal===void 0||t.decimal===void 0?!1:a(e.decimal,t.decimal)}function c(e){return e??`unrecognized`}function l(e){return`viborm:decimal(${e.precision},${e.scale})`}const u=/^viborm:decimal\((\d+),(\d+)\)$/;function d(n){if(!n)return;let r=u.exec(n);if(!r)return;let i=t(r[1],r[2],`mysql`);if(i!==void 0)return i;throw new e(`MySQL column comment has invalid reserved decimal-list marker.`,`V4002`)}function f(e){if(e.decimal===void 0)return;let t=e.type.toUpperCase().replace(/\s+/g,` `).trim(),r=n(`mysql`,e.decimal);return t===r||t.startsWith(`${r} `)?`scalar`:t===h?`list`:void 0}function p(e){if(e.decimal===void 0)return;let t=e.type.toUpperCase().replace(/\s+/g,``).trim(),r=n(`pg`,e.decimal);return t===r?`scalar`:t===`${r}[]`?`list`:void 0}function m(e){return p(e)??f(e)??i(e)}const h=`JSON`,g=`TEXT`;function _(e,t){return`viborm_decimal_${e===`scalar`?`s`:`l`}_${t.precision}_${t.scale}`}function v(e,t){let n=`${e} = ${e}::${t}`;return t.endsWith(`[]`)?`${e} IS NULL OR (array_position(${e}, NULL) IS NULL AND ${[`NaN`,`Infinity`,`-Infinity`].map(t=>`array_position(${e}, '${t}'::numeric) IS NULL`).join(` AND `)} AND ${n})`:`${e} IS NULL OR (${`${e} NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)`} AND ${n})`}function y(e,t){return`${e} IS NULL OR ${e} = CAST(${e} AS ${t})`}function b(e,t){return`((${e} is null) or (${e} = cast(${e} as ${t})))`}function x(e,t){let n=`("0"|"-?[1-9][0-9]{0,${t.precision-1}}")`;return{rendered:`CAST(${e} AS CHAR CHARACTER SET utf8mb4)`,hq:`^.(${n}(, ${n})*)?.$`}}function S(e,t){let{rendered:n,hq:r}=x(e,t);return`${e} IS NULL OR (LEFT(${n}, 1) = '[' AND RIGHT(${n}, 1) = ']' AND REGEXP_LIKE(${n}, '${r}', 'c'))`}function C(e,t){let{rendered:n,hq:r}=x(e,t),i=n.replace(`CHAR CHARACTER SET`,`char charset`);return`((${e} is null) or ((${`LEFT(${i}, 1)`} = '[') and (${`RIGHT(${i}, 1)`} = ']') and ${`REGEXP_LIKE(${i}, '${r}', 'c')`}))`}export{c as a,y as c,l as d,f,o as i,C as l,d as m,s as n,m as o,v as p,_ as r,b as s,g as t,S as u};
|
|
2
|
+
//# sourceMappingURL=decimal-D4DRlT2y.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decimal-D4DRlT2y.mjs","names":[],"sources":["../src/migrations/decimal.ts"],"sourcesContent":["/**\n * The migration layer's decimal renders.\n *\n * `@validation/primitives/decimal-codec` owns everything VALUE-shaped: the\n * grammar, canonical text, the logical <-> coefficient conversion, and the two\n * DDL renderings (`decimalColumnType`, `decimalDefaultText`). This module owns\n * what only a MIGRATION asks — the questions whose subject is a pair of\n * descriptors or a stored column rather than a value:\n *\n * - whether two snapshots describe the same domain, whether a change narrows\n * it, and which scalar/list storage shape a decimal column carries;\n * - the MySQL column-comment marker for a JSON-backed list; and\n * - the shared validation predicates used by native-decimal migration drivers.\n *\n * Everything here is PURE and connection-free: migration DDL is generated into\n * durable artifacts, so none of it may consult a database.\n *\n * Nothing here re-derives a precision or a scale. Every entry takes the frozen\n * descriptor its caller already holds (plan §1.1: no migration component stores\n * an independent precision or scale decision).\n */\n\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ColumnDef } from \"./types\";\n\n/**\n * Whether moving from `from` to `to` SHRINKS the set of representable values —\n * the destructive half of a descriptor change.\n *\n * Two independent limits move: the fractional digits (`scale`) and the integer\n * digits (`precision - scale`). A change that lowers either one can find a\n * stored value it cannot hold, and the conversion then refuses; a change that\n * raises both is exact for every existing row. Widening the scale while keeping\n * the precision therefore counts as narrowing, because it takes an integer\n * digit away — `NUMERIC(10,2)` holds 99999999.99 and `NUMERIC(10,5)` does not.\n */\nexport function decimalDomainNarrows(\n from: DecimalDescriptor,\n to: DecimalDescriptor\n): boolean {\n const integerDigitsLost =\n to.precision - to.scale < from.precision - from.scale;\n return integerDigitsLost || to.scale < from.scale;\n}\n\n/**\n * Whether this alteration moves stored values INTO a declared decimal domain —\n * the ONE signal every provider's conversion route reads.\n *\n * Only the TARGET has to declare a domain. An absent source descriptor does not\n * make the change descriptor-free: it means the stored values were written\n * under some other reading, and adopting them under this one is exactly the\n * transition §7.3 governs. Skipping the conversion there is what silently\n * reinterprets a PostgreSQL `numeric` by rounding it through the `USING` cast,\n * and what copies a SQLite integer into a coefficient column at a scale it was\n * never written at. Each provider answers the absent source in its own terms —\n * PostgreSQL's target-domain CHECK is a complete proof on its own, and the\n * SQLite copy reads an untyped `INTEGER` as the logical integer it is — but the\n * QUESTION is one, so this is one predicate.\n *\n * The physical type is part of it beside the descriptor, because a scalar that\n * becomes a list keeps its precision and scale while changing storage class\n * completely. It is compared case-insensitively, the same reading the differ\n * takes: one snapshot side is the serializer's spelling and the other is\n * whatever the catalog answered.\n */\nexport function decimalConversionRequired(\n from: ColumnDef,\n to: ColumnDef\n): boolean {\n if (to.decimal === undefined) return false;\n return (\n !sameDecimalDescriptor(from.decimal, to.decimal) ||\n from.type.toUpperCase() !== to.type.toUpperCase()\n );\n}\n\n/**\n * Whether this alteration can lose data because the target domain is smaller.\n * The migration differ's destructive classifier is the sole consumer-facing\n * decision owner; this function owns only the decimal-domain question it asks.\n */\nexport function decimalChangeNarrows(from: ColumnDef, to: ColumnDef): boolean {\n if (from.decimal === undefined || to.decimal === undefined) return false;\n return decimalDomainNarrows(from.decimal, to.decimal);\n}\n\n/**\n * A storage shape, spelled for a refusal MESSAGE.\n *\n * `undefined` is a real answer here and it has to say so: it means the column's\n * declared type is neither of the two spellings this layer writes, which is a\n * different fact from \"the domain moved\" and must not be reported as one.\n */\nexport function describeDecimalStorageKind(\n kind: DecimalStorageKind | undefined\n): string {\n return kind ?? \"unrecognized\";\n}\n\n// =============================================================================\n// THE MYSQL DESCRIPTOR CARRIER\n// =============================================================================\n\n/**\n * The deterministic VibORM-owned column-comment marker for a JSON-backed MySQL\n * decimal list.\n *\n * A `DECIMAL(p,s)` column spells its own domain, but a decimal LIST is stored\n * as `JSON` (MySQL has no array type), and JSON carries nothing. The marker is\n * that column's descriptor, and it is the whole comment: introspection\n * recognizes only the exact marker (§6.2), so a hand-written comment that\n * merely mentions a decimal is not a descriptor.\n */\nexport function mysqlDecimalListMarker(descriptor: DecimalDescriptor): string {\n return `viborm:decimal(${descriptor.precision},${descriptor.scale})`;\n}\n\nconst MYSQL_LIST_MARKER = /^viborm:decimal\\((\\d+),(\\d+)\\)$/;\n\n/**\n * The domain a MySQL column comment declares, or `undefined` when it is not the\n * reserved marker. A marker-shaped comment with an invalid domain refuses.\n */\nexport function readMysqlDecimalListMarker(\n comment: string | null | undefined\n): DecimalDescriptor | undefined {\n if (!comment) return undefined;\n const match = MYSQL_LIST_MARKER.exec(comment);\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"mysql\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n \"MySQL column comment has invalid reserved decimal-list marker.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n\n// =============================================================================\n// THE DIALECT STORAGE SHAPES\n// =============================================================================\n\n/**\n * How one dialect physically holds a decimal: one value, or a container of\n * them. The migration layer reads it off the column rather than the model,\n * because a snapshot side may have come from introspection.\n */\nexport type { DecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\nimport {\n type DecimalStorageKind,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\n\nexport {\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nexport { sqliteDecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\n/**\n * The storage shape of a MySQL decimal column, or `undefined` when the column\n * holds no decimal.\n *\n * A scalar spells its own domain in `DECIMAL(p,s)` — introspection reads it\n * back lowercased, so the comparison is case-insensitive — and a list is the\n * `JSON` container every MySQL list gets, carrying its domain in the\n * column-comment marker instead.\n *\n * A MODIFIER after the domain does not change the storage shape.\n * `decimal(10,2) unsigned` and `decimal(10,2) zerofill` are the same physical\n * decimal, introspected verbatim through `formatColumnType`'s modifier arm, and\n * a shape of `undefined` for them would refuse the very ALTER that normalizes\n * them — an estate that could never converge. The domain token itself still has\n * to match the descriptor EXACTLY, so `DECIMAL(10,20)` is not `DECIMAL(10,2)`\n * with a modifier.\n */\nexport function mysqlDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \" \").trim();\n const scalar = decimalColumnType(\"mysql\", column.decimal);\n if (type === scalar || type.startsWith(`${scalar} `)) return \"scalar\";\n return type === MYSQL_DECIMAL_LIST_TYPE ? \"list\" : undefined;\n}\n\n/** PostgreSQL's native scalar and native-array decimal storage shapes. */\nexport function postgresDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \"\").trim();\n const scalar = decimalColumnType(\"pg\", column.decimal);\n if (type === scalar) return \"scalar\";\n return type === `${scalar}[]` ? \"list\" : undefined;\n}\n\n/**\n * The provider-independent scalar/list identity of a migration decimal.\n *\n * Rename detection needs the shape, not typmod equality: changing a decimal\n * descriptor necessarily changes PostgreSQL/MySQL's physical type spelling,\n * while it keeps the same value/container identity and can still be a native\n * column rename followed by one exact conversion.\n */\nexport function migrationDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n return (\n postgresDecimalStorageKind(column) ??\n mysqlDecimalStorageKind(column) ??\n sqliteDecimalStorageKind(column)\n );\n}\n\n/** MySQL has no array type; every list is JSON, decimal lists included. */\nexport const MYSQL_DECIMAL_LIST_TYPE = \"JSON\";\n\n/**\n * TEXT, not the blanket `JSON` every other SQLite list gets: the list's\n * reserved CHECK asserts `typeof = 'text'`, and `JSON` has NUMERIC affinity\n * under SQLite's rules (it contains none of INT/CHAR/CLOB/TEXT/BLOB/REAL/FLOA/\n * DOUB), which would try to convert a numeric-looking container on the way in.\n */\nexport const SQLITE_DECIMAL_LIST_TYPE = \"TEXT\";\n\n// =============================================================================\n// THE PostgreSQL / MySQL VALIDATION PREDICATE\n// =============================================================================\n\n/**\n * The transient constraint a native-decimal conversion validates through.\n *\n * It is added, kept live ACROSS the type change, and dropped after. That\n * ordering is the whole design: the constraint proves every EXISTING row\n * already fits the target domain, and — because it stays — no concurrent write\n * can land a value the target would have to round while the conversion runs.\n * It is how \"while writes are excluded\" is spelled on MySQL, whose `LOCK\n * TABLES` the artifact classifier refuses as a transaction leader.\n */\n/**\n * The compact identity of one transient conversion proof.\n *\n * The table and column deliberately stay out of this identity: MySQL can\n * publish a different table-name spelling through `lower_case_table_names`,\n * while an interrupted proof must authenticate before the original spelling\n * is available again. The exact catalog CHECK authenticates its table and\n * column instead. Kind, precision and scale are already a small, bounded,\n * collision-free identity, so spelling them directly is both shorter and\n * stronger than hashing them: recovery can authenticate the declared proof\n * without searching or trusting a lossy digest.\n */\nexport function decimalConversionConstraintName(\n kind: DecimalStorageKind,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${kind === \"scalar\" ? \"s\" : \"l\"}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/**\n * \"The target domain admits this value UNCHANGED\", as a CHECK body.\n *\n * One idea, spelled in each dialect's cast syntax: a cast to the target type\n * rounds a value with too many fractional digits and refuses one with too many\n * integer digits, so a value that survives the cast intact is exactly a value\n * the conversion does not have to change. That is §7.3's rule — \"convert only\n * when every value fits\", and \"no descriptor change rounds existing data\" —\n * without a per-digit predicate. PostgreSQL's `numeric` also admits special\n * non-finite values, and `NaN` compares equal to itself, so finiteness is an\n * independent part of the proof. Arrays prove it for every member beside the\n * existing NULL-member refusal, while the outer `column IS NULL` continues to\n * admit a nullable whole list.\n *\n * The type token is the one `decimalColumnType` produced for the target column,\n * array suffix included; nothing here re-spells it.\n */\nexport function postgresDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n const unchanged = `${column} = ${column}::${targetType}`;\n if (targetType.endsWith(\"[]\")) {\n const hasNoNonFiniteMember = [\"NaN\", \"Infinity\", \"-Infinity\"]\n .map((value) => `array_position(${column}, '${value}'::numeric) IS NULL`)\n .join(\" AND \");\n return `${column} IS NULL OR (array_position(${column}, NULL) IS NULL AND ${hasNoNonFiniteMember} AND ${unchanged})`;\n }\n const hasFiniteValue = `${column} NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)`;\n return `${column} IS NULL OR (${hasFiniteValue} AND ${unchanged})`;\n}\n\n/** {@link postgresDecimalFitsCheck}'s MySQL spelling. */\nexport function mysqlDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n return `${column} IS NULL OR ${column} = CAST(${column} AS ${targetType})`;\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalFitsCheck}. */\nexport function mysqlDecimalFitsCatalogCheck(\n column: string,\n targetType: string\n): string {\n return `((${column} is null) or (${column} = cast(${column} as ${targetType})))`;\n}\n\nfunction mysqlDecimalListCheckParts(\n column: string,\n descriptor: DecimalDescriptor\n): { readonly rendered: string; readonly normalizedContainer: string } {\n const coefficient = `(\"0\"|\"-?[1-9][0-9]{0,${descriptor.precision - 1}}\")`;\n return {\n rendered: `CAST(${column} AS CHAR CHARACTER SET utf8mb4)`,\n normalizedContainer: `^.(${coefficient}(, ${coefficient})*)?.$`,\n };\n}\n\n/**\n * A MySQL JSON decimal list is already in the target domain without changing\n * one stored byte.\n *\n * MySQL CHECK expressions cannot contain a subquery, so this validates the\n * provider's own normalized JSON rendering as one anchored language. Every\n * member must be a JSON string carrying the canonical coefficient grammar,\n * and the digit bound comes from the narrower descriptor that must remain true\n * across the marker change. `LEFT` and `RIGHT` prove the two brackets while\n * the anchored regular expression uses one character for each. That avoids a\n * backslash whose SQL meaning would depend on `NO_BACKSLASH_ESCAPES`.\n */\nexport function mysqlDecimalListFitsCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n return (\n `${column} IS NULL OR (` +\n `LEFT(${rendered}, 1) = '[' AND RIGHT(${rendered}, 1) = ']' AND ` +\n `REGEXP_LIKE(${rendered}, '${normalizedContainer}', 'c'))`\n );\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalListFitsCheck}. */\nexport function mysqlDecimalListFitsCatalogCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n const catalogRendered = rendered.replace(\n \"CHAR CHARACTER SET\",\n \"char charset\"\n );\n return (\n `((${column} is null) or (` +\n `(${`LEFT(${catalogRendered}, 1)`} = '[') and ` +\n `(${`RIGHT(${catalogRendered}, 1)`} = ']') and ` +\n `${`REGEXP_LIKE(${catalogRendered}, '${normalizedContainer}', 'c')`}))`\n );\n}\n"],"mappings":"mKA0CA,SAAgB,EACd,EACA,EACS,CAGT,OADE,EAAG,UAAY,EAAG,MAAQ,EAAK,UAAY,EAAK,OACtB,EAAG,MAAQ,EAAK,MAwB9C,SAAgB,EACd,EACA,EACS,CAET,OADI,EAAG,UAAY,IAAA,GAAkB,GAEnC,CAAC,EAAsB,EAAK,QAAS,EAAG,QAAQ,EAChD,EAAK,KAAK,aAAa,GAAK,EAAG,KAAK,aAAY,CASpD,SAAgB,EAAqB,EAAiB,EAAwB,CAE5E,OADI,EAAK,UAAY,IAAA,IAAa,EAAG,UAAY,IAAA,GAAkB,GAC5D,EAAqB,EAAK,QAAS,EAAG,QAAQ,CAUvD,SAAgB,EACd,EACQ,CACR,OAAO,GAAQ,eAiBjB,SAAgB,EAAuB,EAAuC,CAC5E,MAAO,kBAAkB,EAAW,UAAU,GAAG,EAAW,MAAM,GAGpE,MAAM,EAAoB,kCAM1B,SAAgB,EACd,EAC+B,CAC/B,GAAI,CAAC,EAAS,OACd,IAAM,EAAQ,EAAkB,KAAK,EAAQ,CAC7C,GAAI,CAAC,EAAO,OACZ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AO,cAAc,EAAO,UAAU,EAAO,MAAM,EAAW,GAI1E,SAAgB,EACd,EACA,EACQ,CACR,MAAO,KAAK,EAAO,gBAAgB,EAAO,UAAU,EAAO,MAAM,EAAW,KAG9E,SAAS,EACP,EACA,EACqE,CACrE,IAAM,EAAc,wBAAwB,EAAW,UAAY,EAAE,KACrE,MAAO,CACL,SAAU,QAAQ,EAAO,iCACzB,oBAAqB,MAAM,EAAY,KAAK,EAAY,QACzD,CAeH,SAAgB,EACd,EACA,EACQ,CACR,GAAM,CAAE,WAAU,uBAAwB,EACxC,EACA,EACD,CACD,MACE,GAAG,EAAO,oBACF,EAAS,uBAAuB,EAAS,6BAClC,EAAS,KAAK,EAAoB,UAKrD,SAAgB,EACd,EACA,EACQ,CACR,GAAM,CAAE,WAAU,uBAAwB,EACxC,EACA,EACD,CACK,EAAkB,EAAS,QAC/B,qBACA,eACD,CACD,MACE,KAAK,EAAO,iBACR,QAAQ,EAAgB,MAAM,eAC9B,SAAS,EAAgB,MAAM,cAChC,eAAe,EAAgB,KAAK,EAAoB,SAAS"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as e,r as t}from"./extension-
|
|
2
|
-
//# sourceMappingURL=defaults-
|
|
1
|
+
import{i as e,r as t}from"./extension-Bf4vO5mp.mjs";import{d as n}from"./model-ByktcCGW.mjs";import{i as r}from"./keys-o4Pl6Vsg.mjs";import{i}from"./schema-BzkBJTF-.mjs";import{pt as a}from"./query-DSEMPA7r.mjs";import{h as o,m as s,n as c,p as l,t as u}from"./rule-words-ojG0-vSf.mjs";function d(e,t){return{seal({next:n}){let r={...n.omit?.config};r[e]=Object.freeze({...r[e],[t]:!0}),n.omit=Object.freeze({config:Object.freeze(r)})}}}const f=new Set([`json`,`vector`,`point`,`blob`]);function p(e,t){let i=Array.isArray(t)?t:[t],{scalars:a}=e[`~`].state;return r(e).pl!==void 0&&i.length>0&&i.every(e=>{let[t,...r]=n(e)?Object.keys(e):[],i=t!==void 0&&Object.hasOwn(a,t)?a[t][`~`].state:void 0,o=i&&e[t];return r.length===0&&(o===`asc`||o===`desc`)&&!i.array&&!f.has(i.type)})?i.map(e=>({...e})):void 0}var m=class{rows;queries;defaults=this;pw=void 0;sb=void 0;#e;constructor(e,t){this.rows=e,this.queries=t}prepare(e,t){return this.queries.tm(e,t)}conjunction(){return null}reads(){return this.#e??=this.queries.n4(this)}selector(){}bound(){}cd(){return!1}aw(){}};const h=new WeakMap;function g(e,t){let n=i(i(h,e,()=>new WeakMap),this.domain,()=>new m(this.domain,e));return{rows:this,domain:n,defaults:n,instant:t}}const _=new Map;var v=class{#e;#t;constructor({iz:e,he:t}){let n={root:_,related:_,...e&&{order:new Map(Object.entries(e))}};this.#t=t,this.#e={domain:n,...t&&{he:t.all},prepare:g}}call(e,t){let n=this.#t;return n?.named?{...this.#e,he:n.of(t)}:this.#e}};const y=e=>new v(e),b=new Set([`orderBy`,`create`,`update`,`fields`]);var x=class extends u{join({key:e,field:t,model:n,kl:r,refuse:i}){e!==`fields.${t}`&&i(`${e} does not take omitted`),r(d(n,t))}};const S=C();function C(){return new x}function w(e,t,r){if(e===void 0)return;if(!n(e))return r(`data is an object of fields`);let i={};for(let[n,a]of Object.entries(e))Object.hasOwn(t,n)||r(`names unknown field "${n}"`),i[n]=a instanceof c&&a.i9?a.i9():a;return i}const T=(e,t)=>t===void 0?e:{...e,...t};function E(e,r,i){let a={order:{},data:{},xu:[]},{order:o,data:s,xu:c}=a;for(let[a,l]of Object.entries(r)){let r=n=>t(`Extension "${e}" defaults.${a}: ${n}.`,e);Object.hasOwn(i,a)||t(`Extension "${e}" defaults names unknown model "${a}".`,e),n(l)||r(`an entry is an object`);for(let e of Object.keys(l))b.has(e)||r(`"${e}" is not a defaults key`);let d=i[a],{scalars:f}=d[`~`].state;l.orderBy!==void 0&&(o[a]=p(d,l.orderBy)??r(`orderBy maps a model with a key to { field: "asc" | "desc" } terms over its ordered scalars`));for(let e of[`create`,`update`]){let t=w(l[e],f,r);t!==void 0&&(s[a]={...s[a],[e]:T(s[a]?.[e],t)})}if(l.fields!==void 0){n(l.fields)||r(`fields is an object`);for(let[e,t]of Object.entries(l.fields)){let n=`fields.${e}`;t instanceof u||r(`${n} is written omitted`),t.join({model:a,key:n,field:e,schema:i,kl:e=>c.push(e),lazy:!1,entry:()=>r(`${n} is written omitted`),refuse:r})}}}return a}function D(t){let n={join(r){let{name:i,next:s,schema:c}=r,{order:u,data:d,xu:f}=e(r,n,()=>E(i,t(c),c));for(let e of f)r.kl(e);if(Object.keys(u).length>0&&(s.iz={...s.iz,...u}),Object.keys(d).length===0)return;let p=[],m={...s.jq};for(let[e,t]of Object.entries(d)){let n=m[e];m[e]={create:T(n?.create,t.create),update:T(n?.update,t.update)};for(let e of[...Object.values(t.create??{}),...Object.values(t.update??{})])e instanceof a&&e.arg!==void 0&&p.push(e.arg)}o(r,p),s.jq=m,s.he=new l(s.jq)},seal(e){s(e,y)}};return n}function O(e){return D(t=>typeof e==`function`?e(t):e)}export{S as n,O as t};
|
|
2
|
+
//# sourceMappingURL=defaults-BrXUK350.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults-DAPb-tJ4.mjs","names":["#view","#facts","#stamps"],"sources":["../src/client/default-omit-identity.ts","../src/extensions/order.ts","../src/extensions/plain-domain.ts","../src/extensions/defaults.ts"],"sourcesContent":["/**\n * The fields `defaults` leaves out of results (`fields: { f: omitted }`), as\n * a chain meets them: each joined per model with those before it, on the\n * chain (`chain.omit`), which every later chain keeps and the client reads.\n */\nimport type { ExtensionPart } from \"@extensions/chain\";\nimport type { ClientOmitConfig } from \"./omit\";\nimport type { Schema } from \"./types\";\n\n/** What one `omitted` brings: its field left out of its model's results. */\nexport function omitPart(model: string, field: string): ExtensionPart {\n return {\n seal({ next }) {\n const config: ClientOmitConfig<Schema> = { ...next.omit?.config };\n config[model] = Object.freeze({ ...config[model], [field]: true });\n next.omit = Object.freeze({ config: Object.freeze(config) });\n },\n };\n}\n","/**\n * Default order: per model, the order its reads take when the caller gives\n * no `orderBy`. It reads no argument and filters no row.\n */\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\n\nconst UNORDERED_SCALARS = new Set([\"json\", \"vector\", \"point\", \"blob\"]);\n\n/**\n * One model's default order, read once: its terms, each `{ field: \"asc\" |\n * \"desc\" }`, or `undefined` where they are refused. The model must have a\n * row key (its reads end with it, so the order is total) and each field\n * must be one of its scalars that orders as a value (not a list, JSON,\n * vector or point).\n */\nexport function orderOf(\n model: AnyModel,\n given: unknown\n): readonly Input[] | undefined {\n const terms = Array.isArray(given) ? given : [given];\n const { scalars } = model[\"~\"].state;\n const valid =\n getModelKeyCatalog(model).rowKey !== undefined &&\n terms.length > 0 &&\n terms.every((term) => {\n const [field, ...others] = isPlainRecord(term) ? Object.keys(term) : [];\n const state =\n field !== undefined && Object.hasOwn(scalars, field)\n ? scalars[field]![\"~\"].state\n : undefined;\n // A field was read off `term`, so it is a record.\n const direction = state && (term as Input)[field!];\n return (\n others.length === 0 &&\n (direction === \"asc\" || direction === \"desc\") &&\n !state.array &&\n !UNORDERED_SCALARS.has(state.type)\n );\n });\n return valid ? terms.map((term) => ({ ...term })) : undefined;\n}\n","/**\n * The call facts of a chain whose parts order and stamp rows but neither\n * filter, keep nor judge any (`order`, `data`): a domain that answers every\n * question as one with no layer does, so neither the prepared domain, its\n * layers nor what admits predicates comes with them. Once a\n * part of the chain filters or keeps rows, its own binding reads the order\n * and the stamps too.\n */\nimport type {\n PreparedSelector,\n Queries,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n CallRows,\n CallScope,\n ModelDomain,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallRowsBinding, ResolvedExtensionChain } from \"./chain-state\";\nimport type { PreparedDomain } from \"./row-domain\";\nimport type { Stamps } from \"./stamps\";\n\n/**\n * A domain with no layer, prepared for one engine view: it restricts no row,\n * judges and projects nothing, and holds the chain's order. It prepares a\n * predicate as the view does, for whoever asks.\n */\nexport class PlainDomain implements PreparedDomain {\n readonly rows: RowDomain;\n readonly queries: Queries;\n readonly defaults = this;\n readonly judge = undefined;\n readonly project = undefined;\n #view: Queries | undefined;\n constructor(rows: RowDomain, queries: Queries) {\n this.rows = rows;\n this.queries = queries;\n }\n prepare(model: AnyModel, input: Input): PreparedSelector {\n return this.queries.prepareSelector(model, input);\n }\n conjunction(): null {\n return null;\n }\n /** One read view for every call: a plain call carries no value to read. */\n reads(): Queries {\n return (this.#view ??= this.queries.under(this));\n }\n selector(): undefined {\n return undefined;\n }\n bound(): undefined {\n return undefined;\n }\n restrictsLinkWrite(): boolean {\n return false;\n }\n refuseHiddenLinkRow(): void {\n // No row is hidden and no field gated: every link reads as it is.\n }\n}\n\n/** Each plain domain, prepared once per query owner, as a filtered one is. */\nconst prepared = new WeakMap<Queries, WeakMap<RowDomain, PlainDomain>>();\n\nfunction preparePlain(\n this: CallRows,\n queries: Queries,\n instant: () => Date\n): CallScope {\n const domain = memo(\n memo(prepared, queries, () => new WeakMap()),\n this.domain,\n () => new PlainDomain(this.domain, queries)\n );\n return { rows: this, domain, defaults: domain, instant };\n}\n\n/** No model is restricted. */\nconst NONE: ModelDomain = new Map();\n\n/** The facts every call of a plain chain shares; its stamps are its own where they name an argument. */\nclass PlainBinding implements CallRowsBinding {\n readonly #facts: CallRows;\n readonly #stamps: Stamps | undefined;\n constructor({ defaultOrder: order, stamps }: ResolvedExtensionChain) {\n const domain: RowDomain = {\n root: NONE,\n related: NONE,\n ...(order && { order: new Map(Object.entries(order)) }),\n };\n this.#stamps = stamps;\n this.#facts = {\n domain,\n ...(stamps && { stamps: stamps.all }),\n prepare: preparePlain,\n };\n }\n call(_model: string, values: AdmittedArgs | undefined): CallRows {\n const stamps = this.#stamps;\n return stamps?.named\n ? { ...this.#facts, stamps: stamps.of(values) }\n : this.#facts;\n }\n}\n\n/** The call facts of a chain that only orders and stamps rows. */\nexport const bindPlain = (chain: ResolvedExtensionChain): CallRowsBinding =>\n new PlainBinding(chain);\n","/**\n * `defaults({ [model]: { orderBy?, create?, update?, fields? } })`: what\n * holds where the caller says nothing, and the caller may override: the\n * order a read takes without `orderBy`, the fields a create or an update\n * writes where the caller leaves them out, and the fields a result leaves\n * out by default (`fields: { passwordHash: omitted }`, the word bringing\n * what omits). A chain whose parts filter nothing reads them on a domain\n * that filters nothing (`plain-domain.ts`).\n */\nimport { omitPart } from \"@client/default-omit-identity\";\nimport type { Schema } from \"@client/types\";\nimport {\n type ModelStamps,\n Parameter,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { rebind, refuseUndeclared } from \"./call-rows\";\nimport { type ExtensionPart, extensionError, shared } from \"./chain\";\nimport type {\n AnyTarget,\n DefaultsFacts,\n DefaultsInput,\n ExactEntries,\n FromSchema,\n ModelName,\n OmittedWord,\n Part,\n} from \"./contract\";\nimport { orderOf } from \"./order\";\nimport { bindPlain } from \"./plain-domain\";\nimport { CarriedValue, PredicateWord, type Site } from \"./rule-words\";\nimport { Stamps } from \"./stamps\";\n\ntype Entry = Readonly<Record<string, unknown>>;\n\nconst DEFAULTS_KEYS = new Set([\"orderBy\", \"create\", \"update\", \"fields\"]);\n\n/** `omitted`'s value: it brings what omits. */\nclass Omitted extends CarriedValue {\n join({ key, field, model, bring, refuse }: Site): void {\n if (key !== `fields.${field}`) refuse(`${key} does not take omitted`);\n bring(omitPart(model, field!));\n }\n}\n\n/** The field leaves a model's default results; `omit: { f: false }` or a `select` brings it back. */\nexport const omitted: OmittedWord = /* @__PURE__ */ omittedValue();\nfunction omittedValue(): OmittedWord;\nfunction omittedValue(): unknown {\n return new Omitted();\n}\n\n/**\n * One kind's fields as a call writes them, each a constant, the call's\n * instant, or an argument's value (a parameter read per call).\n */\nfunction stampOf(\n given: unknown,\n scalars: Readonly<Record<string, unknown>>,\n refuse: (problem: string) => never\n): Input | undefined {\n if (given === undefined) return undefined;\n if (!isPlainRecord(given)) return refuse(\"data is an object of fields\");\n const out: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(given)) {\n if (!Object.hasOwn(scalars, field))\n refuse(`names unknown field \"${field}\"`);\n out[field] =\n value instanceof PredicateWord && value.stamp ? value.stamp() : value;\n }\n return out;\n}\n\n/** One kind's fields with an extension's own merged in: it wins a field. */\nconst merged = (\n previous: Input | undefined,\n fields: Input | undefined\n): Input | undefined =>\n fields === undefined ? previous : { ...previous, ...fields };\n\n/** What one defaults part writes of one schema. */\ninterface Written {\n /** Per model, the order its reads take without one. */\n readonly order: Record<string, readonly Input[]>;\n /** Per model, the fields its creates and updates write. */\n readonly data: Record<string, ModelStamps>;\n /** The parts its words bring (`omitted`). */\n readonly brought: ExtensionPart[];\n}\n\n/** One defaults part's entries, read once per schema. */\nfunction writeDefaults(name: string, entries: Entry, schema: Schema): Written {\n const written: Written = { order: {}, data: {}, brought: [] };\n const { order, data, brought } = written;\n for (const [model, entry] of Object.entries(entries)) {\n const refuse: (problem: string) => never = (problem) =>\n extensionError(\n `Extension \"${name}\" defaults.${model}: ${problem}.`,\n name\n );\n if (!Object.hasOwn(schema, model))\n extensionError(\n `Extension \"${name}\" defaults names unknown model \"${model}\".`,\n name\n );\n if (!isPlainRecord(entry)) refuse(\"an entry is an object\");\n for (const key of Object.keys(entry))\n if (!DEFAULTS_KEYS.has(key)) refuse(`\"${key}\" is not a defaults key`);\n const own = schema[model]!;\n const { scalars } = own[\"~\"].state;\n if (entry.orderBy !== undefined)\n order[model] =\n orderOf(own, entry.orderBy) ??\n refuse(\n 'orderBy maps a model with a key to { field: \"asc\" | \"desc\" } terms over its ordered scalars'\n );\n for (const kind of [\"create\", \"update\"] as const) {\n const stamp = stampOf(entry[kind], scalars, refuse);\n if (stamp === undefined) continue;\n data[model] = {\n ...data[model],\n [kind]: merged(data[model]?.[kind], stamp),\n };\n }\n if (entry.fields === undefined) continue;\n if (!isPlainRecord(entry.fields)) refuse(\"fields is an object\");\n for (const [field, word] of Object.entries(entry.fields)) {\n const key = `fields.${field}`;\n if (!(word instanceof CarriedValue)) refuse(`${key} is written omitted`);\n word.join({\n model,\n key,\n field,\n schema,\n bring: (part) => brought.push(part),\n lazy: false,\n entry: () => refuse(`${key} is written omitted`),\n refuse,\n });\n }\n }\n return written;\n}\n\n/**\n * `defaults`: the default order (a later entry for a model replaces one)\n * and the default data (a later one wins a field). The arguments a field\n * names are declared on the chain by its own or an earlier extension.\n */\nfunction defaultsPart(read: (schema: Schema) => Entry): ExtensionPart {\n const part: ExtensionPart = {\n join(application) {\n const { name, next, schema } = application;\n const { order, data, brought } = shared(application, part, () =>\n writeDefaults(name, read(schema), schema)\n );\n for (const omits of brought) application.bring(omits);\n if (Object.keys(order).length > 0)\n next.defaultOrder = { ...next.defaultOrder, ...order };\n if (Object.keys(data).length === 0) return;\n const names: string[] = [];\n const entries: Record<string, ModelStamps> = { ...next.defaultData };\n for (const [model, entry] of Object.entries(data)) {\n const known = entries[model];\n entries[model] = {\n create: merged(known?.create, entry.create),\n update: merged(known?.update, entry.update),\n };\n for (const value of [\n ...Object.values(entry.create ?? {}),\n ...Object.values(entry.update ?? {}),\n ])\n if (value instanceof Parameter && value.arg !== undefined)\n names.push(value.arg);\n }\n refuseUndeclared(application, names);\n next.defaultData = entries;\n next.stamps = new Stamps(next.defaultData);\n },\n seal(application) {\n rebind(application, bindPlain);\n },\n };\n return part;\n}\n\n/**\n * What holds where the caller says nothing: the order of reads, the fields\n * writes stamp, the fields results leave out. Given a function of the\n * schema, it is read where the extension is applied.\n */\nexport function defaults<T extends AnyTarget, const D = DefaultsInput<T>>(\n defaults: D &\n (DefaultsInput<T> | FromSchema<T, DefaultsInput<T>>) &\n NoInfer<ExactEntries<D, DefaultsInput<T>>>\n): Part<T, DefaultsFacts<D, ModelName<T>>>;\nexport function defaults(\n entries: Entry | ((schema: Schema) => Entry)\n): unknown {\n return defaultsPart((schema) =>\n typeof entries === \"function\" ? entries(schema) : entries\n );\n}\n"],"mappings":"8RAUA,SAAgB,EAAS,EAAe,EAA8B,CACpE,MAAO,CACL,KAAK,CAAE,QAAQ,CACb,IAAM,EAAmC,CAAE,GAAG,EAAK,MAAM,OAAQ,CACjE,EAAO,GAAS,OAAO,OAAO,CAAE,GAAG,EAAO,IAAS,GAAQ,GAAM,CAAC,CAClE,EAAK,KAAO,OAAO,OAAO,CAAE,OAAQ,OAAO,OAAO,EAAO,CAAE,CAAC,EAE/D,CCRH,MAAM,EAAoB,IAAI,IAAI,CAAC,OAAQ,SAAU,QAAS,OAAO,CAAC,CAStE,SAAgB,EACd,EACA,EAC8B,CAC9B,IAAM,EAAQ,MAAM,QAAQ,EAAM,CAAG,EAAQ,CAAC,EAAM,CAC9C,CAAE,WAAY,EAAM,KAAK,MAmB/B,OAjBE,EAAmB,EAAM,CAAC,SAAW,IAAA,IACrC,EAAM,OAAS,GACf,EAAM,MAAO,GAAS,CACpB,GAAM,CAAC,EAAO,GAAG,GAAU,EAAc,EAAK,CAAG,OAAO,KAAK,EAAK,CAAG,EAAE,CACjE,EACJ,IAAU,IAAA,IAAa,OAAO,OAAO,EAAS,EAAM,CAChD,EAAQ,GAAQ,KAAK,MACrB,IAAA,GAEA,EAAY,GAAU,EAAe,GAC3C,OACE,EAAO,SAAW,IACjB,IAAc,OAAS,IAAc,SACtC,CAAC,EAAM,OACP,CAAC,EAAkB,IAAI,EAAM,KAAK,EAEpC,CACW,EAAM,IAAK,IAAU,CAAE,GAAG,EAAM,EAAE,CAAG,IAAA,GCZtD,IAAa,EAAb,KAAmD,CACjD,KACA,QACA,SAAoB,KACpB,MAAiB,IAAA,GACjB,QAAmB,IAAA,GACnB,GACA,YAAY,EA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AU,EAAE,CAAC,CACrC,CACK,aAAiB,GAAa,EAAM,MAAQ,IAAA,IAC9C,EAAM,KAAK,EAAM,IAAI,CAE3B,EAAiB,EAAa,EAAM,CACpC,EAAK,YAAc,EACnB,EAAK,OAAS,IAAI,EAAO,EAAK,YAAY,EAE5C,KAAK,EAAa,CAChB,EAAO,EAAa,EAAU,EAEjC,CACD,OAAO,EAaT,SAAgB,EACd,EACS,CACT,OAAO,EAAc,GACnB,OAAO,GAAY,WAAa,EAAQ,EAAO,CAAG,EACnD"}
|
|
1
|
+
{"version":3,"file":"defaults-BrXUK350.mjs","names":["#view","#facts","#stamps"],"sources":["../src/client/default-omit-identity.ts","../src/extensions/order.ts","../src/extensions/plain-domain.ts","../src/extensions/defaults.ts"],"sourcesContent":["/**\n * The fields `defaults` leaves out of results (`fields: { f: omitted }`), as\n * a chain meets them: each joined per model with those before it, on the\n * chain (`chain.omit`), which every later chain keeps and the client reads.\n */\nimport type { ExtensionPart } from \"@extensions/chain\";\nimport type { ClientOmitConfig } from \"./omit\";\nimport type { Schema } from \"./types\";\n\n/** What one `omitted` brings: its field left out of its model's results. */\nexport function omitPart(model: string, field: string): ExtensionPart {\n return {\n seal({ next }) {\n const config: ClientOmitConfig<Schema> = { ...next.omit?.config };\n config[model] = Object.freeze({ ...config[model], [field]: true });\n next.omit = Object.freeze({ config: Object.freeze(config) });\n },\n };\n}\n","/**\n * Default order: per model, the order its reads take when the caller gives\n * no `orderBy`. It reads no argument and filters no row.\n */\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport { getModelKeyCatalog } from \"@schema/model/keys\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\n\nconst UNORDERED_SCALARS = new Set([\"json\", \"vector\", \"point\", \"blob\"]);\n\n/**\n * One model's default order, read once: its terms, each `{ field: \"asc\" |\n * \"desc\" }`, or `undefined` where they are refused. The model must have a\n * row key (its reads end with it, so the order is total) and each field\n * must be one of its scalars that orders as a value (not a list, JSON,\n * vector or point).\n */\nexport function orderOf(\n model: AnyModel,\n given: unknown\n): readonly Input[] | undefined {\n const terms = Array.isArray(given) ? given : [given];\n const { scalars } = model[\"~\"].state;\n const valid =\n getModelKeyCatalog(model).rowKey !== undefined &&\n terms.length > 0 &&\n terms.every((term) => {\n const [field, ...others] = isPlainRecord(term) ? Object.keys(term) : [];\n const state =\n field !== undefined && Object.hasOwn(scalars, field)\n ? scalars[field]![\"~\"].state\n : undefined;\n // A field was read off `term`, so it is a record.\n const direction = state && (term as Input)[field!];\n return (\n others.length === 0 &&\n (direction === \"asc\" || direction === \"desc\") &&\n !state.array &&\n !UNORDERED_SCALARS.has(state.type)\n );\n });\n return valid ? terms.map((term) => ({ ...term })) : undefined;\n}\n","/**\n * The call facts of a chain whose parts order and stamp rows but neither\n * filter, keep nor judge any (`order`, `data`): a domain that answers every\n * question as one with no layer does, so neither the prepared domain, its\n * layers nor what admits predicates comes with them. Once a\n * part of the chain filters or keeps rows, its own binding reads the order\n * and the stamps too.\n */\nimport type {\n PreparedSelector,\n Queries,\n} from \"@query-engine/raptor3/shared/query\";\nimport type {\n CallRows,\n CallScope,\n ModelDomain,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport { type Input, memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { CallRowsBinding, ResolvedExtensionChain } from \"./chain-state\";\nimport type { PreparedDomain } from \"./row-domain\";\nimport type { Stamps } from \"./stamps\";\n\n/**\n * A domain with no layer, prepared for one engine view: it restricts no row,\n * judges and projects nothing, and holds the chain's order. It prepares a\n * predicate as the view does, for whoever asks.\n */\nexport class PlainDomain implements PreparedDomain {\n readonly rows: RowDomain;\n readonly queries: Queries;\n readonly defaults = this;\n readonly judge = undefined;\n readonly project = undefined;\n #view: Queries | undefined;\n constructor(rows: RowDomain, queries: Queries) {\n this.rows = rows;\n this.queries = queries;\n }\n prepare(model: AnyModel, input: Input): PreparedSelector {\n return this.queries.prepareSelector(model, input);\n }\n conjunction(): null {\n return null;\n }\n /** One read view for every call: a plain call carries no value to read. */\n reads(): Queries {\n return (this.#view ??= this.queries.under(this));\n }\n selector(): undefined {\n return undefined;\n }\n bound(): undefined {\n return undefined;\n }\n restrictsLinkWrite(): boolean {\n return false;\n }\n refuseHiddenLinkRow(): void {\n // No row is hidden and no field gated: every link reads as it is.\n }\n}\n\n/** Each plain domain, prepared once per query owner, as a filtered one is. */\nconst prepared = new WeakMap<Queries, WeakMap<RowDomain, PlainDomain>>();\n\nfunction preparePlain(\n this: CallRows,\n queries: Queries,\n instant: () => Date\n): CallScope {\n const domain = memo(\n memo(prepared, queries, () => new WeakMap()),\n this.domain,\n () => new PlainDomain(this.domain, queries)\n );\n return { rows: this, domain, defaults: domain, instant };\n}\n\n/** No model is restricted. */\nconst NONE: ModelDomain = new Map();\n\n/** The facts every call of a plain chain shares; its stamps are its own where they name an argument. */\nclass PlainBinding implements CallRowsBinding {\n readonly #facts: CallRows;\n readonly #stamps: Stamps | undefined;\n constructor({ defaultOrder: order, stamps }: ResolvedExtensionChain) {\n const domain: RowDomain = {\n root: NONE,\n related: NONE,\n ...(order && { order: new Map(Object.entries(order)) }),\n };\n this.#stamps = stamps;\n this.#facts = {\n domain,\n ...(stamps && { stamps: stamps.all }),\n prepare: preparePlain,\n };\n }\n call(_model: string, values: AdmittedArgs | undefined): CallRows {\n const stamps = this.#stamps;\n return stamps?.named\n ? { ...this.#facts, stamps: stamps.of(values) }\n : this.#facts;\n }\n}\n\n/** The call facts of a chain that only orders and stamps rows. */\nexport const bindPlain = (chain: ResolvedExtensionChain): CallRowsBinding =>\n new PlainBinding(chain);\n","/**\n * `defaults({ [model]: { orderBy?, create?, update?, fields? } })`: what\n * holds where the caller says nothing, and the caller may override: the\n * order a read takes without `orderBy`, the fields a create or an update\n * writes where the caller leaves them out, and the fields a result leaves\n * out by default (`fields: { passwordHash: omitted }`, the word bringing\n * what omits). A chain whose parts filter nothing reads them on a domain\n * that filters nothing (`plain-domain.ts`).\n */\nimport { omitPart } from \"@client/default-omit-identity\";\nimport type { Schema } from \"@client/types\";\nimport {\n type ModelStamps,\n Parameter,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { rebind, refuseUndeclared } from \"./call-rows\";\nimport { type ExtensionPart, extensionError, shared } from \"./chain\";\nimport type {\n AnyTarget,\n DefaultsFacts,\n DefaultsInput,\n ExactEntries,\n FromSchema,\n ModelName,\n OmittedWord,\n Part,\n} from \"./contract\";\nimport { orderOf } from \"./order\";\nimport { bindPlain } from \"./plain-domain\";\nimport { CarriedValue, PredicateWord, type Site } from \"./rule-words\";\nimport { Stamps } from \"./stamps\";\n\ntype Entry = Readonly<Record<string, unknown>>;\n\nconst DEFAULTS_KEYS = new Set([\"orderBy\", \"create\", \"update\", \"fields\"]);\n\n/** `omitted`'s value: it brings what omits. */\nclass Omitted extends CarriedValue {\n join({ key, field, model, bring, refuse }: Site): void {\n if (key !== `fields.${field}`) refuse(`${key} does not take omitted`);\n bring(omitPart(model, field!));\n }\n}\n\n/** The field leaves a model's default results; `omit: { f: false }` or a `select` brings it back. */\nexport const omitted: OmittedWord = /* @__PURE__ */ omittedValue();\nfunction omittedValue(): OmittedWord;\nfunction omittedValue(): unknown {\n return new Omitted();\n}\n\n/**\n * One kind's fields as a call writes them, each a constant, the call's\n * instant, or an argument's value (a parameter read per call).\n */\nfunction stampOf(\n given: unknown,\n scalars: Readonly<Record<string, unknown>>,\n refuse: (problem: string) => never\n): Input | undefined {\n if (given === undefined) return undefined;\n if (!isPlainRecord(given)) return refuse(\"data is an object of fields\");\n const out: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(given)) {\n if (!Object.hasOwn(scalars, field))\n refuse(`names unknown field \"${field}\"`);\n out[field] =\n value instanceof PredicateWord && value.stamp ? value.stamp() : value;\n }\n return out;\n}\n\n/** One kind's fields with an extension's own merged in: it wins a field. */\nconst merged = (\n previous: Input | undefined,\n fields: Input | undefined\n): Input | undefined =>\n fields === undefined ? previous : { ...previous, ...fields };\n\n/** What one defaults part writes of one schema. */\ninterface Written {\n /** Per model, the order its reads take without one. */\n readonly order: Record<string, readonly Input[]>;\n /** Per model, the fields its creates and updates write. */\n readonly data: Record<string, ModelStamps>;\n /** The parts its words bring (`omitted`). */\n readonly brought: ExtensionPart[];\n}\n\n/** One defaults part's entries, read once per schema. */\nfunction writeDefaults(name: string, entries: Entry, schema: Schema): Written {\n const written: Written = { order: {}, data: {}, brought: [] };\n const { order, data, brought } = written;\n for (const [model, entry] of Object.entries(entries)) {\n const refuse: (problem: string) => never = (problem) =>\n extensionError(\n `Extension \"${name}\" defaults.${model}: ${problem}.`,\n name\n );\n if (!Object.hasOwn(schema, model))\n extensionError(\n `Extension \"${name}\" defaults names unknown model \"${model}\".`,\n name\n );\n if (!isPlainRecord(entry)) refuse(\"an entry is an object\");\n for (const key of Object.keys(entry))\n if (!DEFAULTS_KEYS.has(key)) refuse(`\"${key}\" is not a defaults key`);\n const own = schema[model]!;\n const { scalars } = own[\"~\"].state;\n if (entry.orderBy !== undefined)\n order[model] =\n orderOf(own, entry.orderBy) ??\n refuse(\n 'orderBy maps a model with a key to { field: \"asc\" | \"desc\" } terms over its ordered scalars'\n );\n for (const kind of [\"create\", \"update\"] as const) {\n const stamp = stampOf(entry[kind], scalars, refuse);\n if (stamp === undefined) continue;\n data[model] = {\n ...data[model],\n [kind]: merged(data[model]?.[kind], stamp),\n };\n }\n if (entry.fields === undefined) continue;\n if (!isPlainRecord(entry.fields)) refuse(\"fields is an object\");\n for (const [field, word] of Object.entries(entry.fields)) {\n const key = `fields.${field}`;\n if (!(word instanceof CarriedValue)) refuse(`${key} is written omitted`);\n word.join({\n model,\n key,\n field,\n schema,\n bring: (part) => brought.push(part),\n lazy: false,\n entry: () => refuse(`${key} is written omitted`),\n refuse,\n });\n }\n }\n return written;\n}\n\n/**\n * `defaults`: the default order (a later entry for a model replaces one)\n * and the default data (a later one wins a field). The arguments a field\n * names are declared on the chain by its own or an earlier extension.\n */\nfunction defaultsPart(read: (schema: Schema) => Entry): ExtensionPart {\n const part: ExtensionPart = {\n join(application) {\n const { name, next, schema } = application;\n const { order, data, brought } = shared(application, part, () =>\n writeDefaults(name, read(schema), schema)\n );\n for (const omits of brought) application.bring(omits);\n if (Object.keys(order).length > 0)\n next.defaultOrder = { ...next.defaultOrder, ...order };\n if (Object.keys(data).length === 0) return;\n const names: string[] = [];\n const entries: Record<string, ModelStamps> = { ...next.defaultData };\n for (const [model, entry] of Object.entries(data)) {\n const known = entries[model];\n entries[model] = {\n create: merged(known?.create, entry.create),\n update: merged(known?.update, entry.update),\n };\n for (const value of [\n ...Object.values(entry.create ?? {}),\n ...Object.values(entry.update ?? {}),\n ])\n if (value instanceof Parameter && value.arg !== undefined)\n names.push(value.arg);\n }\n refuseUndeclared(application, names);\n next.defaultData = entries;\n next.stamps = new Stamps(next.defaultData);\n },\n seal(application) {\n rebind(application, bindPlain);\n },\n };\n return part;\n}\n\n/**\n * What holds where the caller says nothing: the order of reads, the fields\n * writes stamp, the fields results leave out. Given a function of the\n * schema, it is read where the extension is applied.\n */\nexport function defaults<T extends AnyTarget, const D = DefaultsInput<T>>(\n defaults: D &\n (DefaultsInput<T> | FromSchema<T, DefaultsInput<T>>) &\n NoInfer<ExactEntries<D, DefaultsInput<T>>>\n): Part<T, DefaultsFacts<D, ModelName<T>>>;\nexport function defaults(\n entries: Entry | ((schema: Schema) => Entry)\n): unknown {\n return defaultsPart((schema) =>\n typeof entries === \"function\" ? entries(schema) : entries\n );\n}\n"],"mappings":"8RAUA,SAAgB,EAAS,EAAe,EAA8B,CACpE,MAAO,CACL,KAAK,CAAE,QAAQ,CACb,IAAM,EAAmC,CAAE,GAAG,EAAK,MAAM,OAAQ,CACjE,EAAO,GAAS,OAAO,OAAO,CAAE,GAAG,EAAO,IAA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Ft as ScalarType, Go as NativeTypeMap, Ha as ReferentialAction, Ji as IndexType, Uo as NativeType, Va as JunctionReferentialAction, jt as AutoGenerateType, sa as JsonValue } from "./database-adapter-
|
|
1
|
+
import { Ft as ScalarType, Go as NativeTypeMap, Ha as ReferentialAction, Ji as IndexType, Uo as NativeType, Va as JunctionReferentialAction, jt as AutoGenerateType, sa as JsonValue } from "./database-adapter-cW0nmWM6.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/schema/json/document.d.ts
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as e,O as t,k as n}from"./error-mapping-B9rSvgG9.mjs";import{
|
|
2
|
-
//# sourceMappingURL=driver-
|
|
1
|
+
import{A as e,O as t,k as n}from"./error-mapping-B9rSvgG9.mjs";import{N as r}from"./model-ByktcCGW.mjs";import{t as i}from"./validation-CEnhYqhl.mjs";import{h as a,i as o}from"./unit-words-DjVhRXAQ.mjs";import{E as s,_ as c,a as l,c as u,n as d,r as f,t as p}from"./spans-CVl3RKUR.mjs";const m=`:reval`,h=3e4;function g(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}async function _(e,t,n){let r=`${t}${m}`;if(!n)return await e.delete([r]),!1;let i=await e.get(r);return i&&e.now()-i.createdAt<i.ttl?!1:(await e.set(r,h,{value:!0,createdAt:e.now(),ttl:h}),!0)}const v=`viborm`,y=`${v}:cache`;function b(e){return e.split(``).map(e=>e.charCodeAt(0).toString(16).padStart(4,`0`)).join(``)}function x(e){if(e===void 0)return`u`;if(typeof e==`number`){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!1),`n:${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}return`s:${b(e)}`}function S(e){return[y,`r6`,`d:${b(e.dialect)}`,e.namespace===void 0?`x`:`k:${b(e.namespace)}`,x(e.version)].join(`:`)}function C(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(n>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}const w=/^(\d+(?:\.\d+)?)\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/,T=[1,1e3,6e4,36e5,864e5,6048e5,2592e6];function E(t){if(typeof t==`number`){if(!Number.isFinite(t)||t<=0||t>2**53-1)throw new e(`TTL must be positive, got: ${t}`);return t}let n=w.exec(t.trim().toLowerCase());if(!n)throw new e(`Invalid TTL format: "${t}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`);let r=Math.floor(Number.parseFloat(n[1])*T[n.slice(2).findIndex(e=>e!==void 0)]);if(!Number.isSafeInteger(r)||r<=0)throw new e(`TTL must be positive, got: ${r}ms from "${t}"`);return r}const D=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function O(e){return e===void 0||e.autoInvalidate===!0||e.invalidate!==void 0&&e.invalidate.length>0}const k=300*1e3,A=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),k),E),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:E(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:k,swr:!1,bypass:!1}}),j=Object.freeze([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function M(e,n){throw new t(`Invalid ${e}: ${n.map(e=>e.message).join(`, `)}`)}function N(e){let t=i(D,e);t.issues&&M(`mutation cache options`,t.issues);let{autoInvalidate:n,invalidate:r}=t.value;if(r===void 0)return Object.freeze({autoInvalidate:n});let a=[...r];return Object.freeze(a),Object.freeze({autoInvalidate:n,invalidate:a})}function P(e){let t=i(A,e);t.issues&&M(`cache options`,t.issues);let{bypass:n,key:r,ttl:a,swr:o}=t.value;return Object.freeze({ttlMs:a,swr:o===void 0||o===!1?!1:a+(o===!0?a:o),bypass:n,...r===void 0?{}:{key:r}})}const F=(e,t,n,r)=>({log:`cache`,at:Date.now(),meta:{event:e,status:t},error:n,...r});function I(e,t,n,r){o(e,F(`miss`,`cache-set-failed`,t))||o(n,F(`miss`,`cache-set-failed`,t,r))}function L(e,t,n,r,i){if(t===void 0)return r();let o={[p]:n,...i===void 0?{}:{[f]:String(i)},...e===`delete`||e===`clear`?{[c]:void 0}:{}};return a(t,{kind:`cache`,operation:e,note:{span:`viborm.cache.${e}`,attributes:o}},r)}const R=(e,t)=>({...F(`revalidate`,`start`,void 0,e),span:s,root:!0,database:t,attributes:{[l]:e.model,[u]:e.operation}}),z={now:()=>Date.now(),setTimeout:(e,t)=>{let n=setTimeout(e,t);return{cancel:()=>clearTimeout(n),unref:()=>n.unref?.()}}},B=Symbol(`serve`),V=Symbol(`invalidate`),H=Symbol(`get`),U=Symbol(`set`),W=Symbol(`drop`),G=Symbol(`backend`);function K(e,t){if(t.startsWith(`${v}:`))throw new n(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${e}:${t}`}var q=class{static get name(){return`CacheDriver`}#e=0;driverName;clock;constructor(e,t=z){this.driverName=e,this.clock=t}async[B](e){let{id:t,read:n,namespace:r,codec:i,model:a,operation:s,origin:c}=e,l=K(r,`${a}:${s}:${C(t)}${n.key===void 0?``:`:${n.key}`}`),u=JSON.stringify([t,n.key]),d=this.#e,f=(e,t)=>this[U](l,e,{ttl:n.ttlMs,swrTtl:n.swr||void 0},c,t,u,d),p=`bypass`;if(!n.bypass){let t=await this[H](l,c);if(t?.identity===u){let{createdAt:n,ttl:r,expiresAt:a}=t;if([n,r,a].every(Number.isFinite)&&r>0&&a>=n){let a=i.materialize(t.value),s=this.clock.now();if(s-n<r)return o(c,F(`hit`)),a;if(e.revalidate?.({request:e,entry:t,now:s,key:l,backend:this[G](),store:f}))return a}}p=`miss`}let m=await i.run();if(d===this.#e)try{g(f(i.snapshot(),e),e.waitUntil)}catch(e){o(c,F(`miss`,`cache-set-failed`,e))}return o(c,F(p)),m}async[H](e,t){return L(`get`,t,this.driverName,async t=>{let n=await this.get(e);return t!==void 0&&o(t,{attributes:{[d]:n?this.clock.now()-n.createdAt>n.ttl?`stale`:`hit`:`miss`}}),n})}async[U](e,t,n,r,i,a,o){if(o!==void 0&&o!==this.#e)return;let s=n.swrTtl??n.ttl,c=this.clock.now(),l={value:t,createdAt:c,ttl:n.ttl,...a===void 0?{}:{identity:a,expiresAt:c+s}};return L(`set`,r,this.driverName,async t=>{try{await this.set(e,s,l),o!==void 0&&o!==this.#e&&await this.delete([e])}catch(e){throw i!==void 0&&t!==void 0&&I(i.origin,e,t,i),e}},n.ttl)}[G](){return{get:e=>this.get(e),set:(e,t,n)=>this.set(e,t,n),delete:e=>this.delete(e),now:()=>this.clock.now()}}async[V](e,t,n,r){if(!O(t))return;this.#e+=1;let i=t===void 0||t.autoInvalidate===!0?[[`clear`,r(e)]]:[];for(let e of t?.invalidate??[])i.push(e.endsWith(`*`)?[`clear`,r(e.slice(0,-1))]:[`delete`,r(e)]);return L(`invalidate`,n,this.driverName,async e=>{await Promise.all(i.map(([t,n])=>this[W](t,n,e)))})}[W](e,t,n){return this.#e+=1,L(e,n,this.driverName,()=>e===`clear`?this.clear(t):this.delete([t,`${t}${m}`]))}};export{S as _,V as a,K as c,j as d,N as f,y as g,v as h,H as i,F as l,O as m,q as n,B as o,P as p,W as r,U as s,G as t,R as u,_ as v,g as y};
|
|
2
|
+
//# sourceMappingURL=driver-BOsmU3kz.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver-kiIQS_Fd.mjs","names":["v"],"sources":["../src/cache/cache-background.ts","../src/cache/key.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/units.ts","../src/cache/driver.ts"],"sourcesContent":["import type { CacheEntry, WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nconst REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n\n/** A driver's own storage primitives, unobserved, and its clock. */\nexport interface Backend {\n get(key: string): Promise<CacheEntry | null>;\n set(key: string, ttl: number, entry: CacheEntry): Promise<void>;\n delete(keys: string[]): Promise<void>;\n now(): number;\n}\n\n/**\n * Claim the refresh of the entry at `key` (whether this caller performs\n * it), or release the claim: a marker beside the entry, with a short TTL.\n */\nexport async function marker(\n backend: Backend,\n key: string,\n claim: boolean\n): Promise<boolean> {\n const marked = `${key}${REVALIDATING_SUFFIX}`;\n if (!claim) {\n await backend.delete([marked]);\n return false;\n }\n const existing = await backend.get(marked);\n if (existing && backend.now() - existing.createdAt < existing.ttl)\n return false;\n await backend.set(marked, REVALIDATING_TTL_MS, {\n value: true,\n createdAt: backend.now(),\n ttl: REVALIDATING_TTL_MS,\n });\n return true;\n}\n","/**\n * Cache key spaces: the official namespace one cache scope partitions on,\n * and the hash that names an entry inside it. What a read is keyed on is the\n * prepared call itself (`key(run)`).\n */\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for the official cache extension's scopes. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\n// r5 entries are keyed by the prepared call (`key(run)`): the statement the\n// engine sends, so a rule's filter, order and projection key an entry by\n// what they do to that statement.\n// r6 entries hold the rows the driver returned, not the decoded answer: an r5\n// answer read as rows would be refused at best.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r6\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n // `split(\"\")` gives the code units, never a pair as one code point.\n return value\n .split(\"\")\n .map((unit) => unit.charCodeAt(0).toString(16).padStart(4, \"0\"))\n .join(\"\");\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n return `n:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n // `x` unknown, `k:<hex>` known. An unknown namespace is a bare `x` with\n // no body, so it cannot be reached by encoding any string whatsoever — a\n // database literally named `undefined` encodes as `k:0075...`. Absence is\n // a distinct value here, not a spelling.\n facts.namespace === undefined ? \"x\" : `k:${encodeText(facts.namespace)}`,\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nexport function fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/** `<number> <unit>`, each unit's spellings one group, in the order of `UNIT_MS`. */\nconst TTL_PATTERN =\n /^(\\d+(?:\\.\\d+)?)\\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/;\n\n/** Milliseconds per unit, a month being thirty days. */\nconst UNIT_MS = [1, 1e3, 6e4, 36e5, 864e5, 6048e5, 2592e6];\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const match = TTL_PATTERN.exec(ttl.trim().toLowerCase());\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`\n );\n }\n\n const result = Math.floor(\n Number.parseFloat(match[1]!) *\n UNIT_MS[match.slice(2).findIndex((unit) => unit !== undefined)]!\n );\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import { CacheConfigurationError } from \"@errors\";\nimport { parse } from \"@validation\";\nimport v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\ntype CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nconst cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nconst DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\ntype WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nconst withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n parseTTL\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) =>\n value === undefined || typeof value === \"boolean\"\n ? value\n : parseTTL(value)\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n\n// =============================================================================\n// THE CACHE'S TWO ARGUMENTS, AND THE READS IT SERVES\n// =============================================================================\n\n/**\n * The reads a cached view serves, as its refusal of anything else lists\n * them.\n */\nexport const CACHEABLE: readonly string[] = Object.freeze([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** One read's options, as the cache applies them. */\nexport interface CacheReadOptions {\n readonly ttlMs: number;\n readonly swr: number | false;\n readonly bypass: boolean;\n readonly key?: string;\n}\n\nfunction refused(what: string, issues: readonly { message: string }[]): never {\n throw new CacheConfigurationError(\n `Invalid ${what}: ${issues.map((issue) => issue.message).join(\", \")}`\n );\n}\n\n/**\n * A write's `cache` argument: what it invalidates once durable. Frozen, as\n * the argument a call admitted and nothing else holds.\n */\nexport function admitMutationOptions(value: unknown): CacheInvalidationOptions {\n const parsed = parse(cacheInvalidationSchema, value);\n if (parsed.issues) refused(\"mutation cache options\", parsed.issues);\n const { autoInvalidate, invalidate } = parsed.value;\n if (invalidate === undefined) return Object.freeze({ autoInvalidate });\n const keys = [...invalidate];\n Object.freeze(keys);\n return Object.freeze({ autoInvalidate, invalidate: keys });\n}\n\n/** `$withCache(options)`: the options of every read through the view. */\nexport function admitReadOptions(value: unknown): CacheReadOptions {\n const parsed = parse(withCacheSchema, value);\n if (parsed.issues) refused(\"cache options\", parsed.issues);\n const { bypass, key, ttl, swr } = parsed.value;\n return Object.freeze({\n ttlMs: ttl,\n // The SWR window: the stale window added to the TTL, `true` the TTL again.\n swr:\n swr === undefined || swr === false\n ? false\n : ttl + (swr === true ? ttl : swr),\n bypass,\n ...(key === undefined ? {} : { key }),\n });\n}\n","/**\n * The cache's units (`get`, `set`, `invalidate`, `revalidate`, and the\n * `delete` and `clear` an invalidation runs) and the outcomes of a read\n * (`hit`, a stale `hit`, `miss`, `bypass`, `cache-set-failed`), written with\n * the words any extension has: each step is a `cache` unit it emits with\n * `work` (on the call's context or `run`, a method's scope, or the unit of\n * the step it is part of), and what a presenter shows of it is noted on it\n * with `note`, in the shape the official instrumentation presents any\n * extension's units with (`InstrumentationNote`): the span as the unit\n * starts, then its attributes and its logs. A read's outcomes are noted on\n * the call's own `operation` unit.\n */\nimport type { UnitContext } from \"@extensions/contract\";\nimport type { Database } from \"@extensions/database\";\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport {\n ATTR_CACHE_DRIVER,\n ATTR_CACHE_TTL,\n ATTR_DB_COLLECTION,\n ATTR_DB_OPERATION_NAME,\n ATTR_VIBORM_CORRELATION_ID,\n SPAN_OPERATION,\n type VibORMSpanName,\n} from \"../instrumentation/spans\";\nimport type { InstrumentationNote } from \"../instrumentation/types\";\n\n/** The call a step's logs name: its model and the operation it asked. */\ninterface CacheCall {\n readonly model: string;\n readonly operation: string;\n}\n\n/**\n * One decision of a read, as a cache log presents it: the call is named\n * where the note is not on the call's own unit. Never a key or a suffix.\n */\nexport const cacheOutcome = (\n event: string,\n status?: string,\n error?: unknown,\n call?: CacheCall\n): InstrumentationNote => ({\n log: \"cache\",\n at: Date.now(),\n meta: { event, status },\n error,\n ...call,\n});\n\n/**\n * A background set failure joins its read's outcomes while that read's\n * operation still runs, so it presents after the logical miss; otherwise the\n * set unit presents it itself.\n */\nexport function placeSetFailure(\n background: object,\n failure: unknown,\n unit: UnitContext,\n call: CacheCall | undefined\n): void {\n if (!note(background, cacheOutcome(\"miss\", \"cache-set-failed\", failure)))\n note(unit, cacheOutcome(\"miss\", \"cache-set-failed\", failure, call));\n}\n\n/**\n * Run one cache step as a `cache` unit of the chain `origin` belongs to;\n * `execute` is handed the unit, to note what the step learns. A step asked\n * with no origin (a backend method called directly) belongs to no chain.\n */\nexport function cacheStep<T>(\n step: \"get\" | \"set\" | \"invalidate\" | \"delete\" | \"clear\",\n origin: object | undefined,\n driverName: string,\n execute: (unit?: UnitContext) => Promise<T>,\n ttl?: number\n): Promise<T> {\n if (origin === undefined) return execute();\n const attributes: InstrumentationNote[\"attributes\"] = {\n [ATTR_CACHE_DRIVER]: driverName,\n ...(ttl === undefined ? {} : { [ATTR_CACHE_TTL]: String(ttl) }),\n // A backend step of an invalidation names its driver alone.\n ...(step === \"delete\" || step === \"clear\"\n ? { [ATTR_VIBORM_CORRELATION_ID]: undefined }\n : {}),\n };\n return work(\n origin,\n // Its span is the public `SPAN_CACHE_<STEP>`: spelled from the step,\n // which costs no bytes, and checked against those constants.\n {\n kind: \"cache\",\n operation: step,\n note: {\n span: `viborm.cache.${step}` satisfies VibORMSpanName,\n attributes,\n },\n },\n execute\n );\n}\n\n/**\n * What a revalidation's own `cache` unit starts with: it is presented as the\n * root operation it replays.\n */\nexport const revalidationStart = (\n call: CacheCall,\n database: Database\n): InstrumentationNote => ({\n ...cacheOutcome(\"revalidate\", \"start\", undefined, call),\n span: SPAN_OPERATION,\n root: true,\n database,\n attributes: {\n [ATTR_DB_COLLECTION]: call.model,\n [ATTR_DB_OPERATION_NAME]: call.operation,\n },\n});\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport type { Database } from \"@extensions/database\";\nimport { note } from \"@extensions/unit-words\";\nimport { ATTR_CACHE_RESULT } from \"../instrumentation/spans\";\nimport {\n type Backend,\n REVALIDATING_SUFFIX,\n scheduleBackground,\n} from \"./cache-background\";\nimport { CACHE_PREFIX, fastHash } from \"./key\";\nimport {\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\nimport { cacheOutcome, cacheStep, placeSetFailure } from \"./units\";\n\n/** A timer a `CacheClock` armed, cancelled through its handle. */\nexport interface CacheTimer {\n cancel(): void;\n /** Release the host's hold on the event loop, where it has one. */\n unref?(): void;\n}\n\n/**\n * Where a cache reads time and arms its timers: the host's own, unless a\n * test hands a clock it advances instead of sleeping through a TTL.\n */\nexport interface CacheClock {\n now(): number;\n setTimeout(callback: () => void, ms: number): CacheTimer;\n}\n\nconst hostClock: CacheClock = {\n // Read when called: a test's fake timers replace `Date.now`.\n now: () => Date.now(),\n setTimeout: (callback, ms) => {\n const timer = setTimeout(callback, ms);\n // A host that is not Node hands back a number, with no `unref`.\n return { cancel: () => clearTimeout(timer), unref: () => timer.unref?.() };\n },\n};\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/**\n * One read's codec: `run` runs the prepared read (during the serve, or once\n * after it as a refresh), `snapshot` stores what that run returned.\n */\nexport interface DetachedCacheResultCodec<T> {\n run(): Promise<T>;\n snapshot(): unknown;\n materialize(snapshot: unknown): T;\n}\n\n/** One read the official cache serves, as its extension hands it over. */\ninterface CacheServe<T> {\n /** The prepared call's key: equal for two reads that send one statement. */\n readonly id: string;\n readonly codec: DetachedCacheResultCodec<T>;\n readonly read: CacheReadOptions;\n readonly namespace: string;\n readonly waitUntil: WaitUntilFn | undefined;\n readonly model: string;\n readonly operation: string;\n /** The call's `run`: what the read's units and outcomes belong to. */\n readonly origin: object;\n /** The database the read works against, which a revalidation presents. */\n readonly database: Database;\n /** What refreshes a stale entry: `staleWhileRevalidate`, when the cache was given it. */\n readonly revalidate?: Revalidate | undefined;\n}\n\n/**\n * One stale entry, as the driver hands it over: its read, its entry and\n * age, its prefixed key and the driver's backend (what the marker that\n * claims a refresh uses), and the store of the new rows.\n */\nexport interface Refresh {\n readonly request: CacheServe<unknown>;\n readonly entry: CacheEntry<unknown>;\n readonly now: number;\n readonly key: string;\n readonly backend: Backend;\n store(stored: unknown): Promise<void>;\n}\n\n/**\n * Whether a stale entry is served while it is refreshed in the background:\n * what `swr` brings, so a cache without it carries none of it.\n */\nexport type Revalidate = (refresh: Refresh) => boolean;\n\n/**\n * The keys of the two methods a driver serves its extension with: one read\n * through the store, and a namespace's invalidation. No package entry\n * exports them, so only the cache's own extension calls them.\n */\nexport const SERVE = Symbol(\"serve\");\nexport const INVALIDATE = Symbol(\"invalidate\");\n\n/**\n * The keys of the steps on a prefixed key the driver owns, observed as\n * `cache` units: what its extension and the unscoped storage functions\n * (`storage.ts`, which an application that never calls them does not carry)\n * reach. No package entry exports them either.\n */\nexport const GET = Symbol(\"get\");\nexport const SET = Symbol(\"set\");\nexport const DROP = Symbol(\"drop\");\nexport const BACKEND = Symbol(\"backend\");\n\n/** How a key is dropped: the entries under it, or the one entry it names. */\ntype Drop = \"clear\" | \"delete\";\n\n/**\n * A relative key rebased into an official scope. An EMPTY relative key is\n * the whole scope — `$invalidate(\"*\")` — and it rebases to `<scope>:`, WITH\n * the separator, because the storage backends clear by `startsWith`. A bare\n * `<scope>` would also match every sibling scope whose namespace string\n * merely extends this one, and one axis of the scope grammar can do that:\n * the cache `version` is the last component and its `s:` body is\n * variable-length, so `version: \"a\"` is a strict prefix of `version: \"ab\"`\n * at the same dialect and namespace. That axis is exactly what §7.1 leaves\n * users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's\n * entries. Adding the separator loses nothing: every key this scope can hold\n * is `<model>:<operation>:<hash>`, so no stored key is ever equal to the\n * bare scope.\n */\nexport function scopedKey(namespace: string, key: string): string {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Symbol-keyed steps handle prefixed keys, instrumentation, and delegation\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: CacheClock;\n\n constructor(driverName: string, clock: CacheClock = hostClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async [SERVE]<T>(request: CacheServe<T>): Promise<T> {\n const { id, read, namespace, codec, model, operation, origin } = request;\n const cacheKey = scopedKey(\n namespace,\n `${model}:${operation}:${fastHash(id)}${read.key === undefined ? \"\" : `:${read.key}`}`\n );\n const identity = JSON.stringify([id, read.key]);\n const revision = this.#fillRevision;\n const store = (stored: unknown, background?: CacheServe<unknown>) =>\n this[SET](\n cacheKey,\n stored,\n { ttl: read.ttlMs, swrTtl: read.swr || undefined },\n origin,\n background,\n identity,\n revision\n );\n let outcome = \"bypass\";\n if (!read.bypass) {\n const cached = await this[GET]<unknown>(cacheKey, origin);\n // Read as the backend gives it: an entry of another identity, or whose\n // times are not a finite span, is a miss.\n if (cached?.identity === identity) {\n const { createdAt, ttl, expiresAt } = cached;\n if (\n [createdAt, ttl, expiresAt].every(Number.isFinite) &&\n ttl > 0 &&\n expiresAt! >= createdAt\n ) {\n const value = codec.materialize(cached.value);\n const now = this.clock.now();\n if (now - createdAt < ttl) {\n note(origin, cacheOutcome(\"hit\"));\n return value;\n }\n if (\n request.revalidate?.({\n request,\n entry: cached,\n now,\n key: cacheKey,\n backend: this[BACKEND](),\n store,\n })\n )\n return value;\n }\n }\n outcome = \"miss\";\n }\n const result = await codec.run();\n if (revision === this.#fillRevision) {\n try {\n // The observed set unit presents a failure, which the background\n // promise then holds.\n scheduleBackground(store(codec.snapshot(), request), request.waitUntil);\n } catch (error) {\n note(origin, cacheOutcome(\"miss\", \"cache-set-failed\", error));\n }\n }\n note(origin, cacheOutcome(outcome));\n return result;\n }\n\n // ============================================================\n // STEPS - on prefixed keys, observed as `cache` units\n // ============================================================\n\n async [GET]<T>(\n prefixedKey: string,\n origin?: object\n ): Promise<CacheEntry<T> | null> {\n return cacheStep(\"get\", origin, this.driverName, async (unit) => {\n const entry = await this.get<T>(prefixedKey);\n if (unit !== undefined)\n note(unit, {\n attributes: {\n [ATTR_CACHE_RESULT]: entry\n ? this.clock.now() - entry.createdAt > entry.ttl\n ? \"stale\"\n : \"hit\"\n : \"miss\",\n },\n });\n return entry;\n });\n }\n\n async [SET]<T>(\n prefixedKey: string,\n value: T,\n options: CacheSetOptions,\n origin?: object,\n /** The read a background set belongs to, whose outcomes a failure joins. */\n background?: CacheServe<unknown>,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n const createdAt = this.clock.now();\n const entry: CacheEntry<T> = {\n value,\n createdAt,\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : { identity, expiresAt: createdAt + storageTtl }),\n };\n\n return cacheStep(\n \"set\",\n origin,\n this.driverName,\n async (unit) => {\n try {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n } catch (failure) {\n if (background !== undefined && unit !== undefined)\n placeSetFailure(background.origin, failure, unit, background);\n throw failure;\n }\n },\n options.ttl\n );\n }\n\n /** The backend's own primitives, unobserved, and the clock. */\n [BACKEND](): Backend {\n return {\n get: (key) => this.get(key),\n set: (key, ttl, entry) => this.set(key, ttl, entry),\n delete: (keys) => this.delete(keys),\n now: () => this.clock.now(),\n };\n }\n\n /**\n * Invalidate after a mutation: the entries under `prefix` (relative keys\n * rebased by `prefixed`), and the targets `options` names.\n */\n async [INVALIDATE](\n prefix: string,\n options: CacheInvalidationOptions | undefined,\n origin: object | undefined,\n prefixed: (key: string) => string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n // Every target is rebased, and so validated, before any is dropped.\n const targets: [Drop, string][] =\n options === undefined || options.autoInvalidate === true\n ? [[\"clear\", prefixed(prefix)]]\n : [];\n for (const entry of options?.invalidate ?? [])\n targets.push(\n entry.endsWith(\"*\")\n ? [\"clear\", prefixed(entry.slice(0, -1))]\n : [\"delete\", prefixed(entry)]\n );\n return cacheStep(\"invalidate\", origin, this.driverName, async (unit) => {\n await Promise.all(\n targets.map(([drop, key]) => this[DROP](drop, key, unit))\n );\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n /**\n * Drop the entries under `prefixedKey` (`clear`), or that entry and its\n * revalidation marker (`delete`). Not `async`: a step that fails is\n * rejected by the promise the caller holds, with no promise between them\n * left a tick without a handler (workerd reports one).\n */\n [DROP](drop: Drop, prefixedKey: string, origin?: object): Promise<void> {\n this.#fillRevision += 1;\n return cacheStep(drop, origin, this.driverName, () =>\n drop === \"clear\"\n ? this.clear(prefixedKey)\n : this.delete([prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`])\n );\n }\n}\n"],"mappings":"8RAEA,MAAa,EAAsB,SAC7B,EAAsB,IAE5B,SAAgB,EACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GAiBV,eAAsB,EACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAS,GAAG,IAAM,IACxB,GAAI,CAAC,EAEH,OADA,MAAM,EAAQ,OAAO,CAAC,EAAO,CAAC,CACvB,GAET,IAAM,EAAW,MAAM,EAAQ,IAAI,EAAO,C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I,CAC3B,KAAM,EAAK,EAAK,IAAU,KAAK,IAAI,EAAK,EAAK,EAAM,CACnD,OAAS,GAAS,KAAK,OAAO,EAAK,CACnC,QAAW,KAAK,MAAM,KAAK,CAC5B,CAOH,MAAO,GACL,EACA,EACA,EACA,EACe,CACf,GAAI,CAAC,EAAyB,EAAQ,CAAE,OACxC,MAAA,GAAsB,EAEtB,IAAM,EACJ,IAAY,IAAA,IAAa,EAAQ,iBAAmB,GAChD,CAAC,CAAC,QAAS,EAAS,EAAO,CAAC,CAAA,CAC5B,EAAE,CACR,IAAK,IAAM,KAAS,GAAS,YAAc,EAAE,CAC3C,EAAQ,KACN,EAAM,SAAS,IAAG,CACd,CAAC,QAAS,EAAS,EAAM,MAAM,EAAG,GAAG,CAAC,CAAA,CACtC,CAAC,SAAU,EAAS,EAAM,CAAA,CAC/B,CACH,OAAO,EAAU,aAAc,EAAQ,KAAK,WAAY,KAAO,IAAS,CACtE,MAAM,QAAQ,IACZ,EAAQ,KAAK,CAAC,EAAM,KAAS,KAAK,GAAM,EAAM,EAAK,EAAK,CAAA,CACzD,EACD,CAmBJ,CAAC,GAAM,EAAY,EAAqB,EAAgC,CAEtE,MADA,OAAA,GAAsB,EACf,EAAU,EAAM,EAAQ,KAAK,eAClC,IAAS,QACL,KAAK,MAAM,EAAW,CACtB,KAAK,OAAO,CAAC,EAAa,GAAG,IAAc,IAAsB,CAAA,CACtE"}
|
|
1
|
+
{"version":3,"file":"driver-BOsmU3kz.mjs","names":["v"],"sources":["../src/cache/cache-background.ts","../src/cache/key.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/units.ts","../src/cache/driver.ts"],"sourcesContent":["import type { CacheEntry, WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nconst REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n\n/** A driver's own storage primitives, unobserved, and its clock. */\nexport interface Backend {\n get(key: string): Promise<CacheEntry | null>;\n set(key: string, ttl: number, entry: CacheEntry): Promise<void>;\n delete(keys: string[]): Promise<void>;\n now(): number;\n}\n\n/**\n * Claim the refresh of the entry at `key` (whether this caller performs\n * it), or release the claim: a marker beside the entry, with a short TTL.\n */\nexport async function marker(\n backend: Backend,\n key: string,\n claim: boolean\n): Promise<boolean> {\n const marked = `${key}${REVALIDATING_SUFFIX}`;\n if (!claim) {\n await backend.delete([marked]);\n return false;\n }\n const existing = await backend.get(marked);\n if (existing && backend.now() - existing.createdAt < existing.ttl)\n return false;\n await backend.set(marked, REVALIDATING_TTL_MS, {\n value: true,\n createdAt: backend.now(),\n ttl: REVALIDATING_TTL_MS,\n });\n return true;\n}\n","/**\n * Cache key spaces: the official namespace one cache scope partitions on,\n * and the hash that names an entry inside it. What a read is keyed on is the\n * prepared call itself (`key(run)`).\n */\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for the official cache extension's scopes. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\n// r5 entries are keyed by the prepared call (`key(run)`): the statement the\n// engine sends, so a rule's filter, order and projection key an entry by\n// what they do to that statement.\n// r6 entries hold the rows the driver returned, not the decoded answer: an r5\n// answer read as rows would be refused at best.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r6\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n // `split(\"\")` gives the code units, never a pair as one code point.\n return value\n .split(\"\")\n .map((unit) => unit.charCodeAt(0).toString(16).padStart(4, \"0\"))\n .join(\"\");\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n return `n:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n // `x` unknown, `k:<hex>` known. An unknown namespace is a bare `x` with\n // no body, so it cannot be reached by encoding any string whatsoever — a\n // database literally named `undefined` encodes as `k:0075...`. Absence is\n // a distinct value here, not a spelling.\n facts.namespace === undefined ? \"x\" : `k:${encodeText(facts.namespace)}`,\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nexport function fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/** `<number> <unit>`, each unit's spellings one group, in the order of `UNIT_MS`. */\nconst TTL_PATTERN =\n /^(\\d+(?:\\.\\d+)?)\\s*(?:(ms|milliseconds?)|(s|sec|seconds?)|(m|min|minutes?)|(h|hr|hours?)|(d|days?)|(w|weeks?)|(months?))$/;\n\n/** Milliseconds per unit, a month being thirty days. */\nconst UNIT_MS = [1, 1e3, 6e4, 36e5, 864e5, 6048e5, 2592e6];\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const match = TTL_PATTERN.exec(ttl.trim().toLowerCase());\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\"), the unit one of ms, s, sec, m, min, h, hr, d, w, month, or a word for it.`\n );\n }\n\n const result = Math.floor(\n Number.parseFloat(match[1]!) *\n UNIT_MS[match.slice(2).findIndex((unit) => unit !== undefined)]!\n );\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import { CacheConfigurationError } from \"@errors\";\nimport { parse } from \"@validation\";\nimport v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\ntype CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nconst cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nconst DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\ntype WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nconst withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n parseTTL\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) =>\n value === undefined || typeof value === \"boolean\"\n ? value\n : parseTTL(value)\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n\n// =============================================================================\n// THE CACHE'S TWO ARGUMENTS, AND THE READS IT SERVES\n// =============================================================================\n\n/**\n * The reads a cached view serves, as its refusal of anything else lists\n * them.\n */\nexport const CACHEABLE: readonly string[] = Object.freeze([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** One read's options, as the cache applies them. */\nexport interface CacheReadOptions {\n readonly ttlMs: number;\n readonly swr: number | false;\n readonly bypass: boolean;\n readonly key?: string;\n}\n\nfunction refused(what: string, issues: readonly { message: string }[]): never {\n throw new CacheConfigurationError(\n `Invalid ${what}: ${issues.map((issue) => issue.message).join(\", \")}`\n );\n}\n\n/**\n * A write's `cache` argument: what it invalidates once durable. Frozen, as\n * the argument a call admitted and nothing else holds.\n */\nexport function admitMutationOptions(value: unknown): CacheInvalidationOptions {\n const parsed = parse(cacheInvalidationSchema, value);\n if (parsed.issues) refused(\"mutation cache options\", parsed.issues);\n const { autoInvalidate, invalidate } = parsed.value;\n if (invalidate === undefined) return Object.freeze({ autoInvalidate });\n const keys = [...invalidate];\n Object.freeze(keys);\n return Object.freeze({ autoInvalidate, invalidate: keys });\n}\n\n/** `$withCache(options)`: the options of every read through the view. */\nexport function admitReadOptions(value: unknown): CacheReadOptions {\n const parsed = parse(withCacheSchema, value);\n if (parsed.issues) refused(\"cache options\", parsed.issues);\n const { bypass, key, ttl, swr } = parsed.value;\n return Object.freeze({\n ttlMs: ttl,\n // The SWR window: the stale window added to the TTL, `true` the TTL again.\n swr:\n swr === undefined || swr === false\n ? false\n : ttl + (swr === true ? ttl : swr),\n bypass,\n ...(key === undefined ? {} : { key }),\n });\n}\n","/**\n * The cache's units (`get`, `set`, `invalidate`, `revalidate`, and the\n * `delete` and `clear` an invalidation runs) and the outcomes of a read\n * (`hit`, a stale `hit`, `miss`, `bypass`, `cache-set-failed`), written with\n * the words any extension has: each step is a `cache` unit it emits with\n * `work` (on the call's context or `run`, a method's scope, or the unit of\n * the step it is part of), and what a presenter shows of it is noted on it\n * with `note`, in the shape the official instrumentation presents any\n * extension's units with (`InstrumentationNote`): the span as the unit\n * starts, then its attributes and its logs. A read's outcomes are noted on\n * the call's own `operation` unit.\n */\nimport type { UnitContext } from \"@extensions/contract\";\nimport type { Database } from \"@extensions/database\";\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport {\n ATTR_CACHE_DRIVER,\n ATTR_CACHE_TTL,\n ATTR_DB_COLLECTION,\n ATTR_DB_OPERATION_NAME,\n ATTR_VIBORM_CORRELATION_ID,\n SPAN_OPERATION,\n type VibORMSpanName,\n} from \"../instrumentation/spans\";\nimport type { InstrumentationNote } from \"../instrumentation/types\";\n\n/** The call a step's logs name: its model and the operation it asked. */\ninterface CacheCall {\n readonly model: string;\n readonly operation: string;\n}\n\n/**\n * One decision of a read, as a cache log presents it: the call is named\n * where the note is not on the call's own unit. Never a key or a suffix.\n */\nexport const cacheOutcome = (\n event: string,\n status?: string,\n error?: unknown,\n call?: CacheCall\n): InstrumentationNote => ({\n log: \"cache\",\n at: Date.now(),\n meta: { event, status },\n error,\n ...call,\n});\n\n/**\n * A background set failure joins its read's outcomes while that read's\n * operation still runs, so it presents after the logical miss; otherwise the\n * set unit presents it itself.\n */\nexport function placeSetFailure(\n background: object,\n failure: unknown,\n unit: UnitContext,\n call: CacheCall | undefined\n): void {\n if (!note(background, cacheOutcome(\"miss\", \"cache-set-failed\", failure)))\n note(unit, cacheOutcome(\"miss\", \"cache-set-failed\", failure, call));\n}\n\n/**\n * Run one cache step as a `cache` unit of the chain `origin` belongs to;\n * `execute` is handed the unit, to note what the step learns. A step asked\n * with no origin (a backend method called directly) belongs to no chain.\n */\nexport function cacheStep<T>(\n step: \"get\" | \"set\" | \"invalidate\" | \"delete\" | \"clear\",\n origin: object | undefined,\n driverName: string,\n execute: (unit?: UnitContext) => Promise<T>,\n ttl?: number\n): Promise<T> {\n if (origin === undefined) return execute();\n const attributes: InstrumentationNote[\"attributes\"] = {\n [ATTR_CACHE_DRIVER]: driverName,\n ...(ttl === undefined ? {} : { [ATTR_CACHE_TTL]: String(ttl) }),\n // A backend step of an invalidation names its driver alone.\n ...(step === \"delete\" || step === \"clear\"\n ? { [ATTR_VIBORM_CORRELATION_ID]: undefined }\n : {}),\n };\n return work(\n origin,\n // Its span is the public `SPAN_CACHE_<STEP>`: spelled from the step,\n // which costs no bytes, and checked against those constants.\n {\n kind: \"cache\",\n operation: step,\n note: {\n span: `viborm.cache.${step}` satisfies VibORMSpanName,\n attributes,\n },\n },\n execute\n );\n}\n\n/**\n * What a revalidation's own `cache` unit starts with: it is presented as the\n * root operation it replays.\n */\nexport const revalidationStart = (\n call: CacheCall,\n database: Database\n): InstrumentationNote => ({\n ...cacheOutcome(\"revalidate\", \"start\", undefined, call),\n span: SPAN_OPERATION,\n root: true,\n database,\n attributes: {\n [ATTR_DB_COLLECTION]: call.model,\n [ATTR_DB_OPERATION_NAME]: call.operation,\n },\n});\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport type { Database } from \"@extensions/database\";\nimport { note } from \"@extensions/unit-words\";\nimport { ATTR_CACHE_RESULT } from \"../instrumentation/spans\";\nimport {\n type Backend,\n REVALIDATING_SUFFIX,\n scheduleBackground,\n} from \"./cache-background\";\nimport { CACHE_PREFIX, fastHash } from \"./key\";\nimport {\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\nimport { cacheOutcome, cacheStep, placeSetFailure } from \"./units\";\n\n/** A timer a `CacheClock` armed, cancelled through its handle. */\nexport interface CacheTimer {\n cancel(): void;\n /** Release the host's hold on the event loop, where it has one. */\n unref?(): void;\n}\n\n/**\n * Where a cache reads time and arms its timers: the host's own, unless a\n * test hands a clock it advances instead of sleeping through a TTL.\n */\nexport interface CacheClock {\n now(): number;\n setTimeout(callback: () => void, ms: number): CacheTimer;\n}\n\nconst hostClock: CacheClock = {\n // Read when called: a test's fake timers replace `Date.now`.\n now: () => Date.now(),\n setTimeout: (callback, ms) => {\n const timer = setTimeout(callback, ms);\n // A host that is not Node hands back a number, with no `unref`.\n return { cancel: () => clearTimeout(timer), unref: () => timer.unref?.() };\n },\n};\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/**\n * One read's codec: `run` runs the prepared read (during the serve, or once\n * after it as a refresh), `snapshot` stores what that run returned.\n */\nexport interface DetachedCacheResultCodec<T> {\n run(): Promise<T>;\n snapshot(): unknown;\n materialize(snapshot: unknown): T;\n}\n\n/** One read the official cache serves, as its extension hands it over. */\ninterface CacheServe<T> {\n /** The prepared call's key: equal for two reads that send one statement. */\n readonly id: string;\n readonly codec: DetachedCacheResultCodec<T>;\n readonly read: CacheReadOptions;\n readonly namespace: string;\n readonly waitUntil: WaitUntilFn | undefined;\n readonly model: string;\n readonly operation: string;\n /** The call's `run`: what the read's units and outcomes belong to. */\n readonly origin: object;\n /** The database the read works against, which a revalidation presents. */\n readonly database: Database;\n /** What refreshes a stale entry: `staleWhileRevalidate`, when the cache was given it. */\n readonly revalidate?: Revalidate | undefined;\n}\n\n/**\n * One stale entry, as the driver hands it over: its read, its entry and\n * age, its prefixed key and the driver's backend (what the marker that\n * claims a refresh uses), and the store of the new rows.\n */\nexport interface Refresh {\n readonly request: CacheServe<unknown>;\n readonly entry: CacheEntry<unknown>;\n readonly now: number;\n readonly key: string;\n readonly backend: Backend;\n store(stored: unknown): Promise<void>;\n}\n\n/**\n * Whether a stale entry is served while it is refreshed in the background:\n * what `swr` brings, so a cache without it carries none of it.\n */\nexport type Revalidate = (refresh: Refresh) => boolean;\n\n/**\n * The keys of the two methods a driver serves its extension with: one read\n * through the store, and a namespace's invalidation. No package entry\n * exports them, so only the cache's own extension calls them.\n */\nexport const SERVE = Symbol(\"serve\");\nexport const INVALIDATE = Symbol(\"invalidate\");\n\n/**\n * The keys of the steps on a prefixed key the driver owns, observed as\n * `cache` units: what its extension and the unscoped storage functions\n * (`storage.ts`, which an application that never calls them does not carry)\n * reach. No package entry exports them either.\n */\nexport const GET = Symbol(\"get\");\nexport const SET = Symbol(\"set\");\nexport const DROP = Symbol(\"drop\");\nexport const BACKEND = Symbol(\"backend\");\n\n/** How a key is dropped: the entries under it, or the one entry it names. */\ntype Drop = \"clear\" | \"delete\";\n\n/**\n * A relative key rebased into an official scope. An EMPTY relative key is\n * the whole scope — `$invalidate(\"*\")` — and it rebases to `<scope>:`, WITH\n * the separator, because the storage backends clear by `startsWith`. A bare\n * `<scope>` would also match every sibling scope whose namespace string\n * merely extends this one, and one axis of the scope grammar can do that:\n * the cache `version` is the last component and its `s:` body is\n * variable-length, so `version: \"a\"` is a strict prefix of `version: \"ab\"`\n * at the same dialect and namespace. That axis is exactly what §7.1 leaves\n * users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's\n * entries. Adding the separator loses nothing: every key this scope can hold\n * is `<model>:<operation>:<hash>`, so no stored key is ever equal to the\n * bare scope.\n */\nexport function scopedKey(namespace: string, key: string): string {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Symbol-keyed steps handle prefixed keys, instrumentation, and delegation\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: CacheClock;\n\n constructor(driverName: string, clock: CacheClock = hostClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async [SERVE]<T>(request: CacheServe<T>): Promise<T> {\n const { id, read, namespace, codec, model, operation, origin } = request;\n const cacheKey = scopedKey(\n namespace,\n `${model}:${operation}:${fastHash(id)}${read.key === undefined ? \"\" : `:${read.key}`}`\n );\n const identity = JSON.stringify([id, read.key]);\n const revision = this.#fillRevision;\n const store = (stored: unknown, background?: CacheServe<unknown>) =>\n this[SET](\n cacheKey,\n stored,\n { ttl: read.ttlMs, swrTtl: read.swr || undefined },\n origin,\n background,\n identity,\n revision\n );\n let outcome = \"bypass\";\n if (!read.bypass) {\n const cached = await this[GET]<unknown>(cacheKey, origin);\n // Read as the backend gives it: an entry of another identity, or whose\n // times are not a finite span, is a miss.\n if (cached?.identity === identity) {\n const { createdAt, ttl, expiresAt } = cached;\n if (\n [createdAt, ttl, expiresAt].every(Number.isFinite) &&\n ttl > 0 &&\n expiresAt! >= createdAt\n ) {\n const value = codec.materialize(cached.value);\n const now = this.clock.now();\n if (now - createdAt < ttl) {\n note(origin, cacheOutcome(\"hit\"));\n return value;\n }\n if (\n request.revalidate?.({\n request,\n entry: cached,\n now,\n key: cacheKey,\n backend: this[BACKEND](),\n store,\n })\n )\n return value;\n }\n }\n outcome = \"miss\";\n }\n const result = await codec.run();\n if (revision === this.#fillRevision) {\n try {\n // The observed set unit presents a failure, which the background\n // promise then holds.\n scheduleBackground(store(codec.snapshot(), request), request.waitUntil);\n } catch (error) {\n note(origin, cacheOutcome(\"miss\", \"cache-set-failed\", error));\n }\n }\n note(origin, cacheOutcome(outcome));\n return result;\n }\n\n // ============================================================\n // STEPS - on prefixed keys, observed as `cache` units\n // ============================================================\n\n async [GET]<T>(\n prefixedKey: string,\n origin?: object\n ): Promise<CacheEntry<T> | null> {\n return cacheStep(\"get\", origin, this.driverName, async (unit) => {\n const entry = await this.get<T>(prefixedKey);\n if (unit !== undefined)\n note(unit, {\n attributes: {\n [ATTR_CACHE_RESULT]: entry\n ? this.clock.now() - entry.createdAt > entry.ttl\n ? \"stale\"\n : \"hit\"\n : \"miss\",\n },\n });\n return entry;\n });\n }\n\n async [SET]<T>(\n prefixedKey: string,\n value: T,\n options: CacheSetOptions,\n origin?: object,\n /** The read a background set belongs to, whose outcomes a failure joins. */\n background?: CacheServe<unknown>,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n const createdAt = this.clock.now();\n const entry: CacheEntry<T> = {\n value,\n createdAt,\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : { identity, expiresAt: createdAt + storageTtl }),\n };\n\n return cacheStep(\n \"set\",\n origin,\n this.driverName,\n async (unit) => {\n try {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n } catch (failure) {\n if (background !== undefined && unit !== undefined)\n placeSetFailure(background.origin, failure, unit, background);\n throw failure;\n }\n },\n options.ttl\n );\n }\n\n /** The backend's own primitives, unobserved, and the clock. */\n [BACKEND](): Backend {\n return {\n get: (key) => this.get(key),\n set: (key, ttl, entry) => this.set(key, ttl, entry),\n delete: (keys) => this.delete(keys),\n now: () => this.clock.now(),\n };\n }\n\n /**\n * Invalidate after a mutation: the entries under `prefix` (relative keys\n * rebased by `prefixed`), and the targets `options` names.\n */\n async [INVALIDATE](\n prefix: string,\n options: CacheInvalidationOptions | undefined,\n origin: object | undefined,\n prefixed: (key: string) => string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n // Every target is rebased, and so validated, before any is dropped.\n const targets: [Drop, string][] =\n options === undefined || options.autoInvalidate === true\n ? [[\"clear\", prefixed(prefix)]]\n : [];\n for (const entry of options?.invalidate ?? [])\n targets.push(\n entry.endsWith(\"*\")\n ? [\"clear\", prefixed(entry.slice(0, -1))]\n : [\"delete\", prefixed(entry)]\n );\n return cacheStep(\"invalidate\", origin, this.driverName, async (unit) => {\n await Promise.all(\n targets.map(([drop, key]) => this[DROP](drop, key, unit))\n );\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n /**\n * Drop the entries under `prefixedKey` (`clear`), or that entry and its\n * revalidation marker (`delete`). Not `async`: a step that fails is\n * rejected by the promise the caller holds, with no promise between them\n * left a tick without a handler (workerd reports one).\n */\n [DROP](drop: Drop, prefixedKey: string, origin?: object): Promise<void> {\n this.#fillRevision += 1;\n return cacheStep(drop, origin, this.driverName, () =>\n drop === \"clear\"\n ? this.clear(prefixedKey)\n : this.delete([prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`])\n );\n }\n}\n"],"mappings":"8RAEA,MAAa,EAAsB,SAC7B,EAAsB,IAE5B,SAAgB,EACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GAiBV,eAAsB,EACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAS,GAAG,IAAM,IACxB,GAAI,CAAC,EAEH,OADA,MAAM,EAAQ,OAAO,CAAC,EAAO,CAAC,CACvB,GAET,IAAM,EAAW,MAAM,EAAQ,IAAI,EAAO,CAQ1C,OAPI,GAAY,EAAQ,KAAK,CAAG,EAAS,UAAY,EAAS,IACrD,IACT,MAAM,EAAQ,IAAI,EAAQ,EAAqB,CAC7C,MAAO,GACP,UAAW,EAAQ,KAAK,CACxB,IAAK,EACN,CAAC,CACK,ICvCT,MAAa,EAAe,SAGf,EAAgC,GAAG,EAAa,QAgD7D,SAAS,EAAW,EAAuB,CAEzC,OAAO,EACJ,MAAM,GAAG,CACT,IAAK,GAAS,EAAK,WAAW,EAAE,CAAC,SAAS,GAA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