viborm 1.3.1 → 1.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-CWLEmon2.mjs} +2 -2
- package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-CWLEmon2.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DGJPz8-G.mjs} +2 -2
- package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DGJPz8-G.mjs.map} +1 -1
- package/dist/{bind-parameter-capacity-qfEejeOX.mjs → bind-parameter-capacity-DiwRmZ1h.mjs} +2 -2
- package/dist/{bind-parameter-capacity-qfEejeOX.mjs.map → bind-parameter-capacity-DiwRmZ1h.mjs.map} +1 -1
- package/dist/{builder-s1ySUuMb.mjs → builder-D6Ug-zjM.mjs} +2 -2
- package/dist/{builder-s1ySUuMb.mjs.map → builder-D6Ug-zjM.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/chain-B5IbqLGi.mjs +2 -0
- package/dist/chain-B5IbqLGi.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/client-BmcHzDBa.mjs +2 -0
- package/dist/client-BmcHzDBa.mjs.map +1 -0
- package/dist/{client-70MrTq1E.d.mts → client-DR0vYetv.d.mts} +2 -2
- package/dist/{client-BgJ7Faln.mjs → client-DjtWangN.mjs} +3 -3
- package/dist/{client-BgJ7Faln.mjs.map → client-DjtWangN.mjs.map} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
- package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/datetime-physical-codec-qKxFtI3B.mjs +2 -0
- package/dist/datetime-physical-codec-qKxFtI3B.mjs.map +1 -0
- package/dist/{driver-vn-9CN0y.mjs → driver-BvP7eW0A.mjs} +2 -2
- package/dist/{driver-vn-9CN0y.mjs.map → driver-BvP7eW0A.mjs.map} +1 -1
- package/dist/{driver-B9fIori_.mjs → driver-Bzc0GCQ4.mjs} +2 -2
- package/dist/{driver-B9fIori_.mjs.map → driver-Bzc0GCQ4.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
- package/dist/error-mapping-6op318w6.mjs.map +1 -0
- package/dist/every-WUr3mlvg.mjs +2 -0
- package/dist/{every-CcpKWCVo.mjs.map → every-WUr3mlvg.mjs.map} +1 -1
- package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
- package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
- package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
- package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
- package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
- package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
- package/dist/{hydration-BsPZI4jE.mjs → hydration-BflrXEIQ.mjs} +2 -2
- package/dist/{hydration-BsPZI4jE.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
- package/dist/{identifier-conversion-BneQiLxQ.mjs → identifier-conversion-Bs7A2GGU.mjs} +2 -2
- package/dist/{identifier-conversion-BneQiLxQ.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map} +1 -1
- package/dist/identity-Bj2EN6Ss.mjs +2 -0
- package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
- package/dist/{index-VsM29vYN.d.mts → index-B_jh2oaQ.d.mts} +38 -11
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{key-D9LtHxVK.mjs → key-B89Z4vxn.mjs} +2 -2
- package/dist/{key-D9LtHxVK.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
- package/dist/{libsql-BlSBYwd_.mjs → libsql-C8dn4id0.mjs} +2 -2
- package/dist/{libsql-BlSBYwd_.mjs.map → libsql-C8dn4id0.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-C0k-_S_n.mjs → memory-B7CcHS6I.mjs} +2 -2
- package/dist/{memory-C0k-_S_n.mjs.map → memory-B7CcHS6I.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/mysql-adapter-ABpgFB2N.mjs +2 -0
- package/dist/mysql-adapter-ABpgFB2N.mjs.map +1 -0
- package/dist/{mysql-DOLHwIM_.mjs → mysql-mUmhH9Cf.mjs} +2 -2
- package/dist/{mysql-DOLHwIM_.mjs.map → mysql-mUmhH9Cf.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
- package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
- package/dist/{object-store-D9mvOHP4.d.mts → object-store-Ds9NKRU6.d.mts} +3 -3
- package/dist/permissions.d.mts +2 -2
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
- package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
- package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-C79aDzOg.mjs} +2 -2
- package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-C79aDzOg.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C1NzLBge.d.mts → planner-DHZG9Vy7.d.mts} +1 -1
- package/dist/{postgres-DQVSTqVm.mjs → postgres-BACQ_wqF.mjs} +2 -2
- package/dist/{postgres-DQVSTqVm.mjs.map → postgres-BACQ_wqF.mjs.map} +1 -1
- package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-Ci07rgh_.mjs} +2 -2
- package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-Ci07rgh_.mjs.map} +1 -1
- package/dist/postgres-adapter-DaMvNOkx.mjs +2 -0
- package/dist/postgres-adapter-DaMvNOkx.mjs.map +1 -0
- package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-D403cLyA.mjs} +2 -2
- package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-D403cLyA.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-DSv2tYFr.mjs} +2 -2
- package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-DSv2tYFr.mjs.map} +1 -1
- package/dist/result-shape-BKydBCsR.mjs +2 -0
- package/dist/result-shape-BKydBCsR.mjs.map +1 -0
- package/dist/rows-v1VuwOTa.mjs +2 -0
- package/dist/rows-v1VuwOTa.mjs.map +1 -0
- package/dist/{scalar-CpEwuJvn.mjs → scalar-Cm7nMFmO.mjs} +2 -2
- package/dist/{scalar-CpEwuJvn.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-BnzGHn7k.mjs → schema-D3-ScVH6.mjs} +2 -2
- package/dist/{schema-BnzGHn7k.mjs.map → schema-D3-ScVH6.mjs.map} +1 -1
- package/dist/{schema-introspection-DZsdP6bi.mjs → schema-introspection-TdJrSaKd.mjs} +3 -3
- package/dist/{schema-introspection-DZsdP6bi.mjs.map → schema-introspection-TdJrSaKd.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-uZfvbYjz.mjs} +2 -2
- package/dist/select-assembly-uZfvbYjz.mjs.map +1 -0
- package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
- package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
- package/dist/sha256-CEYo7k7R.mjs +2 -0
- package/dist/sha256-CEYo7k7R.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/sql-BvHwL73I.mjs +2 -0
- package/dist/sql-BvHwL73I.mjs.map +1 -0
- package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
- package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
- package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-DPc9T6Lh.mjs +2 -0
- package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +1 -0
- package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-BvSlEs5W.mjs} +2 -2
- package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-BvSlEs5W.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-CYdZ_KXH.mjs} +2 -2
- package/dist/standard-sql-CYdZ_KXH.mjs.map +1 -0
- package/dist/{to-many-C5RMZl05.mjs → to-many-Btc9X5Ga.mjs} +2 -2
- package/dist/{to-many-C5RMZl05.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
- package/dist/{utils-C3r4gO3Y.mjs → utils-Qr8ug94X.mjs} +2 -2
- package/dist/{utils-C3r4gO3Y.mjs.map → utils-Qr8ug94X.mjs.map} +1 -1
- package/dist/v-514RME2X.mjs +2 -0
- package/dist/v-514RME2X.mjs.map +1 -0
- package/dist/{validation-BQtO6srU.mjs → validation-CPnrLcjW.mjs} +2 -2
- package/dist/{validation-BQtO6srU.mjs.map → validation-CPnrLcjW.mjs.map} +1 -1
- package/dist/validation-gwZYm3Yn.mjs +2 -0
- package/dist/validation-gwZYm3Yn.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CVSrhn0u.mjs → validator-CQOw7G3q.mjs} +2 -2
- package/dist/{validator-CVSrhn0u.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
- package/dist/version-0RVYpih5.mjs +2 -0
- package/dist/{version-C8QLCt1n.mjs.map → version-0RVYpih5.mjs.map} +1 -1
- package/package.json +15 -15
- package/dist/chain-7qiFSE8J.mjs +0 -2
- package/dist/chain-7qiFSE8J.mjs.map +0 -1
- package/dist/client-6YgGlXzN.mjs +0 -2
- package/dist/client-6YgGlXzN.mjs.map +0 -1
- package/dist/controls-KQ85SWfT.mjs +0 -2
- package/dist/controls-KQ85SWfT.mjs.map +0 -1
- package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
- package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
- package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
- package/dist/every-CcpKWCVo.mjs +0 -2
- package/dist/identity-oQvIe7u8.mjs +0 -2
- package/dist/identity-oQvIe7u8.mjs.map +0 -1
- package/dist/mysql-adapter-C6c5govr.mjs +0 -2
- package/dist/mysql-adapter-C6c5govr.mjs.map +0 -1
- package/dist/postgres-adapter-CxEit2-v.mjs +0 -2
- package/dist/postgres-adapter-CxEit2-v.mjs.map +0 -1
- package/dist/result-shape-B6yWtnx_.mjs +0 -2
- package/dist/result-shape-B6yWtnx_.mjs.map +0 -1
- package/dist/select-assembly-CkGe2ABs.mjs.map +0 -1
- package/dist/sql-Bhxq9arK.mjs +0 -2
- package/dist/sql-Bhxq9arK.mjs.map +0 -1
- package/dist/sqlite-adapter-BXAJy3mI.mjs +0 -2
- package/dist/sqlite-adapter-BXAJy3mI.mjs.map +0 -1
- package/dist/standard-sql-CoGqv-iX.mjs.map +0 -1
- package/dist/v-DtLdBQYg.mjs +0 -2
- package/dist/v-DtLdBQYg.mjs.map +0 -1
- package/dist/validation-BamBwne9.mjs +0 -2
- package/dist/validation-BamBwne9.mjs.map +0 -1
- package/dist/version-C8QLCt1n.mjs +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{Pt as t}from"./geo-point-codec-
|
|
2
|
-
//# sourceMappingURL=hydration-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{Pt as t}from"./geo-point-codec-D95uXgDF.mjs";import{S as n,T as r}from"./scalar-Cm7nMFmO.mjs";function hydrateSchemaNames(e,t=!1){let i=Object.entries(e);if(t){for(let[e,t]of i)bindModelNames(e,t);return}let a=r(i);if(a)throw new n([a]);for(let[e,t]of i)preflightModelIdentifiers(e,t);for(let[e,t]of i)bindModelNames(e,t)}function preflightModelIdentifiers(e,t){let n=t[`~`].state;assertValidIdentifier(`Model`,e),n.tableName!==void 0&&assertValidIdentifier(`Mapped table`,n.tableName,e);for(let t of Object.keys(n.shape))assertValidIdentifier(`Field`,t,e);for(let t of Object.values(n.scalars))t[`~`].state.columnName!==void 0&&assertValidIdentifier(`Mapped column`,t[`~`].state.columnName,e)}function bindModelNames(e,t){let n=t[`~`].names,r=t[`~`].state,i=t[`~`].nameRegistry;n.ts=e,n.sql=r.tableName??e;for(let[e,t]of Object.entries(r.scalars)){let n={ts:e,sql:t[`~`].state.columnName??e};i.fields.set(e,n)}}function assertValidIdentifier(e,n,r){if(t(n))return;let i=r?` in '${r}'`:``,a=String(n);throw Error(`${e} '${a}'${i} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`)}export{hydrateSchemaNames as t};
|
|
2
|
+
//# sourceMappingURL=hydration-BflrXEIQ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-
|
|
1
|
+
{"version":3,"file":"hydration-BflrXEIQ.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"}
|
|
@@ -1,2 +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-
|
|
2
|
-
//# sourceMappingURL=identifier-conversion-
|
|
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-D95uXgDF.mjs";import{o as a}from"./sql-BvHwL73I.mjs";import{f as o,p as s}from"./scalar-Cm7nMFmO.mjs";import{t as c}from"./hydration-BflrXEIQ.mjs";import{l,m as u,n as d,u as f}from"./validator-CQOw7G3q.mjs";import{N as p}from"./standard-sql-CYdZ_KXH.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-Bs7A2GGU.mjs.map
|
package/dist/{identifier-conversion-BneQiLxQ.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identifier-conversion-BneQiLxQ.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,EAAK,CAEnB,EAAU,IAAI,EAAI,CAAC,EAAK,CAAC,CAG7B,OAAO,ECiBT,MAAM,EAAM,cACN,EAAY,kCACZ,EAAS,cAYT,EAAW,CACf,KAAM,CACJ,OAAQ,GACR,MAAO,IAAI,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,OACvD,KAAM,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,GAAG,GAC3F,KAAM,QACN,IAAK,IAAA,GACN,CACD,KAAM,CACJ,OAAQ,GACR,MAAO,SAAS,EAAU,OAC1B,KAAM,QAAQ,EAAU,OAAO,GAAG,GAClC,KAAM,QACN,IAAK,IAAA,GACN,CACD,MAAO,CACL,OAAQ,GACR,MAAO,IAAI,EAAO,OAClB,KAAM,EAAO,OAAO,GAAG,CACvB,KAAM,IAAA,GACN,IAAK,EACN,CACF,CAGD,SAAS,UAAU,EAAkB,CAGnC,OAFI,EAAO,SAAW,OAAe,EAAS,KAC1C,EAAO,SAAW,QAAgB,EAAS,MACxC,EAAS,KAIlB,MAAM,IAAO,GAAuBA,EAAI,IAAI,OAAO,EAAM,CAAC,CAG1D,SAAS,QACP,EACA,EACA,EACA,EACK,CACL,IAAM,EAAQ,EAAuB,IAAY,QAAU,IAAM,IAAI,CAC/D,EACJ,IAAY,cAAgB,EAAY,GAAG,EAAM,EAAU,CAAC,GAAK,GACnE,OAAOA,EAAI,IAAI,GAAG,EAAY,EAAM,EAAa,EAAM,CAAC,CAAC,MAAM,IAAQ,CAUzE,SAAS,UACP,EACA,EACA,EACA,EACK,CACL,IAAM,EAAQ,EAAuB,IAAY,QAAU,IAAM,IAAI,CACrE,OAAOA,EAAI,IAAI,GAAG,EAAM,GAAG,EAAM,EAAc,EAAO,EAAM,CAAC,GAAG,CAIlE,SAAS,WAAW,EAAa,EAAuB,CACtD,IAAM,EAAS,EAAO,OAEtB,OADK,EACE,CAAG,UAAU,EAAO,IAAI,IAAI,EAAO,OAAS,EAAE,CAAC,GADlC,EAWtB,SAAS,SAAS,EAAiB,EAAuB,CACxD,OAAO,IAAY,QAAU,CAAG,QAAQ,EAAW,aAAe,EAcpE,SAAS,WAAW,EAAiB,EAAuB,CAI1D,OAHI,IAAY,aACP,CAAG,QAAQ,EAAW,uBAExB,SAAS,EAAY,EAAQ,CAItC,SAAS,UAAU,EAAa,EAAkB,EAAuB,CACvE,IAAM,EAAU,UAAU,EAAO,CAC3B,EAAU,WAAW,EAAQ,EAAO,CACpC,EACJ,IAAY,aACR,CAAG,GAAG,EAAQ,KAAK,EAAQ,QAC3B,IAAY,QACV,CAAG,GAAG,EAAQ,UAAU,EAAQ,QAChC,CAAG,GAAG,EAAQ,QAAQ,EAAQ,OAEhC,EAAU,CAAG,GADLA,EAAI,IAAI,IAAY,QAAU,cAAgB,SAAS,CACzC,GAAG,EAAQ,MAAM,IAAI,EAAQ,OAAO,CAAC,OAAO,IAClE,EACJ,EAAQ,MAAQ,IAAA,GACZ,EACA,CAAG,GAAG,EAAQ,OAAO,WAAW,EAAS,EAAQ,CAAC,MAAM,EAAQ,MAChE,EAAS,EAAO,OAMtB,OALK,EAKE,CAAG,GAJM,SACd,CAAG,UAAU,EAAO,OAAO,IAAI,EAAO,OAAS,EAAE,CAAC,GAClD,EACD,CACoB,KAAK,GAAG,EAAO,GAAG,OAAO,IAL1B,EAYtB,SAAS,QAAQ,EAAa,EAAkB,EAAuB,CACrE,IAAM,EAAO,UAAU,EAAO,CAAC,KACzB,EAAU,WAAW,EAAQ,EAAO,CAC1C,OAAO,SACL,IAAS,IAAA,GAAY,EAAU,CAAG,GAAGA,EAAI,IAAI,EAAK,CAAC,GAAG,EAAQ,GAC9D,EACD,CAOH,SAAS,mBACP,EACA,EACA,EACA,EACqB,CACrB,MAAO,CACL,KAAM,eACN,MAAO,CAAG,gBAAgB,EAAO,qBAAqB,QAAQ,EAAQ,EAAQ,EAAQ,CAAC,eAAe,IACtG,OAAQ,GACT,CAgBH,SAAS,kBAAkB,EAAiB,EAAwB,CAClE,OAAO,EAAmB,EAAM,CAAC,kBAAkB,KAChD,GAAQ,EAAI,SAAW,GAAK,EAAI,KAAO,EACzC,CAIH,MAAM,YAAc,EAAW,KAAyC,CACtE,KAAM,eACN,MAAO,CAAG,oCAAoC,EAAK,SAAS,EAAU,SACtE,OAAQ,GACT,EAGD,SAAS,mBACP,EACA,EACsC,CACtC,IAAM,EAAgD,EAAE,CACxD,IAAK,IAAM,KAAQ,EAAc,EAAM,CACjC,KAAK,OAAS,eAEhB,EAAK,UAAU,KAAO,EAAK,MAAQ,EAAK,UAAU,GAAK,EAAK,UAAU,IAC9D,SAAW,EAAQ,MAC7B,IAAK,IAAM,KAAU,EAAK,UAAU,QAC9B,EAAO,kBAAoB,EAAQ,OACvC,EAAQ,KAAK,CAAE,MAAO,EAAK,MAAM,OAAQ,MAAO,EAAO,aAAc,CAAC,CAG1E,OAAO,EAWT,SAAgB,2BACd,EACgC,CAChC,GAAM,CAAE,QAAO,QAAO,UAAS,aAAc,EAC7C,EAAmB,EAAQ,OAAO,CAClC,IAAM,EAAQ,EAAqB,EAAQ,OAAO,CAC5C,EAAS,EAAW,EAAO,EAAO,EAAM,CAC9C,GAAI,IAAW,IAAA,IAAa,CAAC,EAAkB,EAAO,OAAO,CAC3D,MAAM,IAAI,EACR,IAAI,EAAa,EAAM,CAAC,GAAG,EAAc,EAAO,EAAM,CAAC,uIACvD,EAAgB,cACjB,CAEH,IAAM,EAAS,QAAQ,EAAO,EAAS,EAAW,IAAI,CAChD,EAAM,UAAU,EAAO,EAAO,EAAS,IAAI,CAC3C,EAAgC,CACpC,WACE,EACA,CAAG,GAAG,EAAI,wBAAwB,UAAU,EAAK,EAAQ,EAAQ,CAAC,GACnE,CACF,CACK,EAAQ,UAAU,EAAO,CAAC,OAAS,IAAA,GACrC,GACF,EAAO,KAAK,mBAAmB,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
|
+
{"version":3,"file":"identifier-conversion-Bs7A2GGU.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":"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"}
|
|
@@ -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{t as r}from"./sha256-CEYo7k7R.mjs";const i=`sha256`,a={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`},o=/^[0-9a-f]{64}$/,s=new TextEncoder;function isSha256(e){return typeof e==`string`&&o.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 r(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=s.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 s.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,a as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,i as t};
|
|
2
|
+
//# sourceMappingURL=identity-Bj2EN6Ss.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity-Bj2EN6Ss.mjs","names":[],"sources":["../src/migrations/identity.ts"],"sourcesContent":["/**\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":"yKAcA,MAAa,EAAiB,SAEjB,EAAc,CACzB,OAAQ,6BACR,SAAU,+BACV,IAAK,0BACL,SAAU,+BACV,WAAY,iCACZ,MAAO,4BACP,KAAM,2BACN,KAAM,2BACN,UAAW,iCACX,MAAO,4BACR,CAIK,EAAQ,iBACR,EAAO,IAAI,YAEjB,SAAgB,SAAS,EAAiC,CACxD,OAAO,OAAO,GAAU,UAAY,EAAM,KAAK,EAAM,CAGvD,SAAgB,YAAY,EAAgB,EAAuB,CACjE,GAAI,CAAC,SAAS,EAAM,CAClB,MAAM,IAAI,EACR,GAAG,EAAM,2CACT,EAAgB,yBACjB,CAEH,OAAO,EAGT,SAAgB,UAAU,EAA2B,CACnD,IAAI,EAAM,GACV,IAAK,IAAM,KAAQ,EAAO,EAAM,CAAE,GAAO,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAC3E,OAAO,EAGT,SAAgB,WAAW,EAAoB,EAA2B,CACxE,IAAM,EAAS,EAAK,OAAO,EAAO,CAC5B,EAAQ,IAAI,WAAW,EAAO,OAAS,EAAI,EAAM,OAAO,CAI9D,OAHA,EAAM,IAAI,EAAQ,EAAE,CACpB,EAAM,EAAO,QAAU,EACvB,EAAM,IAAI,EAAO,EAAO,OAAS,EAAE,CAC5B,UAAU,EAAM,CAGzB,SAAgB,UAAU,EAA0B,CAClD,OAAO,EAAK,OAAO,EAAK,CAW1B,SAAgB,WAAW,EAA2B,CACpD,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,UAAW,GAAM,CAAC,CAAC,OAChE,EACD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as sqlTag, n as Sql } from "./sql-
|
|
1
|
+
import { c as sqlTag, n as Sql } from "./sql-Q_twK-wW.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema/scalars/native-types.d.ts
|
|
@@ -1150,8 +1150,15 @@ declare class ForbiddenError extends VibORMError {
|
|
|
1150
1150
|
static readonly diagnosticName = "ForbiddenError";
|
|
1151
1151
|
/** Literal discriminant: this class always carries `FORBIDDEN`. */
|
|
1152
1152
|
readonly code: typeof VibORMErrorCode.FORBIDDEN;
|
|
1153
|
+
/**
|
|
1154
|
+
* `reason` names what refused the operation where the operation alone does
|
|
1155
|
+
* not say it, e.g. a field an update writes through a nested write;
|
|
1156
|
+
* `cause`, the failure it explains (an upsert's unique violation).
|
|
1157
|
+
*/
|
|
1153
1158
|
constructor(model: string, operation: string, options?: {
|
|
1154
1159
|
meta?: VibORMErrorMeta;
|
|
1160
|
+
reason?: string;
|
|
1161
|
+
cause?: Error;
|
|
1155
1162
|
});
|
|
1156
1163
|
}
|
|
1157
1164
|
/**
|
|
@@ -5098,7 +5105,11 @@ type ScalarFields = {
|
|
|
5098
5105
|
* its filter where it is not.
|
|
5099
5106
|
*
|
|
5100
5107
|
* `verbs` judges, per model, what a call may do to the rows it sees: a mode
|
|
5101
|
-
* only narrows them (R8).
|
|
5108
|
+
* only narrows them (R8). A model's entry may be a function returning it:
|
|
5109
|
+
* it is called when a call of the chain first needs that model, and its
|
|
5110
|
+
* entry admitted then, so a refusal of it fails that call instead of
|
|
5111
|
+
* `$extends`. A function returning deeply frozen plain data is called once
|
|
5112
|
+
* per schema; one returning anything else, once per client.
|
|
5102
5113
|
*/
|
|
5103
5114
|
type RowsContribution = {
|
|
5104
5115
|
readonly control: string;
|
|
@@ -5112,7 +5123,7 @@ type RowsContribution = {
|
|
|
5112
5123
|
};
|
|
5113
5124
|
};
|
|
5114
5125
|
readonly verbs?: {
|
|
5115
|
-
readonly [model: string]: RowsVerbs;
|
|
5126
|
+
readonly [model: string]: RowsVerbs | (() => RowsVerbs);
|
|
5116
5127
|
};
|
|
5117
5128
|
};
|
|
5118
5129
|
/**
|
|
@@ -5130,7 +5141,9 @@ type RowsContribution = {
|
|
|
5130
5141
|
* updated row at the predicates that judged its old row, and, for each field
|
|
5131
5142
|
* its data writes, at that field's `moves` entry, and where it writes the
|
|
5132
5143
|
* key of an `acyclic` relation (a to-one relation of the model to itself),
|
|
5133
|
-
* outside its own subtree.
|
|
5144
|
+
* outside its own subtree. `acyclic` may be a function returning that list:
|
|
5145
|
+
* it is called the first time an update writes the key of one of the
|
|
5146
|
+
* model's self relations. A refused row is written by no statement.
|
|
5134
5147
|
*
|
|
5135
5148
|
* `evidence` declares a projection key (`evidence.as`) a `select` or
|
|
5136
5149
|
* `include` may name at every depth, on reads and on the rows a write
|
|
@@ -5156,7 +5169,7 @@ type RowsVerbs = {
|
|
|
5156
5169
|
readonly moves?: {
|
|
5157
5170
|
readonly [field: string]: string;
|
|
5158
5171
|
};
|
|
5159
|
-
readonly acyclic?: readonly string[];
|
|
5172
|
+
readonly acyclic?: readonly string[] | (() => readonly string[]);
|
|
5160
5173
|
readonly evidence?: {
|
|
5161
5174
|
readonly as: string;
|
|
5162
5175
|
readonly names: readonly string[];
|
|
@@ -5943,11 +5956,13 @@ type GroupByResultType<T$1 extends ModelShape, Args> = Args extends {
|
|
|
5943
5956
|
//#region src/client/projected-types.d.ts
|
|
5944
5957
|
/** The row operations a projection key reaches. */
|
|
5945
5958
|
type ProjectedOperation = "findMany" | "findFirst" | "findUnique" | "findFirstOrThrow" | "findUniqueOrThrow" | "create" | "update" | "upsert" | "delete";
|
|
5959
|
+
/** Each model's entry, a lazy one's (a function's) as it resolves. */
|
|
5960
|
+
type ResolvedVerbs<Verbs$1> = { [M in keyof Verbs$1]: Verbs$1[M] extends ((...args: never[]) => infer Entry) ? Entry : Verbs$1[M] };
|
|
5946
5961
|
type VerbsOf<Definition$1> = Definition$1 extends {
|
|
5947
5962
|
readonly rows: {
|
|
5948
5963
|
readonly verbs: infer Verbs;
|
|
5949
5964
|
};
|
|
5950
|
-
} ? Verbs : never;
|
|
5965
|
+
} ? ResolvedVerbs<Verbs> : never;
|
|
5951
5966
|
type DeclaredEvidence<Entry> = Entry extends {
|
|
5952
5967
|
readonly evidence: {
|
|
5953
5968
|
readonly as: infer Key extends string;
|
|
@@ -6036,7 +6051,7 @@ type DeclaresEvidence<C$1 extends VibORMConfig, Definition$1> = Definition$1 ext
|
|
|
6036
6051
|
readonly rows: {
|
|
6037
6052
|
readonly verbs: infer Verbs extends object;
|
|
6038
6053
|
};
|
|
6039
|
-
} ? [EvidenceModels<C$1, Verbs
|
|
6054
|
+
} ? [EvidenceModels<C$1, ResolvedVerbs<Verbs>>] extends [never] ? false : true : false;
|
|
6040
6055
|
/** Per model, the fields a definition's verbs read-gate, each `boolean`. */
|
|
6041
6056
|
type GatedOmit<Verbs$1> = { [M in keyof Verbs$1 as Verbs$1[M] extends {
|
|
6042
6057
|
readonly reads: object;
|
|
@@ -6056,8 +6071,8 @@ type GatedConfig<C$1 extends VibORMConfig, Definition$1> = Definition$1 extends
|
|
|
6056
6071
|
readonly rows: {
|
|
6057
6072
|
readonly verbs: infer Verbs extends object;
|
|
6058
6073
|
};
|
|
6059
|
-
} ? [keyof GatedOmit<Verbs
|
|
6060
|
-
readonly omit: MergedOmit<ConfigOmit$1<C$1>, GatedOmit<Verbs
|
|
6074
|
+
} ? [keyof GatedOmit<ResolvedVerbs<Verbs>>] extends [never] ? C$1 : Omit<C$1, "omit"> & {
|
|
6075
|
+
readonly omit: MergedOmit<ConfigOmit$1<C$1>, GatedOmit<ResolvedVerbs<Verbs>>>;
|
|
6061
6076
|
} : C$1;
|
|
6062
6077
|
//#endregion
|
|
6063
6078
|
//#region src/client/client.d.ts
|
|
@@ -12790,7 +12805,10 @@ interface DatabaseAdapter {
|
|
|
12790
12805
|
emptyArray: () => Sql;
|
|
12791
12806
|
/**
|
|
12792
12807
|
* Aggregate rows into a JSON array. An empty aggregate is the empty array,
|
|
12793
|
-
* never SQL NULL, so no caller wraps it in its own COALESCE.
|
|
12808
|
+
* never SQL NULL, so no caller wraps it in its own COALESCE. `expr` is a
|
|
12809
|
+
* JSON value as built here (`object`, `array`): one read back through a
|
|
12810
|
+
* subquery column goes through `document` first, which SQLite needs to
|
|
12811
|
+
* keep it a JSON value rather than a quoted string.
|
|
12794
12812
|
*/
|
|
12795
12813
|
agg: (expr: Sql) => Sql;
|
|
12796
12814
|
/** Build JSON object from explicit column list (works on all databases) */
|
|
@@ -13027,10 +13045,16 @@ interface DatabaseAdapter {
|
|
|
13027
13045
|
* Common Table Expressions
|
|
13028
13046
|
*/
|
|
13029
13047
|
cte: {
|
|
13030
|
-
/**
|
|
13048
|
+
/**
|
|
13049
|
+
* Build WITH clause: WITH name AS (query), ... A member `inlined` is read
|
|
13050
|
+
* correlated to each outer row through its own columns: PostgreSQL would
|
|
13051
|
+
* materialize a member read twice and scan it, without an index, once
|
|
13052
|
+
* per row, so it is written `NOT MATERIALIZED` there.
|
|
13053
|
+
*/
|
|
13031
13054
|
with: (definitions: {
|
|
13032
13055
|
name: string;
|
|
13033
13056
|
query: Sql;
|
|
13057
|
+
inlined?: boolean;
|
|
13034
13058
|
}[]) => Sql;
|
|
13035
13059
|
/**
|
|
13036
13060
|
* Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).
|
|
@@ -13383,6 +13407,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
|
|
|
13383
13407
|
with: (definitions: {
|
|
13384
13408
|
name: string;
|
|
13385
13409
|
query: Sql;
|
|
13410
|
+
inlined?: boolean;
|
|
13386
13411
|
}[]) => Sql;
|
|
13387
13412
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13388
13413
|
};
|
|
@@ -13620,6 +13645,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
|
|
|
13620
13645
|
with: (definitions: {
|
|
13621
13646
|
name: string;
|
|
13622
13647
|
query: Sql;
|
|
13648
|
+
inlined?: boolean;
|
|
13623
13649
|
}[]) => Sql;
|
|
13624
13650
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13625
13651
|
};
|
|
@@ -13909,6 +13935,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
|
|
|
13909
13935
|
with: (definitions: {
|
|
13910
13936
|
name: string;
|
|
13911
13937
|
query: Sql;
|
|
13938
|
+
inlined?: boolean;
|
|
13912
13939
|
}[]) => Sql;
|
|
13913
13940
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13914
13941
|
};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $n as AutoGenerate, $r as ValidationErrorSource, $t as AccumulatedExtensionState, Ai as CacheConfigurationError, B as VariantToOneRelation, Bi as wrapError, Bn as ModelFieldRefs, Br as JsonNull, Ci as UniqueConstraintError, Cr as IsoDateSchema, Ct as s, Di as isNotNullConstraintError, Dr as EnumSchema, Dt as renderSchemaType, Ei as isForeignKeyError, Et as renderOperationResultType, F as LinkedClientConfig, Fi as VibORMError, Ft as VibORMClient, Gi as GeoPolygon, Gn as IndexOptions, H as BigIntScalar, Hi as GeoArea, Hn as isFieldRef, Hr as JsonNullSentinel, I as Links, Ii as VibORMErrorCode, It as VibORMConfig, Jn as Model, Ki as DecimalDescriptor, Kr as AnyRelation, Kt as NoControls, L as RelationLinks, Li as isRetryableError, Ln as StringSchema, Lr as AnyJsonNullSentinel, Lt as createClient, M as ClientSchema, Mi as CacheInvalidTTLError, Mt as ExtendedOperationResult, N as FlatSchema, Ni as CacheOperationNotCacheableError, Nr as BigIntSchema, Nt as ExtensionState, Oi as isUniqueConstraintError, Ot as validateOperationPayload, P as Linked, Pi as PrismaErrorCode, Qn as DecimalSchema, Qr as ValidationError, Qt as StatementHandler, R as ModelShape, Ri as isVibORMError, Rn as AnyFieldRef, Rr as AnyNull, Si as NotNullConstraintError, St as ModelToManyRelation, Ti as isCheckConstraintError, Tr as IsoTimestampSchema, Tt as getOperationPayloadSchema, Ui as GeoBounds, Un as AnyModel, Ur as isJsonNullSentinel, V as Scalar, Vi as DiagnosticDisclosure, Vn as createModelFieldRefs, Vr as JsonNullKind, Wi as GeoPoint, Wn as IndexDefinition, Xn as ModelState, Xr as RelationCardinality, Xt as defineExtension, Y as VibSchema, Yn as ModelInternal, Yr as ReferentialAction, Yt as ClientExtension, Zn as UpdateState, Zr as RelationSlot, Zt as StatementContext, _ as ObservationCompletion, _i as isUnsupportedOperationError, _n as UnwrapPendingOperation, _r as InputJsonValue, _t as DateScalar, ai as FeatureNotSupportedError, an as MergeExtensionState, ar as UpdateState$1, bi as CheckConstraintError, bt as ModelToOneRelation, ci as NestedWriteError, cn as validateSchemaOrThrow, cr as VectorSchema, ct as StringScalar, di as QueryEngineError, dn as SchemaValidationIssue, dr as ObjectSchema, dt as JsonScalar, ei as isValidationError, en as ClientExtensionState, fi as QueryError, fn as Severity, ft as IntScalar, gi as isPendingOperationError, gn as PendingOperation, gt as DateTimeScalar, hi as isNotFoundError, hr as NumberSchema, ht as TimeScalar, ii as ConnectionError, in as ExtensionResultConsumerState, ji as CacheInvalidKeyError, jr as BlobSchema, jt as ExtendedClient, ki as isValueTooLongError, kr as BooleanSchema, kt as ClientTypeState, li as NotFoundError, ln as SchemaValidationError, lt as PointScalar, mi as isClientInitializationError, mr as IntegerSchema, mt as DecimalScalar, ni as TransactionError, nn as ExtensionCacheState, nr as InitialScalarState, oi as ForbiddenError, on as RawOperation, ot as NumericScalar, pi as UnsupportedOperationError, pn as ValidationResult, pt as EnumScalar, qi as Decimal, qn as InitialModelState, qr as Getter, qt as PlacedControl, ri as ClientInitializationError, rn as ExtensionContributionState, rr as ScalarState, si as NestedWriteAssertionError, sn as validateSchema, st as VectorScalar, ti as InvalidTransactionInputError, tn as EmptyClientExtensionState, tr as GeneratorDefaultBrand, ui as PendingOperationError, un as isSchemaValidationError, ur as PointSchema, ut as NumberScalar, v as ObservationUnit, vi as MigrationError, vn as UnwrapPendingOperations, vr as JsonSchema, vt as BooleanScalar, wi as ValueTooLongError, wr as IsoTimeSchema, wt as getSchemas, xi as ForeignKeyError, xt as ReferencesStage, y as ObserveHandler, yi as isMigrationError, yn as isPendingOperation, yr as JsonValue, yt as BlobScalar, z as VariantToManyRelation, zi as toPrismaErrorCode, zn as FieldRef, zr as DbNull } from "./index-
|
|
2
|
-
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-
|
|
1
|
+
import { $n as AutoGenerate, $r as ValidationErrorSource, $t as AccumulatedExtensionState, Ai as CacheConfigurationError, B as VariantToOneRelation, Bi as wrapError, Bn as ModelFieldRefs, Br as JsonNull, Ci as UniqueConstraintError, Cr as IsoDateSchema, Ct as s, Di as isNotNullConstraintError, Dr as EnumSchema, Dt as renderSchemaType, Ei as isForeignKeyError, Et as renderOperationResultType, F as LinkedClientConfig, Fi as VibORMError, Ft as VibORMClient, Gi as GeoPolygon, Gn as IndexOptions, H as BigIntScalar, Hi as GeoArea, Hn as isFieldRef, Hr as JsonNullSentinel, I as Links, Ii as VibORMErrorCode, It as VibORMConfig, Jn as Model, Ki as DecimalDescriptor, Kr as AnyRelation, Kt as NoControls, L as RelationLinks, Li as isRetryableError, Ln as StringSchema, Lr as AnyJsonNullSentinel, Lt as createClient, M as ClientSchema, Mi as CacheInvalidTTLError, Mt as ExtendedOperationResult, N as FlatSchema, Ni as CacheOperationNotCacheableError, Nr as BigIntSchema, Nt as ExtensionState, Oi as isUniqueConstraintError, Ot as validateOperationPayload, P as Linked, Pi as PrismaErrorCode, Qn as DecimalSchema, Qr as ValidationError, Qt as StatementHandler, R as ModelShape, Ri as isVibORMError, Rn as AnyFieldRef, Rr as AnyNull, Si as NotNullConstraintError, St as ModelToManyRelation, Ti as isCheckConstraintError, Tr as IsoTimestampSchema, Tt as getOperationPayloadSchema, Ui as GeoBounds, Un as AnyModel, Ur as isJsonNullSentinel, V as Scalar, Vi as DiagnosticDisclosure, Vn as createModelFieldRefs, Vr as JsonNullKind, Wi as GeoPoint, Wn as IndexDefinition, Xn as ModelState, Xr as RelationCardinality, Xt as defineExtension, Y as VibSchema, Yn as ModelInternal, Yr as ReferentialAction, Yt as ClientExtension, Zn as UpdateState, Zr as RelationSlot, Zt as StatementContext, _ as ObservationCompletion, _i as isUnsupportedOperationError, _n as UnwrapPendingOperation, _r as InputJsonValue, _t as DateScalar, ai as FeatureNotSupportedError, an as MergeExtensionState, ar as UpdateState$1, bi as CheckConstraintError, bt as ModelToOneRelation, ci as NestedWriteError, cn as validateSchemaOrThrow, cr as VectorSchema, ct as StringScalar, di as QueryEngineError, dn as SchemaValidationIssue, dr as ObjectSchema, dt as JsonScalar, ei as isValidationError, en as ClientExtensionState, fi as QueryError, fn as Severity, ft as IntScalar, gi as isPendingOperationError, gn as PendingOperation, gt as DateTimeScalar, hi as isNotFoundError, hr as NumberSchema, ht as TimeScalar, ii as ConnectionError, in as ExtensionResultConsumerState, ji as CacheInvalidKeyError, jr as BlobSchema, jt as ExtendedClient, ki as isValueTooLongError, kr as BooleanSchema, kt as ClientTypeState, li as NotFoundError, ln as SchemaValidationError, lt as PointScalar, mi as isClientInitializationError, mr as IntegerSchema, mt as DecimalScalar, ni as TransactionError, nn as ExtensionCacheState, nr as InitialScalarState, oi as ForbiddenError, on as RawOperation, ot as NumericScalar, pi as UnsupportedOperationError, pn as ValidationResult, pt as EnumScalar, qi as Decimal, qn as InitialModelState, qr as Getter, qt as PlacedControl, ri as ClientInitializationError, rn as ExtensionContributionState, rr as ScalarState, si as NestedWriteAssertionError, sn as validateSchema, st as VectorScalar, ti as InvalidTransactionInputError, tn as EmptyClientExtensionState, tr as GeneratorDefaultBrand, ui as PendingOperationError, un as isSchemaValidationError, ur as PointSchema, ut as NumberScalar, v as ObservationUnit, vi as MigrationError, vn as UnwrapPendingOperations, vr as JsonSchema, vt as BooleanScalar, wi as ValueTooLongError, wr as IsoTimeSchema, wt as getSchemas, xi as ForeignKeyError, xt as ReferencesStage, y as ObserveHandler, yi as isMigrationError, yn as isPendingOperation, yr as JsonValue, yt as BlobScalar, z as VariantToManyRelation, zi as toPrismaErrorCode, zn as FieldRef, zr as DbNull } from "./index-B_jh2oaQ.mjs";
|
|
2
|
+
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-Q_twK-wW.mjs";
|
|
3
3
|
export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, type ClientTypeState, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain-B5IbqLGi.mjs";import{a as n,i as r,n as i,o as a,r as o,t as s}from"./base-D3m1S7Uc.mjs";import{i as c,n as l,r as u,t as d}from"./cache-CIPRF-pz.mjs";import{C as f,D as p,E as m,S as h,T as g,b as _,v,w as y,x as b,y as x}from"./error-mapping-6op318w6.mjs";import{n as S,t as C}from"./migrations-Bn1SatyB.mjs";import{_ as w,a as T,c as E,d as D,f as O,g as k,h as A,i as j,l as M,m as N,n as P,o as F,p as I,r as L,t as R,u as z,v as B}from"./validation-gwZYm3Yn.mjs";import{n as V,t as H}from"./transaction-4dfqals6.mjs";import{D as U,E as W,O as G,P as K,T as q,j as J,k as Y}from"./v-514RME2X.mjs";import{F as X}from"./geo-point-codec-D95uXgDF.mjs";import{a as Z,i as Q,n as $,o as ee,r as te,t as ne}from"./sql-BvHwL73I.mjs";import{C as re,S as ie}from"./scalar-Cm7nMFmO.mjs";import{a as ae,i as oe}from"./validator-CQOw7G3q.mjs";import{n as se}from"./builder-D6Ug-zjM.mjs";import{d as ce,m as le}from"./result-shape-BKydBCsR.mjs";import{t as ue}from"./client-BmcHzDBa.mjs";import{i as de,n as fe,r as pe,t as me}from"./schema-introspection-TdJrSaKd.mjs";import{t as he}from"./schema-D3-ScVH6.mjs";const getSchemas=e=>se(e).proxy;export{q as AnyNull,d as CacheConfigurationError,l as CacheInvalidKeyError,u as CacheInvalidTTLError,c as CacheOperationNotCacheableError,v as CheckConstraintError,L as ClientInitializationError,j as ConnectionError,W as DbNull,X as Decimal,T as FeatureNotSupportedError,F as ForbiddenError,x as ForeignKeyError,H as InvalidTransactionInputError,U as JsonNull,G as JsonNullSentinel,C as MigrationError,E as NestedWriteAssertionError,M as NestedWriteError,z as NotFoundError,_ as NotNullConstraintError,ce as PendingOperation,D as PendingOperationError,O as QueryEngineError,I as QueryError,ie as SchemaValidationError,ne as Sql,V as TransactionError,b as UniqueConstraintError,N as UnsupportedOperationError,R as ValidationError,h as ValueTooLongError,s as VibORMError,i as VibORMErrorCode,ue as createClient,J as createModelFieldRefs,t as defineExtension,$ as empty,me as getOperationPayloadSchema,getSchemas,f as isCheckConstraintError,A as isClientInitializationError,K as isFieldRef,y as isForeignKeyError,Y as isJsonNullSentinel,S as isMigrationError,k as isNotFoundError,g as isNotNullConstraintError,le as isPendingOperation,w as isPendingOperationError,o as isRetryableError,re as isSchemaValidationError,te as isSql,m as isUniqueConstraintError,B as isUnsupportedOperationError,P as isValidationError,p as isValueTooLongError,r as isVibORMError,Q as join,Z as raw,fe as renderOperationResultType,pe as renderSchemaType,he as s,ee as sql,n as toPrismaErrorCode,de as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,a as wrapError};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Fi as VibORMError, Vi as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-
|
|
1
|
+
import { Fi as VibORMError, Vi as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-B_jh2oaQ.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/instrumentation/types.d.ts
|
|
4
4
|
|
package/dist/instrumentation.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{p as r,t as i}from"./chain-7qiFSE8J.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-D3m1S7Uc.mjs";import{c as g,s as _,u as ee}from"./observation-Co72iCd1.mjs";import{t as te}from"./version-C8QLCt1n.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`)throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{l as r,t as i}from"./chain-B5IbqLGi.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-D3m1S7Uc.mjs";import{c as g,s as _,u as ee}from"./observation-Co72iCd1.mjs";import{t as te}from"./version-0RVYpih5.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`)throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
|
|
2
2
|
//# sourceMappingURL=instrumentation.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./cache-CIPRF-pz.mjs";import{M as n,P as r,_ as i,k as a}from"./v-
|
|
2
|
-
//# sourceMappingURL=key-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./cache-CIPRF-pz.mjs";import{M as n,P as r,_ as i,k as a}from"./v-514RME2X.mjs";import{r as o}from"./sql-BvHwL73I.mjs";const s=`viborm`,c=`${s}:cache`;function encodeText(e){let t=``;for(let n=0;n<e.length;n+=1)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t}function encodeVersion(e){if(e===void 0)return`u`;if(typeof e==`number`){let t=new Uint8Array(8);new DataView(t.buffer).setFloat64(0,e,!1);let n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return`n:${n}`}return`s:${encodeText(e)}`}function encodeNamespace(e){return e===void 0?`x`:`k:${encodeText(e)}`}function createOfficialCacheNamespace(e){return[c,`r4`,`d:${encodeText(e.dialect)}`,encodeNamespace(e.namespace),encodeVersion(e.version)].join(`:`)}function cacheLookupOf(e,t,n){let r=stableStringify(n);return{key:`${e}:${t}:${fastHash(r)}`,identity:JSON.stringify([e,t,r])}}function brandToken(e,t){return`viborm.${e}:${t}`}function stableStringify(e,i=new WeakSet){if(e===null)return`null`;if(e===void 0)return``;let s=typeof e;if(s===`boolean`||s===`number`)return String(e);if(s===`string`)return JSON.stringify(e);if(s===`bigint`)return brandToken(`bigint`,String(e));if(s!==`object`)throw new t(`Uncacheable value type: ${s}`);if(o(e)&&typeof e.toStatement==`function`)return brandToken(`sql`,`${JSON.stringify(e.toStatement(`?`))}:${stableStringify(e.values,i)}`);if(r(e)){let t=n(e);return brandToken(`field-ref`,`${JSON.stringify(t.model)}:${JSON.stringify(t.field)}`)}if(a(e))return brandToken(`json-null`,e.kind);if(e instanceof Date)return brandToken(`date`,e.toISOString());if(e instanceof Uint8Array){let t;if(typeof Buffer<`u`)t=Buffer.from(e).toString(`base64`);else{let n=``;for(let t of e)n+=String.fromCharCode(t);t=btoa(n)}return brandToken(`bytes`,t)}if(i.has(e))throw new t(`Circular reference in cache key args`);i.add(e);let c;if(Array.isArray(e))c=`[${e.map(e=>stableStringify(e,i)).join(`,`)}]`;else{let t=e;c=`{${Object.keys(t).sort().filter(e=>t[e]!==void 0).map(e=>`${JSON.stringify(e)}:${stableStringify(t[e],i)}`).join(`,`)}}`}return i.delete(e),c}function isCanonicalKeyData(e){try{return hasCanonicalForm(e,new Set)}catch{return!1}}function hasCanonicalForm(e,t){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:case`bigint`:return!0;case`number`:return Number.isFinite(e);case`object`:break;default:return!1}if(e instanceof Date)return!Number.isNaN(e.getTime());if(e instanceof Uint8Array)return!0;if(t.has(e)||!(Array.isArray(e)||i(e)))return!1;t.add(e);let n=Object.values(e).every(e=>hasCanonicalForm(e,t));return t.delete(e),n}function fastHash(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(n>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}export{isCanonicalKeyData as a,createOfficialCacheNamespace as i,c as n,stableStringify as o,cacheLookupOf as r,s as t};
|
|
2
|
+
//# sourceMappingURL=key-B89Z4vxn.mjs.map
|