viborm 1.1.0 → 1.2.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-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +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/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-CRBo95D0.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
- package/dist/{datetime-physical-codec-BK93pJGW.mjs.map → datetime-physical-codec-oIhiYZEP.mjs.map} +1 -1
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-ZIbkciaz.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/{execution-context-Bm_qTp1i.mjs → execution-context-BKR3bgES.mjs} +1 -1
- package/dist/{execution-context-Bm_qTp1i.mjs.map → execution-context-BKR3bgES.mjs.map} +1 -1
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-BbcE-gyl.d.mts → index-C_XLSTy2.d.mts} +624 -351
- 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/instrumentation.mjs.map +1 -1
- package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -561
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/object-store-DyYOCtmX.d.mts +156 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-Bbw8W81b.d.mts → planner-C6Lfsasx.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-DXj_pOT0.mjs → provider-limits-BHATED_m.mjs} +2 -2
- package/dist/{provider-limits-DXj_pOT0.mjs.map → provider-limits-BHATED_m.mjs.map} +1 -1
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map} +1 -1
- package/dist/{utils-CRFUUfNn.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-JDaZht4U.mjs +2 -0
- package/dist/{version-De1l_ZMF.mjs.map → version-JDaZht4U.mjs.map} +1 -1
- package/package.json +75 -33
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-Op1fx9Bo.mjs +0 -6
- package/dist/batch-refs-Op1fx9Bo.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-C8gXvWIA.mjs +0 -2
- package/dist/client-C8gXvWIA.mjs.map +0 -1
- package/dist/client-z9mcpRtA.mjs +0 -435
- package/dist/client-z9mcpRtA.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/datetime-physical-codec-BK93pJGW.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs.map +0 -1
- package/dist/driver-ZIbkciaz.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs.map +0 -1
- package/dist/error-mapping-LKqxnw-b.mjs +0 -2
- package/dist/error-mapping-LKqxnw-b.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BLqNdigQ.mjs +0 -2
- package/dist/fs-estate-BLqNdigQ.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-DtZdwqzc.mjs +0 -2
- package/dist/mysql-adapter-DtZdwqzc.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs.map +0 -1
- package/dist/postgres-adapter-ButxrmEa.mjs +0 -2
- package/dist/postgres-adapter-ButxrmEa.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-CKLOBSKl.mjs +0 -2
- package/dist/result-shape-CKLOBSKl.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-C7P7lwIs.mjs +0 -6
- package/dist/schema-introspection-C7P7lwIs.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-1krz0OXw.mjs +0 -2
- package/dist/sqlite-adapter-1krz0OXw.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-CRFUUfNn.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-De1l_ZMF.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminal-BbRi0CNZ.mjs","names":[],"sources":["../src/schema/field-ref.ts","../src/schema/json-null.ts","../src/schema/relation/terminal.ts"],"sourcesContent":["/**\n * Field references (Prisma `FieldRef` parity)\n *\n * A field reference is an opaque, symbol-branded token that stands for a COLUMN\n * instead of a bound parameter in a filter operand position:\n *\n * ```ts\n * client.post.findMany({ where: { views: { gt: (ctx) => ctx.fields.likes } } });\n * // -> ... WHERE \"t0\".\"views\" > \"t0\".\"likes\"\n * ```\n *\n * The token is the MECHANISM; the callback is the surface that hands one out —\n * `ctx.fields` is this file's per-model table, built for the model whose filter\n * the operand sits in (see `validation/primitives/operand.ts`). A token held\n * directly is just as valid: it is what the callback returns.\n *\n * The token carries only what both the validation layer and the SQL builders\n * need — the owning model's schema key, the field's schema key, and the field's\n * scalar type — so it can be created without touching the model graph and\n * compared without any registry lookup.\n *\n * Two rules govern it, and each is enforced where it is actually decidable:\n *\n * - TYPE. A reference's scalar type must match the filter operand's scalar\n * type. Decided by the validation layer ({@link file://../validation/primitives/operand.ts}),\n * which knows the operand's type and nothing about models — scalar filter\n * schemas are interned across models by design (see `validation/scalars/intern.ts`).\n *\n * - SAME MODEL. A reference may only be used in a filter on its own model\n * (Prisma's rule: a field reference compares two columns of the SAME row).\n * Decided by the where-builder ({@link file://../query-engine/builders/where-builder.ts}),\n * because \"the model being filtered\" is a property of the QUERY SCOPE, not of\n * the schema: a nested relation `where` re-scopes to the relation's target\n * model while reusing that model's own (interned, model-blind) filter schemas.\n * The builder must resolve the referenced column against the current scope to\n * emit it at all, so the check is intrinsic there, not a duplicated guard. It\n * runs at SQL-build time — before any I/O.\n */\n\nimport type { Model } from \"./model/model\";\nimport type { ScalarType } from \"./scalars/common\";\n\n/**\n * Brand carried by every field reference. `Symbol.for` (not a fresh symbol) so\n * a reference stays recognizable across duplicated module instances.\n */\nexport const FIELD_REF_BRAND: unique symbol = Symbol.for(\"viborm.field-ref\");\n\n/**\n * An opaque reference to a scalar column of `TModel`.\n *\n * `TType` is the field's scalar type; it is what makes an `Int` reference\n * unassignable to a `String` filter operand at the type level.\n */\n/** What a reference knows about its column, held UNDER the brand symbol. */\nexport interface FieldRefPayload<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n /** Schema key of the model owning the field (e.g. `\"post\"`). */\n readonly model: TModel;\n /** Schema key of the field (e.g. `\"likes\"`), NOT the mapped column name. */\n readonly field: string;\n /** Scalar type of the field (e.g. `\"int\"`). */\n readonly type: TType;\n /** Whether the field is a list scalar. List references are not supported. */\n readonly list: boolean;\n}\n\nexport interface FieldRef<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n // The ONLY key, and it is a symbol on purpose. A reference rides operand\n // unions everywhere a filter value goes; if it exposed string-keyed members\n // (`model`, `field`, ...) the editor would offer them as completions inside\n // every filter object literal that admits a reference. The payload lives\n // under the brand so the token contributes NOTHING to those completions.\n readonly [FIELD_REF_BRAND]: FieldRefPayload<TModel, TType>;\n}\n\n/** Any field reference, regardless of model or scalar type. */\nexport type AnyFieldRef = FieldRef<string, ScalarType>;\n\n/**\n * Runtime brand check. Deliberately a plain property probe: it runs once per\n * filter operand, so it must be a single `typeof` plus one symbol lookup.\n */\nexport function isFieldRef(value: unknown): value is AnyFieldRef {\n if (typeof value !== \"object\" || value === null) return false;\n const payload = (value as { [FIELD_REF_BRAND]?: unknown })[FIELD_REF_BRAND];\n return typeof payload === \"object\" && payload !== null;\n}\n\n/** The reference's column facts. The one sanctioned way to read them. */\nexport function fieldRefPayload(ref: AnyFieldRef): FieldRefPayload {\n return ref[FIELD_REF_BRAND];\n}\n\n/** Human-readable spelling of a reference, for error messages. */\nexport function formatFieldRef(ref: AnyFieldRef): string {\n const payload = fieldRefPayload(ref);\n return `${payload.model}.${payload.field}`;\n}\n\nfunction createFieldRef(\n model: string,\n field: string,\n type: ScalarType,\n list: boolean\n): AnyFieldRef {\n return Object.freeze({\n [FIELD_REF_BRAND]: Object.freeze({ model, field, type, list }),\n });\n}\n\n// =============================================================================\n// TYPE-LEVEL PROJECTION: model -> its reference table\n// =============================================================================\n\ntype ScalarsOf<M> = M extends { \"~\": { state: { scalars: infer S } } }\n ? S\n : never;\n\ntype ScalarTypeOf<S> = S extends {\n \"~\": { state: { type: infer T extends ScalarType } };\n}\n ? T\n : ScalarType;\n\ntype ReferenceableScalarKeys<M> = {\n [K in keyof ScalarsOf<M>]: ScalarTypeOf<ScalarsOf<M>[K]> extends \"point\"\n ? never\n : K;\n}[keyof ScalarsOf<M>];\n\n/**\n * One model's reference table — the type of `ctx.fields` inside an operand\n * callback: one reference per scalar field, and nothing else on it, so a\n * mistyped field name is a compile error before it is a runtime one.\n */\nexport type ModelFieldRefs<TModelName extends string, M> = {\n readonly [K in ReferenceableScalarKeys<M> & string]: FieldRef<\n TModelName,\n ScalarTypeOf<ScalarsOf<M>[K]>\n >;\n};\n\n// =============================================================================\n// RUNTIME PROJECTION\n// =============================================================================\n\nconst UNKNOWN_FIELD = (modelName: string, key: string, known: string[]) =>\n new Error(\n `Unknown scalar field \"${key}\" on model '${modelName}'. Known fields: ${known.join(\", \")}.`\n );\n\n/**\n * The reference table for ONE model: `{ likes, views, … }`, each entry built on\n * first read and memoized.\n *\n * This is what an operand callback receives as `ctx.fields`, built once per\n * model and cached there — a query that never compares columns never builds\n * one, and a model's table costs a single object until a field is read. The\n * model name is passed in because the token carries the model's SCHEMA KEY,\n * which is what the where-builder compares the query scope against (hydration\n * sets `names.ts` to that key — see `hydration.ts`).\n */\nexport function createModelFieldRefs<\n TName extends string,\n M extends Model<any>,\n>(modelName: TName, model: M): ModelFieldRefs<TName, M> {\n const cache = new Map<string, AnyFieldRef>();\n const scalars = model[\"~\"].state.scalars;\n const referenceableNames = Object.keys(scalars).filter(\n (key) => scalars[key]![\"~\"].state.type !== \"point\"\n );\n const referenceableSet = new Set(referenceableNames);\n const table = new Proxy(Object.create(null) as Record<string, AnyFieldRef>, {\n get(_target, key) {\n if (typeof key !== \"string\") return undefined;\n const cached = cache.get(key);\n if (cached) return cached;\n const scalar = referenceableSet.has(key) ? scalars[key] : undefined;\n if (!scalar) {\n throw UNKNOWN_FIELD(modelName, key, referenceableNames);\n }\n const state = scalar[\"~\"].state;\n const ref = createFieldRef(modelName, key, state.type, state.array);\n cache.set(key, ref);\n return ref;\n },\n has: (_target, key) => typeof key === \"string\" && referenceableSet.has(key),\n ownKeys: () => referenceableNames,\n getOwnPropertyDescriptor: (_target, key) =>\n typeof key === \"string\" && referenceableSet.has(key)\n ? {\n enumerable: true,\n configurable: true,\n }\n : undefined,\n });\n // The one projection this file owes its callers: the proxy answers exactly\n // the model's scalar keys (`has`/`ownKeys` above enforce it, and any other key\n // throws), which is what `ModelFieldRefs` describes and no proxy signature can.\n return table as ModelFieldRefs<TName, M>;\n}\n","/**\n * JSON null sentinels (Prisma `DbNull` / `JsonNull` / `AnyNull` parity)\n *\n * A nullable JSON column has TWO different nulls, and SQL can tell them apart\n * while JavaScript cannot:\n *\n * - the SQL NULL — the column holds no document at all (`col IS NULL`);\n * - the JSON null — the column holds a document, and that document is the\n * JSON value `null` (`'null'::jsonb`, `CAST('null' AS JSON)`, the text\n * `null` on SQLite).\n *\n * Both read back as JavaScript `null`, so a bare `null` cannot name either one\n * without guessing. Prisma solves this with three exported sentinel values, and\n * so does this file:\n *\n * ```ts\n * import { AnyNull, DbNull, JsonNull } from \"viborm\";\n *\n * await client.entry.update({ where, data: { meta: DbNull } }); // -> SQL NULL\n * await client.entry.update({ where, data: { meta: JsonNull } }); // -> 'null'\n * await client.entry.findMany({ where: { meta: { equals: AnyNull } } });\n * ```\n *\n * `AnyNull` is FILTER-ONLY, exactly as in Prisma: \"either null\" is a question,\n * not a value, so there is nothing for a write to store. The validation layer\n * refuses it in write position by name (see\n * {@link file://../validation/primitives/json-null.ts}).\n *\n * THE TOKENS ARE CLASS INSTANCES ON PURPOSE. `v.json()` accepts a plain object\n * with any keys, so a plain-object token would type-check as an ordinary JSON\n * document and could be PERSISTED as user data — the same hazard field\n * references have (see {@link file://./field-ref.ts}). A class instance has a\n * prototype that is not `Object.prototype`, so JSON validation rejects it\n * structurally: a sentinel nested anywhere inside a document\n * (`{ a: DbNull }`) fails validation instead of landing in the column as `{}`.\n * Only the top-level operand positions that explicitly opt in accept one.\n *\n * The `kind` property is an OWN ENUMERABLE STRING key, not only the symbol\n * brand, so a token reads as itself in a dump and a structural serializer at\n * least tells the three apart rather than flattening all three to `{}`.\n *\n * BEING TOLD APART IS NOT THE SAME AS BEING RECOGNIZED, and this file used to\n * claim otherwise. A JSON column accepts an ARBITRARY object, so\n * `{ kind: \"DbNull\" }` is ordinary user data — and a serializer walking\n * `Object.keys` gives it the same identity as the sentinel. The cache key\n * builder did exactly that, and a cached client served the rows of\n * `equals: DbNull` for `equals: { kind: \"DbNull\" }`, in both directions, for\n * the whole TTL. A consumer that must not confuse the two asks\n * {@link isJsonNullSentinel} and keys the answer somewhere a document cannot\n * reach, as {@link file://../cache/key.ts} now does.\n */\n\n/**\n * Brand carried by every JSON null sentinel. `Symbol.for` (not a fresh symbol)\n * so a token stays recognizable across duplicated module instances, exactly as\n * for field references.\n */\nexport const JSON_NULL_BRAND: unique symbol = Symbol.for(\"viborm.json-null\");\n\n/** The three sentinels, by name. */\nexport type JsonNullKind = \"DbNull\" | \"JsonNull\" | \"AnyNull\";\n\n/**\n * A JSON null sentinel. `TKind` is what makes `AnyNull` unassignable to a write\n * slot while `DbNull` and `JsonNull` are assignable to it.\n */\nexport class JsonNullSentinel<TKind extends JsonNullKind = JsonNullKind> {\n readonly [JSON_NULL_BRAND]: TKind;\n /** Own enumerable key so structural serializers separate the three. */\n readonly kind: TKind;\n\n constructor(kind: TKind) {\n this[JSON_NULL_BRAND] = kind;\n this.kind = kind;\n Object.freeze(this);\n }\n\n /** Readable in error messages: `DbNull`, not `[object Object]`. */\n toString(): string {\n return this.kind;\n }\n\n /** Distinct under `JSON.stringify` (instrumentation, dedup keys). */\n toJSON(): string {\n return `viborm.json-null:${this.kind}`;\n }\n}\n\n/** Any sentinel, regardless of kind. */\nexport type AnyJsonNullSentinel = JsonNullSentinel<JsonNullKind>;\n\n/** The database NULL: the column holds no JSON document. */\nexport const DbNull: JsonNullSentinel<\"DbNull\"> = new JsonNullSentinel(\n \"DbNull\"\n);\n\n/** The JSON null: the column holds the JSON document `null`. */\nexport const JsonNull: JsonNullSentinel<\"JsonNull\"> = new JsonNullSentinel(\n \"JsonNull\"\n);\n\n/** Either null. Filter positions only — see the module header. */\nexport const AnyNull: JsonNullSentinel<\"AnyNull\"> = new JsonNullSentinel(\n \"AnyNull\"\n);\n\nconst KINDS: ReadonlySet<string> = new Set<JsonNullKind>([\n \"DbNull\",\n \"JsonNull\",\n \"AnyNull\",\n]);\n\n/**\n * Runtime brand check. A property probe rather than `instanceof`, so a token\n * created by a duplicated copy of this module is still recognized (the same\n * reason {@link file://./field-ref.ts} probes its symbol).\n */\nexport function isJsonNullSentinel(\n value: unknown\n): value is AnyJsonNullSentinel {\n if (typeof value !== \"object\" || value === null) return false;\n const brand = (value as { [JSON_NULL_BRAND]?: unknown })[JSON_NULL_BRAND];\n return typeof brand === \"string\" && KINDS.has(brand);\n}\n\n/** The sentinel's kind, or `undefined` when the value is not a sentinel. */\nexport function jsonNullKindOf(value: unknown): JsonNullKind | undefined {\n return isJsonNullSentinel(value) ? value.kind : undefined;\n}\n","// Shared immutable-terminal machinery: the construction-time refusal vocabulary\n// and the source-independent target once-cell.\n//\n// Every structurally knowable fact about a declaration is decided HERE or in the\n// factory/modifier that owns it, before the value enters trusted relation state.\n// Facts that need the schema graph — is the settled return a registered model,\n// which endpoint owns the foreign key, does the pair exist — belong to the\n// full-schema relation resolver and are deliberately absent.\n\nimport { ValidationError } from \"@errors\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport type {\n JunctionReferentialAction,\n JunctionSideActions,\n NonEmptyFieldTuple,\n ReferentialAction,\n} from \"./types\";\n\n/** The builder label carried by every construction-time refusal. */\nexport type RelationBuilder = \"s.toOne\" | \"s.toMany\" | \"s.model\";\n\n/**\n * The one construction-time refusal. Structural input the factories and\n * modifiers can judge on their own never reaches the schema resolver as a\n * `SchemaValidationIssue`; it fails here, at the call the author wrote.\n */\nexport function refuseRelationInput(\n builder: RelationBuilder,\n path: string,\n message: string,\n cause?: Error\n): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path },\n [{ path, message }],\n cause === undefined ? undefined : { cause }\n );\n}\n\n// =============================================================================\n// PLAIN-RECORD READS\n// =============================================================================\n\n/**\n * A caller-supplied map is a variant declaration only when it is a plain\n * record: a hostile prototype would otherwise smuggle inherited entries past\n * own-key enumeration into schema truth.\n */\nexport function isPlainRecord(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Own ENUMERABLE string keys — the declaration surface of a record. Symbol keys\n * and inherited entries are not declarations, and neither is an own key hidden\n * behind `enumerable: false`.\n */\nexport function declaredKeys(record: Record<string, unknown>): string[] {\n return Object.keys(record);\n}\n\n/** Exactly these keys, in any order. */\nexport function hasExactKeys(\n actual: readonly string[],\n expected: readonly string[]\n): boolean {\n return (\n actual.length === expected.length &&\n expected.every((key) => actual.includes(key))\n );\n}\n\n/**\n * Read one caller-owned property exactly once. Accessors are executable input:\n * when one throws, the declaration boundary owns the V4002 refusal and keeps a\n * normalized cause instead of leaking the caller's thrown value.\n */\nexport function readCallerProperty(\n builder: RelationBuilder,\n record: Record<string, unknown>,\n property: string,\n path: string\n): unknown {\n try {\n return Reflect.get(record, property);\n } catch (thrown) {\n refuseRelationInput(\n builder,\n path,\n `Could not read relation input '${path}'`,\n normalizeThrown(\n thrown,\n `Reading relation input '${path}' threw a non-Error value`\n )\n );\n }\n}\n\n// =============================================================================\n// MODIFIER TOKENS\n// =============================================================================\n\n/**\n * A relation name is a non-empty PAIRING LABEL, not a SQL identifier: an\n * explicit `.through(...)` lets `\"Post tags/v2\"` name a pair without pretending\n * the label is a database name.\n */\nexport function normalizeRelationName(\n builder: RelationBuilder,\n name: unknown\n): string {\n if (typeof name !== \"string\" || name.length === 0) {\n refuseRelationInput(\n builder,\n \"name\",\n \"A relation name must be a non-empty string\"\n );\n }\n return name;\n}\n\nexport function normalizeReferentialAction(\n path: string,\n action: unknown\n): ReferentialAction {\n if (\n action === \"cascade\" ||\n action === \"setNull\" ||\n action === \"restrict\" ||\n action === \"noAction\"\n ) {\n return action;\n }\n refuseRelationInput(\n \"s.toOne\",\n path,\n \"A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'\"\n );\n}\n\n/** Junction actions exclude `setNull` at the type level and here. */\nfunction normalizeJunctionAction(\n path: string,\n action: unknown\n): JunctionReferentialAction {\n if (action === \"cascade\" || action === \"restrict\" || action === \"noAction\") {\n return action;\n }\n refuseRelationInput(\n \"s.toMany\",\n path,\n \"A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member\"\n );\n}\n\n/**\n * The ONE normalization of a junction action declaration. A bare action is the\n * symmetric shorthand and becomes the same pair a `{ source, target }` map\n * spells, so trusted state holds one form and no consumer asks which spelling\n * declared it. The map names both sides and nothing else: an omitted side\n * would silently keep a default the author never chose. Every object is read\n * as a map, so an array or a class instance is told what a map must be rather\n * than which actions exist.\n */\nexport function normalizeJunctionActions(\n path: \"onDelete\" | \"onUpdate\",\n declared: unknown\n): JunctionSideActions {\n if (typeof declared !== \"object\" || declared === null) {\n const action = normalizeJunctionAction(path, declared);\n return Object.freeze({ source: action, target: action });\n }\n if (\n !(\n isPlainRecord(declared) &&\n hasExactKeys(declaredKeys(declared), [\"source\", \"target\"])\n )\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `A junction '${path}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`\n );\n }\n const side = (name: \"source\" | \"target\"): JunctionReferentialAction =>\n normalizeJunctionAction(\n `${path}.${name}`,\n readCallerProperty(\"s.toMany\", declared, name, `${path}.${name}`)\n );\n return Object.freeze({ source: side(\"source\"), target: side(\"target\") });\n}\n\n/** One junction table name or side naming token. */\nexport function normalizeJunctionToken(path: string, token: unknown): string {\n if (!isValidSchemaIdentifier(token)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Junction '${path}' must be a valid schema identifier`\n );\n }\n return token;\n}\n\n/** A non-empty foreign-key tuple whose members are distinct. */\nexport function normalizeFieldTuple(\n builder: RelationBuilder,\n path: string,\n fields: readonly string[]\n): NonEmptyFieldTuple {\n const [head, ...rest] = fields;\n if (head === undefined) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' requires at least one field key`\n );\n }\n if (new Set(fields).size !== fields.length) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' cannot repeat a field key in one foreign-key tuple`\n );\n }\n return [head, ...rest];\n}\n\n// =============================================================================\n// TARGET SETTLEMENT\n// =============================================================================\n\ntype SettledTarget =\n | { readonly settled: \"value\"; readonly value: unknown }\n | { readonly settled: \"error\"; readonly error: Error };\n\n/**\n * The declaration-lifetime target cell.\n *\n * A raw getter stays lazy, but it is invoked at most ONCE per target: the first\n * resolution settles its return or one normalized `Error`, and every later\n * consumer — including a second schema graph reusing the same immutable\n * terminal — observes that same outcome. A resolver-local cache alone would let\n * a stateful getter give validation, migrations and the query engine different\n * declaration truth.\n *\n * Only settled outcomes live here. The resolver decides whether a return is a\n * registered model and attaches its own model/field path to any issue, so\n * contextual diagnostics are never cached on the shared terminal.\n */\nexport function createTargetSettlement(\n readGetter: (variantKey: string | undefined) => unknown\n): (variantKey?: string) => unknown {\n const cells = new Map<string, SettledTarget>();\n return (variantKey?: string): unknown => {\n const cellKey = variantKey ?? \"\";\n let cell = cells.get(cellKey);\n if (cell === undefined) {\n cell = settleTargetOnce(readGetter, variantKey);\n cells.set(cellKey, cell);\n }\n if (cell.settled === \"value\") return cell.value;\n throw cell.error;\n };\n}\n\nfunction settleTargetOnce(\n readGetter: (variantKey: string | undefined) => unknown,\n variantKey: string | undefined\n): SettledTarget {\n // READING the getter cannot fail: every `readGetter` handed to\n // {@link createTargetSettlement} is one property read over frozen\n // declaration state. INVOKING it can, and that is the one `try` below.\n const getter = readGetter(variantKey);\n // The read still may not produce one: a variant asked without a key or with\n // an unknown one has no entry, and a forged state can carry a non-function\n // target where the factories admit only a getter. Settling that as a failure\n // is what keeps every later consumer from re-reading a target that can never\n // resolve — and from reading `undefined` as a resolved one.\n if (typeof getter !== \"function\") {\n return {\n settled: \"error\",\n error: new Error(\"Relation target getter is not a function\"),\n };\n }\n try {\n return { settled: \"value\", value: getter() };\n } catch (thrown) {\n return {\n settled: \"error\",\n error: normalizeThrown(\n thrown,\n \"Relation target getter threw a non-Error value\"\n ),\n };\n }\n}\n\n/**\n * One normalization, owned here: a thrown `Error` keeps its identity across\n * every consumer, and a non-Error throw becomes exactly one `Error` that every\n * consumer then shares.\n */\nfunction normalizeThrown(thrown: unknown, nonErrorPrefix: string): Error {\n if (thrown instanceof Error) return thrown;\n let rendered: string;\n try {\n rendered = typeof thrown === \"symbol\" ? thrown.toString() : String(thrown);\n } catch {\n rendered = \"<unrenderable non-Error value>\";\n }\n return new Error(`${nonErrorPrefix}: ${rendered}`);\n}\n"],"mappings":"gIA8CA,MAAa,EAAiC,OAAO,IAAI,mBAAmB,CA0C5E,SAAgB,WAAW,EAAsC,CAC/D,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAW,EAA0C,GAC3D,OAAO,OAAO,GAAY,YAAY,EAIxC,SAAgB,gBAAgB,EAAmC,CACjE,OAAO,EAAI,GAIb,SAAgB,eAAe,EAA0B,CACvD,IAAM,EAAU,gBAAgB,EAAI,CACpC,MAAO,GAAG,EAAQ,MAAM,GAAG,EAAQ,QAGrC,SAAS,eACP,EACA,EACA,EACA,EACa,CACb,OAAO,OAAO,OAAO,EAClB,GAAkB,OAAO,OAAO,CAAE,QAAO,QAAO,OAAM,OAAM,CAAC,CAC/D,CAAC,CAuCJ,MAAM,eAAiB,EAAmB,EAAa,IACjD,MACF,yBAAyB,EAAI,cAAc,EAAU,mBAAmB,EAAM,KAAK,KAAK,CAAC,GAC1F,CAaH,SAAgB,qBAGd,EAAkB,EAAoC,CACtD,IAAM,EAAQ,IAAI,IACZ,EAAU,EAAM,KAAK,MAAM,QAC3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QAAS,QACT,MAAO,gBACL,EACA,iDACD,CACF,EASL,SAAS,gBAAgB,EAAiB,EAA+B,CACvE,GAAI,aAAkB,MAAO,OAAO,EACpC,IAAI,EACJ,GAAI,CACF,EAAW,OAAO,GAAW,SAAW,EAAO,UAAU,CAAG,OAAO,EAAO,MACpE,CACN,EAAW,iCAEb,OAAW,MAAM,GAAG,EAAe,IAAI,IAAW"}
|
|
1
|
+
{"version":3,"file":"terminal-C8cq1WWX.mjs","names":[],"sources":["../src/schema/field-ref.ts","../src/schema/json-null.ts","../src/schema/relation/terminal.ts"],"sourcesContent":["/**\n * Field references (Prisma `FieldRef` parity)\n *\n * A field reference is an opaque, symbol-branded token that stands for a COLUMN\n * instead of a bound parameter in a filter operand position:\n *\n * ```ts\n * client.post.findMany({ where: { views: { gt: (ctx) => ctx.fields.likes } } });\n * // -> ... WHERE \"t0\".\"views\" > \"t0\".\"likes\"\n * ```\n *\n * The token is the MECHANISM; the callback is the surface that hands one out —\n * `ctx.fields` is this file's per-model table, built for the model whose filter\n * the operand sits in (see `validation/primitives/operand.ts`). A token held\n * directly is just as valid: it is what the callback returns.\n *\n * The token carries only what both the validation layer and the SQL builders\n * need — the owning model's schema key, the field's schema key, and the field's\n * scalar type — so it can be created without touching the model graph and\n * compared without any registry lookup.\n *\n * Two rules govern it, and each is enforced where it is actually decidable:\n *\n * - TYPE. A reference's scalar type must match the filter operand's scalar\n * type. Decided by the validation layer ({@link file://../validation/primitives/operand.ts}),\n * which knows the operand's type and nothing about models — scalar filter\n * schemas are interned across models by design (see `validation/scalars/intern.ts`).\n *\n * - SAME MODEL. A reference may only be used in a filter on its own model\n * (Prisma's rule: a field reference compares two columns of the SAME row).\n * Decided by the where-builder ({@link file://../query-engine/builders/where-builder.ts}),\n * because \"the model being filtered\" is a property of the QUERY SCOPE, not of\n * the schema: a nested relation `where` re-scopes to the relation's target\n * model while reusing that model's own (interned, model-blind) filter schemas.\n * The builder must resolve the referenced column against the current scope to\n * emit it at all, so the check is intrinsic there, not a duplicated guard. It\n * runs at SQL-build time — before any I/O.\n */\n\nimport type { Model } from \"./model/model\";\nimport type { ScalarType } from \"./scalars/common\";\n\n/**\n * Brand carried by every field reference. `Symbol.for` (not a fresh symbol) so\n * a reference stays recognizable across duplicated module instances.\n */\nexport const FIELD_REF_BRAND: unique symbol = Symbol.for(\"viborm.field-ref\");\n\n/**\n * An opaque reference to a scalar column of `TModel`.\n *\n * `TType` is the field's scalar type; it is what makes an `Int` reference\n * unassignable to a `String` filter operand at the type level.\n */\n/** What a reference knows about its column, held UNDER the brand symbol. */\nexport interface FieldRefPayload<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n /** Schema key of the model owning the field (e.g. `\"post\"`). */\n readonly model: TModel;\n /** Schema key of the field (e.g. `\"likes\"`), NOT the mapped column name. */\n readonly field: string;\n /** Scalar type of the field (e.g. `\"int\"`). */\n readonly type: TType;\n /** Whether the field is a list scalar. List references are not supported. */\n readonly list: boolean;\n}\n\nexport interface FieldRef<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n // The ONLY key, and it is a symbol on purpose. A reference rides operand\n // unions everywhere a filter value goes; if it exposed string-keyed members\n // (`model`, `field`, ...) the editor would offer them as completions inside\n // every filter object literal that admits a reference. The payload lives\n // under the brand so the token contributes NOTHING to those completions.\n readonly [FIELD_REF_BRAND]: FieldRefPayload<TModel, TType>;\n}\n\n/** Any field reference, regardless of model or scalar type. */\nexport type AnyFieldRef = FieldRef<string, ScalarType>;\n\n/**\n * Runtime brand check. Deliberately a plain property probe: it runs once per\n * filter operand, so it must be a single `typeof` plus one symbol lookup.\n */\nexport function isFieldRef(value: unknown): value is AnyFieldRef {\n if (typeof value !== \"object\" || value === null) return false;\n const payload = (value as { [FIELD_REF_BRAND]?: unknown })[FIELD_REF_BRAND];\n return typeof payload === \"object\" && payload !== null;\n}\n\n/** The reference's column facts. The one sanctioned way to read them. */\nexport function fieldRefPayload(ref: AnyFieldRef): FieldRefPayload {\n return ref[FIELD_REF_BRAND];\n}\n\n/** Human-readable spelling of a reference, for error messages. */\nexport function formatFieldRef(ref: AnyFieldRef): string {\n const payload = fieldRefPayload(ref);\n return `${payload.model}.${payload.field}`;\n}\n\nfunction createFieldRef(\n model: string,\n field: string,\n type: ScalarType,\n list: boolean\n): AnyFieldRef {\n return Object.freeze({\n [FIELD_REF_BRAND]: Object.freeze({ model, field, type, list }),\n });\n}\n\n// =============================================================================\n// TYPE-LEVEL PROJECTION: model -> its reference table\n// =============================================================================\n\ntype ScalarsOf<M> = M extends { \"~\": { state: { scalars: infer S } } }\n ? S\n : never;\n\ntype ScalarTypeOf<S> = S extends {\n \"~\": { state: { type: infer T extends ScalarType } };\n}\n ? T\n : ScalarType;\n\ntype ReferenceableScalarKeys<M> = {\n [K in keyof ScalarsOf<M>]: ScalarTypeOf<ScalarsOf<M>[K]> extends \"point\"\n ? never\n : K;\n}[keyof ScalarsOf<M>];\n\n/**\n * One model's reference table — the type of `ctx.fields` inside an operand\n * callback: one reference per scalar field, and nothing else on it, so a\n * mistyped field name is a compile error before it is a runtime one.\n */\nexport type ModelFieldRefs<TModelName extends string, M> = {\n readonly [K in ReferenceableScalarKeys<M> & string]: FieldRef<\n TModelName,\n ScalarTypeOf<ScalarsOf<M>[K]>\n >;\n};\n\n// =============================================================================\n// RUNTIME PROJECTION\n// =============================================================================\n\nconst UNKNOWN_FIELD = (modelName: string, key: string, known: string[]) =>\n new Error(\n `Unknown scalar field \"${key}\" on model '${modelName}'. Known fields: ${known.join(\", \")}.`\n );\n\n/**\n * The reference table for ONE model: `{ likes, views, … }`, each entry built on\n * first read and memoized.\n *\n * This is what an operand callback receives as `ctx.fields`, built once per\n * model and cached there — a query that never compares columns never builds\n * one, and a model's table costs a single object until a field is read. The\n * model name is passed in because the token carries the model's SCHEMA KEY,\n * which is what the where-builder compares the query scope against (hydration\n * sets `names.ts` to that key — see `hydration.ts`).\n */\nexport function createModelFieldRefs<\n TName extends string,\n M extends Model<any>,\n>(modelName: TName, model: M): ModelFieldRefs<TName, M> {\n const cache = new Map<string, AnyFieldRef>();\n const scalars = model[\"~\"].state.scalars;\n const referenceableNames = Object.keys(scalars).filter(\n (key) => scalars[key]![\"~\"].state.type !== \"point\"\n );\n const referenceableSet = new Set(referenceableNames);\n const table = new Proxy(Object.create(null) as Record<string, AnyFieldRef>, {\n get(_target, key) {\n if (typeof key !== \"string\") return undefined;\n const cached = cache.get(key);\n if (cached) return cached;\n const scalar = referenceableSet.has(key) ? scalars[key] : undefined;\n if (!scalar) {\n throw UNKNOWN_FIELD(modelName, key, referenceableNames);\n }\n const state = scalar[\"~\"].state;\n const ref = createFieldRef(modelName, key, state.type, state.array);\n cache.set(key, ref);\n return ref;\n },\n has: (_target, key) => typeof key === \"string\" && referenceableSet.has(key),\n ownKeys: () => referenceableNames,\n getOwnPropertyDescriptor: (_target, key) =>\n typeof key === \"string\" && referenceableSet.has(key)\n ? {\n enumerable: true,\n configurable: true,\n }\n : undefined,\n });\n // The one projection this file owes its callers: the proxy answers exactly\n // the model's scalar keys (`has`/`ownKeys` above enforce it, and any other key\n // throws), which is what `ModelFieldRefs` describes and no proxy signature can.\n return table as ModelFieldRefs<TName, M>;\n}\n","/**\n * JSON null sentinels (Prisma `DbNull` / `JsonNull` / `AnyNull` parity)\n *\n * A nullable JSON column has TWO different nulls, and SQL can tell them apart\n * while JavaScript cannot:\n *\n * - the SQL NULL — the column holds no document at all (`col IS NULL`);\n * - the JSON null — the column holds a document, and that document is the\n * JSON value `null` (`'null'::jsonb`, `CAST('null' AS JSON)`, the text\n * `null` on SQLite).\n *\n * Both read back as JavaScript `null`, so a bare `null` cannot name either one\n * without guessing. Prisma solves this with three exported sentinel values, and\n * so does this file:\n *\n * ```ts\n * import { AnyNull, DbNull, JsonNull } from \"viborm\";\n *\n * await client.entry.update({ where, data: { meta: DbNull } }); // -> SQL NULL\n * await client.entry.update({ where, data: { meta: JsonNull } }); // -> 'null'\n * await client.entry.findMany({ where: { meta: { equals: AnyNull } } });\n * ```\n *\n * `AnyNull` is FILTER-ONLY, exactly as in Prisma: \"either null\" is a question,\n * not a value, so there is nothing for a write to store. The validation layer\n * refuses it in write position by name (see\n * {@link file://../validation/primitives/json-null.ts}).\n *\n * THE TOKENS ARE CLASS INSTANCES ON PURPOSE. `v.json()` accepts a plain object\n * with any keys, so a plain-object token would type-check as an ordinary JSON\n * document and could be PERSISTED as user data — the same hazard field\n * references have (see {@link file://./field-ref.ts}). A class instance has a\n * prototype that is not `Object.prototype`, so JSON validation rejects it\n * structurally: a sentinel nested anywhere inside a document\n * (`{ a: DbNull }`) fails validation instead of landing in the column as `{}`.\n * Only the top-level operand positions that explicitly opt in accept one.\n *\n * The `kind` property is an OWN ENUMERABLE STRING key, not only the symbol\n * brand, so a token reads as itself in a dump and a structural serializer at\n * least tells the three apart rather than flattening all three to `{}`.\n *\n * BEING TOLD APART IS NOT THE SAME AS BEING RECOGNIZED, and this file used to\n * claim otherwise. A JSON column accepts an ARBITRARY object, so\n * `{ kind: \"DbNull\" }` is ordinary user data — and a serializer walking\n * `Object.keys` gives it the same identity as the sentinel. The cache key\n * builder did exactly that, and a cached client served the rows of\n * `equals: DbNull` for `equals: { kind: \"DbNull\" }`, in both directions, for\n * the whole TTL. A consumer that must not confuse the two asks\n * {@link isJsonNullSentinel} and keys the answer somewhere a document cannot\n * reach, as {@link file://../cache/key.ts} now does.\n */\n\n/**\n * Brand carried by every JSON null sentinel. `Symbol.for` (not a fresh symbol)\n * so a token stays recognizable across duplicated module instances, exactly as\n * for field references.\n */\nexport const JSON_NULL_BRAND: unique symbol = Symbol.for(\"viborm.json-null\");\n\n/** The three sentinels, by name. */\nexport type JsonNullKind = \"DbNull\" | \"JsonNull\" | \"AnyNull\";\n\n/**\n * A JSON null sentinel. `TKind` is what makes `AnyNull` unassignable to a write\n * slot while `DbNull` and `JsonNull` are assignable to it.\n */\nexport class JsonNullSentinel<TKind extends JsonNullKind = JsonNullKind> {\n readonly [JSON_NULL_BRAND]: TKind;\n /** Own enumerable key so structural serializers separate the three. */\n readonly kind: TKind;\n\n constructor(kind: TKind) {\n this[JSON_NULL_BRAND] = kind;\n this.kind = kind;\n Object.freeze(this);\n }\n\n /** Readable in error messages: `DbNull`, not `[object Object]`. */\n toString(): string {\n return this.kind;\n }\n\n /** Distinct under `JSON.stringify` (instrumentation, dedup keys). */\n toJSON(): string {\n return `viborm.json-null:${this.kind}`;\n }\n}\n\n/** Any sentinel, regardless of kind. */\nexport type AnyJsonNullSentinel = JsonNullSentinel<JsonNullKind>;\n\n/** The database NULL: the column holds no JSON document. */\nexport const DbNull: JsonNullSentinel<\"DbNull\"> = new JsonNullSentinel(\n \"DbNull\"\n);\n\n/** The JSON null: the column holds the JSON document `null`. */\nexport const JsonNull: JsonNullSentinel<\"JsonNull\"> = new JsonNullSentinel(\n \"JsonNull\"\n);\n\n/** Either null. Filter positions only — see the module header. */\nexport const AnyNull: JsonNullSentinel<\"AnyNull\"> = new JsonNullSentinel(\n \"AnyNull\"\n);\n\nconst KINDS: ReadonlySet<string> = new Set<JsonNullKind>([\n \"DbNull\",\n \"JsonNull\",\n \"AnyNull\",\n]);\n\n/**\n * Runtime brand check. A property probe rather than `instanceof`, so a token\n * created by a duplicated copy of this module is still recognized (the same\n * reason {@link file://./field-ref.ts} probes its symbol).\n */\nexport function isJsonNullSentinel(\n value: unknown\n): value is AnyJsonNullSentinel {\n if (typeof value !== \"object\" || value === null) return false;\n const brand = (value as { [JSON_NULL_BRAND]?: unknown })[JSON_NULL_BRAND];\n return typeof brand === \"string\" && KINDS.has(brand);\n}\n\n/** The sentinel's kind, or `undefined` when the value is not a sentinel. */\nexport function jsonNullKindOf(value: unknown): JsonNullKind | undefined {\n return isJsonNullSentinel(value) ? value.kind : undefined;\n}\n","// Shared immutable-terminal machinery: the construction-time refusal vocabulary\n// and the source-independent target once-cell.\n//\n// Every structurally knowable fact about a declaration is decided HERE or in the\n// factory/modifier that owns it, before the value enters trusted relation state.\n// Facts that need the schema graph — is the settled return a registered model,\n// which endpoint owns the foreign key, does the pair exist — belong to the\n// full-schema relation resolver and are deliberately absent.\n\nimport { ValidationError } from \"@errors\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport type {\n JunctionReferentialAction,\n JunctionSideActions,\n NonEmptyFieldTuple,\n ReferentialAction,\n} from \"./types\";\n\n/** The builder label carried by every construction-time refusal. */\nexport type RelationBuilder = \"s.toOne\" | \"s.toMany\" | \"s.model\";\n\n/**\n * The one construction-time refusal. Structural input the factories and\n * modifiers can judge on their own never reaches the schema resolver as a\n * `SchemaValidationIssue`; it fails here, at the call the author wrote.\n */\nexport function refuseRelationInput(\n builder: RelationBuilder,\n path: string,\n message: string,\n cause?: Error\n): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path },\n [{ path, message }],\n cause === undefined ? undefined : { cause }\n );\n}\n\n// =============================================================================\n// PLAIN-RECORD READS\n// =============================================================================\n\n/**\n * A caller-supplied map is a variant declaration only when it is a plain\n * record: a hostile prototype would otherwise smuggle inherited entries past\n * own-key enumeration into schema truth.\n */\nexport function isPlainRecord(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Own ENUMERABLE string keys — the declaration surface of a record. Symbol keys\n * and inherited entries are not declarations, and neither is an own key hidden\n * behind `enumerable: false`.\n */\nexport function declaredKeys(record: Record<string, unknown>): string[] {\n return Object.keys(record);\n}\n\n/** Exactly these keys, in any order. */\nexport function hasExactKeys(\n actual: readonly string[],\n expected: readonly string[]\n): boolean {\n return (\n actual.length === expected.length &&\n expected.every((key) => actual.includes(key))\n );\n}\n\n/**\n * Read one caller-owned property exactly once. Accessors are executable input:\n * when one throws, the declaration boundary owns the V4002 refusal and keeps a\n * normalized cause instead of leaking the caller's thrown value.\n */\nexport function readCallerProperty(\n builder: RelationBuilder,\n record: Record<string, unknown>,\n property: string,\n path: string\n): unknown {\n try {\n return Reflect.get(record, property);\n } catch (thrown) {\n refuseRelationInput(\n builder,\n path,\n `Could not read relation input '${path}'`,\n normalizeThrown(\n thrown,\n `Reading relation input '${path}' threw a non-Error value`\n )\n );\n }\n}\n\n// =============================================================================\n// MODIFIER TOKENS\n// =============================================================================\n\n/**\n * A relation name is a non-empty PAIRING LABEL, not a SQL identifier: an\n * explicit `.through(...)` lets `\"Post tags/v2\"` name a pair without pretending\n * the label is a database name.\n */\nexport function normalizeRelationName(\n builder: RelationBuilder,\n name: unknown\n): string {\n if (typeof name !== \"string\" || name.length === 0) {\n refuseRelationInput(\n builder,\n \"name\",\n \"A relation name must be a non-empty string\"\n );\n }\n return name;\n}\n\nexport function normalizeReferentialAction(\n path: string,\n action: unknown\n): ReferentialAction {\n if (\n action === \"cascade\" ||\n action === \"setNull\" ||\n action === \"restrict\" ||\n action === \"noAction\"\n ) {\n return action;\n }\n refuseRelationInput(\n \"s.toOne\",\n path,\n \"A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'\"\n );\n}\n\n/** Junction actions exclude `setNull` at the type level and here. */\nfunction normalizeJunctionAction(\n path: string,\n action: unknown\n): JunctionReferentialAction {\n if (action === \"cascade\" || action === \"restrict\" || action === \"noAction\") {\n return action;\n }\n refuseRelationInput(\n \"s.toMany\",\n path,\n \"A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member\"\n );\n}\n\n/**\n * The ONE normalization of a junction action declaration. A bare action is the\n * symmetric shorthand and becomes the same pair a `{ source, target }` map\n * spells, so trusted state holds one form and no consumer asks which spelling\n * declared it. The map names both sides and nothing else: an omitted side\n * would silently keep a default the author never chose. Every object is read\n * as a map, so an array or a class instance is told what a map must be rather\n * than which actions exist.\n */\nexport function normalizeJunctionActions(\n path: \"onDelete\" | \"onUpdate\",\n declared: unknown\n): JunctionSideActions {\n if (typeof declared !== \"object\" || declared === null) {\n const action = normalizeJunctionAction(path, declared);\n return Object.freeze({ source: action, target: action });\n }\n if (\n !(\n isPlainRecord(declared) &&\n hasExactKeys(declaredKeys(declared), [\"source\", \"target\"])\n )\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `A junction '${path}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`\n );\n }\n const side = (name: \"source\" | \"target\"): JunctionReferentialAction =>\n normalizeJunctionAction(\n `${path}.${name}`,\n readCallerProperty(\"s.toMany\", declared, name, `${path}.${name}`)\n );\n return Object.freeze({ source: side(\"source\"), target: side(\"target\") });\n}\n\n/** One junction table name or side naming token. */\nexport function normalizeJunctionToken(path: string, token: unknown): string {\n if (!isValidSchemaIdentifier(token)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Junction '${path}' must be a valid schema identifier`\n );\n }\n return token;\n}\n\n/** A non-empty foreign-key tuple whose members are distinct. */\nexport function normalizeFieldTuple(\n builder: RelationBuilder,\n path: string,\n fields: readonly string[]\n): NonEmptyFieldTuple {\n const [head, ...rest] = fields;\n if (head === undefined) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' requires at least one field key`\n );\n }\n if (new Set(fields).size !== fields.length) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' cannot repeat a field key in one foreign-key tuple`\n );\n }\n return [head, ...rest];\n}\n\n// =============================================================================\n// TARGET SETTLEMENT\n// =============================================================================\n\ntype SettledTarget =\n | { readonly settled: \"value\"; readonly value: unknown }\n | { readonly settled: \"error\"; readonly error: Error };\n\n/**\n * The declaration-lifetime target cell.\n *\n * A raw getter stays lazy, but it is invoked at most ONCE per target: the first\n * resolution settles its return or one normalized `Error`, and every later\n * consumer — including a second schema graph reusing the same immutable\n * terminal — observes that same outcome. A resolver-local cache alone would let\n * a stateful getter give validation, migrations and the query engine different\n * declaration truth.\n *\n * Only settled outcomes live here. The resolver decides whether a return is a\n * registered model and attaches its own model/field path to any issue, so\n * contextual diagnostics are never cached on the shared terminal.\n */\nexport function createTargetSettlement(\n readGetter: (variantKey: string | undefined) => unknown\n): (variantKey?: string) => unknown {\n const cells = new Map<string, SettledTarget>();\n return (variantKey?: string): unknown => {\n const cellKey = variantKey ?? \"\";\n let cell = cells.get(cellKey);\n if (cell === undefined) {\n cell = settleTargetOnce(readGetter, variantKey);\n cells.set(cellKey, cell);\n }\n if (cell.settled === \"value\") return cell.value;\n throw cell.error;\n };\n}\n\nfunction settleTargetOnce(\n readGetter: (variantKey: string | undefined) => unknown,\n variantKey: string | undefined\n): SettledTarget {\n // READING the getter cannot fail: every `readGetter` handed to\n // {@link createTargetSettlement} is one property read over frozen\n // declaration state. INVOKING it can, and that is the one `try` below.\n const getter = readGetter(variantKey);\n // The read still may not produce one: a variant asked without a key or with\n // an unknown one has no entry, and a forged state can carry a non-function\n // target where the factories admit only a getter. Settling that as a failure\n // is what keeps every later consumer from re-reading a target that can never\n // resolve — and from reading `undefined` as a resolved one.\n if (typeof getter !== \"function\") {\n return {\n settled: \"error\",\n error: new Error(\"Relation target getter is not a function\"),\n };\n }\n try {\n return { settled: \"value\", value: getter() };\n } catch (thrown) {\n return {\n settled: \"error\",\n error: normalizeThrown(\n thrown,\n \"Relation target getter threw a non-Error value\"\n ),\n };\n }\n}\n\n/**\n * One normalization, owned here: a thrown `Error` keeps its identity across\n * every consumer, and a non-Error throw becomes exactly one `Error` that every\n * consumer then shares.\n */\nfunction normalizeThrown(thrown: unknown, nonErrorPrefix: string): Error {\n if (thrown instanceof Error) return thrown;\n let rendered: string;\n try {\n rendered = typeof thrown === \"symbol\" ? thrown.toString() : String(thrown);\n } catch {\n rendered = \"<unrenderable non-Error value>\";\n }\n return new Error(`${nonErrorPrefix}: ${rendered}`);\n}\n"],"mappings":"gIA8CA,MAAa,EAAiC,OAAO,IAAI,mBAAmB,CA0C5E,SAAgB,WAAW,EAAsC,CAC/D,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAW,EAA0C,GAC3D,OAAO,OAAO,GAAY,YAAY,EAIxC,SAAgB,gBAAgB,EAAmC,CACjE,OA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IAAI,IAClB,MAAQ,IAAiC,CACvC,IAAM,EAAU,GAAc,GAC1B,EAAO,EAAM,IAAI,EAAQ,CAK7B,GAJI,IAAS,IAAA,KACX,EAAO,iBAAiB,EAAY,EAAW,CAC/C,EAAM,IAAI,EAAS,EAAK,EAEtB,EAAK,UAAY,QAAS,OAAO,EAAK,MAC1C,MAAM,EAAK,OAIf,SAAS,iBACP,EACA,EACe,CAIf,IAAM,EAAS,EAAW,EAAW,CAMrC,GAAI,OAAO,GAAW,WACpB,MAAO,CACL,QAAS,QACT,MAAW,MAAM,2CAA2C,CAC7D,CAEH,GAAI,CACF,MAAO,CAAE,QAAS,QAAS,MAAO,GAAQ,CAAE,OACrC,EAAQ,CACf,MAAO,CACL,QAAS,QACT,MAAO,gBACL,EACA,iDACD,CACF,EASL,SAAS,gBAAgB,EAAiB,EAA+B,CACvE,GAAI,aAAkB,MAAO,OAAO,EACpC,IAAI,EACJ,GAAI,CACF,EAAW,OAAO,GAAW,SAAW,EAAO,UAAU,CAAG,OAAO,EAAO,MACpE,CACN,EAAW,iCAEb,OAAW,MAAM,GAAG,EAAe,IAAI,IAAW"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n}from"./base-
|
|
2
|
-
//# sourceMappingURL=transaction-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n}from"./base-AdXAoy6l.mjs";var TransactionError=class extends n{static diagnosticName=`TransactionError`;constructor(e,n){super(e,n?.code??t.TRANSACTION_FAILED,n)}},InvalidTransactionInputError=class extends n{static diagnosticName=`InvalidTransactionInputError`;constructor(e){super(`$transaction array must contain only pending operations from client methods`,t.INVALID_TRANSACTION_INPUT,e)}};export{TransactionError as n,InvalidTransactionInputError as t};
|
|
2
|
+
//# sourceMappingURL=transaction-Bnl6ULTw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transaction-Bnl6ULTw.mjs","names":[],"sources":["../src/errors/transaction.ts"],"sourcesContent":["import {\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n type VibORMErrorOptions,\n} from \"./base\";\n\n/**\n * Every code {@link TransactionError} can carry.\n *\n * A family, not a single literal: the driver error mapping raises the same class for a plain\n * failure, a timeout, lock contention, a deadlock and a serialization failure, and the retry policy reads the\n * code to tell them apart. `INVALID_TRANSACTION_INPUT` is in the union too — the transaction\n * OPTION refusals (`drivers/shared/transaction-options.ts`) raise it through this class, while\n * {@link InvalidTransactionInputError} owns the `$transaction([...])` array-form refusal.\n * Measured at the construction sites; the two are told apart by class, not by code.\n */\nexport type TransactionErrorCode =\n | typeof VibORMErrorCode.TRANSACTION_FAILED\n | typeof VibORMErrorCode.TRANSACTION_TIMEOUT\n | typeof VibORMErrorCode.DEADLOCK\n | typeof VibORMErrorCode.SERIALIZATION_FAILURE\n | typeof VibORMErrorCode.INVALID_TRANSACTION_INPUT\n | typeof VibORMErrorCode.TRANSACTION_CONTENTION;\n\n/**\n * Transaction errors\n */\nexport class TransactionError extends VibORMError {\n static override readonly diagnosticName = \"TransactionError\";\n\n /** Discriminant: one of {@link TransactionErrorCode}, never a code outside the family. */\n declare readonly code: TransactionErrorCode;\n\n constructor(\n message: string,\n options?: VibORMErrorOptions & { code?: TransactionErrorCode | undefined }\n ) {\n super(\n message,\n options?.code ?? VibORMErrorCode.TRANSACTION_FAILED,\n options\n );\n }\n}\n\n/**\n * Invalid input passed to $transaction array mode\n */\nexport class InvalidTransactionInputError extends VibORMError {\n static override readonly diagnosticName = \"InvalidTransactionInputError\";\n\n /** Literal discriminant: this class always carries `INVALID_TRANSACTION_INPUT`. */\n declare readonly code: typeof VibORMErrorCode.INVALID_TRANSACTION_INPUT;\n\n constructor(options?: { meta?: VibORMErrorMeta }) {\n super(\n \"$transaction array must contain only pending operations from client methods\",\n VibORMErrorCode.INVALID_TRANSACTION_INPUT,\n options\n );\n }\n}\n"],"mappings":"wFA4BA,IAAa,iBAAb,cAAsC,CAAY,CAChD,OAAyB,eAAiB,mBAK1C,YACE,EACA,EACA,CACA,MACE,EACA,GAAS,MAAQ,EAAgB,mBACjC,EACD,GAOQ,6BAAb,cAAkD,CAAY,CAC5D,OAAyB,eAAiB,+BAK1C,YAAY,EAAsC,CAChD,MACE,8EACA,EAAgB,0BAChB,EACD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"./chunk-BuuaeEvq.mjs";import{t as n}from"./transaction-
|
|
2
|
-
//# sourceMappingURL=transaction-operation-
|
|
1
|
+
import{n as e,t}from"./chunk-BuuaeEvq.mjs";import{t as n}from"./transaction-Bnl6ULTw.mjs";var r=t({readTransactionOperation:()=>readTransactionOperation,registerTransactionOperationOwner:()=>registerTransactionOperationOwner,transactionOperationOwner:()=>transactionOperationOwner});const i=[],a=new WeakMap;function transactionOperationOwner(e){let t=Object.getPrototypeOf(e),r=a.get(t);if(r===void 0)throw new n;return r}function registerTransactionOperationOwner(e,t,n){let r=n,resolve=n=>t(n)&&Object.getPrototypeOf(n)===e?r:void 0,o=Object.freeze({resolve});i.push(o),a.set(e,r)}function readTransactionOperation(e){for(let t of i)try{let n=t.resolve(e);if(n!==void 0)return n}catch{}}export{r as i,registerTransactionOperationOwner as n,transactionOperationOwner as r,readTransactionOperation as t};
|
|
2
|
+
//# sourceMappingURL=transaction-operation-CKK3l_9x.mjs.map
|
package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-operation-
|
|
1
|
+
{"version":3,"file":"transaction-operation-CKK3l_9x.mjs","names":[],"sources":["../src/query-engine/transaction-operation.ts"],"sourcesContent":["import type {\n AnyDriver,\n QueryExecutionContext,\n QueryResult,\n} from \"@drivers/exports\";\nimport { InvalidTransactionInputError } from \"@errors\";\nimport type { ObservationCompletionFactsReader } from \"@extensions/observation\";\nimport type {\n QueryInterceptorExecutionControl,\n TransactionWriteOutcomes,\n WriteOutcomeNotifications,\n} from \"@extensions/query\";\nimport type { PreparedBatchOperation, PreparedQuery } from \"./types\";\n\n/** One shared owner table registered once by each genuine operation class. */\nexport interface TransactionOperationOwner<Owner extends object = object> {\n clientId(owner: Owner): symbol;\n scopeId(owner: Owner): symbol;\n model(owner: Owner): string;\n operation(owner: Owner): string;\n context(owner: Owner): QueryExecutionContext;\n requiresInterception(owner: Owner): boolean;\n prepareAdmission(owner: Owner, phase?: \"input\" | \"plan\"): void;\n stagePackageWriteOutcomes(\n owner: Owner,\n outcomes: TransactionWriteOutcomes\n ): void;\n startInterception(\n owner: Owner,\n child: (notifications?: WriteOutcomeNotifications) => Promise<unknown>,\n outcomes: TransactionWriteOutcomes,\n control: QueryInterceptorExecutionControl\n ): Promise<unknown>;\n executeCore(\n owner: Owner,\n driver: AnyDriver,\n notifications?: WriteOutcomeNotifications\n ): Promise<unknown>;\n isWrite(owner: Owner): boolean;\n hasObservation(owner: Owner): boolean;\n observe(\n owner: Owner,\n child: () => Promise<unknown>,\n readCompletionFacts?: ObservationCompletionFactsReader\n ): Promise<unknown>;\n reserveWith(owner: Owner, driver: AnyDriver): void;\n executeWith(owner: Owner, driver: AnyDriver): Promise<unknown>;\n prepare(owner: Owner, driver?: AnyDriver): PreparedQuery | undefined;\n prepareBatch(\n owner: Owner\n ): Promise<PreparedBatchOperation<unknown> | undefined>;\n parseResult(owner: Owner, raw: QueryResult<unknown>): unknown;\n observeBatchPhase<Result>(\n owner: Owner,\n driver: AnyDriver,\n execute: () => Result | Promise<Result>\n ): Promise<Result>;\n}\n\n/** The private authority resolved only while coordinating an array. */\nexport type TransactionOperationCapability = object;\n\ninterface RegisteredTransactionOperationOwner {\n readonly resolve: TransactionOperationResolver;\n}\n\ntype TransactionOperationResolver = (\n value: object\n) => TransactionOperationOwner<TransactionOperationCapability> | undefined;\n\nconst transactionOperationOwners: RegisteredTransactionOperationOwner[] = [];\nconst transactionOperationOwnersByPrototype = new WeakMap<\n object,\n TransactionOperationOwner<TransactionOperationCapability>\n>();\n\n/** Resolve the one class owner after the capability passed admission. */\nexport function transactionOperationOwner(\n operation: TransactionOperationCapability\n): TransactionOperationOwner<TransactionOperationCapability> {\n const prototype = Object.getPrototypeOf(operation);\n const owner = transactionOperationOwnersByPrototype.get(prototype);\n if (owner === undefined) throw new InvalidTransactionInputError();\n return owner;\n}\n\n/** Register one class-owned array authority for its exact private brand. */\nexport function registerTransactionOperationOwner<Owner extends object>(\n prototype: object,\n authenticate: (value: object) => value is Owner,\n owner: TransactionOperationOwner<Owner>\n): void {\n const resolvedOwner: TransactionOperationOwner<TransactionOperationCapability> =\n owner;\n const resolve = (\n value: object\n ): TransactionOperationOwner<TransactionOperationCapability> | undefined =>\n authenticate(value) && Object.getPrototypeOf(value) === prototype\n ? resolvedOwner\n : undefined;\n const registration: RegisteredTransactionOperationOwner = Object.freeze({\n resolve,\n });\n transactionOperationOwners.push(registration);\n transactionOperationOwnersByPrototype.set(prototype, resolvedOwner);\n}\n\n/** Resolve one owner only for an object constructed by its registered class. */\nexport function readTransactionOperation(\n value: object\n): TransactionOperationOwner<TransactionOperationCapability> | undefined {\n for (const registration of transactionOperationOwners) {\n try {\n const owner = registration.resolve(value);\n if (owner !== undefined) return owner;\n } catch {\n // A hostile candidate cannot interrupt the remaining genuine owners.\n }\n }\n return undefined;\n}\n\n/** The static thenable accepted by internal transaction composition. */\nexport interface TransactionOperation<T> extends PromiseLike<T> {}\n"],"mappings":"2RAsEA,MAAM,EAAoE,EAAE,CACtE,EAAwC,IAAI,QAMlD,SAAgB,0BACd,EAC2D,CAC3D,IAAM,EAAY,OAAO,eAAe,EAAU,CAC5C,EAAQ,EAAsC,IAAI,EAAU,CAClE,GAAI,IAAU,IAAA,GAAW,MAAM,IAAI,EACnC,OAAO,EAIT,SAAgB,kCACd,EACA,EACA,EACM,CACN,IAAM,EACJ,EACI,QACJ,GAEA,EAAa,EAAM,EAAI,OAAO,eAAe,EAAM,GAAK,EACpD,EACA,IAAA,GACA,EAAoD,OAAO,OAAO,CACtE,QACD,CAAC,CACF,EAA2B,KAAK,EAAa,CAC7C,EAAsC,IAAI,EAAW,EAAc,CAIrE,SAAgB,yBACd,EACuE,CACvE,IAAK,IAAM,KAAgB,EACzB,GAAI,CACF,IAAM,EAAQ,EAAa,QAAQ,EAAM,CACzC,GAAI,IAAU,IAAA,GAAW,OAAO,OAC1B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./base-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./base-AdXAoy6l.mjs";import{n}from"./suppressed-failure-BwULh-8h.mjs";import{a as r}from"./validator-X9-bwtRo.mjs";import{existsSync as i}from"node:fs";import{resolve as a}from"node:path";import{loadEnvFile as o}from"node:process";import{createJiti as s}from"jiti";const c=[`viborm.config.ts`,`viborm.config.mts`,`viborm.config.js`,`viborm.config.mjs`];function findFile(e,t){for(let n of t){let t=a(e,n);if(i(t))return t}return null}function failCli(e,n=!1){let r=t(e),i=e instanceof Error?e.message:typeof e==`string`?e:`CLI operation failed`,a=r?e.code:void 0,o=a?.startsWith(`V11`)?Number(a.slice(1))-11e3+10:r?2:1;process.stderr.write(n?`${JSON.stringify({error:r?e.toJSON():{name:e instanceof Error?e.name:`Error`,message:i},exitCode:o})}\n`:`${a?`[${a}] `:``}${i}\n`),process.exit(o)}async function finishCli(e,t,r=!1){let i=t;try{await e?.$disconnect()}catch(e){i={value:t?n(t.value,e):e}}i&&(r?failCli(i.value,!0):failCli(i.value))}async function runCli(e,t,n){let r,i;try{let t=await loadConfig(e);r=t.client,await n(t)}catch(e){i={value:e}}finally{await finishCli(r,i,t)}}function printJson(e,t){if(t){process.stdout.write(`${JSON.stringify(e,null,2)}\n`);return}let n=[],render=(e,t=``)=>{if(Array.isArray(e)){for(let r of e)n.push(`${t}-`),render(r,`${t} `);e.length===0&&n.push(`${t}(none)`)}else if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))typeof i==`object`&&i?(n.push(`${t}${r}:`),render(i,`${t} `)):n.push(`${t}${r}: ${String(i)}`);else n.push(`${t}${String(e)}`)};render(e),process.stdout.write(`${n.join(`
|
|
2
|
+
`)}\n`)}async function loadConfig(e={}){let t=process.cwd(),n=a(t,`.env`);i(n)&&o(n);let s=e.config?a(t,e.config):findFile(t,c);if(!(s&&i(s))){let t=e.config?[e.config]:c;throw Error(`Could not find VibORM configuration file.
|
|
2
3
|
|
|
3
4
|
Searched for:\n${t.map(e=>` - ${e}`).join(`
|
|
4
5
|
`)}\n\nCreate a viborm.config.ts file:
|
|
@@ -21,5 +22,5 @@ Searched for:\n${t.map(e=>` - ${e}`).join(`
|
|
|
21
22
|
id: s.string().id(),
|
|
22
23
|
name: s.string(),
|
|
23
24
|
});
|
|
24
|
-
`);return e.skipValidation||r(p),{client:u.client,driver:d,models:p,migrations:u.migrations}}function loadCliModule(e){return s(e,{tsconfigPaths:!0,interopDefault:!0}).import(e)}function extractModels(e){let t={};for(let[n,r]of Object.entries(e))isModel(r)&&(t[n]=r);return t}function isModel(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);return typeof n==`object`&&!!n&&`scalars`in n}function isValidClient(e){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:Reflect.get(e,`$driver`)!==void 0&&Reflect.get(e,`$schema`)!==void 0}function defineConfig(e){return e}export{
|
|
25
|
-
//# sourceMappingURL=utils-
|
|
25
|
+
`);return e.skipValidation||r(p),{client:u.client,driver:d,models:p,migrations:u.migrations}}function loadCliModule(e){return s(e,{tsconfigPaths:!0,interopDefault:!0}).import(e)}function extractModels(e){let t={};for(let[n,r]of Object.entries(e))isModel(r)&&(t[n]=r);return t}function isModel(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);return typeof n==`object`&&!!n&&`scalars`in n}function isValidClient(e){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:Reflect.get(e,`$driver`)!==void 0&&Reflect.get(e,`$schema`)!==void 0}function defineConfig(e){return e}export{runCli as i,loadCliModule as n,printJson as r,defineConfig as t};
|
|
26
|
+
//# sourceMappingURL=utils-CZNaOZR7.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-CZNaOZR7.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = await loadCliModule<\n VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig }\n >(configPath);\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unkn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,n as i,o as a,r as o,s}from"./value-guards-CK9guf2Z.mjs";import{t as c}from"./validation-Dk9Q_-C7.mjs";import{g as l,m as ee,v as u,x as d,y as f}from"./terminal-C8cq1WWX.mjs";import{o as te,r as p}from"./sql-Bp7jicEX.mjs";import{B as m,F as ne,H as h,I as g,J as _,K as v,Nt as re,R as y,U as b,V as x,W as S,Y as C,a as w,d as T,f as E,i as ie,m as D,o as ae,p as O,q as oe,r as se,z as k}from"./geo-point-codec-lhxH42SK.mjs";function array(e){let t=e[`~standard`].validate,n=h(`array`,e=>oe(e,t));return n.item=e,n}const A=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Uint8Array`})])}),j=Object.getPrototypeOf(Uint8Array.prototype);function localBufferPrototype(){try{let e=Reflect.get(globalThis,`Buffer`);if(typeof e!=`function`)return;let t=Reflect.get(e,`prototype`);if(typeof t==`object`&&t&&Object.getPrototypeOf(t)===Uint8Array.prototype)return t}catch{return}}const M=localBufferPrototype();function hasOwnViewMetadata(e){return Object.getOwnPropertyDescriptor(e,`buffer`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteOffset`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteLength`)!==void 0}function hasTrustedLocalPrototype(e){let t=Object.getPrototypeOf(e);return(t===Uint8Array.prototype||t===M)&&!hasOwnViewMetadata(e)}function validateBlob(e){try{if(!n(e))return A;let t=Reflect.get(j,`buffer`,e),r=Reflect.get(j,`byteOffset`,e),i=Reflect.get(j,`byteLength`,e),a=hasTrustedLocalPrototype(e),o=new Uint8Array(t,r,i);return S(a?e:o)}catch{return A}}function blob(e){return x(`blob`,validateBlob,e)}const N=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected boolean`})])});function validateBoolean(e){return i(e)?S(e):N}function boolean(e){return x(`boolean`,validateBoolean,e)}const P=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Date`})])}),F=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected valid Date`})])});function validateDate(e){if(!o(e))return P;let t=Date.prototype.getTime.call(e);return Number.isNaN(t)?F:e instanceof Date?S(e):S(new Date(t))}function date(e){return x(`date`,validateDate,e)}const I=Object.freeze({issues:Object.freeze([Object.freeze({message:g})])});function validateDecimal(e){let t=y(e);return t===void 0?I:S(t)}function buildDecimalValueValidator(e){let t=e?.schema,n=e?.decimal,validate=validateDecimal;if(t!==void 0){let e=t[`~standard`].validate,n=validate;validate=t=>{let r=n(t);if(r.issues)return r;let i=e(ne(r.value));if(`then`in i)return C(i),b(`Async schemas are not supported`);if(i.issues)return v(i.issues);let a=k(i.value);return a===void 0?b(`Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type`):S(a)}}if(n!==void 0){let e=validate;validate=t=>{let r=e(t);if(r.issues)return r;let i=m(r.value,n.precision,n.scale);return i===void 0?r:b(i)}}return validate}function decimal(e){let t=e===void 0?void 0:{...e,schema:void 0};return x(`decimal`,buildDecimalValueValidator(e),t)}function enum_(e,t){let n=new Set(e),baseValidate=t=>s(t)&&n.has(t)?S(t):{issues:[{message:`Expected one of: ${e.join(` | `)}`}]};return x(`enum`,baseValidate,t,{values:e})}function getNestedValue(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function declaresPath(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:getNestedValue(e,t.slice(0,n));return a(r)&&t.slice(n+1)in r}function entriesFromObject(e,t){let n={};for(let r of Object.keys(e)){let i=getNestedValue(e[r],t);i!==void 0&&(n[r]=i)}return Object.keys(e).length>0&&Object.keys(n).length===0&&refuseUnmatchedPath(e,t),n}function fromObject(e,t,n){return D(entriesFromObject(e,t),n)}function refuseUnmatchedPath(e,t){if(!Object.values(e).some(e=>declaresPath(e,t)))throw new c({kind:`schema-builder`,builder:`fromObject`,path:t},[{path:t,message:`fromObject path "${t}" did not match any entries in the source object`}])}const L=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-](\d{2}):(\d{2}))$/,R=/^(\d{4})-(\d{2})-(\d{2})$/,z=/^\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/,B=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string or Date`})])}),V=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)`})])}),H=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date in ISO timestamp`})])});function validateIsoTimestamp(e){if(o(e))return E(Date.prototype.getTime.call(e))?S(Date.prototype.toISOString.call(e)):H;if(!s(e))return B;let t=L.exec(e);return t?!(O(Number(t[1]),Number(t[2]),Number(t[3]))&&T(Number(t[4]),Number(t[5]),Number(t[6])))||Number(t[7]??0)>23||Number(t[8]??0)>59||!E(Date.parse(e))?H:S(new Date(e).toISOString()):V}function isoTimestamp(e){return x(`iso_timestamp`,validateIsoTimestamp,e)}const U=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO date format (YYYY-MM-DD)`})])}),W=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date`})])});function validateIsoDate(e){if(o(e))return E(Date.prototype.getTime.call(e))?S(Date.prototype.toISOString.call(e).slice(0,10)):W;if(!s(e))return B;let t=R.exec(e);return t?O(Number(t[1]),Number(t[2]),Number(t[3]))?S(e):W:U}function isoDate(e){return x(`iso_date`,validateIsoDate,e)}const G=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO time format (HH:mm:ss)`})])}),K=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid time`})])});function validateIsoTime(e){if(o(e))return Number.isNaN(Date.prototype.getTime.call(e))?K:S(Date.prototype.toISOString.call(e).split(`T`)[1].replace(`Z`,``));if(!s(e))return B;if(!z.test(e))return G;let t=e.split(`:`),n=Number(t[0]),r=Number(t[1]),i=Math.trunc(Number(t[2]));return n<0||n>23||r<0||r>59||i<0||i>59?K:S(e.padEnd(12,e.includes(`.`)?`0`:`.000`))}function isoTime(e){return x(`iso_time`,validateIsoTime,e)}const ce=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected JSON-compatible value`})])}),q=Symbol(`invalid JSON`);function normalizeJson(e,n=new WeakMap){if(e===null||s(e)||i(e))return e;if(t(e))return Number.isFinite(e)?e:q;if(!(a(e)||Array.isArray(e))||d(e))return q;let r=n.get(e);if(r!==void 0)return r;if(n.set(e,q),Array.isArray(e)){let t=[];for(let r of e){let e=r===void 0?null:normalizeJson(r,n);if(e===q)return q;t.push(e)}return n.set(e,t),t}let o=Object.getPrototypeOf(e);if(o!==null&&o!==Object.prototype)return q;let c={};for(let t of Object.keys(e)){let r=e[t];if(r===void 0)continue;let i=normalizeJson(r,n);if(i===q)return q;Object.defineProperty(c,t,{value:i,enumerable:!0,configurable:!0,writable:!0})}return n.set(e,c),c}function validateJson(e){let t=normalizeJson(e);return t===q?ce:S(t)}function json(e){return x(`json`,validateJson,e)}const J=[`DbNull`,`JsonNull`,`AnyNull`];function listKinds(e){return e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} or ${e.at(-1)}`}function refuseSentinel(e,t,n){return b(`${J.filter(e=>!t.includes(e)).length===J.length?`JSON null sentinels are not supported in ${n}`:`${e.kind} is not supported in ${n}; that slot accepts ${listKinds(t)}`}.`)}function checkSentinel(e,t,n){return t.includes(e.kind)?S(e):refuseSentinel(e,t,n)}function copyOptionality(e,t,n){e.allowed=n,e.wrapped=t,e.acceptsUndefined=t.acceptsUndefined===!0}function jsonNullOr(e,t,n){let r=h(`json_null_or`,r=>l(r)?checkSentinel(r,e,n):_(t,r));return copyOptionality(r,t,e),r}function jsonWrite(e,t,n,r){let i=h(`json_write`,i=>{if(l(i))return checkSentinel(i,e,n);if(i===null)return b(r);let a=_(t,i);return!a.issues&&a.value===null&&i!==void 0?checkSentinel(ee,e,n):a});return copyOptionality(i,t,e),i}function lazy(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return new Proxy({},{get(e,t,n){let i=resolve(),a=Reflect.get(i,t,n);return r(a)?a.bind(i):a},has(e,t){return Reflect.has(resolve(),t)},ownKeys(e){return Reflect.ownKeys(resolve())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(resolve(),t)},getPrototypeOf(e){return Reflect.getPrototypeOf(resolve())}})}function lazyRef(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return{type:`lazyRef`,get wrapped(){return resolve()},get entries(){return resolve().entries},"~standard":{version:1,vendor:`viborm`,validate:e=>resolve()[`~standard`].validate(e),get jsonSchema(){return resolve()[`~standard`].jsonSchema}}}}function literal(e,t){let n=e===null?`null`:String(e),r=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected literal: ${n}`})])}),baseValidate=t=>t===e?S(t):r;return x(`literal`,baseValidate,t,{value:e})}function nullable(e){let t=e[`~standard`].validate,n=h(`nullable`,e=>e===null?S(null):t(e));return n.wrapped=e,n}function maybeNullable(e,t){return t?nullable(e):e}function omit(e,t){return D(e.entries,{...e.options||{},omit:t})}let Y=0;function limitFilterDepth(e){let t=e[`~standard`].validate;return Object.defineProperty(e[`~standard`],`validate`,{value:e=>{if(Y>=16)return b(`Filter nesting exceeds 16 levels`);Y++;try{return t(e)}finally{Y--}}}),e}let X;const Z=new WeakMap;function runInOperandScope(e,t){let n=X;X=e;try{return t()}finally{X=n}}function scopeOperands(e,t){let n=e[`~standard`],r=n.validate;return n.validate=e=>runInOperandScope(t,()=>r(e)),limitFilterDepth(e)}function currentContext(){let e=X;if(!e)return;let t=Z.get(e);if(t)return t;let n={fields:u(e[`~`].names.ts??`unknown`,e),sql:te};return Z.set(e,n),n}const Q="A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)";function describe$1(e){return e===null?`null`:Array.isArray(e)?`an array`:`a value of type '${typeof e}'`}e(describe$1,`describe`);function resolveCallback(e,t){let n=currentContext();if(!n)return b(`A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.`);let i;try{i=e(n)}catch(e){return b(`Filter callback threw: ${e instanceof Error?e.message:String(e)}`)}return d(i)?checkRef(i,t):p(i)?S(i):a(i)&&r(i.then)?(C(i),b(`${Q}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`)):b(`${Q}; it returned ${describe$1(i)}.`)}function comparisonOperand(e,t){let n=h(`comparison_operand`,n=>r(n)?resolveCallback(n,e):d(n)?checkRef(n,e):p(n)?S(n):_(t,n));return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function fieldRefOr(e,t){let n=h(`field_ref_or`,n=>d(n)?checkRef(n,e):_(t,n));return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function closeOperands(e,t,n){let r=e[`~standard`],i={"~standard":{version:r.version,vendor:r.vendor,validate:r.validate}},a=h(`no_field_ref`,e=>{let r=findOpaqueOperand(e,n);if(r)return b(`${r} is not supported in ${t}.`);let a=_(i,e);if(a.issues)return a;let o=findOpaqueOperand(a.value,n);return o?b(`${o} is not supported in ${t}.`):a});return a.wrapped=e,a.acceptsUndefined=e.acceptsUndefined??!1,a}function noFieldRef(e,t){return closeOperands(e,t,!1)}function noOperandExpression(e,t){return closeOperands(e,t,!0)}function findOpaqueOperand(e,t){let n=new WeakSet,r=[e];for(;r.length>0;){let e=r.pop();if(t&&typeof e==`function`)return`A filter callback`;if(!(typeof e!=`object`||!e)){if(d(e)){let t=f(e);return`Field reference '${t.model}.${t.field}'`}if(t&&p(e))return`An SQL fragment`;if(!n.has(e)&&(n.add(e),!(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))){if(Array.isArray(e)){for(let t of e)r.push(t);continue}for(let t of Object.keys(e))r.push(e[t])}}}}function checkRef(e,t){let n=f(e);return n.list?b(`Field reference '${n.model}.${n.field}' is a list field; list fields cannot be used as a comparison operand.`):n.type===t?S(e):b(`Field reference '${n.model}.${n.field}' is of type '${n.type}', but a '${t}' operand is required here.`)}function transform(e){return{type:`transform`,transform:e}}function pipe(e,...t){let n=h(`pipe`,n=>{let r=_(e,n);if(r.issues)return r;let i=r.value;for(let e of t)if(e.type===`transform`)try{i=e.transform(i)}catch(e){return b(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}return S(i)});return n.schema=e,n.actions=t,n}function point(e){return x(`point`,se,e)}function record(e,t){let n=h(`record`,n=>{if(!a(n))return b(`Expected object, received ${Array.isArray(n)?`array`:typeof n}`);let r={};for(let[i,a]of Object.entries(n)){let n=_(e,i);if(n.issues)return b(`Invalid key "${i}": ${n.issues[0].message}`,[i]);let o=_(t,a);if(o.issues){let e=o.issues[0],t=e.path?[i].concat(e.path):[i];return b(e.message,t)}r[n.value]=o.value}return S(r)});return n.key=e,n.value=t,n}function entriesFromKeys(e,t){let n={};for(let r of e)n[r]=t;return n}function fromKeys(e,t,n){return D(entriesFromKeys(e,t),n)}function refused(e){return h(`refused`,()=>b(e))}function coerce(e,t){let n=h(`transform`,n=>{let r=_(e,n);if(r.issues)return{issues:r.issues};try{return S(t(r.value))}catch(e){return b(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}});return n.wrapped=e,n.acceptsUndefined=e.acceptsUndefined===!0,n}const le=coerce,shorthandFilter=e=>coerce(e,e=>({equals:e})),shorthandUpdate=e=>coerce(e,e=>({set:e})),shorthandArray=e=>coerce(e,e=>[e]),ue=Object.freeze([Object.freeze({message:`Async schemas are not supported`})]);function tagsOf(e){let t,n=new Map;for(let r of e){let{type:e,entries:i,options:a}=r;if(e!==`object`||!i||a?.array===!0)return;t??=Object.keys(i).find(e=>isLiteral(i[e]));let o=t===void 0?void 0:i[t];if(!(isLiteral(o)&&o.acceptsUndefined!==!0)||n.has(o.value)||a?.omit?.includes(t))return;n.set(o.value,r[`~standard`].validate)}return t===void 0||n.size<2?void 0:{key:t,members:n}}function isLiteral(e){return a(e)&&e.type===`literal`}function settled(e){return`then`in e?(C(e),{issues:ue}):e}function describe({message:e,path:t}){return t?.length?`${t.join(`.`)}: ${e}`:e}function union(e){let t=e.map(e=>e[`~standard`].validate),n=null,r=h(`union`,r=>{n===null&&(n=tagsOf(e));let i=n&&a(r)&&n.members.get(r[n.key]);if(i)return settled(i(r));let o,s=-1,c;for(let e of t){let t=settled(e(r));if(!t.issues)return t;let{issues:n}=t,i=n[0].path?.length??0;if(i>s)o=n,s=i,c=void 0;else if(i===s){let e=describe(n[0]);c??=[describe(o[0])],c.includes(e)||c.push(e)}}return c&&c.length>1?b(c.join(`, or `)):o?{issues:o}:b(`Expected no value: the union has no member`)});return r.options=e,r}const singleOrArray=e=>union([coerce(e,e=>[e]),array(e)]),de=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string`})])});function validateString(e){return s(e)?S(e):de}function string(e){return x(`string`,validateString,e)}const fe=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected array of numbers`})])});function createVectorValidator(e){let n=e===void 0?null:Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected vector of ${e} dimensions`})])});return r=>{if(!Array.isArray(r))return fe;let i=r.length;for(let e=0;e<i;e++)if(!(t(r[e])&&Number.isFinite(r[e])))return b(`Expected finite number at index ${e}`);return n&&i!==e?n:S(r)}}function vector(e,t){return x(`vector`,createVectorValidator(e),t,{dimensions:e})}const $={string,number:ae,integer:w,boolean,bigint:re,decimal,literal,enum:enum_,json,date,isoTimestamp,isoDate,isoTime,blob,vector,point,array,nullable,maybeNullable,optional:ie,object:D,omit,fromObject,union,pipe,transformAction:transform,record,fromKeys,coerce,map:le,lazy,lazyRef,singleOrArray,shorthandFilter,shorthandUpdate,shorthandArray,comparisonOperand,fieldRefOr,noFieldRef,noOperandExpression,jsonNullOr,jsonWrite,refused};var pe=$;export{limitFilterDepth as a,validateIsoTimestamp as c,scopeOperands as i,entriesFromObject as l,pe as n,validateIsoDate as o,entriesFromKeys as r,validateIsoTime as s,$ as t};
|
|
2
|
+
//# sourceMappingURL=v-D5Z06FKN.mjs.map
|