viborm 1.3.2 → 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-B8XWzCev.mjs → adapter-namespace-CWLEmon2.mjs} +2 -2
- package/dist/{adapter-namespace-B8XWzCev.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-DoWlPD2h.mjs → batch-refs-DGJPz8-G.mjs} +2 -2
- package/dist/{batch-refs-DoWlPD2h.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-DhxaVYP2.mjs → builder-D6Ug-zjM.mjs} +2 -2
- package/dist/{builder-DhxaVYP2.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/{chain-BjJ_M7EE.mjs → chain-B5IbqLGi.mjs} +2 -2
- package/dist/{chain-BjJ_M7EE.mjs.map → chain-B5IbqLGi.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/client-BmcHzDBa.mjs +2 -0
- package/dist/client-BmcHzDBa.mjs.map +1 -0
- package/dist/{client-Df81J4oB.d.mts → client-DR0vYetv.d.mts} +2 -2
- package/dist/{client-q6ccRgdO.mjs → client-DjtWangN.mjs} +3 -3
- package/dist/{client-q6ccRgdO.mjs.map → client-DjtWangN.mjs.map} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +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-D6_Ik58x.mjs → driver-BvP7eW0A.mjs} +2 -2
- package/dist/{driver-D6_Ik58x.mjs.map → driver-BvP7eW0A.mjs.map} +1 -1
- package/dist/{driver-Ddt147dK.mjs → driver-Bzc0GCQ4.mjs} +2 -2
- package/dist/{driver-Ddt147dK.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-dpzVDwzu.mjs.map → every-WUr3mlvg.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-C2uXmJy6.mjs → hydration-BflrXEIQ.mjs} +2 -2
- package/dist/{hydration-C2uXmJy6.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
- package/dist/{identifier-conversion-C2pwwFOS.mjs → identifier-conversion-Bs7A2GGU.mjs} +2 -2
- package/dist/{identifier-conversion-C2pwwFOS.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map} +1 -1
- package/dist/{index-D4O0Twvs.d.mts → index-B_jh2oaQ.d.mts} +22 -3
- 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-B7vuAYPG.mjs → key-B89Z4vxn.mjs} +2 -2
- package/dist/{key-B7vuAYPG.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
- package/dist/{libsql-DUO6vHad.mjs → libsql-C8dn4id0.mjs} +2 -2
- package/dist/{libsql-DUO6vHad.mjs.map → libsql-C8dn4id0.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-BApsTkt1.mjs → memory-B7CcHS6I.mjs} +2 -2
- package/dist/{memory-BApsTkt1.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/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-D1GlcktG.mjs → mysql-mUmhH9Cf.mjs} +2 -2
- package/dist/{mysql-D1GlcktG.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-BN64q8Zn.d.mts → object-store-Ds9NKRU6.d.mts} +3 -3
- package/dist/permissions.d.mts +1 -1
- 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-CjvR0Ge2.mjs → pinned-session-C79aDzOg.mjs} +2 -2
- package/dist/{pinned-session-CjvR0Ge2.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-8smxUOt9.d.mts → planner-DHZG9Vy7.d.mts} +1 -1
- package/dist/{postgres-Be0jMJWI.mjs → postgres-BACQ_wqF.mjs} +2 -2
- package/dist/{postgres-Be0jMJWI.mjs.map → postgres-BACQ_wqF.mjs.map} +1 -1
- package/dist/{postgres-adapter-C_Mt8lVC.mjs → postgres-adapter-Ci07rgh_.mjs} +2 -2
- package/dist/{postgres-adapter-C_Mt8lVC.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-CYu1dyI_.mjs → postgres-result-D403cLyA.mjs} +2 -2
- package/dist/{postgres-result-CYu1dyI_.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-JXjhWwyb.mjs → rows-v1VuwOTa.mjs} +2 -2
- package/dist/{rows-JXjhWwyb.mjs.map → rows-v1VuwOTa.mjs.map} +1 -1
- package/dist/{scalar-CqqZ6jWd.mjs → scalar-Cm7nMFmO.mjs} +2 -2
- package/dist/{scalar-CqqZ6jWd.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-Cv-hhpl5.mjs → schema-D3-ScVH6.mjs} +2 -2
- package/dist/{schema-Cv-hhpl5.mjs.map → schema-D3-ScVH6.mjs.map} +1 -1
- package/dist/{schema-introspection-B2Rvqgut.mjs → schema-introspection-TdJrSaKd.mjs} +2 -2
- package/dist/{schema-introspection-B2Rvqgut.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-BxtETbG9.mjs → select-assembly-uZfvbYjz.mjs} +2 -2
- package/dist/select-assembly-uZfvbYjz.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.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-DIOll4P7.mjs → sqlite-utils-BvSlEs5W.mjs} +2 -2
- package/dist/{sqlite-utils-DIOll4P7.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-mJt0RHHE.mjs → standard-sql-CYdZ_KXH.mjs} +2 -2
- package/dist/standard-sql-CYdZ_KXH.mjs.map +1 -0
- package/dist/{to-many-BSipkSbK.mjs → to-many-Btc9X5Ga.mjs} +2 -2
- package/dist/{to-many-BSipkSbK.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
- package/dist/{utils-DjXObbUK.mjs → utils-Qr8ug94X.mjs} +2 -2
- package/dist/{utils-DjXObbUK.mjs.map → utils-Qr8ug94X.mjs.map} +1 -1
- package/dist/{v-CrJYqdzu.mjs → v-514RME2X.mjs} +2 -2
- package/dist/{v-CrJYqdzu.mjs.map → v-514RME2X.mjs.map} +1 -1
- 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-BqzpyNmt.mjs → validator-CQOw7G3q.mjs} +2 -2
- package/dist/{validator-BqzpyNmt.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
- package/dist/version-0RVYpih5.mjs +2 -0
- package/dist/{version-Dus3if78.mjs.map → version-0RVYpih5.mjs.map} +1 -1
- package/package.json +13 -13
- package/dist/client-BCgMXn6N.mjs +0 -2
- package/dist/client-BCgMXn6N.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-dpzVDwzu.mjs +0 -2
- package/dist/mysql-adapter-ClOoHKpn.mjs +0 -2
- package/dist/mysql-adapter-ClOoHKpn.mjs.map +0 -1
- package/dist/postgres-adapter-BoQ4RRwr.mjs +0 -2
- package/dist/postgres-adapter-BoQ4RRwr.mjs.map +0 -1
- package/dist/result-shape-DQc-tDJ5.mjs +0 -2
- package/dist/result-shape-DQc-tDJ5.mjs.map +0 -1
- package/dist/select-assembly-BxtETbG9.mjs.map +0 -1
- package/dist/sql-Bhxq9arK.mjs +0 -2
- package/dist/sql-Bhxq9arK.mjs.map +0 -1
- package/dist/sqlite-adapter-B_LNxPA0.mjs +0 -2
- package/dist/sqlite-adapter-B_LNxPA0.mjs.map +0 -1
- package/dist/standard-sql-mJt0RHHE.mjs.map +0 -1
- package/dist/validation-BamBwne9.mjs +0 -2
- package/dist/validation-BamBwne9.mjs.map +0 -1
- package/dist/version-Dus3if78.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-C2pwwFOS.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identifier-conversion-C2pwwFOS.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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Ae,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":"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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S,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,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
|
/**
|
|
@@ -12798,7 +12805,10 @@ interface DatabaseAdapter {
|
|
|
12798
12805
|
emptyArray: () => Sql;
|
|
12799
12806
|
/**
|
|
12800
12807
|
* Aggregate rows into a JSON array. An empty aggregate is the empty array,
|
|
12801
|
-
* 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.
|
|
12802
12812
|
*/
|
|
12803
12813
|
agg: (expr: Sql) => Sql;
|
|
12804
12814
|
/** Build JSON object from explicit column list (works on all databases) */
|
|
@@ -13035,10 +13045,16 @@ interface DatabaseAdapter {
|
|
|
13035
13045
|
* Common Table Expressions
|
|
13036
13046
|
*/
|
|
13037
13047
|
cte: {
|
|
13038
|
-
/**
|
|
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
|
+
*/
|
|
13039
13054
|
with: (definitions: {
|
|
13040
13055
|
name: string;
|
|
13041
13056
|
query: Sql;
|
|
13057
|
+
inlined?: boolean;
|
|
13042
13058
|
}[]) => Sql;
|
|
13043
13059
|
/**
|
|
13044
13060
|
* Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).
|
|
@@ -13391,6 +13407,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
|
|
|
13391
13407
|
with: (definitions: {
|
|
13392
13408
|
name: string;
|
|
13393
13409
|
query: Sql;
|
|
13410
|
+
inlined?: boolean;
|
|
13394
13411
|
}[]) => Sql;
|
|
13395
13412
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13396
13413
|
};
|
|
@@ -13628,6 +13645,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
|
|
|
13628
13645
|
with: (definitions: {
|
|
13629
13646
|
name: string;
|
|
13630
13647
|
query: Sql;
|
|
13648
|
+
inlined?: boolean;
|
|
13631
13649
|
}[]) => Sql;
|
|
13632
13650
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13633
13651
|
};
|
|
@@ -13917,6 +13935,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
|
|
|
13917
13935
|
with: (definitions: {
|
|
13918
13936
|
name: string;
|
|
13919
13937
|
query: Sql;
|
|
13938
|
+
inlined?: boolean;
|
|
13920
13939
|
}[]) => Sql;
|
|
13921
13940
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13922
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{a as t}from"./chain-
|
|
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{l as r,t as i}from"./chain-BjJ_M7EE.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-Dus3if78.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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"key-B7vuAYPG.mjs","names":[],"sources":["../src/cache/key.ts"],"sourcesContent":["/**\n * Cache Key Generation\n *\n * Generates deterministic cache keys from operation parameters.\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport { fieldRefPayload, isFieldRef } from \"@schema/field-ref\";\nimport { isJsonNullSentinel } from \"@schema/json-null\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { isSql } from \"@sql\";\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for authenticated official cache extensions. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r4\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n let encoded = \"\";\n for (let index = 0; index < value.length; index += 1) {\n encoded += value.charCodeAt(index).toString(16).padStart(4, \"0\");\n }\n return encoded;\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n let encoded = \"\";\n for (const byte of bytes) encoded += byte.toString(16).padStart(2, \"0\");\n return `n:${encoded}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * `x` unknown, `k:<hex>` known.\n *\n * An unknown namespace is a bare `x` with no body, so it cannot be reached by\n * encoding any string whatsoever — a database literally named `undefined`\n * encodes as `k:0075...`. Absence is a distinct value here, not a spelling.\n */\nfunction encodeNamespace(namespace: string | undefined): string {\n return namespace === undefined ? \"x\" : `k:${encodeText(namespace)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n encodeNamespace(facts.namespace),\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Build the versioned prefix\n */\nfunction buildPrefix(version?: string | number): string {\n return version !== undefined ? `${CACHE_PREFIX}:v${version}` : CACHE_PREFIX;\n}\n\n/** Hash for storage lookup, exact identity for collision verification. */\nexport function cacheLookupOf(\n model: string,\n operation: string,\n args: unknown\n): {\n readonly key: string;\n readonly identity: string;\n} {\n const serialized = stableStringify(args);\n return {\n key: `${model}:${operation}:${fastHash(serialized)}`,\n identity: JSON.stringify([model, operation, serialized]),\n };\n}\n\n/**\n * Generate a deterministic cache key from operation parameters\n *\n * Returns a FULLY PREFIXED key for external use (manual invalidation, etc.)\n *\n * Key structure: viborm[:v<version>]:<model>:<operation>:<hash>\n *\n * @example\n * generateCacheKey(\"user\", \"findMany\", { where: { active: true } })\n * // \"viborm:user:findMany:abc123...\"\n *\n * generateCacheKey(\"user\", \"findMany\", { where: { active: true } }, 2)\n * // \"viborm:v2:user:findMany:abc123...\"\n */\nexport function generateCacheKey(\n modelName: string,\n operation: string,\n args: unknown,\n version?: string | number\n): string {\n const prefix = buildPrefix(version);\n const argsHash = hashArgs(args);\n return `${prefix}:${modelName}:${operation}:${argsHash}`;\n}\n\n/**\n * Generate prefix for cache invalidation\n * Used to clear all cached queries for a model\n *\n * Returns a FULLY PREFIXED prefix for external use.\n */\nexport function generateCachePrefix(\n modelName?: string,\n version?: string | number\n): string {\n const prefix = buildPrefix(version);\n return modelName ? `${prefix}:${modelName}` : prefix;\n}\n\n/**\n * Generate a deterministic hash from query arguments\n */\nfunction hashArgs(args: unknown): string {\n const serialized = stableStringify(args);\n return fastHash(serialized);\n}\n\n/**\n * The two bytes that open and close a NON-JSON value's serialization: U+001F\n * (unit separator) and U+001E (record separator).\n *\n * They are what makes the token below UNFORGEABLE, and the reason is\n * mechanical: every string this serializer emits — operand values AND object\n * keys — goes through `JSON.stringify`, and JSON escapes every code point below\n * U+0020 into a printable six-character escape. A raw separator byte can\n * therefore never appear in the output by any route except the one deliberately\n * taken here, so a user document may spell the LETTERS of a token but never the\n * token. (Verified across the whole C0/C1 range, and for lone surrogates, by\n * the \"no JSON value can forge a brand token\" test.)\n */\nconst BRAND_OPEN = \"\\u001F\";\nconst BRAND_CLOSE = \"\\u001E\";\n\n/**\n * Serialize a value that is not a JSON value — one of the branded operand\n * tokens, or a scalar JSON cannot carry — into the reserved namespace.\n *\n * `namespace` names the KIND and `body` distinguishes two values of that kind;\n * the delimiters are balanced, so a token nested inside another token's body\n * (an `Sql` whose bound values hold a `Date`) stays unambiguous.\n */\nfunction brandToken(namespace: string, body: string): string {\n return `${BRAND_OPEN}viborm.${namespace}:${body}${BRAND_CLOSE}`;\n}\n\n/**\n * Stable JSON stringify that handles:\n * - Sorted object keys (deterministic)\n * - Date objects (ISO string)\n * - BigInt\n * - Uint8Array (base64)\n * - SQL fragments (statement text + bound values)\n * - Field references (the model and field they name)\n * - JSON null sentinels (`DbNull` / `JsonNull` / `AnyNull`)\n * - undefined values (omitted)\n * - Circular references (throws)\n *\n * It is only ever handed a VALIDATED payload (see\n * `PendingOperation.cacheKeyArgs`), so the non-JSON values it can meet are the\n * ones validation deliberately admits: a field reference, an SQL fragment, and\n * a JSON null sentinel. Admitted control values reach it only once\n * {@link isCanonicalKeyData} accepts them: in a read's key, and as the key of\n * the facts `rows` binds to a call's values (`extensions/rows.ts`).\n *\n * EVERY ONE OF THEM KEYS IN THE RESERVED NAMESPACE, because a user document is\n * allowed to look exactly like any of them. A JSON column takes an arbitrary\n * object, so `{ kind: \"DbNull\" }` is ordinary user data — and while the sentinel\n * carries `kind` as an own enumerable key precisely so a structural serializer\n * could tell the three apart, that only moved the collision one shape over:\n * walking `Object.keys` made `equals: DbNull` and `equals: { kind: \"DbNull\" }`\n * the same cache entry, and a cached client served one query's rows for the\n * other, in both directions, for the whole TTL.\n *\n * The sentinel is the one that collided in production spelling — a JSON filter\n * operand admits both a sentinel and an arbitrary document. The other two\n * cannot meet their look-alike at one position TODAY, and only because\n * validation holds those doors shut (`v.noFieldRef` refuses a reference\n * wherever arbitrary data is legal; `v.json` refuses a real `Sql` as\n * non-JSON-compatible) — while the fragment's look-alike still reached the\n * fragment branch and crashed there, see the note on it below. A key builder\n * that is correct only because a schema elsewhere is holding a door is one\n * refactor from being wrong again, so the rule here is structural instead:\n * what is not a JSON value does not serialize like one.\n */\nexport function stableStringify(\n value: unknown,\n seen = new WeakSet<object>()\n): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"\";\n\n const type = typeof value;\n\n if (type === \"boolean\" || type === \"number\") {\n return String(value);\n }\n\n if (type === \"string\") {\n return JSON.stringify(value);\n }\n\n if (type === \"bigint\") {\n return brandToken(\"bigint\", String(value));\n }\n\n if (type !== \"object\") {\n // Functions and symbols are not cacheable\n throw new CacheInvalidKeyError(`Uncacheable value type: ${type}`);\n }\n\n // A fragment is identified by what it will EMIT, not by its instance fields:\n // an `Sql` memoizes its flattened text on first read, so enumerating its own\n // properties would key the same fragment differently depending on whether\n // anything had compiled it yet.\n //\n // THE METHOD IS PART OF THE TEST because `isSql` is a duck-type probe\n // (`strings` and `values`, both arrays), and a JSON column may legally hold\n // `{ strings: [], values: [] }` — validation says so in as many words\n // (`v.noFieldRef`: such a document \"is honest user data and must stay\n // accepted\"). That document reached here as a fragment and threw a bare\n // `TypeError: value.toStatement is not a function` out of cache key\n // generation. A real fragment carries the method that flattens it and a\n // document cannot, because `v.json` refuses a function; so the look-alike\n // falls through to the object branch below and keys as the data it is.\n if (isSql(value) && typeof value.toStatement === \"function\") {\n return brandToken(\n \"sql\",\n `${JSON.stringify(value.toStatement(\"?\"))}:${stableStringify(value.values, seen)}`\n );\n }\n\n // A reference names a COLUMN: the model and field are its identity, and its\n // `type`/`list` are derived from them by `createModelFieldRefs`.\n if (isFieldRef(value)) {\n const payload = fieldRefPayload(value);\n return brandToken(\n \"field-ref\",\n `${JSON.stringify(payload.model)}:${JSON.stringify(payload.field)}`\n );\n }\n\n if (isJsonNullSentinel(value)) {\n return brandToken(\"json-null\", value.kind);\n }\n\n if (value instanceof Date) {\n return brandToken(\"date\", value.toISOString());\n }\n\n if (value instanceof Uint8Array) {\n // Use Buffer in Node.js, btoa in browser/edge\n let base64: string;\n if (typeof Buffer !== \"undefined\") {\n base64 = Buffer.from(value).toString(\"base64\");\n } else {\n let binary = \"\";\n for (const byte of value) {\n binary += String.fromCharCode(byte);\n }\n base64 = btoa(binary);\n }\n return brandToken(\"bytes\", base64);\n }\n\n // `seen` holds the objects on the current PATH only, as in\n // {@link isCanonicalKeyData}: one object reached twice through different\n // keys (`{ a: ids, b: ids }`) is data, not a cycle.\n if (seen.has(value as object))\n throw new CacheInvalidKeyError(\"Circular reference in cache key args\");\n seen.add(value as object);\n let serialized: string;\n if (Array.isArray(value)) {\n serialized = `[${value.map((v) => stableStringify(v, seen)).join(\",\")}]`;\n } else {\n const obj = value as Record<string, unknown>;\n const pairs = Object.keys(obj)\n .sort()\n .filter((k) => obj[k] !== undefined)\n .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k], seen)}`);\n serialized = `{${pairs.join(\",\")}}`;\n }\n seen.delete(value as object);\n return serialized;\n}\n\n/**\n * Whether {@link stableStringify} keys this value by its content: plain\n * records and arrays of JSON scalars, bigints, valid `Date`s and\n * `Uint8Array`s. A class instance would key as its own enumerable fields (a\n * `Map` as `{}`), a function or symbol throws, and a cycle throws; the caller\n * bypasses the cache for any of those rather than alias or fail. A value it\n * cannot inspect is not canonical either.\n */\nexport function isCanonicalKeyData(value: unknown): boolean {\n try {\n return hasCanonicalForm(value, new Set());\n } catch {\n return false;\n }\n}\n\nfunction hasCanonicalForm(value: unknown, seen: Set<object>): boolean {\n if (value === null) return true;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n case \"bigint\":\n return true;\n case \"number\":\n return Number.isFinite(value);\n case \"object\":\n break;\n default:\n return false;\n }\n // The two instance kinds `stableStringify` brands, tested as it tests them.\n if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (value instanceof Uint8Array) return true;\n if (seen.has(value)) return false;\n if (!(Array.isArray(value) || isPlainRecord(value))) return false;\n seen.add(value);\n const canonical = Object.values(value).every((entry) =>\n hasCanonicalForm(entry, seen)\n );\n seen.delete(value);\n return canonical;\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nfunction fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n"],"mappings":"mLAeA,MAAa,EAAe,SAGf,EAAgC,GAAG,EAAa,QA2C7D,SAAS,WAAW,EAAuB,CACzC,IAAI,EAAU,GACd,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EACjD,GAAW,EAAM,WAAW,EAAM,CAAC,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAElE,OAAO,EAIT,SAAS,cAAc,EAA8C,CACnE,GAAI,IAAY,IAAA,GAAW,MAAO,IAClC,GAAI,OAAO,GAAY,SAAU,CAC/B,IAAM,EAAQ,IAAI,WAAW,EAAE,CAC/B,IAAI,SAAS,EAAM,OAAO,CAAC,WAAW,EAAG,EAAS,GAAM,CACxD,IAAI,EAAU,GACd,IAAK,IAAM,KAAQ,EAAO,GAAW,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CACvE,MAAO,KAAK,IAEd,MAAO,KAAK,WAAW,EAAQ,GAUjC,SAAS,gBAAgB,EAAuC,C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AAI,EAAc,EAAM,EAAG,MAAO,GAC5D,EAAK,IAAI,EAAM,CACf,IAAM,EAAY,OAAO,OAAO,EAAM,CAAC,MAAO,GAC5C,iBAAiB,EAAO,EAAK,CAC9B,CAED,OADA,EAAK,OAAO,EAAM,CACX,EAOT,SAAS,SAAS,EAAqB,CACrC,IAAI,EAAK,WACL,EAAK,WAET,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,IAAK,CACnC,IAAM,EAAK,EAAI,WAAW,EAAE,CAE5B,EAAK,KAAK,KAAK,EAAK,EAAI,WAAc,CAEtC,EAAK,KAAK,KAAK,EAAK,EAAI,WAAc,CAYxC,MARA,GAAK,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,CAE/C,GAAM,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,CAEhD,EAAK,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,CAE/C,GAAM,KAAK,KAAK,EAAM,IAAO,GAAK,WAAc,EAI7C,IAAO,GAAG,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,EAEvC,IAAO,GACL,SAAS,GAAG,CACZ,SAAS,EAAG,IAAI"}
|
|
1
|
+
{"version":3,"file":"key-B89Z4vxn.mjs","names":[],"sources":["../src/cache/key.ts"],"sourcesContent":["/**\n * Cache Key Generation\n *\n * Generates deterministic cache keys from operation parameters.\n */\n\nimport { CacheInvalidKeyError } from \"@errors\";\nimport { fieldRefPayload, isFieldRef } from \"@schema/field-ref\";\nimport { isJsonNullSentinel } from \"@schema/json-null\";\nimport { isPlainRecord } from \"@schema/relation/terminal\";\nimport { isSql } from \"@sql\";\n\n/**\n * Prefix for all VibORM cache keys\n */\nexport const CACHE_PREFIX = \"viborm\";\n\n/** Namespace root reserved for authenticated official cache extensions. */\nexport const OFFICIAL_CACHE_NAMESPACE_ROOT = `${CACHE_PREFIX}:cache`;\n\n/**\n * Private storage-format revision. It moved r1 → r2 when the SQL namespace and\n * dialect entered the derivation below: every r1 entry keyed a scope that made\n * no claim about which schema or database produced the rows, so no r1 entry may\n * ever be served to an r2 reader. The bump is the invalidation.\n *\n * It moved r2 → r3 when a decimal became a value object. An r2 entry stored a\n * decimal's canonical text and MATERIALIZED it as that same string, which is\n * what an r2 reader's caller was handed; an r3 reader rebuilds a `Decimal` from\n * the identical bytes. The stored bytes did not change — their MEANING did, and\n * a reader that served the old bytes under the new contract would hand one\n * client a string where every other read gives it a value object. Same rule as\n * before: the bump is the invalidation.\n */\n// r4 entries carry their full canonical identity, checked before materialization.\nconst OFFICIAL_CACHE_SNAPSHOT_REVISION = \"r4\";\n\n/**\n * The facts one official cache scope partitions on.\n *\n * `dialect` is load-bearing on its own: a PostgreSQL schema `billing` and a\n * MySQL database `billing` are different stores that spell their qualifier the\n * same way. `namespace` is `undefined` for exactly the families the feature\n * leaves unqualified — SQLite and unbound MySQL/PlanetScale — and that absence\n * is encoded as its own token, never as text that a real namespace could spell.\n */\nexport interface OfficialCacheScopeFacts {\n readonly version: string | number | undefined;\n readonly dialect: string;\n readonly namespace: string | undefined;\n}\n\n/**\n * Encode text as fixed-width hex per UTF-16 code unit.\n *\n * Fixed width is what makes the joined namespace INJECTIVE: every component\n * below is either a bare discriminator letter or `<letter>:<hex>`, hex never\n * contains the `:` separator, and no variable-length body can absorb the\n * component after it. Two different fact tuples therefore cannot produce one\n * namespace, which is the whole isolation guarantee.\n */\nfunction encodeText(value: string): string {\n let encoded = \"\";\n for (let index = 0; index < value.length; index += 1) {\n encoded += value.charCodeAt(index).toString(16).padStart(4, \"0\");\n }\n return encoded;\n}\n\n/** `u` unversioned, `n:<f64 hex>` numeric, `s:<hex>` string. */\nfunction encodeVersion(version: string | number | undefined): string {\n if (version === undefined) return \"u\";\n if (typeof version === \"number\") {\n const bytes = new Uint8Array(8);\n new DataView(bytes.buffer).setFloat64(0, version, false);\n let encoded = \"\";\n for (const byte of bytes) encoded += byte.toString(16).padStart(2, \"0\");\n return `n:${encoded}`;\n }\n return `s:${encodeText(version)}`;\n}\n\n/**\n * `x` unknown, `k:<hex>` known.\n *\n * An unknown namespace is a bare `x` with no body, so it cannot be reached by\n * encoding any string whatsoever — a database literally named `undefined`\n * encodes as `k:0075...`. Absence is a distinct value here, not a spelling.\n */\nfunction encodeNamespace(namespace: string | undefined): string {\n return namespace === undefined ? \"x\" : `k:${encodeText(namespace)}`;\n}\n\n/**\n * Build the private namespace for one client-bound official cache extension.\n *\n * Pure: the same facts always give the same string, which is why re-binding the\n * chain after another extension is appended retains the scope by value instead\n * of needing a registry to hand the old one back.\n */\nexport function createOfficialCacheNamespace(\n facts: OfficialCacheScopeFacts\n): string {\n return [\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n OFFICIAL_CACHE_SNAPSHOT_REVISION,\n `d:${encodeText(facts.dialect)}`,\n encodeNamespace(facts.namespace),\n encodeVersion(facts.version),\n ].join(\":\");\n}\n\n/**\n * Build the versioned prefix\n */\nfunction buildPrefix(version?: string | number): string {\n return version !== undefined ? `${CACHE_PREFIX}:v${version}` : CACHE_PREFIX;\n}\n\n/** Hash for storage lookup, exact identity for collision verification. */\nexport function cacheLookupOf(\n model: string,\n operation: string,\n args: unknown\n): {\n readonly key: string;\n readonly identity: string;\n} {\n const serialized = stableStringify(args);\n return {\n key: `${model}:${operation}:${fastHash(serialized)}`,\n identity: JSON.stringify([model, operation, serialized]),\n };\n}\n\n/**\n * Generate a deterministic cache key from operation parameters\n *\n * Returns a FULLY PREFIXED key for external use (manual invalidation, etc.)\n *\n * Key structure: viborm[:v<version>]:<model>:<operation>:<hash>\n *\n * @example\n * generateCacheKey(\"user\", \"findMany\", { where: { active: true } })\n * // \"viborm:user:findMany:abc123...\"\n *\n * generateCacheKey(\"user\", \"findMany\", { where: { active: true } }, 2)\n * // \"viborm:v2:user:findMany:abc123...\"\n */\nexport function generateCacheKey(\n modelName: string,\n operation: string,\n args: unknown,\n version?: string | number\n): string {\n const prefix = buildPrefix(version);\n const argsHash = hashArgs(args);\n return `${prefix}:${modelName}:${operation}:${argsHash}`;\n}\n\n/**\n * Generate prefix for cache invalidation\n * Used to clear all cached queries for a model\n *\n * Returns a FULLY PREFIXED prefix for external use.\n */\nexport function generateCachePrefix(\n modelName?: string,\n version?: string | number\n): string {\n const prefix = buildPrefix(version);\n return modelName ? `${prefix}:${modelName}` : prefix;\n}\n\n/**\n * Generate a deterministic hash from query arguments\n */\nfunction hashArgs(args: unknown): string {\n const serialized = stableStringify(args);\n return fastHash(serialized);\n}\n\n/**\n * The two bytes that open and close a NON-JSON value's serialization: U+001F\n * (unit separator) and U+001E (record separator).\n *\n * They are what makes the token below UNFORGEABLE, and the reason is\n * mechanical: every string this serializer emits — operand values AND object\n * keys — goes through `JSON.stringify`, and JSON escapes every code point below\n * U+0020 into a printable six-character escape. A raw separator byte can\n * therefore never appear in the output by any route except the one deliberately\n * taken here, so a user document may spell the LETTERS of a token but never the\n * token. (Verified across the whole C0/C1 range, and for lone surrogates, by\n * the \"no JSON value can forge a brand token\" test.)\n */\nconst BRAND_OPEN = \"\\u001F\";\nconst BRAND_CLOSE = \"\\u001E\";\n\n/**\n * Serialize a value that is not a JSON value — one of the branded operand\n * tokens, or a scalar JSON cannot carry — into the reserved namespace.\n *\n * `namespace` names the KIND and `body` distinguishes two values of that kind;\n * the delimiters are balanced, so a token nested inside another token's body\n * (an `Sql` whose bound values hold a `Date`) stays unambiguous.\n */\nfunction brandToken(namespace: string, body: string): string {\n return `${BRAND_OPEN}viborm.${namespace}:${body}${BRAND_CLOSE}`;\n}\n\n/**\n * Stable JSON stringify that handles:\n * - Sorted object keys (deterministic)\n * - Date objects (ISO string)\n * - BigInt\n * - Uint8Array (base64)\n * - SQL fragments (statement text + bound values)\n * - Field references (the model and field they name)\n * - JSON null sentinels (`DbNull` / `JsonNull` / `AnyNull`)\n * - undefined values (omitted)\n * - Circular references (throws)\n *\n * It is only ever handed a VALIDATED payload (see\n * `PendingOperation.cacheKeyArgs`), so the non-JSON values it can meet are the\n * ones validation deliberately admits: a field reference, an SQL fragment, and\n * a JSON null sentinel. Admitted control values reach it only once\n * {@link isCanonicalKeyData} accepts them: in a read's key, and as the key of\n * the facts `rows` binds to a call's values (`extensions/rows.ts`).\n *\n * EVERY ONE OF THEM KEYS IN THE RESERVED NAMESPACE, because a user document is\n * allowed to look exactly like any of them. A JSON column takes an arbitrary\n * object, so `{ kind: \"DbNull\" }` is ordinary user data — and while the sentinel\n * carries `kind` as an own enumerable key precisely so a structural serializer\n * could tell the three apart, that only moved the collision one shape over:\n * walking `Object.keys` made `equals: DbNull` and `equals: { kind: \"DbNull\" }`\n * the same cache entry, and a cached client served one query's rows for the\n * other, in both directions, for the whole TTL.\n *\n * The sentinel is the one that collided in production spelling — a JSON filter\n * operand admits both a sentinel and an arbitrary document. The other two\n * cannot meet their look-alike at one position TODAY, and only because\n * validation holds those doors shut (`v.noFieldRef` refuses a reference\n * wherever arbitrary data is legal; `v.json` refuses a real `Sql` as\n * non-JSON-compatible) — while the fragment's look-alike still reached the\n * fragment branch and crashed there, see the note on it below. A key builder\n * that is correct only because a schema elsewhere is holding a door is one\n * refactor from being wrong again, so the rule here is structural instead:\n * what is not a JSON value does not serialize like one.\n */\nexport function stableStringify(\n value: unknown,\n seen = new WeakSet<object>()\n): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"\";\n\n const type = typeof value;\n\n if (type === \"boolean\" || type === \"number\") {\n return String(value);\n }\n\n if (type === \"string\") {\n return JSON.stringify(value);\n }\n\n if (type === \"bigint\") {\n return brandToken(\"bigint\", String(value));\n }\n\n if (type !== \"object\") {\n // Functions and symbols are not cacheable\n throw new CacheInvalidKeyError(`Uncacheable value type: ${type}`);\n }\n\n // A fragment is identified by what it will EMIT, not by its instance fields:\n // an `Sql` memoizes its flattened text on first read, so enumerating its own\n // properties would key the same fragment differently depending on whether\n // anything had compiled it yet.\n //\n // THE METHOD IS PART OF THE TEST because `isSql` is a duck-type probe\n // (`strings` and `values`, both arrays), and a JSON column may legally hold\n // `{ strings: [], values: [] }` — validation says so in as many words\n // (`v.noFieldRef`: such a document \"is honest user data and must stay\n // accepted\"). That document reached here as a fragment and threw a bare\n // `TypeError: value.toStatement is not a function` out of cache key\n // generation. A real fragment carries the method that flattens it and a\n // document cannot, because `v.json` refuses a function; so the look-alike\n // falls through to the object branch below and keys as the data it is.\n if (isSql(value) && typeof value.toStatement === \"function\") {\n return brandToken(\n \"sql\",\n `${JSON.stringify(value.toStatement(\"?\"))}:${stableStringify(value.values, seen)}`\n );\n }\n\n // A reference names a COLUMN: the model and field are its identity, and its\n // `type`/`list` are derived from them by `createModelFieldRefs`.\n if (isFieldRef(value)) {\n const payload = fieldRefPayload(value);\n return brandToken(\n \"field-ref\",\n `${JSON.stringify(payload.model)}:${JSON.stringify(payload.field)}`\n );\n }\n\n if (isJsonNullSentinel(value)) {\n return brandToken(\"json-null\", value.kind);\n }\n\n if (value instanceof Date) {\n return brandToken(\"date\", value.toISOString());\n }\n\n if (value instanceof Uint8Array) {\n // Use Buffer in Node.js, btoa in browser/edge\n let base64: string;\n if (typeof Buffer !== \"undefined\") {\n base64 = Buffer.from(value).toString(\"base64\");\n } else {\n let binary = \"\";\n for (const byte of value) {\n binary += String.fromCharCode(byte);\n }\n base64 = btoa(binary);\n }\n return brandToken(\"bytes\", base64);\n }\n\n // `seen` holds the objects on the current PATH only, as in\n // {@link isCanonicalKeyData}: one object reached twice through different\n // keys (`{ a: ids, b: ids }`) is data, not a cycle.\n if (seen.has(value as object))\n throw new CacheInvalidKeyError(\"Circular reference in cache key args\");\n seen.add(value as object);\n let serialized: string;\n if (Array.isArray(value)) {\n serialized = `[${value.map((v) => stableStringify(v, seen)).join(\",\")}]`;\n } else {\n const obj = value as Record<string, unknown>;\n const pairs = Object.keys(obj)\n .sort()\n .filter((k) => obj[k] !== undefined)\n .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k], seen)}`);\n serialized = `{${pairs.join(\",\")}}`;\n }\n seen.delete(value as object);\n return serialized;\n}\n\n/**\n * Whether {@link stableStringify} keys this value by its content: plain\n * records and arrays of JSON scalars, bigints, valid `Date`s and\n * `Uint8Array`s. A class instance would key as its own enumerable fields (a\n * `Map` as `{}`), a function or symbol throws, and a cycle throws; the caller\n * bypasses the cache for any of those rather than alias or fail. A value it\n * cannot inspect is not canonical either.\n */\nexport function isCanonicalKeyData(value: unknown): boolean {\n try {\n return hasCanonicalForm(value, new Set());\n } catch {\n return false;\n }\n}\n\nfunction hasCanonicalForm(value: unknown, seen: Set<object>): boolean {\n if (value === null) return true;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n case \"bigint\":\n return true;\n case \"number\":\n return Number.isFinite(value);\n case \"object\":\n break;\n default:\n return false;\n }\n // The two instance kinds `stableStringify` brands, tested as it tests them.\n if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (value instanceof Uint8Array) return true;\n if (seen.has(value)) return false;\n if (!(Array.isArray(value) || isPlainRecord(value))) return false;\n seen.add(value);\n const canonical = Object.values(value).every((entry) =>\n hasCanonicalForm(entry, seen)\n );\n seen.delete(value);\n return canonical;\n}\n\n/**\n * Fast non-cryptographic hash (djb2 variant)\n * Produces a 16-character hex string\n */\nfunction fastHash(str: string): string {\n let h1 = 0xde_ad_be_ef;\n let h2 = 0x41_c6_ce_57;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h1 = Math.imul(h1 ^ ch, 2_654_435_761);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash mixing requires 32-bit XOR.\n h2 = Math.imul(h2 ^ ch, 1_597_334_677);\n }\n\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3_266_489_909);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2_246_822_507);\n // biome-ignore lint/suspicious/noBitwiseOperators: Hash finalization requires 32-bit mixing.\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3_266_489_909);\n\n return (\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h2 >>> 0).toString(16).padStart(8, \"0\") +\n // biome-ignore lint/suspicious/noBitwiseOperators: Hex output requires unsigned 32-bit values.\n (h1 >>> 0)\n .toString(16)\n .padStart(8, \"0\")\n );\n}\n"],"mappings":"mLAeA,MAAa,EAAe,SAGf,EAAgC,GAAG,EAAa,QA2C7D,SAAS,WAAW,EAAuB,CACzC,IAAI,EAAU,GACd,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,EACjD,GAAW,EAAM,WAAW,EAAM,CAAC,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAElE,OAAO,EAIT,SAAS,cAAc,EAA8C,CACnE,GAAI,IAAY,IAAA,GAAW,MAAO,IAClC,GAAI,OAAO,GAAY,SAAU,CAC/B,IAAM,EAAQ,IAAI,WAAW,EAAE,CAC/B,IAAI,SAAS,EAAM,OAAO,CAAC,WAAW,EAAG,EAAS,GAAM,CACxD,IAAI,EAAU,GACd,IAAK,IAAM,KAAQ,EAAO,GAAW,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CACvE,MAAO,KAAK,IAEd,MAAO,KAAK,WAAW,EAAQ,GAUjC,SAAS,gBAAgB,EAAuC,CAC9D,OAAO,IAAc,IAAA,GAAY,IAAM,KAAK,WAAW,EAAU,GAUnE,SAAgB,6BACd,EACQ,CACR,MAAO,CACL,EACA,KACA,KAAK,WAAW,EAAM,QAAQ,GAC9B,gBAAgB,EAAM,UAAU,CAChC,cAAc,EAAM,QAAQ,CAC7B,CAAC,KAAK,IAAI,CAWb,SAAgB,cACd,EACA,EACA,EAIA,CACA,IAAM,EAAa,gBAAgB,EAAK,CAC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