viborm 1.2.3 → 1.3.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/README.md +6 -1
- package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
- package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
- package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
- package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
- package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
- package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
- package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
- package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
- package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
- package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
- package/dist/builder-Df24l2Bd.mjs +2 -0
- package/dist/builder-Df24l2Bd.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
- package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
- package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
- package/dist/chain-C7c1YTXD.mjs +2 -0
- package/dist/chain-C7c1YTXD.mjs.map +1 -0
- package/dist/cli.mjs +2 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-GoDZgqdq.d.mts → client-70MrTq1E.d.mts} +3 -3
- package/dist/client-DM1UHfYG.mjs +49 -0
- package/dist/client-DM1UHfYG.mjs.map +1 -0
- package/dist/client-_WKrPNmm.mjs +2 -0
- package/dist/client-_WKrPNmm.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +1 -1
- package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
- package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/controls-Da-efekX.mjs +2 -0
- package/dist/controls-Da-efekX.mjs.map +1 -0
- package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
- package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
- package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
- package/dist/driver-B9fIori_.mjs +2 -0
- package/dist/driver-B9fIori_.mjs.map +1 -0
- package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
- package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-C9WgitPi.mjs +2 -0
- package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
- package/dist/every-1pKZteeB.mjs +2 -0
- package/dist/{every-DCY4HV0X.mjs.map → every-1pKZteeB.mjs.map} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
- package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
- package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
- package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
- package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
- package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
- package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
- package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
- package/dist/hydration-DsyHNSDS.mjs +2 -0
- package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
- package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
- package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
- package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
- package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
- package/dist/{index-BaK35ze2.d.mts → index-VsM29vYN.d.mts} +5269 -4918
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
- package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
- package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
- package/dist/key-D_kagnFv.mjs +2 -0
- package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
- package/dist/{libsql-x0RPVRDS.mjs → libsql-DFAoHXrI.mjs} +3 -3
- package/dist/{libsql-x0RPVRDS.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-gv5jLGYm.mjs → memory-GTWgeDNY.mjs} +2 -2
- package/dist/{memory-gv5jLGYm.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +5 -5
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +5 -5
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +5 -5
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.d.mts +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.d.mts +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
- package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-C6c5govr.mjs +2 -0
- package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
- package/dist/{mysql-B5cqxG99.mjs → mysql-xChEivOe.mjs} +6 -6
- package/dist/{mysql-B5cqxG99.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
- package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
- package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
- package/dist/{object-store-Cj8Cnnba.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
- package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
- package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
- package/dist/permissions.d.mts +424 -0
- package/dist/permissions.mjs +2 -0
- package/dist/permissions.mjs.map +1 -0
- package/dist/pg.d.mts +9 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
- package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
- package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
- package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-DH-K2gSq.d.mts → planner-C1NzLBge.d.mts} +1 -1
- package/dist/{postgres-DrXDok0O.mjs → postgres-BqAxDWTQ.mjs} +4 -4
- package/dist/{postgres-DrXDok0O.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
- package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
- package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
- package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
- package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
- package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
- package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
- package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
- package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
- package/dist/result-shape-CDgX_vzn.mjs +2 -0
- package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
- package/dist/scalar-S8yMvdmx.mjs +4 -0
- package/dist/scalar-S8yMvdmx.mjs.map +1 -0
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-9N9jQlVL.mjs +2 -0
- package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
- package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
- package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
- package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
- package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
- package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +27 -96
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-Bhxq9arK.mjs +2 -0
- package/dist/sql-Bhxq9arK.mjs.map +1 -0
- package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
- package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
- package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
- package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +3 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
- package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
- package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
- package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
- package/dist/to-many-C1PuFIpf.mjs +2 -0
- package/dist/to-many-C1PuFIpf.mjs.map +1 -0
- package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
- package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
- package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
- package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
- package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
- package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
- package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
- package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
- package/dist/v-CYTUI0H5.mjs +2 -0
- package/dist/v-CYTUI0H5.mjs.map +1 -0
- package/dist/validation-BQtO6srU.mjs +2 -0
- package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
- package/dist/validation-BamBwne9.mjs +2 -0
- package/dist/validation-BamBwne9.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DgffZq9C.mjs +2 -0
- package/dist/validator-DgffZq9C.mjs.map +1 -0
- package/dist/version-CXuJzC-q.mjs +2 -0
- package/dist/{version-Bemp-64P.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
- package/package.json +35 -9
- package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs +0 -2
- package/dist/builder-Ycvq3ETg.mjs.map +0 -1
- package/dist/chain-Dh0FV72b.mjs +0 -2
- package/dist/chain-Dh0FV72b.mjs.map +0 -1
- package/dist/client-B1p6Le_h.mjs +0 -49
- package/dist/client-B1p6Le_h.mjs.map +0 -1
- package/dist/client-BLiBmykn.mjs +0 -2
- package/dist/client-BLiBmykn.mjs.map +0 -1
- package/dist/controls-DXgIn4zh.mjs +0 -2
- package/dist/controls-DXgIn4zh.mjs.map +0 -1
- package/dist/driver-BlnKXPFF.mjs +0 -2
- package/dist/driver-BlnKXPFF.mjs.map +0 -1
- package/dist/error-mapping-CnPCv1dm.mjs +0 -2
- package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
- package/dist/every-DCY4HV0X.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
- package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
- package/dist/hydration-CAxOL4aI.mjs +0 -2
- package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs +0 -2
- package/dist/identifier-hQCs8M1n.mjs.map +0 -1
- package/dist/key-BeoOwGr3.mjs +0 -2
- package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
- package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
- package/dist/registration-preflight-DEjv050M.mjs +0 -4
- package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
- package/dist/result-shape-CTNdNSW3.mjs +0 -2
- package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
- package/dist/scalar-U0wD5bKy.mjs +0 -2
- package/dist/scalar-U0wD5bKy.mjs.map +0 -1
- package/dist/schema-Cjem1-0f.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs +0 -2
- package/dist/sql-Bp7jicEX.mjs.map +0 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
- package/dist/terminal-C8cq1WWX.mjs +0 -2
- package/dist/terminal-C8cq1WWX.mjs.map +0 -1
- package/dist/v-D5Z06FKN.mjs +0 -2
- package/dist/v-D5Z06FKN.mjs.map +0 -1
- package/dist/validation-Dk9Q_-C7.mjs +0 -2
- package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
- package/dist/validation-PF9-_nKd.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs +0 -2
- package/dist/validator-X9-bwtRo.mjs.map +0 -1
- package/dist/version-Bemp-64P.mjs +0 -2
- /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-
|
|
1
|
+
{"version":3,"file":"hydration-DsyHNSDS.mjs","names":[],"sources":["../src/schema/hydration.ts"],"sourcesContent":["/**\n * Schema Hydration\n *\n * Hydrates schema name slots (tsName, sqlName) for models and scalars.\n * This is called once at client initialization when the full schema context is available.\n *\n * - tsName: The TypeScript key name in the schema (e.g., \"email\", \"User\")\n * - sqlName: The resolved database name (e.g., \"email_column\", \"users\")\n *\n * Names are stored in the model's nameRegistry, not on the scalar instances.\n * This allows the same scalar to be reused across multiple models with different keys.\n */\n\nimport { isValidSchemaIdentifier } from \"./identifier\";\nimport type { Model, NameRegistry } from \"./model\";\nimport { preflightModelRegistrationIdentity } from \"./registration-preflight\";\nimport type { Scalar } from \"./scalars/base\";\nimport type { SchemaNames } from \"./scalars/common\";\nimport { SchemaValidationError } from \"./validation/error\";\n\n/**\n * Schema type - record of model names to Model instances\n */\nexport type Schema = Record<string, Model<any>>;\n\n/**\n * Hydrate name slots for all models and scalars in a schema.\n *\n * This function populates the model's nameRegistry:\n * - model[\"~\"].names.ts = schema key (e.g., \"User\")\n * - model[\"~\"].names.sql = tableName ?? schema key (e.g., \"users\")\n * - model[\"~\"].nameRegistry.fields.get(fieldKey) = {ts, sql}\n *\n * Operation schemas are registry-owned; hydration only binds reusable schema\n * definitions to model-local names and relation sources.\n *\n * @param schema - The schema object mapping model names to Model instances\n */\nexport function hydrateSchemaNames(schema: Schema, checked = false): void {\n const registrations = Object.entries(schema);\n // A schema `viborm check` validated binds its names without re-proving them.\n if (checked) {\n for (const [modelKey, model] of registrations)\n bindModelNames(modelKey, model);\n return;\n }\n // TWO ordered phases. The preflight proves every model's identity and name\n // stability BEFORE a single registry write, so a schema that fails validation\n // never leaves models 0..N-1 bound while model N is refused.\n const identityIssue = preflightModelRegistrationIdentity(registrations);\n if (identityIssue) throw new SchemaValidationError([identityIssue]);\n for (const [modelKey, model] of registrations) {\n preflightModelIdentifiers(modelKey, model);\n }\n for (const [modelKey, model] of registrations) {\n bindModelNames(modelKey, model);\n }\n}\n\n/**\n * Prove one model's identity: its identifiers are legal, and its schema key is\n * the one this model object is already bound to.\n *\n * A model object binds ONE schema key for its lifetime. Re-registering the same\n * object under the same key is idempotent — the same schema composed twice, or\n * a second client over the same models, is a normal thing to do — while a second\n * key is refused, because every derived name, junction table, index and\n * constraint in the estate is generated from the schema key and two keys would\n * make one model object mean two different tables.\n */\nfunction preflightModelIdentifiers(modelKey: string, model: Model<any>): void {\n const state = model[\"~\"].state;\n\n assertValidIdentifier(\"Model\", modelKey);\n if (state.tableName !== undefined) {\n assertValidIdentifier(\"Mapped table\", state.tableName, modelKey);\n }\n for (const fieldKey of Object.keys(state.shape)) {\n assertValidIdentifier(\"Field\", fieldKey, modelKey);\n }\n for (const scalar of Object.values(state.scalars as Record<string, Scalar>)) {\n if (scalar[\"~\"].state.columnName !== undefined) {\n assertValidIdentifier(\n \"Mapped column\",\n scalar[\"~\"].state.columnName,\n modelKey\n );\n }\n }\n}\n\n/**\n * Bind one model's names and its scalar name registry.\n *\n * A relation has no name entry — its key is its only name, with no column to\n * map — and no relation is given a source model: `.extends()` may reuse one\n * relation object under more than one model or key, so a contextual operation\n * carries its own slot identity instead.\n */\nfunction bindModelNames(modelKey: string, model: Model<any>): void {\n const names = model[\"~\"].names as SchemaNames;\n const state = model[\"~\"].state;\n const registry = model[\"~\"].nameRegistry as NameRegistry;\n\n names.ts = modelKey;\n names.sql = state.tableName ?? modelKey;\n\n for (const [fieldKey, scalar] of Object.entries(\n state.scalars as Record<string, Scalar>\n )) {\n const fieldNames: SchemaNames = {\n ts: fieldKey,\n sql: scalar[\"~\"].state.columnName ?? fieldKey,\n };\n registry.fields.set(fieldKey, fieldNames);\n }\n\n // Operation schemas are built by SchemaRegistry, not during name hydration.\n}\n\nfunction assertValidIdentifier(\n kind: \"Field\" | \"Mapped column\" | \"Mapped table\" | \"Model\",\n identifier: unknown,\n modelName?: string\n): void {\n if (isValidSchemaIdentifier(identifier)) return;\n const location = modelName ? ` in '${modelName}'` : \"\";\n const renderedIdentifier = String(identifier);\n throw new Error(\n `${kind} '${renderedIdentifier}'${location} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`\n );\n}\n\n/**\n * Check if a schema has been hydrated\n */\nexport function isSchemaHydrated(schema: Schema): boolean {\n const firstModel = Object.values(schema)[0];\n if (!firstModel) {\n return true;\n } // Empty schema is considered hydrated\n return firstModel[\"~\"].names.ts !== undefined;\n}\n\n/**\n * Get the SQL name for a model (throws if not hydrated)\n */\nexport function getModelSqlName(model: Model<any>): string {\n const sqlName = model[\"~\"].names.sql;\n if (!sqlName) {\n throw new Error(\n \"Schema not hydrated. Call hydrateSchemaNames() or create a client first.\"\n );\n }\n return sqlName;\n}\n\n/**\n * Get the SQL name for a scalar field key.\n * Delegates to model[\"~\"].getFieldName().\n */\nexport function getFieldSqlName(model: Model<any>, fieldKey: string): string {\n return model[\"~\"].getFieldName(fieldKey).sql;\n}\n"],"mappings":"8IAsCA,SAAgB,mBAAmB,EAAgB,EAAU,GAAa,CACxE,IAAM,EAAgB,OAAO,QAAQ,EAAO,CAE5C,GAAI,EAAS,CACX,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CACjC,OAKF,IAAM,EAAgB,EAAmC,EAAc,CACvE,GAAI,EAAe,MAAM,IAAI,EAAsB,CAAC,EAAc,CAAC,CACnE,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,0BAA0B,EAAU,EAAM,CAE5C,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CAenC,SAAS,0BAA0B,EAAkB,EAAyB,CAC5E,IAAM,EAAQ,EAAM,KAAK,MAEzB,sBAAsB,QAAS,EAAS,CACpC,EAAM,YAAc,IAAA,IACtB,sBAAsB,eAAgB,EAAM,UAAW,EAAS,CAElE,IAAK,IAAM,KAAY,OAAO,KAAK,EAAM,MAAM,CAC7C,sBAAsB,QAAS,EAAU,EAAS,CAEpD,IAAK,IAAM,KAAU,OAAO,OAAO,EAAM,QAAkC,CACrE,EAAO,KAAK,MAAM,aAAe,IAAA,IACnC,sBACE,gBACA,EAAO,KAAK,MAAM,WAClB,EACD,CAaP,SAAS,eAAe,EAAkB,EAAyB,CACjE,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAQ,EAAM,KAAK,MACnB,EAAW,EAAM,KAAK,aAE5B,EAAM,GAAK,EACX,EAAM,IAAM,EAAM,WAAa,EAE/B,IAAK,GAAM,CAAC,EAAU,KAAW,OAAO,QACtC,EAAM,QACP,CAAE,CACD,IAAM,EAA0B,CAC9B,GAAI,EACJ,IAAK,EAAO,KAAK,MAAM,YAAc,EACtC,CACD,EAAS,OAAO,IAAI,EAAU,EAAW,EAM7C,SAAS,sBACP,EACA,EACA,EACM,CACN,GAAI,EAAwB,EAAW,CAAE,OACzC,IAAM,EAAW,EAAY,QAAQ,EAAU,GAAK,GAC9C,EAAqB,OAAO,EAAW,CAC7C,MAAU,MACR,GAAG,EAAK,IAAI,EAAmB,GAAG,EAAS,4HAC5C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{ct as r,dt as i}from"./geo-point-codec-DyEHMdJg.mjs";import{o as a}from"./sql-Bhxq9arK.mjs";import{f as o,p as s}from"./scalar-S8yMvdmx.mjs";import{t as c}from"./hydration-DsyHNSDS.mjs";import{l,m as u,n as d,u as f}from"./validator-DgffZq9C.mjs";import{N as p}from"./standard-sql-CoGqv-iX.mjs";function mapReferentialAction(e){switch(e.toUpperCase()){case`CASCADE`:return`cascade`;case`SET NULL`:return`setNull`;case`RESTRICT`:return`restrict`;case`SET DEFAULT`:return`setDefault`;default:return`noAction`}}function groupBy(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function groupByNested(e,t,n){let r=new Map;for(let i of e){let e=t(i),a=n(i),o=r.get(e);o||(o=new Map,r.set(e,o));let s=o.get(a);s?s.push(i):o.set(a,[i])}return r}const m=`[0-9a-fA-F]`,h=`[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]`,g=`[0-9A-Za-z]`,_={uuid:{length:36,regex:`^${m}{8}-${m}{4}-${m}{4}-${m}{4}-${m}{12}$`,glob:`${m.repeat(8)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(12)}`,fold:`lower`,max:void 0},ulid:{length:26,regex:`^[0-7]${h}{25}$`,glob:`[0-7]${h.repeat(25)}`,fold:`upper`,max:void 0},ksuid:{length:27,regex:`^${g}{27}$`,glob:g.repeat(27),fold:void 0,max:i}};function patternOf(e){return e.format===`ulid`?_.ulid:e.format===`ksuid`?_.ksuid:_.uuid}const int=e=>a.raw(String(e));function fromSql(e,t,n,r){let i=p(t===`mysql`?"`":`"`),o=t===`postgresql`&&n?`${i(n)}.`:``;return a.raw(`${o+i(s(e))} AS ${r}`)}function columnSql(e,t,n,r){let i=p(n===`mysql`?"`":`"`);return a.raw(`${r}.${i(o(e,t))}`)}function payloadSql(e,t){let n=t.prefix;return n?a`substr(${e}, ${int(n.length+2)})`:e}function bytesSql(e,t){return t===`mysql`?a`CAST(${e} AS BINARY)`:e}function orderedSql(e,t){return t===`postgresql`?a`CAST(${e} AS text) COLLATE "C"`:bytesSql(e,t)}function admitsSql(e,t,n){let r=patternOf(t),i=payloadSql(e,t),o=n===`postgresql`?a`${i} ~ ${r.regex}`:n===`mysql`?a`${i} REGEXP ${r.regex}`:a`${i} GLOB ${r.glob}`,s=a`${a.raw(n===`mysql`?`CHAR_LENGTH`:`length`)}(${i}) = ${int(r.length)} AND ${o}`,c=r.max===void 0?s:a`${s} AND ${orderedSql(i,n)} <= ${r.max}`,l=t.prefix;return l?a`${bytesSql(a`substr(${e}, 1, ${int(l.length+1)})`,n)} = ${`${l}-`} AND ${c}`:c}function foldSql(e,t,n){let r=patternOf(t).fold,i=payloadSql(e,t);return bytesSql(r===void 0?i:a`${a.raw(r)}(${i})`,n)}function foldCollisionCheck(e,t,n,r){return{kind:`trusted-read`,query:a`SELECT COUNT(${t}) = COUNT(DISTINCT ${foldSql(t,n,r)}) AS ok FROM ${e}`,equals:!0}}function isSingleColumnKey(e,t){return u(e).referenceableKeys.some(e=>e.length===1&&e[0]===t)}const noRowWhere=(e,t)=>({kind:`trusted-read`,query:a`SELECT NOT EXISTS (SELECT 1 FROM ${e} WHERE ${t}) AS ok`,equals:!0});function referencingColumns(e,t){let n=[];for(let r of l(t))if(r.kind===`foreignKey`&&(r.endpoints[0]===r.owner?r.endpoints[1]:r.endpoints[0]).source===e.model)for(let t of r.reference.members)t.referencedField===e.field&&n.push({model:r.owner.source,field:t.foreignField});return n}function identifierConversionChecks(e){let{model:i,field:l,dialect:u,namespace:p}=e;c(e.schema);let m=d(e.schema),h=f(i,l,m);if(h===void 0||!r(h.format))throw new n(`'${s(i)}.${o(i,l)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,t.INVALID_INPUT);let g=fromSql(i,u,p,`p`),_=columnSql(i,l,u,`p`),v=[noRowWhere(g,a`${_} IS NOT NULL AND NOT (${admitsSql(_,h,u)})`)],y=patternOf(h).fold!==void 0;y&&v.push(foldCollisionCheck(g,_,h,u));for(let t of referencingColumns(e,m)){let e=fromSql(t.model,u,p,`c`),n=columnSql(t.model,t.field,u,`c`);v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT (${admitsSql(n,h,u)})`)),y&&isSingleColumnKey(t.model,t.field)&&v.push(foldCollisionCheck(e,n,h,u)),v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${g} WHERE ${foldSql(_,h,u)} = ${foldSql(n,h,u)})`))}return v}const v=/^(?:text|citext|varchar\(\d+\)|character varying.*)$/i,literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function postgresTextToUuidGuard(e,t){let n=`${e}.${t}`;return`DO \$viborm\$ DECLARE invalid bigint; BEGIN SELECT count(*) INTO invalid FROM ${e} WHERE ${t} IS NOT NULL AND ${t} !~ ${literal(_.uuid.regex)}; IF invalid > 0 THEN RAISE EXCEPTION ${literal(`VibORM: % row(s) of ${n} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; END IF; END \$viborm\$`}function isPostgresTextToUuid(e,t){return t.toLowerCase()===`uuid`&&v.test(e.trim())}export{groupByNested as a,groupBy as i,isPostgresTextToUuid as n,mapReferentialAction as o,postgresTextToUuidGuard as r,identifierConversionChecks as t};
|
|
2
|
+
//# sourceMappingURL=identifier-conversion-DaZ9yNpv.mjs.map
|
package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identifier-conversion-GgbwHc2G.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"6bASA,SAAgB,qBAAqB,EAAiC,CACpE,OAAQ,EAAK,a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GAAyB,IAAI,EAAK,WAAW,IAAK,KAAK,CAAC,GAsBzE,SAAgB,wBACd,EACA,EACQ,CACR,IAAM,EAAS,GAAG,EAAe,GAAG,IACpC,MACE,iFACqC,EAAe,SAAS,EAAa,mBAAmB,EAAa,MAAM,QAAQ,EAAS,KAAK,MAAM,CAAC,wCAE1I,QAAQ,uBAAuB,EAAO,0aAA0a,CAAC,mCAMxd,SAAgB,qBACd,EACA,EACS,CACT,OACE,EAAO,aAAa,GAAK,QAAU,EAAe,KAAK,EAAS,MAAM,CAAC"}
|
|
1
|
+
{"version":3,"file":"identifier-conversion-DaZ9yNpv.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"6aASA,SAAgB,qBAAqB,EAAiC,CACpE,OAAQ,EAAK,aAAa,CAA1B,CACE,IAAK,UACH,MAAO,UACT,IAAK,WACH,MAAO,UACT,IAAK,WACH,MAAO,WACT,IAAK,cACH,MAAO,aACT,QACE,MAAO,YAWb,SAAgB,QACd,EACA,EACkB,CAClB,IAAM,EAAM,IAAI,IAChB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAM,EAAK,CACjB,EAAW,EAAI,IAAI,EAAI,CACzB,EACF,EAAS,KAAK,EAAK,CAEnB,EAAI,IAAI,EAAK,CAAC,EAAK,CAAC,CAGxB,OAAO,EAWT,SAAgB,cACd,EACA,EACA,EAC+B,CAC/B,IAAM,EAAM,IAAI,IAChB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAK,EAAa,EAAK,CACvB,EAAK,EAAe,EAAK,CAE3B,EAAY,EAAI,IAAI,EAAG,CACtB,IACH,EAAY,IAAI,IAChB,EAAI,IAAI,EAAI,EAAU,EAGxB,IAAM,EAAW,EAAU,IAAI,EAAG,CAC9B,EACF,EAAS,KAAK,E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B,EAAQ,EAAK,EAAQ,EAAQ,CAAC,CAE/D,IAAK,IAAM,KAAa,mBAAmB,EAAS,EAAM,CAAE,CAC1D,IAAM,EAAQ,QAAQ,EAAU,MAAO,EAAS,EAAW,IAAI,CACzD,EAAK,UAAU,EAAU,MAAO,EAAU,MAAO,EAAS,IAAI,CACpE,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,wBAAwB,UAAU,EAAI,EAAQ,EAAQ,CAAC,GACjE,CACF,CACG,GAAS,kBAAkB,EAAU,MAAO,EAAU,MAAM,EAC9D,EAAO,KAAK,mBAAmB,EAAO,EAAI,EAAQ,EAAQ,CAAC,CAE7D,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,6CAA6C,EAAO,SAAS,QAAQ,EAAK,EAAQ,EAAQ,CAAC,KAAK,QAAQ,EAAI,EAAQ,EAAQ,CAAC,GACvI,CACF,CAEH,OAAO,EAQT,MAAM,EAAiB,wDAGjB,QAAW,GAAyB,IAAI,EAAK,WAAW,IAAK,KAAK,CAAC,GAsBzE,SAAgB,wBACd,EACA,EACQ,CACR,IAAM,EAAS,GAAG,EAAe,GAAG,IACpC,MACE,iFACqC,EAAe,SAAS,EAAa,mBAAmB,EAAa,MAAM,QAAQ,EAAS,KAAK,MAAM,CAAC,wCAE1I,QAAQ,uBAAuB,EAAO,0aAA0a,CAAC,mCAMxd,SAAgB,qBACd,EACA,EACS,CACT,OACE,EAAO,aAAa,GAAK,QAAU,EAAe,KAAK,EAAS,MAAM,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-
|
|
2
|
-
//# sourceMappingURL=identity-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";const r=2**32,words=e=>{let t=new DataView(new ArrayBuffer(e.length*4));for(let[n,r]of e.entries())t.setUint32(n*4,r);return t},i=words([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=new Uint8Array(words([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]).buffer),o=new Uint8Array(32),s=new DataView(o.buffer),c=new DataView(new ArrayBuffer(256)),rotate=(e,t)=>e>>>t|e<<32-t,fold=(e,t)=>{s.setInt32(e,s.getInt32(e)+t|0)};function compress(e,t){for(let n=0;n<16;n++)c.setInt32(n*4,e.getInt32(t+n*4));for(let e=16;e<64;e++){let t=c.getInt32((e-15)*4),n=c.getInt32((e-2)*4),r=rotate(t,7)^rotate(t,18)^t>>>3,i=rotate(n,17)^rotate(n,19)^n>>>10;c.setInt32(e*4,i+c.getInt32((e-7)*4)+r+c.getInt32((e-16)*4)|0)}let n=s.getInt32(0),r=s.getInt32(4),a=s.getInt32(8),o=s.getInt32(12),l=s.getInt32(16),u=s.getInt32(20),d=s.getInt32(24),f=s.getInt32(28);for(let e=0;e<64;e++){let t=rotate(l,6)^rotate(l,11)^rotate(l,25),s=l&u^~l&d,p=f+t+s+i.getInt32(e*4)+c.getInt32(e*4)|0,m=rotate(n,2)^rotate(n,13)^rotate(n,22),h=n&r^n&a^r&a;f=d,d=u,u=l,l=o+p|0,o=a,a=r,r=n,n=p+m+h|0}fold(0,n),fold(4,r),fold(8,a),fold(12,o),fold(16,l),fold(20,u),fold(24,d),fold(28,f)}function sha256(e){o.set(a);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),i=Math.floor(t/64);for(let e=0;e<i;e++)compress(n,e*64);let s=t-i*64,c=new Uint8Array(s>55?128:64);c.set(e.subarray(i*64)),c[s]=128;let l=new DataView(c.buffer),u=t*8;l.setUint32(c.length-8,Math.floor(u/r)),l.setUint32(c.length-4,u%r);for(let e=0;e<c.length;e+=64)compress(l,e);return Uint8Array.from(o)}const l=`sha256`,u={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`},d=/^[0-9a-f]{64}$/,f=new TextEncoder;function isSha256(e){return typeof e==`string`&&d.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){let t=``;for(let n of sha256(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=f.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return f.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{isSha256 as a,utf8Bytes as c,domainHash as i,u as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,l as t};
|
|
2
|
+
//# sourceMappingURL=identity-oQvIe7u8.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity-CLFhCTZx.mjs","names":[],"sources":["../src/validation/primitives/sha256.ts","../src/migrations/identity.ts"],"sourcesContent":["// biome-ignore-all lint/suspicious/noBitwiseOperators: SHA-256 is 32-bit word\n// arithmetic. Every operator below is part of FIPS 180-4's definition.\n\n/**\n * SHA-256, the hash Migration V1 identity is defined over.\n *\n * FIPS 180-4: 64-byte blocks, a 64-word message schedule, 64 rounds, a 64-bit\n * big-endian bit length after the `0x80` pad. One exported function, no\n * streaming, no options: the caller hands over the complete message and\n * receives the 32-byte digest.\n *\n * It is synchronous on purpose. WebCrypto's `digest` is the platform hash on\n * every runtime, but it returns a promise, and every content-addressed parser\n * in the migration engine hashes inline; `node:crypto` is synchronous but is\n * not on an edge runtime without a compatibility flag.\n *\n * Every word is read and written through a `DataView` that names big-endian,\n * the byte order the standard is written in, so the host's byte order never\n * enters a digest; it is also the one indexed read in this codebase that is not\n * `T | undefined`, as in the SHA3-512 precedent (`./sha3`).\n *\n * The one caller is `migrations/identity`. Nothing else in VibORM may import\n * this module without its own differential proof against a reference.\n */\n\nconst BLOCK_BYTES = 64;\nconst DIGEST_BYTES = 32;\nconst ROUNDS = 64;\n/** A tail of more than this many bytes leaves no room for the pad and length. */\nconst LAST_BLOCK_ROOM = BLOCK_BYTES - 9;\nconst WORD_SPAN = 2 ** 32;\n\nconst words = (values: readonly number[]): DataView => {\n const view = new DataView(new ArrayBuffer(values.length * 4));\n for (const [index, value] of values.entries()) {\n view.setUint32(index * 4, value);\n }\n return view;\n};\n\n/** The first 32 bits of the fractional parts of the first 64 primes' cube roots. */\nconst ROUND_CONSTANTS = words([\n 0x42_8a_2f_98, 0x71_37_44_91, 0xb5_c0_fb_cf, 0xe9_b5_db_a5, 0x39_56_c2_5b,\n 0x59_f1_11_f1, 0x92_3f_82_a4, 0xab_1c_5e_d5, 0xd8_07_aa_98, 0x12_83_5b_01,\n 0x24_31_85_be, 0x55_0c_7d_c3, 0x72_be_5d_74, 0x80_de_b1_fe, 0x9b_dc_06_a7,\n 0xc1_9b_f1_74, 0xe4_9b_69_c1, 0xef_be_47_86, 0x0f_c1_9d_c6, 0x24_0c_a1_cc,\n 0x2d_e9_2c_6f, 0x4a_74_84_aa, 0x5c_b0_a9_dc, 0x76_f9_88_da, 0x98_3e_51_52,\n 0xa8_31_c6_6d, 0xb0_03_27_c8, 0xbf_59_7f_c7, 0xc6_e0_0b_f3, 0xd5_a7_91_47,\n 0x06_ca_63_51, 0x14_29_29_67, 0x27_b7_0a_85, 0x2e_1b_21_38, 0x4d_2c_6d_fc,\n 0x53_38_0d_13, 0x65_0a_73_54, 0x76_6a_0a_bb, 0x81_c2_c9_2e, 0x92_72_2c_85,\n 0xa2_bf_e8_a1, 0xa8_1a_66_4b, 0xc2_4b_8b_70, 0xc7_6c_51_a3, 0xd1_92_e8_19,\n 0xd6_99_06_24, 0xf4_0e_35_85, 0x10_6a_a0_70, 0x19_a4_c1_16, 0x1e_37_6c_08,\n 0x27_48_77_4c, 0x34_b0_bc_b5, 0x39_1c_0c_b3, 0x4e_d8_aa_4a, 0x5b_9c_ca_4f,\n 0x68_2e_6f_f3, 0x74_8f_82_ee, 0x78_a5_63_6f, 0x84_c8_78_14, 0x8c_c7_02_08,\n 0x90_be_ff_fa, 0xa4_50_6c_eb, 0xbe_f9_a3_f7, 0xc6_71_78_f2,\n]);\n\n/** The first 32 bits of the fractional parts of the first 8 primes' square roots. */\nconst INITIAL_HASH = new Uint8Array(\n words([\n 0x6a_09_e6_67, 0xbb_67_ae_85, 0x3c_6e_f3_72, 0xa5_4f_f5_3a, 0x51_0e_52_7f,\n 0x9b_05_68_8c, 0x1f_83_d9_ab, 0x5b_e0_cd_19,\n ]).buffer\n);\n\n/**\n * The running hash and the message schedule, allocated once: `sha256` is\n * synchronous from entry to return, and every entry begins by resetting the\n * hash to its initial value.\n */\nconst hashBytes = new Uint8Array(DIGEST_BYTES);\nconst hash = new DataView(hashBytes.buffer);\nconst schedule = new DataView(new ArrayBuffer(ROUNDS * 4));\n\nconst rotate = (word: number, bits: number): number =>\n (word >>> bits) | (word << (32 - bits));\n\n/** Folds one working variable back into the running hash. */\nconst fold = (at: number, word: number): void => {\n hash.setInt32(at, (hash.getInt32(at) + word) | 0);\n};\n\n/** The compression function over the 64 bytes of `block` at `offset`. */\nfunction compress(block: DataView, offset: number): void {\n for (let t = 0; t < 16; t++) {\n schedule.setInt32(t * 4, block.getInt32(offset + t * 4));\n }\n for (let t = 16; t < ROUNDS; t++) {\n const early = schedule.getInt32((t - 15) * 4);\n const late = schedule.getInt32((t - 2) * 4);\n const sigma0 = rotate(early, 7) ^ rotate(early, 18) ^ (early >>> 3);\n const sigma1 = rotate(late, 17) ^ rotate(late, 19) ^ (late >>> 10);\n schedule.setInt32(\n t * 4,\n (sigma1 +\n schedule.getInt32((t - 7) * 4) +\n sigma0 +\n schedule.getInt32((t - 16) * 4)) |\n 0\n );\n }\n\n let a = hash.getInt32(0);\n let b = hash.getInt32(4);\n let c = hash.getInt32(8);\n let d = hash.getInt32(12);\n let e = hash.getInt32(16);\n let f = hash.getInt32(20);\n let g = hash.getInt32(24);\n let h = hash.getInt32(28);\n for (let t = 0; t < ROUNDS; t++) {\n const sum1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25);\n const choose = (e & f) ^ (~e & g);\n const first =\n (h +\n sum1 +\n choose +\n ROUND_CONSTANTS.getInt32(t * 4) +\n schedule.getInt32(t * 4)) |\n 0;\n const sum0 = rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n h = g;\n g = f;\n f = e;\n e = (d + first) | 0;\n d = c;\n c = b;\n b = a;\n a = (first + sum0 + majority) | 0;\n }\n fold(0, a);\n fold(4, b);\n fold(8, c);\n fold(12, d);\n fold(16, e);\n fold(20, f);\n fold(24, g);\n fold(28, h);\n}\n\n/**\n * The SHA-256 digest of one complete message.\n *\n * Byte-identical to `node:crypto` for every input, which a differential test\n * pins against the FIPS 180-4 known-answer vectors and 10,000 random messages\n * crossing every block and padding boundary.\n */\nexport function sha256(bytes: Uint8Array): Uint8Array {\n hashBytes.set(INITIAL_HASH);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / BLOCK_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n compress(message, block * BLOCK_BYTES);\n }\n\n // The tail, `0x80`, zeros, then the bit length as a 64-bit big-endian word:\n // one block, or two when the tail leaves fewer than nine bytes free.\n const tailLength = length - wholeBlocks * BLOCK_BYTES;\n const tail = new Uint8Array(\n tailLength > LAST_BLOCK_ROOM ? 2 * BLOCK_BYTES : BLOCK_BYTES\n );\n tail.set(bytes.subarray(wholeBlocks * BLOCK_BYTES));\n tail[tailLength] = 0x80;\n const padded = new DataView(tail.buffer);\n const bits = length * 8;\n padded.setUint32(tail.length - 8, Math.floor(bits / WORD_SPAN));\n padded.setUint32(tail.length - 4, bits % WORD_SPAN);\n for (let at = 0; at < tail.length; at += BLOCK_BYTES) {\n compress(padded, at);\n }\n\n return Uint8Array.from(hashBytes);\n}\n","/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"+HAyBA,MAKM,EAAY,GAAK,GAEjB,MAAS,GAAwC,CACrD,IAAM,EAAO,IAAI,SAAS,IAAI,YAAY,EAAO,OAAS,EAAE,CAAC,CAC7D,IAAK,GAAM,CAAC,EAAO,KAAU,EAAO,SAAS,CAC3C,EAAK,UAAU,EAAQ,EAAG,EAAM,CAElC,OAAO,GAIH,EAAkB,MAAM,CAC5B,WAAe,WAAe,WAAe,WAAe,UAC5D,WAAe,WAAe,WAAe,WAAe,UAC5D,UAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,UAAe,UAC5D,UAAe,WAAe,WAAe,WAAe,WAC5D,WAAe,WAAe,WAAe,WAAe,WAC5D,UAAe,UAAe,UAAe,UAAe,WAC5D,WAAe,WAAe,WAAe,WAA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ources":["../src/validation/primitives/sha256.ts","../src/migrations/identity.ts"],"sourcesContent":["// biome-ignore-all lint/suspicious/noBitwiseOperators: SHA-256 is 32-bit word\n// arithmetic. Every operator below is part of FIPS 180-4's definition.\n\n/**\n * SHA-256, the hash Migration V1 identity is defined over.\n *\n * FIPS 180-4: 64-byte blocks, a 64-word message schedule, 64 rounds, a 64-bit\n * big-endian bit length after the `0x80` pad. One exported function, no\n * streaming, no options: the caller hands over the complete message and\n * receives the 32-byte digest.\n *\n * It is synchronous on purpose. WebCrypto's `digest` is the platform hash on\n * every runtime, but it returns a promise, and every content-addressed parser\n * in the migration engine hashes inline; `node:crypto` is synchronous but is\n * not on an edge runtime without a compatibility flag.\n *\n * Every word is read and written through a `DataView` that names big-endian,\n * the byte order the standard is written in, so the host's byte order never\n * enters a digest; it is also the one indexed read in this codebase that is not\n * `T | undefined`, as in the SHA3-512 precedent (`./sha3`).\n *\n * The one caller is `migrations/identity`. Nothing else in VibORM may import\n * this module without its own differential proof against a reference.\n */\n\nconst BLOCK_BYTES = 64;\nconst DIGEST_BYTES = 32;\nconst ROUNDS = 64;\n/** A tail of more than this many bytes leaves no room for the pad and length. */\nconst LAST_BLOCK_ROOM = BLOCK_BYTES - 9;\nconst WORD_SPAN = 2 ** 32;\n\nconst words = (values: readonly number[]): DataView => {\n const view = new DataView(new ArrayBuffer(values.length * 4));\n for (const [index, value] of values.entries()) {\n view.setUint32(index * 4, value);\n }\n return view;\n};\n\n/** The first 32 bits of the fractional parts of the first 64 primes' cube roots. */\nconst ROUND_CONSTANTS = words([\n 0x42_8a_2f_98, 0x71_37_44_91, 0xb5_c0_fb_cf, 0xe9_b5_db_a5, 0x39_56_c2_5b,\n 0x59_f1_11_f1, 0x92_3f_82_a4, 0xab_1c_5e_d5, 0xd8_07_aa_98, 0x12_83_5b_01,\n 0x24_31_85_be, 0x55_0c_7d_c3, 0x72_be_5d_74, 0x80_de_b1_fe, 0x9b_dc_06_a7,\n 0xc1_9b_f1_74, 0xe4_9b_69_c1, 0xef_be_47_86, 0x0f_c1_9d_c6, 0x24_0c_a1_cc,\n 0x2d_e9_2c_6f, 0x4a_74_84_aa, 0x5c_b0_a9_dc, 0x76_f9_88_da, 0x98_3e_51_52,\n 0xa8_31_c6_6d, 0xb0_03_27_c8, 0xbf_59_7f_c7, 0xc6_e0_0b_f3, 0xd5_a7_91_47,\n 0x06_ca_63_51, 0x14_29_29_67, 0x27_b7_0a_85, 0x2e_1b_21_38, 0x4d_2c_6d_fc,\n 0x53_38_0d_13, 0x65_0a_73_54, 0x76_6a_0a_bb, 0x81_c2_c9_2e, 0x92_72_2c_85,\n 0xa2_bf_e8_a1, 0xa8_1a_66_4b, 0xc2_4b_8b_70, 0xc7_6c_51_a3, 0xd1_92_e8_19,\n 0xd6_99_06_24, 0xf4_0e_35_85, 0x10_6a_a0_70, 0x19_a4_c1_16, 0x1e_37_6c_08,\n 0x27_48_77_4c, 0x34_b0_bc_b5, 0x39_1c_0c_b3, 0x4e_d8_aa_4a, 0x5b_9c_ca_4f,\n 0x68_2e_6f_f3, 0x74_8f_82_ee, 0x78_a5_63_6f, 0x84_c8_78_14, 0x8c_c7_02_08,\n 0x90_be_ff_fa, 0xa4_50_6c_eb, 0xbe_f9_a3_f7, 0xc6_71_78_f2,\n]);\n\n/** The first 32 bits of the fractional parts of the first 8 primes' square roots. */\nconst INITIAL_HASH = new Uint8Array(\n words([\n 0x6a_09_e6_67, 0xbb_67_ae_85, 0x3c_6e_f3_72, 0xa5_4f_f5_3a, 0x51_0e_52_7f,\n 0x9b_05_68_8c, 0x1f_83_d9_ab, 0x5b_e0_cd_19,\n ]).buffer\n);\n\n/**\n * The running hash and the message schedule, allocated once: `sha256` is\n * synchronous from entry to return, and every entry begins by resetting the\n * hash to its initial value.\n */\nconst hashBytes = new Uint8Array(DIGEST_BYTES);\nconst hash = new DataView(hashBytes.buffer);\nconst schedule = new DataView(new ArrayBuffer(ROUNDS * 4));\n\nconst rotate = (word: number, bits: number): number =>\n (word >>> bits) | (word << (32 - bits));\n\n/** Folds one working variable back into the running hash. */\nconst fold = (at: number, word: number): void => {\n hash.setInt32(at, (hash.getInt32(at) + word) | 0);\n};\n\n/** The compression function over the 64 bytes of `block` at `offset`. */\nfunction compress(block: DataView, offset: number): void {\n for (let t = 0; t < 16; t++) {\n schedule.setInt32(t * 4, block.getInt32(offset + t * 4));\n }\n for (let t = 16; t < ROUNDS; t++) {\n const early = schedule.getInt32((t - 15) * 4);\n const late = schedule.getInt32((t - 2) * 4);\n const sigma0 = rotate(early, 7) ^ rotate(early, 18) ^ (early >>> 3);\n const sigma1 = rotate(late, 17) ^ rotate(late, 19) ^ (late >>> 10);\n schedule.setInt32(\n t * 4,\n (sigma1 +\n schedule.getInt32((t - 7) * 4) +\n sigma0 +\n schedule.getInt32((t - 16) * 4)) |\n 0\n );\n }\n\n let a = hash.getInt32(0);\n let b = hash.getInt32(4);\n let c = hash.getInt32(8);\n let d = hash.getInt32(12);\n let e = hash.getInt32(16);\n let f = hash.getInt32(20);\n let g = hash.getInt32(24);\n let h = hash.getInt32(28);\n for (let t = 0; t < ROUNDS; t++) {\n const sum1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25);\n const choose = (e & f) ^ (~e & g);\n const first =\n (h +\n sum1 +\n choose +\n ROUND_CONSTANTS.getInt32(t * 4) +\n schedule.getInt32(t * 4)) |\n 0;\n const sum0 = rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n h = g;\n g = f;\n f = e;\n e = (d + first) | 0;\n d = c;\n c = b;\n b = a;\n a = (first + sum0 + majority) | 0;\n }\n fold(0, a);\n fold(4, b);\n fold(8, c);\n fold(12, d);\n fold(16, e);\n fold(20, f);\n fold(24, g);\n fold(28, h);\n}\n\n/**\n * The SHA-256 digest of one complete message.\n *\n * Byte-identical to `node:crypto` for every input, which a differential test\n * pins against the FIPS 180-4 known-answer vectors and 10,000 random messages\n * crossing every block and padding boundary.\n */\nexport function sha256(bytes: Uint8Array): Uint8Array {\n hashBytes.set(INITIAL_HASH);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / BLOCK_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n compress(message, block * BLOCK_BYTES);\n }\n\n // The tail, `0x80`, zeros, then the bit length as a 64-bit big-endian word:\n // one block, or two when the tail leaves fewer than nine bytes free.\n const tailLength = length - wholeBlocks * BLOCK_BYTES;\n const tail = new Uint8Array(\n tailLength > LAST_BLOCK_ROOM ? 2 * BLOCK_BYTES : BLOCK_BYTES\n );\n tail.set(bytes.subarray(wholeBlocks * BLOCK_BYTES));\n tail[tailLength] = 0x80;\n const padded = new DataView(tail.buffer);\n const bits = length * 8;\n padded.setUint32(tail.length - 8, Math.floor(bits / WORD_SPAN));\n padded.setUint32(tail.length - 4, bits % WORD_SPAN);\n for (let at = 0; at < tail.length; at += BLOCK_BYTES) {\n compress(padded, at);\n }\n\n return Uint8Array.from(hashBytes);\n}\n","/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"+HAyBA,MAKM,EAAY,GAAK,GAEjB,MAAS,GAAwC,CACrD,IAAM,EAAO,IAAI,SAAS,IAAI,YAAY,EAAO,OAAS,EAAE,CAAC,CAC7D,IAAK,GAAM,CAAC,EAAO,KAAU,EAAO,SAAS,CAC3C,EAAK,UAAU,EAAQ,EAAG,EAAM,CAElC,OAAO,GAIH,EAAkB,MAAM,CAC5B,WAAe,WAAe,WAAe,WAAe,UAC5D,WAAe,WAAe,WAAe,WAAe,UAC5D,UAA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