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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chain-Dh0FV72b.mjs","names":["readOwn","ownKeys","callRows"],"sources":["../src/drivers/driver-identity.ts","../src/client/default-omit-extension.ts","../src/extensions/rows.ts","../src/extensions/definition.ts","../src/extensions/chain.ts"],"sourcesContent":["import type { Dialect } from \"./types\";\n\n/**\n * The configuration facts that name one driver in presented telemetry. No\n * package entry exports this module.\n *\n * `namespace` is the adapter's one normalized SQL qualifier and is absent when\n * the adapter is unqualified. `adapter.namespace` is installed non-writable,\n * so a snapshot taken once (the cached read's, at `$withCache`) cannot go\n * stale. This is the one reader of that property for presentation.\n */\nexport interface DriverIdentity {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly namespace?: string;\n}\n\n/** The public readonly driver fields an identity is read from. */\nexport interface DriverIdentitySource {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly adapter: { readonly namespace?: string };\n}\n\n/**\n * Read one driver's identity from its public readonly configuration, or\n * `undefined` when that read throws (a custom adapter's `namespace` getter):\n * every presenter then omits the driver attributes and presents the rest.\n */\nexport function readDriverIdentity(\n driver: DriverIdentitySource\n): DriverIdentity | undefined {\n try {\n const namespace = driver.adapter.namespace;\n return Object.freeze({\n dialect: driver.dialect,\n driverName: driver.driverName,\n ...(namespace === undefined ? {} : { namespace }),\n });\n } catch {\n // The operation's facts, its spans and a cached read's revalidation\n // identity survive a driver that cannot name itself.\n return undefined;\n }\n}\n","import { ClientInitializationError } from \"@errors\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type {\n GenericRequestHandler,\n OfficialGenericRequestHandler,\n} from \"@extensions/request\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ClientOmitConfig, ExactClientOmitConfig } from \"./omit\";\nimport type { Schema } from \"./types\";\n\nexport const OFFICIAL_DEFAULT_OMIT_NAME = \"viborm.defaultOmit\";\n\ndeclare const officialDefaultOmitConfig: unique symbol;\n\n/** The authenticated request identity carrying one exact static omit witness. */\nexport type OfficialDefaultOmitRequestContribution<Config> =\n OfficialGenericRequestHandler & {\n readonly [officialDefaultOmitConfig]: Config;\n bind(thisArg: unknown): GenericRequestHandler;\n };\n\n/** The official value accepted by the dedicated `$extends` admission branch. */\nexport type OfficialDefaultOmitExtension<Config extends object = object> = {\n readonly name: typeof OFFICIAL_DEFAULT_OMIT_NAME;\n readonly request: OfficialDefaultOmitRequestContribution<Config>;\n};\n\nexport interface OfficialDefaultOmitCapability {\n readonly config: ClientOmitConfig<Schema>;\n}\n\nconst capabilitiesByRequest = new WeakMap<\n CallableFunction,\n OfficialDefaultOmitCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialDefaultOmitCapability\n>();\n\nfunction configurationError(message: string, cause?: unknown): never {\n throw new ClientInitializationError(message, {\n cause: cause === undefined ? undefined : errorCause(cause),\n });\n}\n\nfunction ownKeys(value: object, label: string): PropertyKey[] {\n try {\n return Reflect.ownKeys(value);\n } catch (cause) {\n configurationError(\n `Default omit ${label} members could not be inspected.`,\n cause\n );\n }\n}\n\nfunction readOwn(\n value: Record<string, unknown>,\n key: string,\n label: string\n): unknown {\n try {\n return value[key];\n } catch (cause) {\n configurationError(\n `Default omit ${label} member \"${key}\" could not be read.`,\n cause\n );\n }\n}\n\nfunction isConfigurationRecord(\n value: unknown,\n label: string\n): value is Record<string, unknown> {\n try {\n return isRecord(value);\n } catch (cause) {\n configurationError(`Default omit ${label} could not be inspected.`, cause);\n }\n}\n\nfunction snapshotConfig(value: unknown): ClientOmitConfig<Schema> {\n if (!isConfigurationRecord(value, \"configuration\")) {\n configurationError(\"Default omit configuration must be an object.\");\n }\n const snapshot: Record<\n string,\n Readonly<Record<string, true>>\n > = Object.create(null);\n for (const modelKey of ownKeys(value, \"configuration\")) {\n if (typeof modelKey !== \"string\") {\n configurationError(\n \"Default omit configuration contains a non-string model key.\"\n );\n }\n const entry = readOwn(value, modelKey, \"configuration\");\n if (!isConfigurationRecord(entry, `configuration.${modelKey}`)) {\n configurationError(\n `Default omit configuration member \"${modelKey}\" must be an object.`\n );\n }\n const fields: Record<string, true> = Object.create(null);\n for (const fieldKey of ownKeys(entry, `configuration.${modelKey}`)) {\n if (typeof fieldKey !== \"string\") {\n configurationError(\n `Default omit configuration member \"${modelKey}\" contains a non-string field key.`\n );\n }\n if (readOwn(entry, fieldKey, `configuration.${modelKey}`) !== true) {\n configurationError(\n `Default omit configuration member \"${modelKey}.${fieldKey}\" must be true.`\n );\n }\n fields[fieldKey] = true;\n }\n snapshot[modelKey] = Object.freeze(fields);\n }\n return Object.freeze(snapshot);\n}\n\nexport type DefaultOmitBinder<S extends Schema> = <\n const Config extends ClientOmitConfig<S>,\n>(\n config: Config & NoInfer<ExactClientOmitConfig<Config, S>>\n) => OfficialDefaultOmitExtension<Config & object>;\n\n/** Create VibORM's fixed-name schema-bound default-omit extension. */\nexport function defaultOmit<S extends Schema>(): DefaultOmitBinder<S>;\nexport function defaultOmit(): unknown {\n return (config: unknown): unknown => {\n const capability = Object.freeze({ config: snapshotConfig(config) });\n const request: GenericRequestHandler = () => ({});\n capabilitiesByRequest.set(request, capability);\n return Object.freeze({\n name: OFFICIAL_DEFAULT_OMIT_NAME,\n request,\n });\n };\n}\n\nexport function getOfficialDefaultOmitRequestCapability(\n request: unknown\n): OfficialDefaultOmitCapability | undefined {\n return isFunction(request) ? capabilitiesByRequest.get(request) : undefined;\n}\n\nexport function getOfficialDefaultOmitChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialDefaultOmitCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialDefaultOmitChain(\n chain: ResolvedExtensionChain,\n capability: OfficialDefaultOmitCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n","import { stableStringify } from \"@cache/key\";\nimport type { Schema } from \"@client/types\";\nimport type {\n CallRows,\n ModelDomain,\n ModelStamps,\n RowDomain,\n} from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport type { ResolvedControls, ResolvedDeletion } from \"./chain\";\nimport {\n type AdmittedControls,\n isStableControlValue,\n type RowsContribution,\n rowsModes,\n} from \"./controls\";\nimport type { RuntimeExtensionDefinition } from \"./definition\";\n\ntype Predicates = RowsContribution[\"models\"][string][string];\n\n/** One `rows` member: its control, and where each of its modes sits. */\ninterface BoundRowsMember {\n readonly control: string;\n readonly names: readonly string[];\n readonly modes: ReadonlyMap<unknown, number>;\n readonly fallback: number;\n /** How far one step of this member's mode moves the combination index. */\n readonly stride: number;\n}\n\n/**\n * A chain's row facts, resolved once when an extension is applied: one\n * {@link CallRows} per combination of its `rows` members' modes, with and\n * without the tombstones, each with the chain's `data` stamps, so a call only\n * looks its facts up. When the combination's predicates or the default ones\n * name a control, a call takes those facts with its values put in, kept per\n * combination and values. When a stamp names one, the call's values are put\n * in its stamps for that call alone: they take no room in that memo, so a\n * tenant keeps one domain whoever writes.\n */\nexport interface RowsBinding {\n readonly members: readonly BoundRowsMember[];\n readonly deletion: Readonly<Record<string, ResolvedDeletion>>;\n /** Indexed by mode combination: the call writes tombstones. */\n readonly tombstoning: readonly CallRows[];\n /** Indexed by mode combination: the call deletes physically. */\n readonly physical: readonly CallRows[];\n /**\n * Indexed by mode combination: the controls its domain and the default\n * domain name; empty when none does, and the call takes the facts above.\n */\n readonly references: readonly (readonly string[])[];\n /** Facts with a call's values put in, by combination and values. */\n readonly bound: Map<string, CallRows>;\n /** A stamp names a control: each call puts its values in the stamps. */\n readonly bindsStamps: boolean;\n /** Whether a call must pass a control to touch a model directly. */\n readonly required: RequiredOn;\n /** A model's declared field names, from the receiving schema. */\n readonly fieldsOf: (model: string) => Fields | undefined;\n}\n\ntype RequiredOn = (control: string, model: string) => boolean;\n\nconst NEVER_REQUIRED: RequiredOn = () => false;\n\nconst NO_DELETION: Readonly<Record<string, ResolvedDeletion>> = Object.freeze(\n Object.create(null)\n);\n\n// ponytail: per-value memo, LRU if a tenant count above 256 is measured.\n/** How many bound facts one chain keeps: past it, the oldest goes. */\nconst BOUND_LIMIT = 256;\n\n/** A named control the call did not pass. */\nconst ABSENT = Symbol(\"absent\");\n\n/**\n * The predicate of a model whose required control the call did not pass. Such\n * a call can only reach that model through another one (a relation of a model\n * the control is not required on), and a required control means \"no value, no\n * rows\": it matches nothing, never everything. `{ OR: [] }` is false.\n */\nconst MATCH_NOTHING: Input = Object.freeze({ OR: Object.freeze([]) });\n\n/** The keys whose items are filters: a filter is never a reference. */\nconst LOGICAL = new Set([\"AND\", \"OR\", \"NOT\"]);\n\n/** A model's declared field names: its scalars and relations. */\ntype Fields = ReadonlySet<string>;\n\n/**\n * Whether `key` of a filter is a logical combinator. A model may declare a\n * field named `AND`, `OR` or `NOT`: at that model's filter, the name is the\n * field, as the engine reads it (`Queries.combinator`). Where the model is\n * not known (inside a field's operand), the name is the combinator.\n */\nconst isLogical = (key: string, fields: Fields | undefined): boolean =>\n LOGICAL.has(key) && fields?.has(key) !== true;\n\n/** `{ control: \"<name>\" }` where a predicate takes a value. */\nfunction referenceOf(value: unknown): string | undefined {\n if (!isPlainRecord(value)) return undefined;\n const [key, ...others] = Object.keys(value);\n return key === \"control\" &&\n others.length === 0 &&\n typeof value.control === \"string\"\n ? value.control\n : undefined;\n}\n\n/**\n * Every control a predicate's values name, at any depth. `filter` marks a\n * filter's place (the predicate, an item of `AND`/`OR`/`NOT`), where\n * `{ control }` is a field; `fields` are that filter's model's, when known.\n */\nfunction collectReferences(\n value: unknown,\n names: Set<string>,\n filter: boolean,\n fields?: Fields\n): void {\n const name = filter ? undefined : referenceOf(value);\n if (name !== undefined) names.add(name);\n else if (Array.isArray(value)) {\n for (const item of value) collectReferences(item, names, filter, fields);\n } else if (isPlainRecord(value)) {\n for (const [key, item] of Object.entries(value)) {\n const logical = isLogical(key, fields);\n collectReferences(item, names, logical, logical ? fields : undefined);\n }\n }\n}\n\n/** One definition may reference only its own declared controls. */\nexport function undeclaredControlReferencesOf(\n definition: RuntimeExtensionDefinition,\n schema?: Schema\n): readonly string[] {\n const declared = new Set(Object.keys(definition.controls ?? {}));\n if (definition.rows) declared.add(definition.rows.control);\n const references = new Set<string>();\n const fieldsOf = modelFields(schema);\n for (const [model, modes] of Object.entries(definition.rows?.models ?? {}))\n for (const mode of Object.values(modes)) {\n collectReferences(mode.root, references, true, fieldsOf(model));\n collectReferences(mode.related, references, true, fieldsOf(model));\n }\n for (const entry of Object.values(definition.data?.models ?? {}))\n for (const fields of [entry.create, entry.update])\n for (const value of Object.values(fields ?? {}))\n collectReferences(value, references, false);\n for (const name of Object.keys(definition.deletion?.removeWhen ?? {}))\n references.add(name);\n return [...references].filter((name) => !declared.has(name));\n}\n\n/** The controls a list of domains' predicates name. */\nfunction referencesOf(\n domains: readonly RowDomain[],\n fieldsOf: (model: string) => Fields | undefined\n): readonly string[] {\n const names = new Set<string>();\n for (const { root, related } of domains) {\n for (const models of [root, related]) {\n for (const [model, list] of models) {\n const fields = fieldsOf(model);\n for (const where of list) collectReferences(where, names, true, fields);\n }\n }\n }\n return [...names];\n}\n\n/** The value with the call's values put in: itself when it names none. */\nfunction boundValue(\n value: unknown,\n controls: AdmittedControls | undefined,\n filter: boolean,\n required?: (control: string) => boolean,\n fields?: Fields\n): unknown {\n const name = filter ? undefined : referenceOf(value);\n if (name !== undefined) {\n const given = controls?.[name];\n if (given !== undefined) return given;\n return required?.(name) ? MATCH_NOTHING : ABSENT;\n }\n if (Array.isArray(value)) {\n const items = value.map((item) =>\n boundValue(item, controls, filter, required, fields)\n );\n if (items.includes(MATCH_NOTHING)) return MATCH_NOTHING;\n if (items.includes(ABSENT)) return ABSENT;\n return items.every((item, index) => item === value[index]) ? value : items;\n }\n return isPlainRecord(value)\n ? boundWhere(value, controls, required, filter ? fields : undefined)\n : value;\n}\n\n/**\n * One predicate with the call's values put in. When it names a control the\n * call did not pass: {@link ABSENT} for an optional control (it filters\n * nothing, as a mode without that predicate would), {@link MATCH_NOTHING} for\n * one required on the predicate's model.\n */\nfunction boundWhere(\n where: Input,\n controls: AdmittedControls | undefined,\n required?: (control: string) => boolean,\n fields?: Fields\n): Input | typeof ABSENT {\n let copy: Input | undefined;\n for (const [key, item] of Object.entries(where)) {\n const logical = isLogical(key, fields);\n const value = boundValue(\n item,\n controls,\n logical,\n required,\n logical ? fields : undefined\n );\n if (value === ABSENT) return ABSENT;\n if (value === MATCH_NOTHING) return MATCH_NOTHING;\n if (value !== item) (copy ??= { ...where })[key] = value;\n }\n return copy ?? where;\n}\n\n/** Each model's predicates bound; the same map when none names a control. */\nfunction boundModels(\n models: ModelDomain,\n controls: AdmittedControls | undefined,\n required: RequiredOn,\n fieldsOf: (model: string) => Fields | undefined\n): ModelDomain {\n const bound = new Map<string, readonly Input[]>();\n let changed = false;\n for (const [model, list] of models) {\n const kept: Input[] = [];\n const requiredHere = (control: string) => required(control, model);\n for (const where of list) {\n const value = boundWhere(where, controls, requiredHere, fieldsOf(model));\n changed ||= value !== where;\n if (value !== ABSENT) kept.push(value);\n }\n if (kept.length > 0) bound.set(model, kept);\n }\n return changed ? bound : models;\n}\n\n/** A domain bound; the same object when no predicate names a control. */\nfunction boundDomain(\n domain: RowDomain,\n controls: AdmittedControls | undefined,\n { required, fieldsOf }: Pick<RowsBinding, \"required\" | \"fieldsOf\">\n): RowDomain {\n const root = boundModels(domain.root, controls, required, fieldsOf);\n const related = boundModels(domain.related, controls, required, fieldsOf);\n return root === domain.root && related === domain.related\n ? domain\n : Object.freeze({ root, related });\n}\n\n/**\n * A stamp bound: a field whose value names a control the call did not pass is\n * not written. The same object when no field names a control.\n */\nfunction boundStamp(\n stamp: Input | undefined,\n controls: AdmittedControls | undefined\n): Input | undefined {\n if (stamp === undefined) return undefined;\n const values: Record<string, unknown> = {};\n let changed = false;\n for (const [field, value] of Object.entries(stamp)) {\n const bound = boundValue(value, controls, false);\n changed ||= bound !== value;\n if (bound !== ABSENT) values[field] = bound;\n }\n return changed ? Object.freeze(values) : stamp;\n}\n\n/** Each model's stamps bound; an entry naming no control is kept as is. */\nfunction boundStamps(\n stamps: ReadonlyMap<string, ModelStamps>,\n controls: AdmittedControls | undefined\n): ReadonlyMap<string, ModelStamps> {\n const bound = new Map<string, ModelStamps>();\n for (const [model, entry] of stamps) {\n const create = boundStamp(entry.create, controls);\n const update = boundStamp(entry.update, controls);\n bound.set(\n model,\n create === entry.create && update === entry.update\n ? entry\n : Object.freeze({ create, update })\n );\n }\n return bound;\n}\n\nfunction boundFacts(\n facts: CallRows,\n controls: AdmittedControls | undefined,\n binding: RowsBinding\n): CallRows {\n const domain = boundDomain(facts.domain, controls, binding);\n return Object.freeze({\n ...facts,\n domain,\n defaults:\n facts.defaults === facts.domain\n ? domain\n : boundDomain(facts.defaults, controls, binding),\n });\n}\n\n/** Each model's declared field names, read once from the schema. */\nfunction modelFields(\n schema: Schema | undefined\n): (model: string) => Fields | undefined {\n const known = new Map<string, Fields>();\n return (model) => {\n const state = schema?.[model]?.[\"~\"].state;\n if (state === undefined) return undefined;\n let fields = known.get(model);\n if (fields === undefined) {\n fields = new Set([\n ...Object.keys(state.scalars),\n ...Object.keys(state.relations),\n ]);\n known.set(model, fields);\n }\n return fields;\n };\n}\n\n/** The chain's `required` declarations as one test, by control and model. */\nfunction requiredOn(controls: ResolvedControls | undefined): RequiredOn {\n const required = new Map<string, true | ReadonlySet<string>>();\n for (const control of controls?.all ?? []) {\n if (control.required !== undefined)\n required.set(control.name, control.required);\n }\n if (required.size === 0) return NEVER_REQUIRED;\n return (control, model) => {\n const on = required.get(control);\n return on === true || on?.has(model) === true;\n };\n}\n\n/** One purpose's predicates per model, for one mode of every member. */\nfunction modelDomain(\n rows: readonly RowsContribution[],\n modes: readonly string[],\n purpose: keyof Predicates\n): ModelDomain {\n const domain = new Map<string, Record<string, unknown>[]>();\n for (const [index, member] of rows.entries()) {\n for (const [model, entry] of Object.entries(member.models)) {\n const where = entry[modes[index]!]?.[purpose];\n if (where === undefined) continue;\n const list = domain.get(model) ?? [];\n list.push(where);\n domain.set(model, list);\n }\n }\n return domain;\n}\n\nexport function bindRows(\n rows: readonly RowsContribution[] | undefined,\n deletion: Readonly<Record<string, ResolvedDeletion>> | undefined,\n data?: Readonly<Record<string, ModelStamps>>,\n controls?: ResolvedControls,\n schema?: Schema\n): RowsBinding {\n const declared = rows ?? [];\n const fieldsOf = modelFields(schema);\n let stride = 1;\n const members = declared.map((member): BoundRowsMember => {\n const modes = rowsModes(member);\n const bound = {\n control: member.control,\n names: modes,\n modes: new Map<unknown, number>(\n modes.map((mode, index) => [mode, index])\n ),\n fallback: modes.indexOf(member.default),\n stride,\n };\n stride *= modes.length;\n return bound;\n });\n const domains: RowDomain[] = [];\n for (let combination = 0; combination < stride; combination++) {\n const modes = members.map(\n (member) =>\n member.names[\n Math.floor(combination / member.stride) % member.names.length\n ]!\n );\n domains.push(\n Object.freeze({\n root: modelDomain(declared, modes, \"root\"),\n related: modelDomain(declared, modes, \"related\"),\n })\n );\n }\n const defaults =\n domains[\n members.reduce(\n (index, member) => index + member.fallback * member.stride,\n 0\n )\n ]!;\n const tombstones =\n deletion === undefined ? undefined : new Map(Object.entries(deletion));\n const stamps = data === undefined ? undefined : new Map(Object.entries(data));\n const stampReferences = new Set<string>();\n for (const entry of stamps?.values() ?? []) {\n collectReferences(entry.create, stampReferences, true);\n collectReferences(entry.update, stampReferences, true);\n }\n const physical = domains.map((domain) =>\n Object.freeze({ domain, defaults, ...(stamps && { stamps }) })\n );\n return Object.freeze({\n members,\n deletion: deletion ?? NO_DELETION,\n physical,\n tombstoning:\n tombstones === undefined\n ? physical\n : physical.map((facts) => Object.freeze({ ...facts, tombstones })),\n references: domains.map((domain) =>\n referencesOf([domain, defaults], fieldsOf)\n ),\n bound: new Map(),\n bindsStamps: stampReferences.size > 0,\n required: requiredOn(controls),\n fieldsOf,\n });\n}\n\n/**\n * One call's row facts, from the controls it admitted: the modes its `rows`\n * controls chose (an absent one reads as its default), and whether it deletes\n * physically — its model's `deletion` entry names a `removeWhen` the call's\n * controls match. That control is placed only on the deletes of the models\n * the entry manages, so no other call can match it. When a predicate or a\n * stamp names a control, the call's values are put in.\n */\nexport function callRows(\n binding: RowsBinding,\n model: string,\n controls: AdmittedControls | undefined\n): CallRows {\n let combination = 0;\n for (const member of binding.members) {\n combination +=\n member.stride *\n (member.modes.get(controls?.[member.control]) ?? member.fallback);\n }\n const removeWhen = binding.deletion[model]?.removeWhen;\n const physical =\n removeWhen !== undefined &&\n Object.entries(removeWhen).every(\n ([control, value]) => controls?.[control] === value\n );\n const facts = domainFacts(binding, physical, combination, controls);\n return binding.bindsStamps\n ? Object.freeze({\n ...facts,\n stamps: boundStamps(facts.stamps!, controls),\n })\n : facts;\n}\n\n/** The combination's facts with the call's values put in its domains. */\nfunction domainFacts(\n binding: RowsBinding,\n physical: boolean,\n combination: number,\n controls: AdmittedControls | undefined\n): CallRows {\n const facts = (physical ? binding.physical : binding.tombstoning)[\n combination\n ]!;\n const references = binding.references[combination]!;\n if (references.length === 0) return facts;\n const values: Record<string, unknown> = {};\n for (const name of references) {\n if (controls?.[name] !== undefined) values[name] = controls[name];\n }\n // A value admission could not fix (no canonical spelling, or not\n // copyable) is bound for this call alone: it never takes another value's\n // facts. Every other value is admission's frozen snapshot, so the facts\n // can outlive the call under a key spelling its content.\n if (!Object.values(values).every(isStableControlValue))\n return boundFacts(facts, controls, binding);\n const key = `${physical}${combination}${stableStringify(values)}`;\n let known = binding.bound.get(key);\n if (known === undefined) {\n if (binding.bound.size === BOUND_LIMIT) {\n binding.bound.delete(binding.bound.keys().next().value!);\n }\n known = boundFacts(facts, values, binding);\n binding.bound.set(key, known);\n }\n return known;\n}\n","import type { VibORMConfig } from \"@client/client\";\nimport type { ClientSchema } from \"@client/schema-links\";\nimport type { Operations, Schema } from \"@client/types\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport { ClientInitializationError } from \"@errors\";\nimport { ROUTED_OPERATIONS } from \"@query-engine/routed-operations\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type {\n ControlsContribution,\n DataContribution,\n DeletionContribution,\n RowsContribution,\n} from \"./controls\";\nimport type {\n EmptyClientExtensionState,\n ExtensionClientScope,\n ExtensionMethodDefinitionGuard,\n ExtensionMethodRecord,\n ExtensionModelDelegate,\n ExtensionStateConstraint,\n ResultConsumerContextOf,\n RuntimeClientMethodContribution,\n RuntimeModelMethodContribution,\n} from \"./methods\";\nimport type { ObserveHandler } from \"./observation\";\nimport type {\n GenericQueryHandler,\n QueryHandlerMap,\n RuntimeQueryContribution,\n} from \"./query\";\nimport type {\n GenericRequestHandler,\n RequestHandlerMap,\n RuntimeRequestContribution,\n} from \"./request\";\nimport { undeclaredControlReferencesOf } from \"./rows\";\nimport type { StatementHandler } from \"./statement\";\n\ntype RuntimeExtensionFunction = (...args: never[]) => unknown;\n\n/**\n * One extension definition as the chain binds it: a host-owned frozen\n * snapshot of the six handler members, and `controls`, `rows`, `deletion`\n * and `data` as the definition wrote them.\n */\nexport interface RuntimeExtensionDefinition {\n readonly name: string;\n readonly request?: RuntimeRequestContribution;\n readonly query?: RuntimeQueryContribution;\n readonly statement?: RuntimeExtensionFunction;\n readonly observe?: RuntimeExtensionFunction;\n readonly client?: RuntimeClientMethodContribution;\n readonly model?: RuntimeModelMethodContribution;\n readonly controls?: ControlsContribution;\n readonly rows?: RowsContribution;\n readonly deletion?: DeletionContribution;\n readonly data?: DataContribution;\n}\n\nexport type ControlLiteral = string | number | boolean;\n\n/**\n * What `$extends` hands the chain. Schema-bound row/data/deletion model and\n * field names are checked before they can silently bind to no policy.\n * Handler members retain the hostile-definition boundary below.\n */\nexport type ExtensionDefinitionInput = Readonly<Record<string, unknown>> & {\n readonly controls?: ControlsContribution;\n readonly rows?: RowsContribution;\n readonly deletion?: DeletionContribution;\n readonly data?: DataContribution;\n};\n\nconst DEFINITION_KEYS = new Set([\n \"name\",\n \"request\",\n \"query\",\n \"statement\",\n \"observe\",\n \"client\",\n \"model\",\n \"controls\",\n \"rows\",\n \"deletion\",\n \"data\",\n]);\n\nexport function extensionError(message: string, extension?: string): never {\n throw new ClientInitializationError(message, {\n meta: extension ? { extension } : undefined,\n });\n}\n\nfunction readOwnKeys(\n value: Record<string, unknown>,\n extension?: string\n): PropertyKey[] {\n try {\n return Reflect.ownKeys(value);\n } catch (cause) {\n throw new ClientInitializationError(\n extension\n ? `Extension \"${extension}\" members could not be inspected.`\n : \"Client extension members could not be inspected.\",\n {\n cause: errorCause(cause),\n meta: extension ? { extension } : undefined,\n }\n );\n }\n}\n\nfunction readOwn(\n value: Record<string, unknown>,\n key: string,\n extension?: string\n): unknown {\n try {\n return value[key];\n } catch (cause) {\n throw new ClientInitializationError(\n extension\n ? `Extension \"${extension}\" member \"${key}\" could not be read.`\n : `Client extension member \"${key}\" could not be read.`,\n {\n cause: errorCause(cause),\n meta: extension ? { extension } : undefined,\n }\n );\n }\n}\n\nfunction requireFunction(\n value: unknown,\n label: string,\n extension: string\n): RuntimeExtensionFunction {\n if (!isFunction(value)) {\n extensionError(\n `Extension \"${extension}\" ${label} must be a function.`,\n extension\n );\n }\n return value;\n}\n\nfunction snapshotOperationMap(\n component: unknown,\n label: \"request\" | \"query\",\n extension: string,\n schema?: Schema\n): RuntimeExtensionDefinition[\"request\"] {\n if (isFunction(component)) return component;\n if (!isRecord(component)) {\n extensionError(\n `Extension \"${extension}\" ${label} must be a function or model map.`,\n extension\n );\n }\n\n const models: Record<\n string,\n Readonly<Record<string, RuntimeExtensionFunction>>\n > = Object.create(null);\n for (const modelKey of readOwnKeys(component, extension)) {\n if (typeof modelKey !== \"string\") {\n extensionError(\n `Extension \"${extension}\" ${label} contains a non-string model key.`,\n extension\n );\n }\n if (schema && !Object.hasOwn(schema, modelKey)) {\n extensionError(\n `Extension \"${extension}\" ${label} names unknown model \"${modelKey}\".`,\n extension\n );\n }\n const handlers = readOwn(component, modelKey, extension);\n if (!isRecord(handlers)) {\n extensionError(\n `Extension \"${extension}\" ${label}.${modelKey} must be an operation map.`,\n extension\n );\n }\n const operations: Record<string, RuntimeExtensionFunction> =\n Object.create(null);\n for (const operationKey of readOwnKeys(handlers, extension)) {\n if (typeof operationKey !== \"string\") {\n extensionError(\n `Extension \"${extension}\" ${label}.${modelKey} contains a non-string operation key.`,\n extension\n );\n }\n if (!ROUTED_OPERATIONS.has(operationKey)) {\n extensionError(\n `Extension \"${extension}\" ${label}.${modelKey} names unknown operation \"${operationKey}\".`,\n extension\n );\n }\n operations[operationKey] = requireFunction(\n readOwn(handlers, operationKey, extension),\n `${label}.${modelKey}.${operationKey}`,\n extension\n );\n }\n models[modelKey] = Object.freeze(operations);\n }\n return Object.freeze(models);\n}\n\nfunction snapshotModelFactories(\n component: unknown,\n extension: string,\n schema?: Schema\n): RuntimeExtensionDefinition[\"model\"] {\n if (!isRecord(component)) {\n extensionError(\n `Extension \"${extension}\" model must be a model map.`,\n extension\n );\n }\n const factories: Record<string, RuntimeExtensionFunction> =\n Object.create(null);\n for (const modelKey of readOwnKeys(component, extension)) {\n if (typeof modelKey !== \"string\") {\n extensionError(\n `Extension \"${extension}\" model contains a non-string model key.`,\n extension\n );\n }\n if (schema && !Object.hasOwn(schema, modelKey)) {\n extensionError(\n `Extension \"${extension}\" model names unknown model \"${modelKey}\".`,\n extension\n );\n }\n factories[modelKey] = requireFunction(\n readOwn(component, modelKey, extension),\n `model.${modelKey}`,\n extension\n );\n }\n return Object.freeze(factories);\n}\n\n/** Refuse named policy facts that could otherwise silently bind to nothing. */\nfunction validateNamedPolicies(\n value: ExtensionDefinitionInput,\n schema: Schema | undefined,\n name: string\n): void {\n if (!schema) return;\n const components: (\"rows\" | \"data\" | \"deletion\")[] = [\n \"rows\",\n \"data\",\n \"deletion\",\n ];\n for (const component of components) {\n const declaration = readOwn(value, component, name);\n if (declaration === undefined) continue;\n if (!isRecord(declaration))\n extensionError(\n `Extension \"${name}\" ${component} must be an object.`,\n name\n );\n const models = readOwn(declaration, \"models\", name);\n if (!isRecord(models))\n extensionError(\n `Extension \"${name}\" ${component}.models must be an object.`,\n name\n );\n let expectedModes: readonly string[] | undefined;\n const defaultMode =\n component === \"rows\" ? readOwn(declaration, \"default\", name) : undefined;\n for (const modelName of readOwnKeys(models, name)) {\n if (typeof modelName !== \"string\" || !Object.hasOwn(schema, modelName))\n extensionError(\n `Extension \"${name}\" ${component} names unknown model \"${String(modelName)}\".`,\n name\n );\n const model = schema[modelName]!;\n const entry = readOwn(models, modelName, name);\n if (!isRecord(entry))\n extensionError(\n `Extension \"${name}\" ${component}.${modelName} must be an object.`,\n name\n );\n const fields = (input: unknown, where = false, depth = 0): void => {\n if (depth > 16)\n extensionError(\n `Extension \"${name}\" row predicate exceeds nesting limit.`,\n name\n );\n if (input === undefined) return;\n if (Array.isArray(input) && where) {\n for (const member of input) fields(member, true, depth + 1);\n return;\n }\n if (!isRecord(input))\n extensionError(\n `Extension \"${name}\" ${component}.${modelName} fields must be an object.`,\n name\n );\n for (const key of readOwnKeys(input, name)) {\n if (\n where &&\n typeof key === \"string\" &&\n !Object.hasOwn(model[\"~\"].state.shape, key) &&\n (key === \"AND\" || key === \"OR\" || key === \"NOT\")\n ) {\n fields(readOwn(input, key, name), true, depth + 1);\n continue;\n }\n if (\n typeof key !== \"string\" ||\n !Object.hasOwn(\n where ? model[\"~\"].state.shape : model[\"~\"].state.scalars,\n key\n )\n )\n extensionError(\n `Extension \"${name}\" ${component}.${modelName} names unknown field \"${String(key)}\".`,\n name\n );\n }\n };\n if (component === \"rows\") {\n const modes = readOwnKeys(entry, name).filter(\n (key): key is string => typeof key === \"string\"\n );\n const priorModes = expectedModes;\n if (\n typeof defaultMode !== \"string\" ||\n !modes.includes(defaultMode) ||\n (priorModes &&\n (priorModes.length !== modes.length ||\n modes.some((mode) => !priorModes.includes(mode))))\n )\n extensionError(\n `Extension \"${name}\" row models must share mode names and include the default mode.`,\n name\n );\n expectedModes ??= modes;\n for (const modeName of readOwnKeys(entry, name)) {\n if (typeof modeName !== \"string\")\n extensionError(\n `Extension \"${name}\" row mode must be a string.`,\n name\n );\n const mode = readOwn(entry, modeName, name);\n if (!isRecord(mode))\n extensionError(\n `Extension \"${name}\" row mode must be an object.`,\n name\n );\n fields(readOwn(mode, \"root\", name), true);\n fields(readOwn(mode, \"related\", name), true);\n }\n } else if (component === \"data\") {\n fields(readOwn(entry, \"create\", name));\n fields(readOwn(entry, \"update\", name));\n } else {\n const at = readOwn(entry, \"at\", name);\n if (\n at !== undefined &&\n (typeof at !== \"string\" ||\n !Object.hasOwn(model[\"~\"].state.scalars, at))\n )\n extensionError(\n `Extension \"${name}\" deletion.${modelName}.at names unknown scalar.`,\n name\n );\n fields(readOwn(entry, \"assign\", name));\n }\n }\n }\n}\n\n/**\n * Read a caller-owned definition once. The six handler members are validated\n * and frozen as host-owned snapshots, so a failed application cannot mutate\n * the supplied value; `controls`, `rows`, `deletion` and `data` are bound as\n * written.\n */\nexport function normalizeExtensionDefinition(\n value: ExtensionDefinitionInput,\n schema?: Schema\n): RuntimeExtensionDefinition {\n if (!isRecord(value)) {\n extensionError(\"Client extension must be an object.\");\n }\n const ownKeys = readOwnKeys(value);\n if (!ownKeys.includes(\"name\")) {\n extensionError(\"Client extension name must be a non-empty string.\");\n }\n const rawName = readOwn(value, \"name\");\n if (typeof rawName !== \"string\" || rawName.trim().length === 0) {\n extensionError(\"Client extension name must be a non-empty string.\");\n }\n const name = rawName;\n for (const key of ownKeys) {\n if (typeof key !== \"string\" || !DEFINITION_KEYS.has(key)) {\n extensionError(\n `Extension \"${name}\" has unknown member \"${String(key)}\".`,\n name\n );\n }\n }\n\n const rawRequest = ownKeys.includes(\"request\")\n ? readOwn(value, \"request\", name)\n : undefined;\n const request =\n rawRequest === undefined\n ? undefined\n : snapshotOperationMap(rawRequest, \"request\", name, schema);\n const rawQuery = ownKeys.includes(\"query\")\n ? readOwn(value, \"query\", name)\n : undefined;\n const query =\n rawQuery === undefined\n ? undefined\n : snapshotOperationMap(rawQuery, \"query\", name, schema);\n const rawStatement = ownKeys.includes(\"statement\")\n ? readOwn(value, \"statement\", name)\n : undefined;\n const statement =\n rawStatement === undefined\n ? undefined\n : requireFunction(rawStatement, \"statement\", name);\n const rawObserve = ownKeys.includes(\"observe\")\n ? readOwn(value, \"observe\", name)\n : undefined;\n const observe =\n rawObserve === undefined\n ? undefined\n : requireFunction(rawObserve, \"observe\", name);\n const rawClient = ownKeys.includes(\"client\")\n ? readOwn(value, \"client\", name)\n : undefined;\n const client =\n rawClient === undefined\n ? undefined\n : requireFunction(rawClient, \"client\", name);\n const rawModel = ownKeys.includes(\"model\")\n ? readOwn(value, \"model\", name)\n : undefined;\n const model =\n rawModel === undefined\n ? undefined\n : snapshotModelFactories(rawModel, name, schema);\n const { controls, rows, deletion, data } = value;\n validateNamedPolicies({ rows, deletion, data }, schema, name);\n\n const normalized = Object.freeze({\n name,\n ...(request ? { request } : {}),\n ...(query ? { query } : {}),\n ...(statement ? { statement } : {}),\n ...(observe ? { observe } : {}),\n ...(client ? { client } : {}),\n ...(model ? { model } : {}),\n ...(controls ? { controls } : {}),\n ...(rows ? { rows } : {}),\n ...(deletion ? { deletion } : {}),\n ...(data ? { data } : {}),\n });\n for (const control of undeclaredControlReferencesOf(normalized, schema))\n extensionError(\n `Extension \"${name}\" references undeclared control \"${control}\".`,\n name\n );\n return normalized;\n}\n\ntype ExtensionConfig<S extends Schema> = {\n readonly schema: S;\n readonly driver: AnyDriver;\n};\n\n/**\n * A model factory, declared as a method so a factory typed against the client\n * it extends (`(delegate: M[K & keyof M]) => …`, generic over that client) is\n * compared in either direction rather than only contravariantly.\n */\ntype ModelMethodFactory<Delegate> = {\n factory(delegate: Delegate): ExtensionMethodRecord;\n}[\"factory\"];\n\n/**\n * One factory per schema model. A definition's model key is looked up here by\n * index, never by a conditional: a key outside the schema reads `never` (the\n * factory is refused where it is written), and a key set generic over the\n * client is substituted rather than deferred, so a plugin generic over `C`\n * type-checks and meets the schema check when it is applied.\n */\ntype ModelFactoryTable<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = {\n readonly [ModelName in keyof ClientSchema<C>]: ModelMethodFactory<\n ExtensionModelDelegate<C, X, ModelName>\n >;\n};\n\n/** The model keys a definition's own `model` map names. */\ntype DefinitionModelKeys<Self> = Self extends {\n readonly model?: infer Factories;\n}\n ? keyof Factories\n : never;\n\n/**\n * `Self` is the definition itself when `$extends` checks it (F-bounded), so\n * its model keys come from the definition; otherwise every schema model.\n */\nexport type ContextualExtensionDefinition<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Self = unknown,\n> = ExtensionMembers<C, X> & {\n readonly model?: unknown extends Self\n ? {\n readonly [ModelName in keyof ClientSchema<C>]?: ModelMethodFactory<\n ExtensionModelDelegate<C, X, ModelName>\n >;\n }\n : {\n readonly [ModelName in DefinitionModelKeys<Self>]?: ModelFactoryTable<\n C,\n X\n >[ModelName & keyof ClientSchema<C>];\n };\n};\n\ntype ExtensionMembers<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = {\n readonly name: string;\n readonly request?: GenericRequestHandler | RequestHandlerMap<ClientSchema<C>>;\n readonly query?: GenericQueryHandler | QueryHandlerMap<C, X[\"rows\"]>;\n readonly statement?: StatementHandler;\n readonly observe?: ObserveHandler;\n readonly controls?: ControlsContribution;\n readonly rows?: RowsContribution;\n readonly deletion?: DeletionContribution;\n readonly data?: DataContribution;\n readonly client?: (\n scope: ExtensionClientScope<C, X>\n ) => ExtensionMethodRecord;\n};\n\ntype SchemaGenericExtensionDefinition = Omit<\n ContextualExtensionDefinition<\n ExtensionConfig<Schema>,\n EmptyClientExtensionState\n >,\n \"request\" | \"query\"\n> & {\n readonly request?: GenericRequestHandler;\n readonly query?: GenericQueryHandler;\n};\n\n/**\n * Public reusable extension definition.\n *\n * A schema with a string index has no exact model vocabulary, so its reusable\n * request/query contributions must use the polymorphic all-operation form.\n * Supplying a concrete schema retains its exact model and operation maps.\n */\nexport type ClientExtension<S extends Schema = Schema> = string extends keyof S\n ? SchemaGenericExtensionDefinition\n : ContextualExtensionDefinition<\n ExtensionConfig<S>,\n EmptyClientExtensionState\n >;\n\ntype DefinitionKeys = keyof ContextualExtensionDefinition<\n VibORMConfig,\n EmptyClientExtensionState\n>;\n\ndeclare const schemaBoundExtensionContext: unique symbol;\n\ntype SchemaBoundExtension<Definition> = Definition & {\n readonly [schemaBoundExtensionContext]: ResultConsumerContextOf<Definition>;\n};\n\ntype UnknownDefinitionKeys<Definition> = Record<\n Exclude<\n keyof Definition,\n DefinitionKeys | typeof schemaBoundExtensionContext\n >,\n never\n>;\n\ntype ConfigOmit<C extends VibORMConfig> = \"omit\" extends keyof C\n ? C[Extract<\"omit\", keyof C>]\n : undefined;\n\nexport type HasNamedClientOmit<C extends VibORMConfig> =\n string extends keyof NonNullable<ConfigOmit<C>>\n ? false\n : [Exclude<ConfigOmit<C>, undefined>] extends [never]\n ? false\n : true;\n\n/** Refuse replaying a schema-bound result consumer into an omitted client. */\nexport type SchemaBoundExtensionAdmission<\n Definition,\n C extends VibORMConfig,\n> = Definition extends {\n readonly [schemaBoundExtensionContext]: infer Context;\n}\n ? Context extends \"result-consuming\"\n ? HasNamedClientOmit<C> extends true\n ? { readonly [schemaBoundExtensionContext]: never }\n : unknown\n : unknown\n : unknown;\n\ntype OperationMapGuard<Map, S extends Schema> = Map extends CallableFunction\n ? unknown\n : Map extends object\n ? Record<Exclude<keyof Map, keyof S>, never> & {\n readonly [ModelName in keyof Map]: ModelName extends keyof S\n ? Map[ModelName] extends object\n ? Record<Exclude<keyof Map[ModelName], Operations>, never>\n : never\n : never;\n }\n : never;\n\ntype ComponentMapGuard<\n Definition,\n Key extends \"request\" | \"query\",\n S extends Schema,\n> = Definition extends { readonly [K in Key]: infer Component }\n ? { readonly [K in Key]: OperationMapGuard<Component, S> }\n : unknown;\n\n/** Policy model keys must be a subset of a concrete bound schema. */\ntype PolicyModelsGuard<\n Definition,\n S extends Schema,\n Key extends \"data\" | \"rows\" | \"deletion\",\n> = Definition extends {\n readonly [K in Key]: { readonly models: infer Models };\n}\n ? string extends keyof S\n ? unknown\n : [keyof Models] extends [keyof S]\n ? unknown\n : {\n readonly [K in Key]: { readonly models: Record<keyof Models, never> };\n }\n : unknown;\n\n/** Structural refusal for non-fresh extension definitions and contributions. */\nexport type ExactExtensionDefinition<\n Definition,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = UnknownDefinitionKeys<Definition> &\n ComponentMapGuard<Definition, \"request\", C[\"schema\"]> &\n ComponentMapGuard<Definition, \"query\", C[\"schema\"]> &\n PolicyModelsGuard<Definition, C[\"schema\"], \"data\"> &\n PolicyModelsGuard<Definition, C[\"schema\"], \"rows\"> &\n PolicyModelsGuard<Definition, C[\"schema\"], \"deletion\"> &\n ExtensionMethodDefinitionGuard<Definition, C, X>;\n\nexport type DefineExtensionBinder<S extends Schema> = <const Definition>(\n definition: Definition &\n ContextualExtensionDefinition<\n ExtensionConfig<S>,\n EmptyClientExtensionState\n > &\n ExactExtensionDefinition<\n Definition,\n ExtensionConfig<S>,\n EmptyClientExtensionState\n >\n) => SchemaBoundExtension<Definition>;\n\nexport function defineExtension<\n const Definition extends SchemaGenericExtensionDefinition,\n>(\n definition: Definition &\n ExactExtensionDefinition<\n Definition,\n ExtensionConfig<Schema>,\n EmptyClientExtensionState\n >\n): Definition;\nexport function defineExtension<S extends Schema>(): DefineExtensionBinder<S>;\nexport function defineExtension(\n ...definitions: [] | [definition: ClientExtension]\n): unknown {\n if (definitions.length === 0) {\n return (schemaDefinition: ExtensionDefinitionInput) =>\n normalizeExtensionDefinition(schemaDefinition);\n }\n return normalizeExtensionDefinition(definitions[0]);\n}\n","import {\n getOfficialCacheChainDefinition,\n getOfficialCacheQueryCapability,\n OFFICIAL_CACHE_NAME,\n officialCacheControls,\n registerOfficialCacheChain,\n} from \"@cache/capability\";\nimport {\n getOfficialDefaultOmitChainCapability,\n getOfficialDefaultOmitRequestCapability,\n OFFICIAL_DEFAULT_OMIT_NAME,\n registerOfficialDefaultOmitChain,\n} from \"@client/default-omit-extension\";\nimport type { Schema } from \"@client/types\";\nimport type { ModelStamps } from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { isFunction } from \"@validation/value-guards\";\nimport {\n type DataContribution,\n type DeletionContribution,\n placeControls,\n type ResolvedControl,\n type RowsContribution,\n} from \"./controls\";\nimport {\n type ControlLiteral,\n type ExtensionDefinitionInput,\n extensionError,\n normalizeExtensionDefinition,\n type RuntimeExtensionDefinition,\n} from \"./definition\";\nimport type {\n RuntimeClientMethodContribution,\n RuntimeModelMethodContribution,\n} from \"./methods\";\nimport {\n getOfficialInstrumentationChainCapability,\n getTrustedProtectedObserverCapability,\n registerOfficialInstrumentationChain,\n} from \"./observation\";\nimport { bindRows, type RowsBinding } from \"./rows\";\n\n/** The fixed name admission reserves for the official instrumentation extension. */\nexport const OFFICIAL_INSTRUMENTATION_NAME = \"viborm.instrumentation\";\n\nexport interface ResolvedExtensionHandler<\n Handler extends CallableFunction = CallableFunction,\n> {\n readonly extension: string;\n readonly handler: Handler;\n}\n\n/**\n * A request or query handler. The controls its extension declares travel\n * with it: the only ones its `context.controls` shows.\n */\nexport interface ResolvedOperationHandler<\n Handler extends CallableFunction = CallableFunction,\n> extends ResolvedExtensionHandler<Handler> {\n readonly controls?: readonly string[];\n}\n\n/** One precompiled handler array for each exact execution target. */\nexport interface ResolvedExtensionOperationLookup {\n readonly global: readonly ResolvedOperationHandler[];\n readonly models: Readonly<\n Record<\n string,\n Readonly<Record<string, readonly ResolvedOperationHandler[]>>\n >\n >;\n}\n\nexport interface ResolvedExtension {\n readonly name: string;\n readonly client?: RuntimeClientMethodContribution;\n readonly model?: RuntimeModelMethodContribution;\n}\n\n/** Who owns a request or query handler: its extension and that one's controls. */\ninterface OperationHandlerOwner {\n readonly name: string;\n readonly controls?: readonly string[];\n}\n\n/** A chain's controls, and the list one (model, operation) accepts. */\nexport interface ResolvedControls {\n /** Every control name on the chain: one name space. */\n readonly names: ReadonlySet<string>;\n /** Every control on the chain, in application order: the lists' one source. */\n readonly all: readonly ResolvedControl[];\n /**\n * The controls placed on one model's operation, in application order. Each\n * list is built the first time it is asked for and kept for the chain: a\n * client created per request asks for the one its call needs, never for\n * every operation of every model.\n */\n readonly placed: (\n model: string,\n operation: string\n ) => readonly ResolvedControl[];\n}\n\n/** What a delete of one managed model writes, and who declared it. */\nexport interface ResolvedDeletion {\n readonly extension: string;\n readonly at?: string;\n readonly assign: Readonly<Record<string, unknown>>;\n readonly removeWhen?: Readonly<Record<string, ControlLiteral>>;\n}\n\n/**\n * Absent on an unextended client; frozen whenever it exists, except the\n * `controls`, `rows`, `deletion` and `data` values a definition wrote, held\n * as written.\n */\nexport interface ResolvedExtensionChain {\n readonly controls?: ResolvedControls;\n /**\n * Every `rows` member, as declared (plain data): also a cached read's key,\n * so two chains whose `rows` differ never share an entry and two that\n * declare the same always do.\n */\n readonly rows?: readonly RowsContribution[];\n readonly deletion?: Readonly<Record<string, ResolvedDeletion>>;\n /** Per model, every extension's `data` fields: a later one wins a field. */\n readonly data?: Readonly<Record<string, ModelStamps>>;\n /**\n * Derived from `rows`, `deletion` and `data`: what each call's controls\n * resolve to.\n */\n readonly callRows?: RowsBinding;\n readonly extensions: readonly ResolvedExtension[];\n readonly hasCache: boolean;\n readonly hasRequestHandlers: boolean;\n readonly hasQueryHandlers: boolean;\n readonly hasResultConsumers: boolean;\n readonly request: ResolvedExtensionOperationLookup;\n readonly query: ResolvedExtensionOperationLookup;\n readonly statement: readonly ResolvedExtensionHandler[];\n readonly observe: readonly ResolvedExtensionHandler[];\n}\n\n/** Return the precompiled array itself; lookup scans and merges nothing. */\nexport function lookupResolvedExtensionHandlers(\n chain: ResolvedExtensionChain | undefined,\n component: \"request\" | \"query\",\n model: string | undefined,\n operation: string\n): readonly ResolvedOperationHandler[] | undefined {\n if (chain === undefined) return undefined;\n const lookup = chain[component];\n const global = lookup.global.length === 0 ? undefined : lookup.global;\n if (model === undefined) {\n return component === \"query\" ? global : undefined;\n }\n return lookup.models[model]?.[operation] ?? global;\n}\n\n/** The controls one (model, operation) accepts; the shared empty list when none. */\nexport function lookupPlacedControls(\n chain: ResolvedExtensionChain | undefined,\n model: string,\n operation: string\n): readonly ResolvedControl[] {\n return chain?.controls?.placed(model, operation) ?? NO_CONTROLS;\n}\n\nconst NO_CONTROLS: readonly ResolvedControl[] = Object.freeze([]);\n\nfunction resolvedHandler(\n extension: Pick<ResolvedExtension, \"name\">,\n handler: CallableFunction\n): ResolvedExtensionHandler {\n return Object.freeze({ extension: extension.name, handler });\n}\n\nfunction resolvedOperationHandler(\n extension: OperationHandlerOwner,\n handler: CallableFunction\n): ResolvedOperationHandler {\n return Object.freeze(\n extension.controls === undefined\n ? { extension: extension.name, handler }\n : { extension: extension.name, handler, controls: extension.controls }\n );\n}\n\nfunction appendModelHandler(\n models: Record<string, Record<string, ResolvedOperationHandler[]>>,\n model: string,\n operation: string,\n handler: ResolvedOperationHandler,\n global: readonly ResolvedOperationHandler[]\n): void {\n const operations = (models[model] ??= Object.create(null));\n const handlers = (operations[operation] ??= [...global]);\n handlers.push(handler);\n}\n\nfunction appendGlobalHandler(\n models: Record<string, Record<string, ResolvedOperationHandler[]>>,\n handler: ResolvedOperationHandler\n): void {\n for (const operations of Object.values(models)) {\n for (const handlers of Object.values(operations)) handlers.push(handler);\n }\n}\n\nfunction appendOperationHandlers(\n previous: ResolvedExtensionOperationLookup | undefined,\n extension: OperationHandlerOwner,\n contribution: RuntimeExtensionDefinition[\"request\"]\n): ResolvedExtensionOperationLookup {\n if (contribution === undefined && previous !== undefined) return previous;\n\n const models: Record<\n string,\n Record<string, ResolvedOperationHandler[]>\n > = Object.create(null);\n const global: ResolvedOperationHandler[] = previous\n ? [...previous.global]\n : [];\n\n if (previous) {\n for (const [modelName, operationMap] of Object.entries(previous.models)) {\n const operations: Record<string, ResolvedOperationHandler[]> =\n Object.create(null);\n for (const [operation, handlers] of Object.entries(operationMap)) {\n operations[operation] = [...handlers];\n }\n models[modelName] = operations;\n }\n }\n\n if (contribution) {\n if (isFunction(contribution)) {\n const handler = resolvedOperationHandler(extension, contribution);\n global.push(handler);\n appendGlobalHandler(models, handler);\n } else {\n for (const [modelName, operationMap] of Object.entries(contribution)) {\n for (const [operation, handler] of Object.entries(operationMap)) {\n appendModelHandler(\n models,\n modelName,\n operation,\n resolvedOperationHandler(extension, handler),\n global\n );\n }\n }\n }\n }\n\n const frozenModels: Record<\n string,\n Readonly<Record<string, readonly ResolvedOperationHandler[]>>\n > = Object.create(null);\n for (const [modelName, operationMap] of Object.entries(models)) {\n const frozenOperations: Record<\n string,\n readonly ResolvedOperationHandler[]\n > = Object.create(null);\n for (const [operation, handlers] of Object.entries(operationMap)) {\n frozenOperations[operation] = Object.freeze(handlers);\n }\n frozenModels[modelName] = Object.freeze(frozenOperations);\n }\n return Object.freeze({\n global: Object.freeze(global),\n models: Object.freeze(frozenModels),\n });\n}\n\nfunction hasCompiledHandlers(\n lookup: ResolvedExtensionOperationLookup\n): boolean {\n if (lookup.global.length > 0) return true;\n for (const operations of Object.values(lookup.models)) {\n if (Object.keys(operations).length > 0) return true;\n }\n return false;\n}\n\nfunction appendFlatHandler(\n previous: readonly ResolvedExtensionHandler[] | undefined,\n extension: Pick<ResolvedExtension, \"name\">,\n handler: CallableFunction | undefined\n): readonly ResolvedExtensionHandler[] {\n if (handler === undefined) return previous ?? Object.freeze([]);\n const handlers = previous ? [...previous] : [];\n handlers.push(resolvedHandler(extension, handler));\n return Object.freeze(handlers);\n}\n\nfunction appendObserver(\n previous: readonly ResolvedExtensionHandler[] | undefined,\n extension: Pick<ResolvedExtension, \"name\">,\n handler: CallableFunction | undefined\n): readonly ResolvedExtensionHandler[] {\n if (handler === undefined) return previous ?? Object.freeze([]);\n const official = getTrustedProtectedObserverCapability(handler);\n if (official !== undefined && !official.observesLifecycle) {\n return previous ?? Object.freeze([]);\n }\n return appendFlatHandler(previous, extension, handler);\n}\n\n/**\n * Add one definition's controls to the chain's name space, then index every\n * control of the chain by operation, for every model and for each model some\n * control names.\n */\nfunction appendControls(\n previous: ResolvedControls | undefined,\n declarations: readonly ResolvedControl[]\n): ResolvedControls {\n const names = new Set(previous?.names);\n for (const { name } of declarations) names.add(name);\n const all = Object.freeze([\n ...(previous?.all ?? []),\n ...declarations.map((control) => Object.freeze(control)),\n ]);\n const lists = new Map<string, readonly ResolvedControl[]>();\n const placed = (\n model: string,\n operation: string\n ): readonly ResolvedControl[] => {\n const key = `${model}\\u0000${operation}`;\n let list = lists.get(key);\n if (list === undefined) {\n const found = all.filter(\n (control) =>\n control.operations.has(operation) &&\n (control.models === undefined || control.models.has(model))\n );\n list = found.length === 0 ? NO_CONTROLS : Object.freeze(found);\n lists.set(key, list);\n }\n return list;\n };\n return Object.freeze({ names, all, placed });\n}\n\nconst NO_ASSIGN: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/** One entry per managed model on the chain: a later entry replaces one. */\nfunction appendDeletion(\n previous: Readonly<Record<string, ResolvedDeletion>> | undefined,\n extension: string,\n deletion: DeletionContribution\n): Readonly<Record<string, ResolvedDeletion>> {\n const entries: Record<string, ResolvedDeletion> = Object.create(null);\n Object.assign(entries, previous);\n for (const [model, entry] of Object.entries(deletion.models)) {\n entries[model] = Object.freeze({\n extension,\n ...entry,\n assign: entry.assign ?? NO_ASSIGN,\n ...(deletion.removeWhen === undefined\n ? {}\n : { removeWhen: deletion.removeWhen }),\n });\n }\n return Object.freeze(entries);\n}\n\n/** One kind's fields with an extension's own merged in: it wins a field. */\nfunction withStamp(\n previous: Input | undefined,\n fields: Readonly<Record<string, unknown>> | undefined\n): Input | undefined {\n return fields === undefined\n ? previous\n : Object.freeze({ ...previous, ...fields });\n}\n\nfunction appendData(\n previous: Readonly<Record<string, ModelStamps>> | undefined,\n data: DataContribution\n): Readonly<Record<string, ModelStamps>> {\n const entries: Record<string, ModelStamps> = Object.create(null);\n Object.assign(entries, previous);\n for (const [model, entry] of Object.entries(data.models)) {\n const known = entries[model];\n entries[model] = Object.freeze({\n create: withStamp(known?.create, entry.create),\n update: withStamp(known?.update, entry.update),\n });\n }\n return Object.freeze(entries);\n}\n\n/** The cache's query leaves the chain's handlers; its control is its own. */\nfunction asOfficialCacheDefinition(\n definition: RuntimeExtensionDefinition\n): RuntimeExtensionDefinition {\n const { query: _officialCacheQuery, ...ordinaryDefinition } = definition;\n return Object.freeze({\n ...ordinaryDefinition,\n controls: officialCacheControls,\n });\n}\n\nfunction stripOfficialDefaultOmitRequest(\n definition: RuntimeExtensionDefinition\n): RuntimeExtensionDefinition {\n const { request: _officialDefaultOmitRequest, ...ordinaryDefinition } =\n definition;\n return Object.freeze(ordinaryDefinition);\n}\n\nfunction consumesOperationResults(\n definition: RuntimeExtensionDefinition\n): boolean {\n return (\n (definition.query !== undefined && !isFunction(definition.query)) ||\n definition.client !== undefined ||\n definition.model !== undefined\n );\n}\n\nfunction assertOfficialExtensionAdmission(options: {\n readonly definitionName: string;\n readonly officialName: string;\n readonly label: string;\n readonly hasIdentity: boolean;\n readonly isAlreadyPresent: boolean;\n readonly duplicateMessage: string;\n}): void {\n if (options.hasIdentity && options.isAlreadyPresent) {\n extensionError(options.duplicateMessage, options.definitionName);\n }\n if (options.hasIdentity && options.definitionName !== options.officialName) {\n extensionError(\n `The official ${options.label} extension name must be \"${options.officialName}\".`,\n options.definitionName\n );\n }\n if (!options.hasIdentity && options.definitionName === options.officialName) {\n extensionError(\n `Extension name \"${options.officialName}\" is reserved for the official ${options.label} extension.`,\n options.definitionName\n );\n }\n}\n\nexport function appendResolvedExtension(\n chain: ResolvedExtensionChain | undefined,\n value: ExtensionDefinitionInput,\n schema: Schema\n): ResolvedExtensionChain {\n const definition = normalizeExtensionDefinition(value, schema);\n const incomingCache = getOfficialCacheQueryCapability(definition.query);\n const existingOfficialCache = getOfficialCacheChainDefinition(chain);\n const incomingDefaultOmit = getOfficialDefaultOmitRequestCapability(\n definition.request\n );\n const existingDefaultOmit = getOfficialDefaultOmitChainCapability(chain);\n assertOfficialExtensionAdmission({\n definitionName: definition.name,\n officialName: OFFICIAL_CACHE_NAME,\n label: \"cache\",\n hasIdentity: incomingCache !== undefined,\n isAlreadyPresent: existingOfficialCache !== undefined,\n duplicateMessage:\n \"The official cache extension is already present on this client.\",\n });\n assertOfficialExtensionAdmission({\n definitionName: definition.name,\n officialName: OFFICIAL_DEFAULT_OMIT_NAME,\n label: \"default omit\",\n hasIdentity: incomingDefaultOmit !== undefined,\n // The generic duplicate-name check owns default-omit duplication after\n // instrumentation admission, preserving hostile hybrid error precedence.\n isAlreadyPresent: false,\n duplicateMessage: `Extension \"${OFFICIAL_DEFAULT_OMIT_NAME}\" is already present on this client.`,\n });\n if (incomingDefaultOmit !== undefined && chain?.hasResultConsumers === true) {\n extensionError(\n \"The default omit extension cannot follow an extension that defines model-mapped query, client, or model behavior.\",\n definition.name\n );\n }\n if (definition.rows !== undefined && chain?.hasResultConsumers === true) {\n extensionError(\n `Extension \"${definition.name}\" declares rows, which cannot follow an extension that defines model-mapped query, client, or model behavior.`,\n definition.name\n );\n }\n const incomingOfficial = getTrustedProtectedObserverCapability(\n definition.observe\n );\n const existingOfficial = getOfficialInstrumentationChainCapability(chain);\n assertOfficialExtensionAdmission({\n definitionName: definition.name,\n officialName: OFFICIAL_INSTRUMENTATION_NAME,\n label: \"instrumentation\",\n hasIdentity: incomingOfficial !== undefined,\n isAlreadyPresent: existingOfficial !== undefined,\n duplicateMessage:\n \"The official instrumentation extension is already present on this client.\",\n });\n if (\n chain?.extensions.some((extension) => extension.name === definition.name)\n ) {\n extensionError(\n `Extension \"${definition.name}\" is already present on this client.`,\n definition.name\n );\n }\n const effectiveDefinition =\n incomingCache === undefined\n ? incomingDefaultOmit === undefined\n ? definition\n : stripOfficialDefaultOmitRequest(definition)\n : asOfficialCacheDefinition(definition);\n const declaredControls =\n effectiveDefinition.controls === undefined &&\n effectiveDefinition.rows === undefined\n ? undefined\n : placeControls(effectiveDefinition);\n const resolved: ResolvedExtension = Object.freeze({\n name: definition.name,\n ...(effectiveDefinition.client === undefined\n ? {}\n : { client: effectiveDefinition.client }),\n ...(effectiveDefinition.model === undefined\n ? {}\n : { model: effectiveDefinition.model }),\n });\n const handlerOwner: OperationHandlerOwner =\n declaredControls === undefined\n ? resolved\n : {\n name: definition.name,\n controls: Object.freeze(\n declaredControls.map((control) => control.name)\n ),\n };\n const extensions = Object.freeze(\n chain ? [...chain.extensions, resolved] : [resolved]\n );\n const request = appendOperationHandlers(\n chain?.request,\n handlerOwner,\n effectiveDefinition.request\n );\n const query = appendOperationHandlers(\n chain?.query,\n handlerOwner,\n effectiveDefinition.query\n );\n const controls =\n declaredControls === undefined\n ? chain?.controls\n : appendControls(chain?.controls, declaredControls);\n const rows =\n effectiveDefinition.rows === undefined\n ? chain?.rows\n : Object.freeze([...(chain?.rows ?? []), effectiveDefinition.rows]);\n const deletion =\n effectiveDefinition.deletion === undefined\n ? chain?.deletion\n : appendDeletion(\n chain?.deletion,\n definition.name,\n effectiveDefinition.deletion\n );\n const data =\n effectiveDefinition.data === undefined\n ? chain?.data\n : appendData(chain?.data, effectiveDefinition.data);\n // The binding reads `required` from the controls, already appended: a\n // filter names only its own extension's controls, so a later definition\n // that declares only controls changes nothing it binds.\n const callRows =\n rows === chain?.rows && deletion === chain?.deletion && data === chain?.data\n ? chain?.callRows\n : bindRows(rows, deletion, data, controls, schema);\n const resolvedChain = Object.freeze({\n ...(controls === undefined ? {} : { controls }),\n ...(rows === undefined ? {} : { rows }),\n ...(deletion === undefined ? {} : { deletion }),\n ...(data === undefined ? {} : { data }),\n ...(callRows === undefined ? {} : { callRows }),\n extensions,\n hasCache: incomingCache !== undefined || chain?.hasCache === true,\n hasRequestHandlers: hasCompiledHandlers(request),\n hasQueryHandlers: hasCompiledHandlers(query),\n hasResultConsumers:\n chain?.hasResultConsumers === true ||\n consumesOperationResults(effectiveDefinition),\n request,\n query,\n statement: appendFlatHandler(\n chain?.statement,\n resolved,\n effectiveDefinition.statement\n ),\n observe: appendObserver(\n chain?.observe,\n resolved,\n effectiveDefinition.observe\n ),\n });\n const official = incomingOfficial ?? existingOfficial;\n if (official !== undefined) {\n registerOfficialInstrumentationChain(resolvedChain, official);\n }\n const officialCache = incomingCache ?? existingOfficialCache;\n if (officialCache !== undefined) {\n registerOfficialCacheChain(resolvedChain, officialCache);\n }\n const officialDefaultOmit = incomingDefaultOmit ?? existingDefaultOmit;\n if (officialDefaultOmit !== undefined) {\n registerOfficialDefaultOmitChain(resolvedChain, officialDefaultOmit);\n }\n return resolvedChain;\n}\n"],"mappings":"qaA6BA,SAAgB,mBACd,EAC4B,CAC5B,GAAI,CACF,IAAM,EAAY,EAAO,QAAQ,UACjC,OAAO,OAAO,OAAO,CACnB,QAAS,EAAO,QAChB,WAAY,EAAO,WACnB,GAAI,IAAc,IAAA,GAAY,EAAE,CAAG,CAAE,YAAW,CACjD,CAAC,MACI,CAGN,QC/BJ,MAAa,EAA6B,qBAqBpC,EAAwB,IAAI,QAI5B,EAAsB,IAAI,QAKhC,SAAS,mBAAmB,EAAiB,EAAwB,CACnE,MAAM,IAAI,EAA0B,EAAS,CAC3C,MAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAW,EAAM,CAC3D,CAAC,CAGJ,SAAS,QAAQ,EAAe,EAA8B,CAC5D,GAAI,CACF,OAAO,QAAQ,QAAQ,EAAM,OACtB,EAAO,CACd,mBACE,gBAAgB,EAAM,kCACtB,EACD,EAIL,SAASA,UACP,EACA,EACA,EACS,CACT,GAAI,CACF,OAAO,EAAM,SACN,EAAO,CACd,mBACE,gBAAgB,EAAM,WAAW,EAAI,sBACrC,EACD,yBAIL,SAAS,sBACP,EACA,EACkC,CAClC,GAAI,CACF,OAAO,EAAS,EAAM,OACf,EAAO,CACd,mBAAmB,gBAAgB,EAAM,0BAA2B,EAAM,EAI9E,SAAS,eAAe,EAA0C,CAC3D,sBAAsB,EAAO,gBAAgB,EAChD,mBAAmB,gDAAgD,CAErE,IAAM,EAGF,OAAO,OAAO,KAAK,CACvB,IAAK,IAAM,KAAY,QAAQ,EAAO,gBAAgB,CAAE,CAClD,OAAO,GAAa,UACtB,mBACE,8DACD,CAEH,IAAM,EAAQA,UAAQ,EAAO,EAAU,gBAAgB,CAClD,sBAAsB,EAAO,iBA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WAAW,GAAO,KAAM,EAAoB,KAAK,CAIjDC,EACJ,IAAS,GAAO,MAAQ,IAAa,GAAO,UAAY,IAAS,GAAO,KACpE,GAAO,SACP,SAAS,EAAM,EAAU,EAAM,EAAU,EAAO,CAChD,EAAgB,OAAO,OAAO,CAClC,GAAI,IAAa,IAAA,GAAY,EAAE,CAAG,CAAE,WAAU,CAC9C,GAAI,IAAS,IAAA,GAAY,EAAE,CAAG,CAAE,OAAM,CACtC,GAAI,IAAa,IAAA,GAAY,EAAE,CAAG,CAAE,WAAU,CAC9C,GAAI,IAAS,IAAA,GAAY,EAAE,CAAG,CAAE,OAAM,CACtC,GAAIA,IAAa,IAAA,GAAY,EAAE,CAAG,CAAE,SAAA,EAAU,CAC9C,aACA,SAAU,IAAkB,IAAA,IAAa,GAAO,WAAa,GAC7D,mBAAoB,oBAAoB,EAAQ,CAChD,iBAAkB,oBAAoB,EAAM,CAC5C,mBACE,GAAO,qBAAuB,IAC9B,yBAAyB,EAAoB,CAC/C,UACA,QACA,UAAW,kBACT,GAAO,UACP,EACA,EAAoB,UACrB,CACD,QAAS,eACP,GAAO,QACP,EACA,EAAoB,QACrB,CACF,CAAC,CACI,EAAW,GAAoB,EACjC,IAAa,IAAA,IACf,EAAqC,EAAe,EAAS,CAE/D,IAAM,EAAgB,GAAiB,EACnC,IAAkB,IAAA,IACpB,EAA2B,EAAe,EAAc,CAE1D,IAAM,EAAsB,GAAuB,EAInD,OAHI,IAAwB,IAAA,IAC1B,iCAAiC,EAAe,EAAoB,CAE/D"}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./validator-
|
|
3
|
-
`);async function runCheck(e){
|
|
4
|
-
`)}\n`)
|
|
5
|
-
`)
|
|
6
|
-
`)
|
|
7
|
-
`),e.dryRun){e.json?printJson(i):printPlan(i);return}if(e.json||printPlan(i),i.destructive&&!e.acceptDataLoss&&(e.yes||e.json||!process.stdin.isTTY))throw Error(`Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.`);if(i.outcome!==`noop`&&!e.yes&&!e.acceptDataLoss&&!e.json&&process.stdin.isTTY){let e=await C({message:i.destructive?`Apply this destructive push plan?`:`Apply this push plan?`,initialValue:!i.destructive});if(w(e)||!e){S(`Push cancelled.`);return}}let a=await r.push({consent:i.consent});e.json?printJson(a):E(a.outcome===`noop`?`Schema is up to date.`:`Push applied.`)}catch(e){n={value:e}}finally{await m(t,n,e.json)}}function createPushCommand(){return new v(`push`).description(`Synchronize the schema directly without migration history`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--dry-run`,`Preview without changing the database`).option(`--force-reset`,`Plan a rebuild from an empty database`).option(`-y, --yes`,`Skip prompts for non-destructive plans`).option(`--accept-data-loss`,`Explicitly accept the previewed destructive plan`).option(`--json`,`Print machine-readable JSON`).action(runPush)}const j=createPushCommand(),M=new v;M.name(`viborm`).description(`VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite`).version(a),M.addCommand(O),M.addCommand(j),M.addCommand(A);try{await M.parseAsync()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`CLI failed`}\n`),process.exitCode=1}export{};
|
|
2
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./validator-X9-bwtRo.mjs";import{t as n}from"./hydration-CAxOL4aI.mjs";import{a as r,n as i,o as a,s as o,t as s}from"./client-CCgfcp5A.mjs";import{a as c}from"./identity-CLFhCTZx.mjs";import{t as l}from"./every-4KE0p2Gw.mjs";import{t as u}from"./version-JDaZht4U.mjs";import{i as d,n as f,r as p}from"./utils-CZNaOZR7.mjs";import{t as m}from"./fs-estate-CAhDg7nY.mjs";import{Command as h,InvalidArgumentError as g}from"commander";import{resolve as _}from"node:path";import{writeFile as v}from"node:fs/promises";import{cancel as y,confirm as b,isCancel as x,note as S,outro as C}from"@clack/prompts";const needsRepair=e=>e.type===`decimal`?!e.checked:e.noncanonical!==0,describeAudit=e=>{let t=`[storage] "${e.table}"."${e.column}"`;if((e.type===`decimal`?e.declared:e.noncanonical)===null)return`${t}: the column is missing; typed queries that use it fail.\n Create it through viborm push or migrate.`;if(e.type===`decimal`)return`${t}: declared ${e.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;let n=e.type===`time`?`Time`:`DateTime`,r=e.list?"Rewrite each row through the typed client (`update`), which stores canonical members":`Repair with sqliteCanonical${n}Expression from viborm/migrations`;return`${t}: ${e.noncanonical} row(s) of noncanonical ${n} text compare and sort wrongly.\n ${r}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`},describe=e=>[`[${e.code}] ${e.message}`,e.repair].filter(Boolean).join(`
|
|
3
|
+
`);async function runCheck(e){await d({config:e.config,skipValidation:!0},e.json,async r=>{let{models:i}=r;n(i);let a=t(i),s=e.db?await o({$driver:r.driver,$schema:i}):void 0,c=s?.filter(needsRepair)??[];if(e.json)process.stdout.write(`${JSON.stringify(s?{...a,storage:s}:a,null,2)}\n`);else{for(let e of a.errors)process.stderr.write(`error ${describe(e)}\n`);for(let e of a.warnings)process.stderr.write(`warning ${describe(e)}\n`);for(let e of c)process.stderr.write(`error ${describeAudit(e)}\n`);process.stdout.write(a.valid?`Schema valid (${Object.keys(i).length} models).\n`:`Schema invalid: ${a.errors.length} error(s).\n`),s&&process.stdout.write(`Storage audited: ${s.length} column(s), ${c.length} need repair.\n`)}(!a.valid||c.length>0)&&(process.exitCode=1)})}function createCheckCommand(){return new h(`check`).description(`Validate the schema, so clients can be created with skipSchemaValidation`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--json`,`Print machine-readable JSON`).option(`--db`,`Also audit SQLite storage: DateTime/Time text and decimal columns`).action(runCheck)}const w=createCheckCommand(),T=/^[0-9a-f]{8,63}$/;function positiveInteger(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new g(`must be a positive safe integer`);return t}function selector(e){if(e)return c(e)?{id:e}:T.test(e)?{prefix:e}:{name:e}}const approveDestructive=e=>e.type===`destructive`?e.proceed():void 0,confirmDestructive=async e=>{if(e.type!==`destructive`)return;let t=await b({message:`${e.description} — approve?`,initialValue:!1});return!x(t)&&t?e.proceed():e.reject()};function generateResolver(e,t){if(e.migrations?.resolve)return e.migrations.resolve;if(t.acceptDataLoss)return approveDestructive;if(!(t.dryRun||t.json||!process.stdin.isTTY))return confirmDestructive}async function withMigrations(e,t,n){await d({config:e.opts().config},t.json,async e=>{let r=_(t.dir??e.migrations?.dir??`./migrations`),i=e.migrations?.storage??m(r);await n(s(e.client,{storage:i,...e.migrations?.tables===void 0?{}:{tables:e.migrations.tables}}),e,i)})}function createMigrateCommand(){let e=new h(`migrate`).description(`Manage the authenticated migration estate`).option(`--config <path>`,`Path to viborm.config.ts`);return e.command(`generate`).description(`Publish a new estate state from the current schema`).option(`-n, --name <name>`,`Human-readable state label`).option(`-d, --dir <dir>`,`Estate directory`).option(`--from <stateId>`,`Parent state id, or empty for the virtual root`).option(`--custom <path>`,`Compile a TypeScript manual migration author`).option(`--review <path>`,`Write labelled forward/check/rollback review SQL`).option(`--dry-run`,`Preview without publishing`).option(`--low-lock`,`PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps`).option(`--accept-data-loss`,`Approve destructive changes (drops, type changes) for this generate`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async(e,n)=>{let i=t.from===void 0?void 0:t.from===``||t.from===`empty`?null:c(t.from)?t.from:(await e.show(selector(t.from))).stateId,a;if(t.custom){let n=await f(_(t.custom)),r=(Object.hasOwn(n,`default`)?n.default:void 0)??n.migration;if(!r)throw Error(`A custom migration module must export a default migration or author function`);let o=await e.graph(),s=Object.freeze(i===void 0?o.leaves.length===0?[null]:[...o.leaves]:[i]);a=typeof r==`function`?await r(s):r}let o=generateResolver(n,t),s=await e.generate({name:t.name,from:i,dryRun:t.dryRun,...t.lowLock?{lowLock:!0}:{},...o?{resolve:o}:{},...a?{manualMigration:a}:{}});if(t.json)p(s,!0);else{process.stdout.write(`${s.outcome}: ${s.name??`No schema changes`}${s.stateId?` (${s.stateId})`:``}\n`);for(let e of s.operationsByParent??[])process.stdout.write(`Parent ${e.fromState??`empty`}:\n${e.operations.map(r).join(`
|
|
4
|
+
`)}\n`);for(let e of s.warnings??[])process.stderr.write(`warning: ${e}\n`);(s.reviewSql||s.sql)&&process.stdout.write(`${s.reviewSql||s.sql}\n`)}t.review&&s.reviewSql&&await v(_(t.review),s.reviewSql,`utf8`)})}),e.command(`check`).description(`Validate estate artifacts without touching the database`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{let n=await e.check();p(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`list`).description(`List estate states`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.list(),!!t.json)})}),e.command(`show`).description(`Show one estate state`).argument(`<state>`,`State id, unambiguous prefix, or name`).option(`-d, --dir <dir>`,`Estate directory`).option(`--sql`,`Print labelled forward/check/rollback review SQL`).option(`--review <path>`,`Write review SQL to this file`).option(`--json`,`Print machine-readable output`).action(async(t,n)=>{await withMigrations(e,n,async(e,r,o)=>{let s=await e.show(selector(t));if(!(n.sql||n.review)){p(s,!!n.json);return}let c=await a(o),l=c.states.get(s.stateId),u=l&&c.sql.get(l.sqlHash);if(!(l&&u))throw Error(`The authenticated state SQL is unavailable`);let d=i(l.parents,l.destinationChecks,u);n.json?p({...s,reviewSql:d},!0):(p(s,!1),process.stdout.write(d)),n.review&&await v(_(n.review),d,`utf8`)})}),e.command(`graph`).description(`Print estate roots and leaves`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.graph(),!!t.json)})}),e.command(`status`).description(`Show marker, pending path, and unfinished attempts`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.status(),!!t.json)})}),e.command(`verify`).description(`Lock and compare the live schema to the marker`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{let n=await e.verify();p(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`log`).description(`Print the append-only ledger`).option(`-d, --dir <dir>`,`Estate directory`).option(`--limit <n>`,`Maximum events`,positiveInteger).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{let n=await e.log();p(t.limit?n.slice(-t.limit):n,!!t.json)})}),e.command(`apply`).description(`Apply estate states to the target`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state id, prefix, or name`).option(`--via <stateId...>`,`Force a path through these states`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.apply({to:selector(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e.command(`down`).description(`Roll back along the recorded arrival path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Roll back to this state`).option(`--steps <n>`,`Number of states to roll back`,positiveInteger).option(`--accept-data-loss`,`Approve destructive changes the rollback makes to populated tables`).option(`--expect-revision <n>`,`Refuse unless the marker is at this revision`,positiveInteger).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async(e,n)=>{if(t.to!==void 0&&t.steps!==void 0)throw Error(`down accepts --to or --steps, not both`);let r=generateResolver(n,t),i={dryRun:t.dryRun,...r?{resolve:r}:{},...t.expectRevision===void 0?{}:{expectRevision:t.expectRevision}},a=await e.down(t.to?{to:selector(t.to),...i}:{steps:t.steps,...i});if(!a.preview||t.json)p(a,!!t.json);else{for(let e of a.edges)process.stdout.write(e.sql);a.refusal&&process.stderr.write(`down would refuse: ${a.refusal.code}: ${a.refusal.message}\n`)}a.preview&&a.refusal&&(process.exitCode=1)})}),e.command(`baseline`).description(`Adopt an existing database as a known estate state`).requiredOption(`--to <selector>`,`Existing estate state to adopt`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.baseline({to:selector(t.to),via:t.via}),!!t.json)})}),e.command(`reanchor`).description(`After a restore left the history older than the database, move the marker to the state the live schema matches`).option(`--to <selector>`,`Adopt this state as the new baseline`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.reanchor({to:selector(t.to),via:t.via}),!!t.json)})}),e.command(`resolve`).description(`Resolve an unfinished attempt after live proof`).option(`-d, --dir <dir>`,`Estate directory`).option(`--complete`,`Mark complete when destination proof holds`).option(`--rolled-back`,`Mark rolled back when origin proof holds`).option(`--retry`,`Retry from the first proven incomplete step`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{if([t.complete,t.rolledBack,t.retry].filter(Boolean).length!==1)throw Error(`resolve requires exactly one of --complete, --rolled-back, or --retry`);let n=t.complete?`complete`:t.rolledBack?`rolled-back`:`retry`;p(await e.resolve({outcome:n}),!!t.json)})}),e.command(`reset`).description(`Clear managed objects and replay from empty to a selected state`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state after rebuild`).option(`--via <stateId...>`,`Force a rebuild path`).option(`--confirm`,`Confirm destructive reset (not required for dry-run)`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{if(!(t.dryRun||t.confirm))throw Error(`Reset requires --confirm; inspect --dry-run first`);p(await e.reset({to:selector(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e}const E=createMigrateCommand();function printPlan(e){let t=e.operations.length===0?[`No schema changes.`]:e.operations.map(e=>`[${e.risk}] ${e.label} (${e.id})`),n=e.statements.map((e,t)=>`${t+1}. ${e.sql}${e.parameters.length===0?``:`\n parameters: ${JSON.stringify(e.parameters)}`}`);S([`Target: ${JSON.stringify(e.target)}`,`Plan: ${e.planHash}`,...t,...n.length===0?[]:[``,`SQL:`,...n]].join(`
|
|
5
|
+
`),`Push plan`)}async function runPush(e){await d({config:e.config},e.json,async t=>{let n=t.migrations?.tables===void 0?s(t.client):s(t.client,{tables:t.migrations.tables}),r=await n.push({dryRun:!0,...e.forceReset===!0?{forceReset:!0}:{},...t.migrations?.resolve?{resolve:t.migrations.resolve}:{}});if(!e.json&&t.driver?.dialect===`sqlite`&&[`sqlite3`,`bun-sqlite`,`bun-sql`].includes(t.driver.driverName)&&(await t.driver._executeRaw(`PRAGMA database_list`)).rows.some(e=>e.name===`main`&&e.file===``)&&process.stderr.write(`warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.
|
|
6
|
+
`),e.dryRun){e.json?p(r,!0):printPlan(r);return}if(e.json||printPlan(r),r.destructive&&!e.acceptDataLoss&&(e.yes||e.json||!process.stdin.isTTY))throw Error(`Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.`);if(r.outcome!==`noop`&&!e.yes&&!e.acceptDataLoss&&!e.json&&process.stdin.isTTY){let e=await b({message:r.destructive?`Apply this destructive push plan?`:`Apply this push plan?`,initialValue:!r.destructive});if(x(e)||!e){y(`Push cancelled.`);return}}let i=await n.push({consent:r.consent});e.json?p(i,!0):C(i.outcome===`noop`?`Schema is up to date.`:`Push applied.`)})}function createPushCommand(){return new h(`push`).description(`Synchronize the schema directly without migration history`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--dry-run`,`Preview without changing the database`).option(`--force-reset`,`Plan a rebuild from an empty database`).option(`-y, --yes`,`Skip prompts for non-destructive plans`).option(`--accept-data-loss`,`Explicitly accept the previewed destructive plan`).option(`--json`,`Print machine-readable JSON`).action(runPush)}const D=createPushCommand();l();const O=new h;O.name(`viborm`).description(`VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite`).version(u),O.addCommand(w),O.addCommand(D),O.addCommand(E);try{await O.parseAsync()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`CLI failed`}\n`),process.exitCode=1}export{};
|
|
8
7
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":["printJson"],"sources":["../src/cli/commands/check.ts","../src/cli/commands/migrate.ts","../src/cli/commands/push.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Schema check CLI.\n *\n * Runs every check a client runs when it is created (identifiers, model\n * identity, relation resolution, selector names), plus the advisory rules,\n * against the schema of the configured client. Run it in a build or CI step to\n * create clients with `skipSchemaValidation: true` at runtime.\n */\n\nimport { Command } from \"commander\";\nimport { sqliteNoncanonicalTemporalCount } from \"../../adapters/databases/sqlite/storage/datetime\";\nimport { isSqliteDecimalStorage } from \"../../adapters/databases/sqlite/storage/decimal\";\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport {\n type AnyModel,\n getTableName,\n type ModelState,\n} from \"../../schema/model\";\nimport { sqliteDateTimePhysicalForm } from \"../../schema/scalars/datetime/physical\";\nimport type { SchemaValidationIssue } from \"../../schema/validation/types\";\nimport { validateSchema } from \"../../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../../sql/identifiers\";\nimport { finishCli, loadConfig } from \"../utils\";\n\ninterface CheckCliOptions {\n readonly config?: string;\n readonly json?: boolean;\n readonly db?: boolean;\n}\n\ntype ColumnAudit = { readonly table: string; readonly column: string } & (\n | {\n readonly type: \"datetime\" | \"time\";\n readonly list: boolean;\n /** `null` when the column is missing. */\n readonly noncanonical: number | null;\n }\n | {\n readonly type: \"decimal\";\n /** The catalog's declared type; `null` when the column is missing. */\n readonly declared: string | null;\n readonly checked: boolean;\n }\n);\n\ninterface CatalogColumn {\n readonly definition: string | null;\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nconst quote = createIdentifierQuoter('\"');\n\n/** One SQLite table's declared columns, each beside the table's stored definition. */\nasync function readCatalog(\n driver: AnyDriver,\n table: string\n): Promise<CatalogColumn[]> {\n const { rows } = await driver._executeRaw<\n Omit<CatalogColumn, \"nullable\"> & { notnull: number; pk: number }\n >(\n `SELECT s.sql AS definition, p.name, p.type, p.\"notnull\", p.pk FROM sqlite_schema AS s JOIN pragma_table_info(s.name) AS p WHERE s.type = 'table' AND s.name = ?`,\n [table]\n );\n // SQLite reports a primary key nullable; VibORM writes it NOT NULL.\n return rows.map(({ notnull, pk, ...column }) => ({\n ...column,\n nullable: Number(notnull) === 0 && Number(pk) === 0,\n }));\n}\n\n/**\n * Audit SQLite storage typed queries assume but never inspect: one catalog\n * read per table decides which audited columns exist; each existing text\n * DateTime/Time column's noncanonical rows are counted (one scan each), and\n * each decimal column is checked against the scaled-integer storage of its\n * descriptor. Other dialects store native types.\n */\nasync function auditStorage(\n driver: AnyDriver,\n models: Record<string, AnyModel>\n): Promise<ColumnAudit[]> {\n if (driver.dialect !== \"sqlite\") return [];\n const audits: ColumnAudit[] = [];\n for (const [name, model] of Object.entries(models)) {\n const table = getTableName(model, name);\n const state: ModelState = model[\"~\"].state;\n // A missing table has no catalog rows: each audited column is missing.\n let catalog: Promise<CatalogColumn[]> | undefined;\n const find = async (column: string) =>\n (await (catalog ??= readCatalog(driver, table))).find(\n (entry) => entry.name === column\n );\n for (const [field, scalar] of Object.entries(state.scalars)) {\n const definition = scalar[\"~\"].state;\n const { type, array = false } = definition;\n const column = model[\"~\"].getFieldName(field).sql;\n if (definition.type === \"decimal\") {\n const row = await find(column);\n audits.push({\n table,\n column,\n type: \"decimal\",\n declared: row?.type ?? null,\n checked:\n row !== undefined &&\n isSqliteDecimalStorage(\n row.definition,\n row,\n definition.decimal,\n array ? \"list\" : \"scalar\",\n quote\n ),\n });\n continue;\n }\n const text =\n type === \"time\" ||\n (type === \"datetime\" &&\n (array ||\n sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType) === \"text\"));\n if (!text) continue;\n // Never scan a missing column: SQLite may read its quoted name as text.\n const scan =\n (await find(column)) &&\n (await driver._executeRaw<{ noncanonical: number }>(\n sqliteNoncanonicalTemporalCount(table, column, type, array)\n ));\n audits.push({\n table,\n column,\n type,\n list: array,\n noncanonical: scan ? Number(scan.rows[0]?.noncanonical) : null,\n });\n }\n }\n return audits;\n}\n\nconst needsRepair = (audit: ColumnAudit): boolean =>\n audit.type === \"decimal\" ? !audit.checked : audit.noncanonical !== 0;\n\nconst describeAudit = (audit: ColumnAudit): string => {\n const column = `[storage] \"${audit.table}\".\"${audit.column}\"`;\n if ((audit.type === \"decimal\" ? audit.declared : audit.noncanonical) === null)\n return `${column}: the column is missing; typed queries that use it fail.\\n Create it through viborm push or migrate.`;\n if (audit.type === \"decimal\")\n return `${column}: declared ${audit.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;\n const kind = audit.type === \"time\" ? \"Time\" : \"DateTime\";\n const repair = audit.list\n ? \"Rewrite each row through the typed client (`update`), which stores canonical members\"\n : `Repair with sqliteCanonical${kind}Expression from viborm/migrations`;\n return `${column}: ${audit.noncanonical} row(s) of noncanonical ${kind} text compare and sort wrongly.\\n ${repair}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`;\n};\n\n// The repair hint, when the issue has one, goes on its own indented line.\nconst describe = (issue: SchemaValidationIssue): string =>\n [`[${issue.code}] ${issue.message}`, issue.repair]\n .filter(Boolean)\n .join(\"\\n \");\n\nasync function runCheck(options: CheckCliOptions): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({\n config: options.config,\n skipValidation: true,\n });\n client = config.client;\n const { models } = config;\n // The identifier and identity checks hydration runs, whatever the\n // configured client skipped.\n hydrateSchemaNames(models);\n const result = validateSchema(models);\n const storage = options.db\n ? await auditStorage(config.driver, models)\n : undefined;\n const dirty = storage?.filter(needsRepair) ?? [];\n if (options.json) {\n process.stdout.write(\n `${JSON.stringify(storage ? { ...result, storage } : result, null, 2)}\\n`\n );\n } else {\n for (const issue of result.errors)\n process.stderr.write(`error ${describe(issue)}\\n`);\n for (const issue of result.warnings)\n process.stderr.write(`warning ${describe(issue)}\\n`);\n for (const audit of dirty)\n process.stderr.write(`error ${describeAudit(audit)}\\n`);\n process.stdout.write(\n result.valid\n ? `Schema valid (${Object.keys(models).length} models).\\n`\n : `Schema invalid: ${result.errors.length} error(s).\\n`\n );\n if (storage)\n process.stdout.write(\n `Storage audited: ${storage.length} column(s), ${dirty.length} need repair.\\n`\n );\n }\n if (!result.valid || dirty.length > 0) process.exitCode = 1;\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, options.json);\n }\n}\n\nexport function createCheckCommand(): Command {\n return new Command(\"check\")\n .description(\n \"Validate the schema, so clients can be created with skipSchemaValidation\"\n )\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--json\", \"Print machine-readable JSON\")\n .option(\n \"--db\",\n \"Also audit SQLite storage: DateTime/Time text and decimal columns\"\n )\n .action(runCheck);\n}\n\nexport const checkCommand = createCheckCommand();\n","/**\n * Migration CLI. Composition root is createMigrationClient + loadConfig.\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport {\n createMigrationClient,\n type WritableMigrations,\n} from \"../../migrations/client\";\nimport { loadMigrationGraph } from \"../../migrations/graph\";\nimport { isSha256 } from \"../../migrations/identity\";\nimport { renderMigrationReview } from \"../../migrations/public-view\";\nimport { formatOperation } from \"../../migrations/push/format\";\nimport type { MigrationStorageWriter } from \"../../migrations/storage/contract\";\nimport { createFsStorageWriter } from \"../../migrations/storage/fs-estate\";\nimport type {\n ManualMigrationInput,\n StateSelector,\n} from \"../../migrations/v1-types\";\nimport {\n finishCli,\n type LoadedConfig,\n loadCliModule,\n loadConfig,\n} from \"../utils\";\n\nconst STATE_ID_PREFIX = /^[0-9a-f]{8,63}$/;\n\nfunction positiveInteger(value: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(\"must be a positive safe integer\");\n }\n return parsed;\n}\n\nfunction selector(value: string | undefined): StateSelector | undefined {\n if (!value) return undefined;\n if (isSha256(value)) return { id: value };\n if (STATE_ID_PREFIX.test(value)) return { prefix: value };\n return { name: value };\n}\n\nfunction 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\nasync function withMigrations(\n options: { dir?: string; config?: string; json?: boolean },\n run: (\n migrations: WritableMigrations,\n config: LoadedConfig,\n storage: MigrationStorageWriter\n ) => 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({ config: options.config });\n client = config.client;\n const directory = resolve(\n options.dir ?? config.migrations?.dir ?? \"./migrations\"\n );\n const storage =\n config.migrations?.storage ?? createFsStorageWriter(directory);\n const migrations = createMigrationClient(config.client, {\n storage,\n ...(config.migrations?.tables === undefined\n ? {}\n : { tables: config.migrations.tables }),\n });\n await run(migrations, config, storage);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, options.json);\n }\n}\n\nexport function createMigrateCommand(): Command {\n const migrate = new Command(\"migrate\")\n .description(\"Manage the authenticated migration estate\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\");\n\n migrate\n .command(\"generate\")\n .description(\"Publish a new estate state from the current schema\")\n .option(\"-n, --name <name>\", \"Human-readable state label\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\n \"--from <stateId>\",\n \"Parent state id, or empty for the virtual root\"\n )\n .option(\"--custom <path>\", \"Compile a TypeScript manual migration author\")\n .option(\n \"--review <path>\",\n \"Write labelled forward/check/rollback review SQL\"\n )\n .option(\"--dry-run\", \"Preview without publishing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n name?: string;\n dir?: string;\n from?: string;\n dryRun?: boolean;\n custom?: string;\n review?: string;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations, config) => {\n const from =\n opts.from === undefined\n ? undefined\n : opts.from === \"\" || opts.from === \"empty\"\n ? null\n : isSha256(opts.from)\n ? opts.from\n : (await migrations.show(selector(opts.from)!)).stateId;\n let manualMigration: ManualMigrationInput | undefined;\n if (opts.custom) {\n type Author =\n | ManualMigrationInput\n | ((\n parents: readonly (string | null)[]\n ) => ManualMigrationInput | Promise<ManualMigrationInput>);\n const module = await loadCliModule<{\n default?: Author;\n migration?: Author;\n }>(resolve(opts.custom));\n const author =\n (Object.hasOwn(module, \"default\")\n ? module.default\n : undefined) ?? module.migration;\n if (!author)\n throw new Error(\n \"A custom migration module must export a default migration or author function\"\n );\n const graph = await migrations.graph();\n const parents = Object.freeze(\n from === undefined\n ? graph.leaves.length === 0\n ? [null]\n : [...graph.leaves]\n : [from]\n );\n manualMigration =\n typeof author === \"function\" ? await author(parents) : author;\n }\n const result = await migrations.generate({\n name: opts.name,\n from,\n dryRun: opts.dryRun,\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n ...(manualMigration ? { manualMigration } : {}),\n });\n if (opts.json) printJson(result, true);\n else {\n process.stdout.write(\n `${result.outcome}: ${result.name ?? \"No schema changes\"}${result.stateId ? ` (${result.stateId})` : \"\"}\\n`\n );\n for (const parent of result.operationsByParent ?? []) {\n process.stdout.write(\n `Parent ${parent.fromState ?? \"empty\"}:\\n${parent.operations.map(formatOperation).join(\"\\n\")}\\n`\n );\n }\n for (const warning of result.warnings ?? [])\n process.stderr.write(`warning: ${warning}\\n`);\n if (result.reviewSql || result.sql)\n process.stdout.write(`${result.reviewSql || result.sql}\\n`);\n }\n if (opts.review && result.reviewSql)\n await writeFile(resolve(opts.review), result.reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"check\")\n .description(\"Validate estate artifacts without touching the database\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const result = await migrations.check();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n }\n );\n });\n\n migrate\n .command(\"list\")\n .description(\"List estate states\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.list(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"show\")\n .description(\"Show one estate state\")\n .argument(\"<state>\", \"State id, unambiguous prefix, or name\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--sql\", \"Print labelled forward/check/rollback review SQL\")\n .option(\"--review <path>\", \"Write review SQL to this file\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (\n state: string,\n opts: { dir?: string; sql?: boolean; review?: string; json?: boolean }\n ) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations, _config, storage) => {\n const details = await migrations.show(selector(state)!);\n if (!(opts.sql || opts.review)) {\n printJson(details, Boolean(opts.json));\n return;\n }\n const graph = await loadMigrationGraph(storage);\n const manifest = graph.states.get(details.stateId);\n const blob = manifest && graph.sql.get(manifest.sqlHash);\n if (!(manifest && blob))\n throw new Error(\"The authenticated state SQL is unavailable\");\n const reviewSql = renderMigrationReview(\n manifest.parents,\n manifest.destinationChecks,\n blob\n );\n if (opts.json) printJson({ ...details, reviewSql }, true);\n else {\n printJson(details, false);\n process.stdout.write(reviewSql);\n }\n if (opts.review)\n await writeFile(resolve(opts.review), reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"graph\")\n .description(\"Print estate roots and leaves\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.graph(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"status\")\n .description(\"Show marker, pending path, and unfinished attempts\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(await migrations.status(), Boolean(opts.json));\n }\n );\n });\n\n migrate\n .command(\"verify\")\n .description(\"Lock and compare the live schema to the marker\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const result = await migrations.verify();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n }\n );\n });\n\n migrate\n .command(\"log\")\n .description(\"Print the append-only ledger\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--limit <n>\", \"Maximum events\", positiveInteger)\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; limit?: number; json?: boolean }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n const events = await migrations.log();\n printJson(\n opts.limit ? events.slice(-opts.limit) : events,\n Boolean(opts.json)\n );\n }\n );\n });\n\n migrate\n .command(\"apply\")\n .description(\"Apply estate states to the target\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state id, prefix, or name\")\n .option(\"--via <stateId...>\", \"Force a path through these states\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(\n await migrations.apply({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"down\")\n .description(\"Roll back along the recorded arrival path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Roll back to this state\")\n .option(\"--steps <n>\", \"Number of states to roll back\", positiveInteger)\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n steps?: number;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (opts.to !== undefined && opts.steps !== undefined)\n throw new Error(\"down accepts --to or --steps, not both\");\n printJson(\n await migrations.down(\n opts.to\n ? { to: selector(opts.to)!, dryRun: opts.dryRun }\n : { steps: opts.steps, dryRun: opts.dryRun }\n ),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"baseline\")\n .description(\"Adopt an existing database as a known estate state\")\n .requiredOption(\"--to <selector>\", \"Existing estate state to adopt\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n printJson(\n await migrations.baseline({\n to: selector(opts.to)!,\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"resolve\")\n .description(\"Resolve an unfinished attempt after live proof\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--complete\", \"Mark complete when destination proof holds\")\n .option(\"--rolled-back\", \"Mark rolled back when origin proof holds\")\n .option(\"--retry\", \"Retry from the first proven incomplete step\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n complete?: boolean;\n rolledBack?: boolean;\n retry?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (\n [opts.complete, opts.rolledBack, opts.retry].filter(Boolean)\n .length !== 1\n )\n throw new Error(\n \"resolve requires exactly one of --complete, --rolled-back, or --retry\"\n );\n const outcome = opts.complete\n ? \"complete\"\n : opts.rolledBack\n ? \"rolled-back\"\n : \"retry\";\n printJson(\n await migrations.resolve({ outcome }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n migrate\n .command(\"reset\")\n .description(\n \"Clear managed objects and replay from empty to a selected state\"\n )\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state after rebuild\")\n .option(\"--via <stateId...>\", \"Force a rebuild path\")\n .option(\"--confirm\", \"Confirm destructive reset (not required for dry-run)\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n confirm?: boolean;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(\n { ...opts, config: migrate.opts<{ config?: string }>().config },\n async (migrations) => {\n if (!(opts.dryRun || opts.confirm))\n throw new Error(\n \"Reset requires --confirm; inspect --dry-run first\"\n );\n printJson(\n await migrations.reset({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n }\n );\n }\n );\n\n return migrate;\n}\n\nexport const migrateCommand = createMigrateCommand();\n","/**\n * History-free, authenticated schema push CLI.\n *\n * The preview is inert. Effectful execution receives only the consent emitted\n * by that preview; no generic force authorization reaches the apply call.\n */\n\nimport { cancel, confirm, isCancel, note, outro } from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { createMigrationClient } from \"../../migrations/client\";\nimport type { PushPreview } from \"../../migrations/push-v1\";\nimport { finishCli, loadConfig } from \"../utils\";\n\ninterface PushCliOptions {\n readonly config?: string;\n readonly dryRun?: boolean;\n readonly forceReset?: boolean;\n readonly yes?: boolean;\n readonly acceptDataLoss?: boolean;\n readonly json?: boolean;\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction printPlan(preview: PushPreview): void {\n const operations =\n preview.operations.length === 0\n ? [\"No schema changes.\"]\n : preview.operations.map(\n (operation) =>\n `[${operation.risk}] ${operation.label} (${operation.id})`\n );\n const statements = preview.statements.map(\n (statement, index) =>\n `${index + 1}. ${statement.sql}${\n statement.parameters.length === 0\n ? \"\"\n : `\\n parameters: ${JSON.stringify(statement.parameters)}`\n }`\n );\n const lines = [\n `Target: ${JSON.stringify(preview.target)}`,\n `Plan: ${preview.planHash}`,\n ...operations,\n ...(statements.length === 0 ? [] : [\"\", \"SQL:\", ...statements]),\n ];\n note(lines.join(\"\\n\"), \"Push plan\");\n}\n\nasync function runPush(options: PushCliOptions): Promise<void> {\n let orm: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig({ config: options.config });\n orm = config.client;\n const migrations =\n config.migrations?.tables === undefined\n ? createMigrationClient(config.client)\n : createMigrationClient(config.client, {\n tables: config.migrations.tables,\n });\n // `force` is confined to the inert planning arm. The authenticated apply\n // arm below receives only the consent bound to this exact preview.\n const preview = await migrations.push({\n dryRun: true,\n ...(options.forceReset === true ? { forceReset: true } : {}),\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n });\n\n if (\n !options.json &&\n config.driver?.dialect === \"sqlite\" &&\n [\"sqlite3\", \"bun-sqlite\", \"bun-sql\"].includes(config.driver.driverName)\n ) {\n const databases = await config.driver._executeRaw<{\n name: string;\n file: string;\n }>(\"PRAGMA database_list\");\n if (\n databases.rows.some(\n (database) => database.name === \"main\" && database.file === \"\"\n )\n )\n process.stderr.write(\n \"warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.\\n\"\n );\n }\n\n if (options.dryRun) {\n if (options.json) printJson(preview);\n else printPlan(preview);\n return;\n }\n\n if (!options.json) printPlan(preview);\n\n if (\n preview.destructive &&\n !options.acceptDataLoss &&\n (options.yes || options.json || !process.stdin.isTTY)\n ) {\n throw new Error(\n \"Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.\"\n );\n }\n if (\n preview.outcome !== \"noop\" &&\n !options.yes &&\n !options.acceptDataLoss &&\n !options.json &&\n process.stdin.isTTY\n ) {\n const accepted = await confirm({\n message: preview.destructive\n ? \"Apply this destructive push plan?\"\n : \"Apply this push plan?\",\n initialValue: !preview.destructive,\n });\n if (isCancel(accepted) || !accepted) {\n cancel(\"Push cancelled.\");\n return;\n }\n }\n\n const result = await migrations.push({ consent: preview.consent });\n if (options.json) printJson(result);\n else\n outro(\n result.outcome === \"noop\" ? \"Schema is up to date.\" : \"Push applied.\"\n );\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(orm, failure, options.json);\n }\n}\n\nexport function createPushCommand(): Command {\n return new Command(\"push\")\n .description(\"Synchronize the schema directly without migration history\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--dry-run\", \"Preview without changing the database\")\n .option(\"--force-reset\", \"Plan a rebuild from an empty database\")\n .option(\"-y, --yes\", \"Skip prompts for non-destructive plans\")\n .option(\n \"--accept-data-loss\",\n \"Explicitly accept the previewed destructive plan\"\n )\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runPush);\n}\n\nexport const pushCommand = createPushCommand();\n","#!/usr/bin/env node\n/**\n * VibORM CLI\n *\n * Command-line interface for VibORM database operations.\n */\n\nimport { Command } from \"commander\";\nimport { VIBORM_VERSION } from \"../version\";\nimport { checkCommand } from \"./commands/check\";\nimport { migrateCommand } from \"./commands/migrate\";\nimport { pushCommand } from \"./commands/push\";\n\nconst program = new Command();\n\nprogram\n .name(\"viborm\")\n .description(\"VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite\")\n .version(VIBORM_VERSION);\n\n// Register commands\nprogram.addCommand(checkCommand);\nprogram.addCommand(pushCommand);\nprogram.addCommand(migrateCommand);\n\n// Parse arguments\ntry {\n await program.parseAsync();\n} catch (error: unknown) {\n process.stderr.write(\n `${error instanceof Error ? error.message : \"CLI failed\"}\\n`\n );\n process.exitCode = 1;\n}\n"],"mappings":";iuBAqDA,MAAM,EAAQ,EAAuB,IAAI,CAGzC,eAAe,YACb,EACA,EAC0B,CAC1B,GAAM,CAAE,QAAS,MAAM,EAAO,YAG5B,kKACA,CAAC,EAAM,CACR,CAED,OAAO,EAAK,KAAK,CAAE,UAAS,KAAI,GAAG,MAAc,CAC/C,GAAG,EACH,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AS,CAAC,CAC9D,EAAQ,KAAM,UAAU,EAAO,CAEjC,EACE,EAAO,UAAY,OAAS,wBAA0B,gBACvD,OACI,EAAO,CACd,EAAU,CAAE,MAAO,EAAO,QAClB,CACR,MAAM,EAAU,EAAK,EAAS,EAAQ,KAAK,EAI/C,SAAgB,mBAA6B,CAC3C,OAAO,IAAI,EAAQ,OAAO,CACvB,YAAY,4DAA4D,CACxE,OAAO,kBAAmB,2BAA2B,CACrD,OAAO,YAAa,wCAAwC,CAC5D,OAAO,gBAAiB,wCAAwC,CAChE,OAAO,YAAa,yCAAyC,CAC7D,OACC,qBACA,mDACD,CACA,OAAO,SAAU,8BAA8B,CAC/C,OAAO,QAAQ,CAGpB,MAAa,EAAc,mBAAmB,CC/IxC,EAAU,IAAI,EAEpB,EACG,KAAK,SAAS,CACd,YAAY,0DAA0D,CACtE,QAAQ,EAAe,CAG1B,EAAQ,WAAW,EAAa,CAChC,EAAQ,WAAW,EAAY,CAC/B,EAAQ,WAAW,EAAe,CAGlC,GAAI,CACF,MAAM,EAAQ,YAAY,OACnB,EAAgB,CACvB,QAAQ,OAAO,MACb,GAAG,aAAiB,MAAQ,EAAM,QAAU,aAAa,IAC1D,CACD,QAAQ,SAAW"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli/commands/check.ts","../src/cli/commands/migrate.ts","../src/cli/commands/push.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Schema check CLI.\n *\n * Runs every check a client runs when it is created (identifiers, model\n * identity, relation resolution, selector names), plus the advisory rules,\n * against the schema of the configured client. Run it in a build or CI step to\n * create clients with `skipSchemaValidation: true` at runtime.\n */\n\nimport { Command } from \"commander\";\nimport {\n auditStorage,\n type StorageColumnAudit,\n} from \"../../migrations/sqlite-storage-audit\";\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport type { SchemaValidationIssue } from \"../../schema/validation/types\";\nimport { validateSchema } from \"../../schema/validation/validator\";\nimport { runCli } from \"../utils\";\n\ninterface CheckCliOptions {\n readonly config?: string;\n readonly json?: boolean;\n readonly db?: boolean;\n}\n\nconst needsRepair = (audit: StorageColumnAudit): boolean =>\n audit.type === \"decimal\" ? !audit.checked : audit.noncanonical !== 0;\n\nconst describeAudit = (audit: StorageColumnAudit): string => {\n const column = `[storage] \"${audit.table}\".\"${audit.column}\"`;\n if ((audit.type === \"decimal\" ? audit.declared : audit.noncanonical) === null)\n return `${column}: the column is missing; typed queries that use it fail.\\n Create it through viborm push or migrate.`;\n if (audit.type === \"decimal\")\n return `${column}: declared ${audit.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;\n const kind = audit.type === \"time\" ? \"Time\" : \"DateTime\";\n const repair = audit.list\n ? \"Rewrite each row through the typed client (`update`), which stores canonical members\"\n : `Repair with sqliteCanonical${kind}Expression from viborm/migrations`;\n return `${column}: ${audit.noncanonical} row(s) of noncanonical ${kind} text compare and sort wrongly.\\n ${repair}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`;\n};\n\n// The repair hint, when the issue has one, goes on its own indented line.\nconst describe = (issue: SchemaValidationIssue): string =>\n [`[${issue.code}] ${issue.message}`, issue.repair]\n .filter(Boolean)\n .join(\"\\n \");\n\nasync function runCheck(options: CheckCliOptions): Promise<void> {\n const load = { config: options.config, skipValidation: true };\n await runCli(load, options.json, async (config) => {\n const { models } = config;\n // The identifier and identity checks hydration runs, whatever the\n // configured client skipped.\n hydrateSchemaNames(models);\n const result = validateSchema(models);\n const storage = options.db\n ? await auditStorage({ $driver: config.driver, $schema: models })\n : undefined;\n const dirty = storage?.filter(needsRepair) ?? [];\n if (options.json) {\n process.stdout.write(\n `${JSON.stringify(storage ? { ...result, storage } : result, null, 2)}\\n`\n );\n } else {\n for (const issue of result.errors)\n process.stderr.write(`error ${describe(issue)}\\n`);\n for (const issue of result.warnings)\n process.stderr.write(`warning ${describe(issue)}\\n`);\n for (const audit of dirty)\n process.stderr.write(`error ${describeAudit(audit)}\\n`);\n process.stdout.write(\n result.valid\n ? `Schema valid (${Object.keys(models).length} models).\\n`\n : `Schema invalid: ${result.errors.length} error(s).\\n`\n );\n if (storage)\n process.stdout.write(\n `Storage audited: ${storage.length} column(s), ${dirty.length} need repair.\\n`\n );\n }\n if (!result.valid || dirty.length > 0) process.exitCode = 1;\n });\n}\n\nexport function createCheckCommand(): Command {\n return new Command(\"check\")\n .description(\n \"Validate the schema, so clients can be created with skipSchemaValidation\"\n )\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--json\", \"Print machine-readable JSON\")\n .option(\n \"--db\",\n \"Also audit SQLite storage: DateTime/Time text and decimal columns\"\n )\n .action(runCheck);\n}\n\nexport const checkCommand = createCheckCommand();\n","/**\n * Migration CLI. Composition root is createMigrationClient + loadConfig.\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { confirm, isCancel } from \"@clack/prompts\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport {\n createMigrationClient,\n type WritableMigrations,\n} from \"../../migrations/client\";\nimport { loadMigrationGraph } from \"../../migrations/graph\";\nimport { isSha256 } from \"../../migrations/identity\";\nimport { renderMigrationReview } from \"../../migrations/public-view\";\nimport { formatOperation } from \"../../migrations/push/format\";\nimport type { MigrationStorageWriter } from \"../../migrations/storage/contract\";\nimport { createFsStorageWriter } from \"../../migrations/storage/fs-estate\";\nimport type { ResolveCallback } from \"../../migrations/types\";\nimport type {\n ManualMigrationInput,\n StateSelector,\n} from \"../../migrations/v1-types\";\nimport { type LoadedConfig, loadCliModule, printJson, runCli } from \"../utils\";\n\nconst STATE_ID_PREFIX = /^[0-9a-f]{8,63}$/;\n\nfunction positiveInteger(value: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(\"must be a positive safe integer\");\n }\n return parsed;\n}\n\nfunction selector(value: string | undefined): StateSelector | undefined {\n if (!value) return undefined;\n if (isSha256(value)) return { id: value };\n if (STATE_ID_PREFIX.test(value)) return { prefix: value };\n return { name: value };\n}\n\n/** `--accept-data-loss`: every destructive change approved, nothing else decided. */\nconst approveDestructive: ResolveCallback = (change) =>\n change.type === \"destructive\" ? change.proceed() : undefined;\n\n/** One prompt per destructive change, as `viborm push` asks for its plan. */\nconst confirmDestructive: ResolveCallback = async (change) => {\n if (change.type !== \"destructive\") return;\n const approved = await confirm({\n message: `${change.description} — approve?`,\n initialValue: false,\n });\n return !isCancel(approved) && approved ? change.proceed() : change.reject();\n};\n\n/**\n * The resolver `migrate generate` publishes under, and `migrate down` rolls\n * back under: the config's own, else\n * `--accept-data-loss`, else a prompt on an interactive terminal. With none,\n * generate refuses a destructive change with `V11017`.\n */\nfunction generateResolver(\n config: LoadedConfig,\n opts: { acceptDataLoss?: boolean; dryRun?: boolean; json?: boolean }\n): ResolveCallback | undefined {\n if (config.migrations?.resolve) return config.migrations.resolve;\n if (opts.acceptDataLoss) return approveDestructive;\n if (opts.dryRun || opts.json || !process.stdin.isTTY) return;\n return confirmDestructive;\n}\n\n/** Each subcommand reads the parent's `--config` and its own `--dir`. */\nasync function withMigrations(\n migrate: Command,\n options: { dir?: string; json?: boolean },\n run: (\n migrations: WritableMigrations,\n config: LoadedConfig,\n storage: MigrationStorageWriter\n ) => Promise<void>\n): Promise<void> {\n await runCli(\n { config: migrate.opts<{ config?: string }>().config },\n options.json,\n async (config) => {\n const directory = resolve(\n options.dir ?? config.migrations?.dir ?? \"./migrations\"\n );\n const storage =\n config.migrations?.storage ?? createFsStorageWriter(directory);\n const migrations = createMigrationClient(config.client, {\n storage,\n ...(config.migrations?.tables === undefined\n ? {}\n : { tables: config.migrations.tables }),\n });\n await run(migrations, config, storage);\n }\n );\n}\n\nexport function createMigrateCommand(): Command {\n const migrate = new Command(\"migrate\")\n .description(\"Manage the authenticated migration estate\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\");\n\n migrate\n .command(\"generate\")\n .description(\"Publish a new estate state from the current schema\")\n .option(\"-n, --name <name>\", \"Human-readable state label\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\n \"--from <stateId>\",\n \"Parent state id, or empty for the virtual root\"\n )\n .option(\"--custom <path>\", \"Compile a TypeScript manual migration author\")\n .option(\n \"--review <path>\",\n \"Write labelled forward/check/rollback review SQL\"\n )\n .option(\"--dry-run\", \"Preview without publishing\")\n .option(\n \"--low-lock\",\n \"PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps\"\n )\n .option(\n \"--accept-data-loss\",\n \"Approve destructive changes (drops, type changes) for this generate\"\n )\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n name?: string;\n dir?: string;\n from?: string;\n dryRun?: boolean;\n lowLock?: boolean;\n acceptDataLoss?: boolean;\n custom?: string;\n review?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations, config) => {\n const from =\n opts.from === undefined\n ? undefined\n : opts.from === \"\" || opts.from === \"empty\"\n ? null\n : isSha256(opts.from)\n ? opts.from\n : (await migrations.show(selector(opts.from)!)).stateId;\n let manualMigration: ManualMigrationInput | undefined;\n if (opts.custom) {\n type Author =\n | ManualMigrationInput\n | ((\n parents: readonly (string | null)[]\n ) => ManualMigrationInput | Promise<ManualMigrationInput>);\n const module = await loadCliModule<{\n default?: Author;\n migration?: Author;\n }>(resolve(opts.custom));\n const author =\n (Object.hasOwn(module, \"default\") ? module.default : undefined) ??\n module.migration;\n if (!author)\n throw new Error(\n \"A custom migration module must export a default migration or author function\"\n );\n const graph = await migrations.graph();\n const parents = Object.freeze(\n from === undefined\n ? graph.leaves.length === 0\n ? [null]\n : [...graph.leaves]\n : [from]\n );\n manualMigration =\n typeof author === \"function\" ? await author(parents) : author;\n }\n const approve = generateResolver(config, opts);\n const result = await migrations.generate({\n name: opts.name,\n from,\n dryRun: opts.dryRun,\n ...(opts.lowLock ? { lowLock: true } : {}),\n ...(approve ? { resolve: approve } : {}),\n ...(manualMigration ? { manualMigration } : {}),\n });\n if (opts.json) printJson(result, true);\n else {\n process.stdout.write(\n `${result.outcome}: ${result.name ?? \"No schema changes\"}${result.stateId ? ` (${result.stateId})` : \"\"}\\n`\n );\n for (const parent of result.operationsByParent ?? []) {\n process.stdout.write(\n `Parent ${parent.fromState ?? \"empty\"}:\\n${parent.operations.map(formatOperation).join(\"\\n\")}\\n`\n );\n }\n for (const warning of result.warnings ?? [])\n process.stderr.write(`warning: ${warning}\\n`);\n if (result.reviewSql || result.sql)\n process.stdout.write(`${result.reviewSql || result.sql}\\n`);\n }\n if (opts.review && result.reviewSql)\n await writeFile(resolve(opts.review), result.reviewSql, \"utf8\");\n });\n }\n );\n\n migrate\n .command(\"check\")\n .description(\"Validate estate artifacts without touching the database\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const result = await migrations.check();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n });\n });\n\n migrate\n .command(\"list\")\n .description(\"List estate states\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.list(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"show\")\n .description(\"Show one estate state\")\n .argument(\"<state>\", \"State id, unambiguous prefix, or name\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--sql\", \"Print labelled forward/check/rollback review SQL\")\n .option(\"--review <path>\", \"Write review SQL to this file\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (\n state: string,\n opts: { dir?: string; sql?: boolean; review?: string; json?: boolean }\n ) => {\n await withMigrations(\n migrate,\n opts,\n async (migrations, _config, storage) => {\n const details = await migrations.show(selector(state)!);\n if (!(opts.sql || opts.review)) {\n printJson(details, Boolean(opts.json));\n return;\n }\n const graph = await loadMigrationGraph(storage);\n const manifest = graph.states.get(details.stateId);\n const blob = manifest && graph.sql.get(manifest.sqlHash);\n if (!(manifest && blob))\n throw new Error(\"The authenticated state SQL is unavailable\");\n const reviewSql = renderMigrationReview(\n manifest.parents,\n manifest.destinationChecks,\n blob\n );\n if (opts.json) printJson({ ...details, reviewSql }, true);\n else {\n printJson(details, false);\n process.stdout.write(reviewSql);\n }\n if (opts.review)\n await writeFile(resolve(opts.review), reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"graph\")\n .description(\"Print estate roots and leaves\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.graph(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"status\")\n .description(\"Show marker, pending path, and unfinished attempts\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.status(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"verify\")\n .description(\"Lock and compare the live schema to the marker\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const result = await migrations.verify();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n });\n });\n\n migrate\n .command(\"log\")\n .description(\"Print the append-only ledger\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--limit <n>\", \"Maximum events\", positiveInteger)\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; limit?: number; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const events = await migrations.log();\n printJson(\n opts.limit ? events.slice(-opts.limit) : events,\n Boolean(opts.json)\n );\n });\n });\n\n migrate\n .command(\"apply\")\n .description(\"Apply estate states to the target\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state id, prefix, or name\")\n .option(\"--via <stateId...>\", \"Force a path through these states\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.apply({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"down\")\n .description(\"Roll back along the recorded arrival path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Roll back to this state\")\n .option(\"--steps <n>\", \"Number of states to roll back\", positiveInteger)\n .option(\n \"--accept-data-loss\",\n \"Approve destructive changes the rollback makes to populated tables\"\n )\n .option(\n \"--expect-revision <n>\",\n \"Refuse unless the marker is at this revision\",\n positiveInteger\n )\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n steps?: number;\n acceptDataLoss?: boolean;\n expectRevision?: number;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations, config) => {\n if (opts.to !== undefined && opts.steps !== undefined)\n throw new Error(\"down accepts --to or --steps, not both\");\n const approve = generateResolver(config, opts);\n const common = {\n dryRun: opts.dryRun,\n ...(approve ? { resolve: approve } : {}),\n ...(opts.expectRevision === undefined\n ? {}\n : { expectRevision: opts.expectRevision }),\n };\n const result = await migrations.down(\n opts.to\n ? { to: selector(opts.to)!, ...common }\n : { steps: opts.steps, ...common }\n );\n if (!result.preview || opts.json) {\n printJson(result, Boolean(opts.json));\n } else {\n for (const edge of result.edges) process.stdout.write(edge.sql);\n if (result.refusal) {\n process.stderr.write(\n `down would refuse: ${result.refusal.code}: ${result.refusal.message}\\n`\n );\n }\n }\n // The preview fails where `down` would fail.\n if (result.preview && result.refusal) process.exitCode = 1;\n });\n }\n );\n\n migrate\n .command(\"baseline\")\n .description(\"Adopt an existing database as a known estate state\")\n .requiredOption(\"--to <selector>\", \"Existing estate state to adopt\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.baseline({\n to: selector(opts.to)!,\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"reanchor\")\n .description(\n \"After a restore left the history older than the database, move the marker to the state the live schema matches\"\n )\n .option(\"--to <selector>\", \"Adopt this state as the new baseline\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to?: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.reanchor({\n to: selector(opts.to),\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"resolve\")\n .description(\"Resolve an unfinished attempt after live proof\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--complete\", \"Mark complete when destination proof holds\")\n .option(\"--rolled-back\", \"Mark rolled back when origin proof holds\")\n .option(\"--retry\", \"Retry from the first proven incomplete step\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n complete?: boolean;\n rolledBack?: boolean;\n retry?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n if (\n [opts.complete, opts.rolledBack, opts.retry].filter(Boolean)\n .length !== 1\n )\n throw new Error(\n \"resolve requires exactly one of --complete, --rolled-back, or --retry\"\n );\n const outcome = opts.complete\n ? \"complete\"\n : opts.rolledBack\n ? \"rolled-back\"\n : \"retry\";\n printJson(await migrations.resolve({ outcome }), Boolean(opts.json));\n });\n }\n );\n\n migrate\n .command(\"reset\")\n .description(\n \"Clear managed objects and replay from empty to a selected state\"\n )\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state after rebuild\")\n .option(\"--via <stateId...>\", \"Force a rebuild path\")\n .option(\"--confirm\", \"Confirm destructive reset (not required for dry-run)\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n confirm?: boolean;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n if (!(opts.dryRun || opts.confirm))\n throw new Error(\n \"Reset requires --confirm; inspect --dry-run first\"\n );\n printJson(\n await migrations.reset({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n return migrate;\n}\n\nexport const migrateCommand = createMigrateCommand();\n","/**\n * History-free, authenticated schema push CLI.\n *\n * The preview is inert. Effectful execution receives only the consent emitted\n * by that preview; no generic force authorization reaches the apply call.\n */\n\nimport { cancel, confirm, isCancel, note, outro } from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { createMigrationClient } from \"../../migrations/client\";\nimport type { PushPreview } from \"../../migrations/push-v1\";\nimport { printJson, runCli } from \"../utils\";\n\ninterface PushCliOptions {\n readonly config?: string;\n readonly dryRun?: boolean;\n readonly forceReset?: boolean;\n readonly yes?: boolean;\n readonly acceptDataLoss?: boolean;\n readonly json?: boolean;\n}\n\nfunction printPlan(preview: PushPreview): void {\n const operations =\n preview.operations.length === 0\n ? [\"No schema changes.\"]\n : preview.operations.map(\n (operation) =>\n `[${operation.risk}] ${operation.label} (${operation.id})`\n );\n const statements = preview.statements.map(\n (statement, index) =>\n `${index + 1}. ${statement.sql}${\n statement.parameters.length === 0\n ? \"\"\n : `\\n parameters: ${JSON.stringify(statement.parameters)}`\n }`\n );\n const lines = [\n `Target: ${JSON.stringify(preview.target)}`,\n `Plan: ${preview.planHash}`,\n ...operations,\n ...(statements.length === 0 ? [] : [\"\", \"SQL:\", ...statements]),\n ];\n note(lines.join(\"\\n\"), \"Push plan\");\n}\n\nasync function runPush(options: PushCliOptions): Promise<void> {\n await runCli({ config: options.config }, options.json, async (config) => {\n const migrations =\n config.migrations?.tables === undefined\n ? createMigrationClient(config.client)\n : createMigrationClient(config.client, {\n tables: config.migrations.tables,\n });\n // `force` is confined to the inert planning arm. The authenticated apply\n // arm below receives only the consent bound to this exact preview.\n const preview = await migrations.push({\n dryRun: true,\n ...(options.forceReset === true ? { forceReset: true } : {}),\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n });\n\n if (\n !options.json &&\n config.driver?.dialect === \"sqlite\" &&\n [\"sqlite3\", \"bun-sqlite\", \"bun-sql\"].includes(config.driver.driverName)\n ) {\n const databases = await config.driver._executeRaw<{\n name: string;\n file: string;\n }>(\"PRAGMA database_list\");\n if (\n databases.rows.some(\n (database) => database.name === \"main\" && database.file === \"\"\n )\n )\n process.stderr.write(\n \"warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.\\n\"\n );\n }\n\n if (options.dryRun) {\n if (options.json) printJson(preview, true);\n else printPlan(preview);\n return;\n }\n\n if (!options.json) printPlan(preview);\n\n if (\n preview.destructive &&\n !options.acceptDataLoss &&\n (options.yes || options.json || !process.stdin.isTTY)\n ) {\n throw new Error(\n \"Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.\"\n );\n }\n if (\n preview.outcome !== \"noop\" &&\n !options.yes &&\n !options.acceptDataLoss &&\n !options.json &&\n process.stdin.isTTY\n ) {\n const accepted = await confirm({\n message: preview.destructive\n ? \"Apply this destructive push plan?\"\n : \"Apply this push plan?\",\n initialValue: !preview.destructive,\n });\n if (isCancel(accepted) || !accepted) {\n cancel(\"Push cancelled.\");\n return;\n }\n }\n\n const result = await migrations.push({ consent: preview.consent });\n if (options.json) printJson(result, true);\n else\n outro(\n result.outcome === \"noop\" ? \"Schema is up to date.\" : \"Push applied.\"\n );\n });\n}\n\nexport function createPushCommand(): Command {\n return new Command(\"push\")\n .description(\"Synchronize the schema directly without migration history\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--dry-run\", \"Preview without changing the database\")\n .option(\"--force-reset\", \"Plan a rebuild from an empty database\")\n .option(\"-y, --yes\", \"Skip prompts for non-destructive plans\")\n .option(\n \"--accept-data-loss\",\n \"Explicitly accept the previewed destructive plan\"\n )\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runPush);\n}\n\nexport const pushCommand = createPushCommand();\n","#!/usr/bin/env node\n/**\n * VibORM CLI\n *\n * Command-line interface for VibORM database operations.\n */\n\nimport { Command } from \"commander\";\nimport { registerEveryMigrationDriver } from \"../migrations/dialects/every\";\nimport { VIBORM_VERSION } from \"../version\";\nimport { checkCommand } from \"./commands/check\";\nimport { migrateCommand } from \"./commands/migrate\";\nimport { pushCommand } from \"./commands/push\";\n\nregisterEveryMigrationDriver();\n\nconst program = new Command();\n\nprogram\n .name(\"viborm\")\n .description(\"VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite\")\n .version(VIBORM_VERSION);\n\n// Register commands\nprogram.addCommand(checkCommand);\nprogram.addCommand(pushCommand);\nprogram.addCommand(migrateCommand);\n\n// Parse arguments\ntry {\n await program.parseAsync();\n} catch (error: unknown) {\n process.stderr.write(\n `${error instanceof Error ? error.message : \"CLI failed\"}\\n`\n );\n process.exitCode = 1;\n}\n"],"mappings":";opBAyBA,MAAM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