viborm 1.3.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
- package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
- package/dist/{adapter-namespace-B8XWzCev.mjs → adapter-namespace-BLejG8FA.mjs} +2 -2
- package/dist/{adapter-namespace-B8XWzCev.mjs.map → adapter-namespace-BLejG8FA.mjs.map} +1 -1
- package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
- package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/{batch-refs-DoWlPD2h.mjs → batch-refs-BYCu1JnQ.mjs} +2 -2
- package/dist/{batch-refs-DoWlPD2h.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
- package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
- package/dist/builder-BS8EW4BQ.mjs +2 -0
- package/dist/builder-BS8EW4BQ.mjs.map +1 -0
- package/dist/bun-sql.d.mts +3 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
- package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
- package/dist/chain-D5J9hIw-.mjs +2 -0
- package/dist/chain-D5J9hIw-.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/client-Bhl2mWam.mjs +2 -0
- package/dist/client-Bhl2mWam.mjs.map +1 -0
- package/dist/{client-Df81J4oB.d.mts → client-BzgBm_86.d.mts} +4 -2
- package/dist/{client-q6ccRgdO.mjs → client-aU3YhZ6G.mjs} +16 -16
- package/dist/client-aU3YhZ6G.mjs.map +1 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
- package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/datetime-physical-codec-lX7IJBlz.mjs +2 -0
- package/dist/datetime-physical-codec-lX7IJBlz.mjs.map +1 -0
- package/dist/driver-CQQbCQh9.mjs +2 -0
- package/dist/{driver-Ddt147dK.mjs.map → driver-CQQbCQh9.mjs.map} +1 -1
- package/dist/{driver-D6_Ik58x.mjs → driver-u2qJicrE.mjs} +2 -2
- package/dist/{driver-D6_Ik58x.mjs.map → driver-u2qJicrE.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-CzF00eDV.mjs +2 -0
- package/dist/{every-dpzVDwzu.mjs.map → every-CzF00eDV.mjs.map} +1 -1
- package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
- package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.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-Dc0Rf4Gi.mjs} +2 -2
- package/dist/{identifier-conversion-C2pwwFOS.mjs.map → identifier-conversion-Dc0Rf4Gi.mjs.map} +1 -1
- package/dist/identity-CmRos0Yf.mjs +2 -0
- package/dist/identity-CmRos0Yf.mjs.map +1 -0
- package/dist/{index-D4O0Twvs.d.mts → index-B4IWFJfv.d.mts} +1304 -1056
- 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/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
- package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +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-CrDXsfpL.mjs} +2 -2
- package/dist/{libsql-DUO6vHad.mjs.map → libsql-CrDXsfpL.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-BApsTkt1.mjs → memory-TXO4KgBy.mjs} +2 -2
- package/dist/{memory-BApsTkt1.mjs.map → memory-TXO4KgBy.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-D1GlcktG.mjs → mysql-C2vOPcuA.mjs} +2 -2
- package/dist/{mysql-D1GlcktG.mjs.map → mysql-C2vOPcuA.mjs.map} +1 -1
- package/dist/mysql-adapter-C5CMIYRS.mjs +2 -0
- package/dist/mysql-adapter-C5CMIYRS.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +3 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-BF7gr4_b.mjs +2 -0
- package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
- package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
- package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
- package/dist/{object-store-BN64q8Zn.d.mts → object-store-uRqi0URP.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 +26 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +3 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{physical-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-FYOFV_gB.mjs} +2 -2
- package/dist/{pinned-session-CjvR0Ge2.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-8smxUOt9.d.mts → planner-SzkGh-3T.d.mts} +1 -1
- package/dist/{postgres-Be0jMJWI.mjs → postgres-BSmy1PYR.mjs} +2 -2
- package/dist/{postgres-Be0jMJWI.mjs.map → postgres-BSmy1PYR.mjs.map} +1 -1
- package/dist/postgres-adapter-B1RyJlWL.mjs +2 -0
- package/dist/postgres-adapter-B1RyJlWL.mjs.map +1 -0
- package/dist/postgres-adapter-BAqRfWl1.mjs +2 -0
- package/dist/postgres-adapter-BAqRfWl1.mjs.map +1 -0
- package/dist/postgres-result-BCUQf8b_.mjs +2 -0
- package/dist/{postgres-result-CYu1dyI_.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
- package/dist/postgres.d.mts +3 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-V09frtmK.mjs} +2 -2
- package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-V09frtmK.mjs.map} +1 -1
- package/dist/relation-bound-BrZLsSke.mjs +2 -0
- package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
- package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
- package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
- package/dist/result-shape-Fi1-Fvri.mjs +2 -0
- package/dist/result-shape-Fi1-Fvri.mjs.map +1 -0
- package/dist/{rows-JXjhWwyb.mjs → rows-BiaiswSV.mjs} +2 -2
- package/dist/{rows-JXjhWwyb.mjs.map → rows-BiaiswSV.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-introspection-B2Rvqgut.mjs → schema-introspection-C1-XrQP4.mjs} +2 -2
- package/dist/{schema-introspection-B2Rvqgut.mjs.map → schema-introspection-C1-XrQP4.mjs.map} +1 -1
- package/dist/{schema-Cv-hhpl5.mjs → schema-tGtziyCJ.mjs} +2 -2
- package/dist/{schema-Cv-hhpl5.mjs.map → schema-tGtziyCJ.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-BjT_fDbu.mjs +2 -0
- package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
- package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
- package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
- package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +3 -3
- package/dist/sql-BvHwL73I.mjs +2 -0
- package/dist/sql-BvHwL73I.mjs.map +1 -0
- package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
- package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CoDeF2h2.mjs +2 -0
- package/dist/sqlite-adapter-CoDeF2h2.mjs.map +1 -0
- package/dist/{sqlite-utils-DIOll4P7.mjs → sqlite-utils-C0TyzOys.mjs} +2 -2
- package/dist/{sqlite-utils-DIOll4P7.mjs.map → sqlite-utils-C0TyzOys.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/{standard-sql-mJt0RHHE.mjs → standard-sql-DmKF8msN.mjs} +2 -2
- package/dist/standard-sql-DmKF8msN.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/transaction-operation-CU1zlxiG.mjs.map +1 -1
- package/dist/{utils-DjXObbUK.mjs → utils-DkAxKcDD.mjs} +2 -2
- package/dist/{utils-DjXObbUK.mjs.map → utils-DkAxKcDD.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-C7Z6wTJa.mjs} +2 -2
- package/dist/{validation-BQtO6srU.mjs.map → validation-C7Z6wTJa.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-n393hhwM.mjs +2 -0
- package/dist/{version-Dus3if78.mjs.map → version-n393hhwM.mjs.map} +1 -1
- package/package.json +14 -14
- package/dist/bind-parameter-capacity-qfEejeOX.mjs +0 -2
- package/dist/bind-parameter-capacity-qfEejeOX.mjs.map +0 -1
- package/dist/builder-DhxaVYP2.mjs +0 -2
- package/dist/builder-DhxaVYP2.mjs.map +0 -1
- package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
- package/dist/chain-BjJ_M7EE.mjs +0 -2
- package/dist/chain-BjJ_M7EE.mjs.map +0 -1
- package/dist/client-BCgMXn6N.mjs +0 -2
- package/dist/client-BCgMXn6N.mjs.map +0 -1
- package/dist/client-q6ccRgdO.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/driver-Ddt147dK.mjs +0 -2
- package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
- package/dist/every-dpzVDwzu.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs +0 -2
- package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
- 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/postgres-adapter-C_Mt8lVC.mjs +0 -2
- package/dist/postgres-adapter-C_Mt8lVC.mjs.map +0 -1
- package/dist/postgres-result-CYu1dyI_.mjs +0 -2
- 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 +0 -2
- 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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chain-D5J9hIw-.mjs","names":["readOwn","isPlainRecord","rewritten","ownKeys"],"sources":["../src/drivers/driver-identity.ts","../src/client/default-omit-extension.ts","../src/client/omit.ts","../src/extensions/result.ts","../src/extensions/definition.ts","../src/extensions/chain.ts"],"sourcesContent":["import type { Dialect } from \"./types\";\n\n/**\n * The configuration facts that name one driver in presented telemetry. No\n * package entry exports this module.\n *\n * `namespace` is the adapter's one normalized SQL qualifier and is absent when\n * the adapter is unqualified. `adapter.namespace` is installed non-writable,\n * so a snapshot taken once (the cached read's, at `$withCache`) cannot go\n * stale. This is the one reader of that property for presentation.\n */\nexport interface DriverIdentity {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly namespace?: string;\n}\n\n/** The public readonly driver fields an identity is read from. */\nexport interface DriverIdentitySource {\n readonly dialect: Dialect;\n readonly driverName: string;\n readonly adapter: { readonly namespace?: string };\n}\n\n/**\n * Read one driver's identity from its public readonly configuration, or\n * `undefined` when that read throws (a custom adapter's `namespace` getter):\n * every presenter then omits the driver attributes and presents the rest.\n */\nexport function readDriverIdentity(\n driver: DriverIdentitySource\n): DriverIdentity | undefined {\n try {\n const namespace = driver.adapter.namespace;\n return Object.freeze({\n dialect: driver.dialect,\n driverName: driver.driverName,\n ...(namespace === undefined ? {} : { namespace }),\n });\n } catch {\n // The operation's facts, its spans and a cached read's revalidation\n // identity survive a driver that cannot name itself.\n return undefined;\n }\n}\n","import { ClientInitializationError } from \"@errors\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type {\n GenericRequestHandler,\n OfficialGenericRequestHandler,\n} from \"@extensions/request\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ClientOmitConfig, ExactClientOmitConfig } from \"./omit\";\nimport type { Schema } from \"./types\";\n\nexport const OFFICIAL_DEFAULT_OMIT_NAME = \"viborm.defaultOmit\";\n\ndeclare const officialDefaultOmitConfig: unique symbol;\n\n/** The authenticated request identity carrying one exact static omit witness. */\nexport type OfficialDefaultOmitRequestContribution<Config> =\n OfficialGenericRequestHandler & {\n readonly [officialDefaultOmitConfig]: Config;\n bind(thisArg: unknown): GenericRequestHandler;\n };\n\n/** The official value accepted by the dedicated `$extends` admission branch. */\nexport type OfficialDefaultOmitExtension<Config extends object = object> = {\n readonly name: typeof OFFICIAL_DEFAULT_OMIT_NAME;\n readonly request: OfficialDefaultOmitRequestContribution<Config>;\n};\n\nexport interface OfficialDefaultOmitCapability {\n readonly config: ClientOmitConfig<Schema>;\n}\n\nconst capabilitiesByRequest = new WeakMap<\n CallableFunction,\n OfficialDefaultOmitCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialDefaultOmitCapability\n>();\n\nfunction configurationError(message: string, cause?: unknown): never {\n throw new ClientInitializationError(message, {\n cause: cause === undefined ? undefined : errorCause(cause),\n });\n}\n\nfunction ownKeys(value: object, label: string): PropertyKey[] {\n try {\n return Reflect.ownKeys(value);\n } catch (cause) {\n configurationError(\n `Default omit ${label} members could not be inspected.`,\n cause\n );\n }\n}\n\nfunction readOwn(\n value: Record<string, unknown>,\n key: string,\n label: string\n): unknown {\n try {\n return value[key];\n } catch (cause) {\n configurationError(\n `Default omit ${label} member \"${key}\" could not be read.`,\n cause\n );\n }\n}\n\nfunction isConfigurationRecord(\n value: unknown,\n label: string\n): value is Record<string, unknown> {\n try {\n return isRecord(value);\n } catch (cause) {\n configurationError(`Default omit ${label} could not be inspected.`, cause);\n }\n}\n\nfunction snapshotConfig(value: unknown): ClientOmitConfig<Schema> {\n if (!isConfigurationRecord(value, \"configuration\")) {\n configurationError(\"Default omit configuration must be an object.\");\n }\n const snapshot: Record<\n string,\n Readonly<Record<string, true>>\n > = Object.create(null);\n for (const modelKey of ownKeys(value, \"configuration\")) {\n if (typeof modelKey !== \"string\") {\n configurationError(\n \"Default omit configuration contains a non-string model key.\"\n );\n }\n const entry = readOwn(value, modelKey, \"configuration\");\n if (!isConfigurationRecord(entry, `configuration.${modelKey}`)) {\n configurationError(\n `Default omit configuration member \"${modelKey}\" must be an object.`\n );\n }\n const fields: Record<string, true> = Object.create(null);\n for (const fieldKey of ownKeys(entry, `configuration.${modelKey}`)) {\n if (typeof fieldKey !== \"string\") {\n configurationError(\n `Default omit configuration member \"${modelKey}\" contains a non-string field key.`\n );\n }\n if (readOwn(entry, fieldKey, `configuration.${modelKey}`) !== true) {\n configurationError(\n `Default omit configuration member \"${modelKey}.${fieldKey}\" must be true.`\n );\n }\n fields[fieldKey] = true;\n }\n snapshot[modelKey] = Object.freeze(fields);\n }\n return Object.freeze(snapshot);\n}\n\nexport type DefaultOmitBinder<S extends Schema> = <\n const Config extends ClientOmitConfig<S>,\n>(\n config: Config & NoInfer<ExactClientOmitConfig<Config, S>>\n) => OfficialDefaultOmitExtension<Config & object>;\n\n/** Create VibORM's fixed-name schema-bound default-omit extension. */\nexport function defaultOmit<S extends Schema>(): DefaultOmitBinder<S>;\nexport function defaultOmit(): unknown {\n return (config: unknown): unknown => {\n const capability = Object.freeze({ config: snapshotConfig(config) });\n const request: GenericRequestHandler = () => ({});\n capabilitiesByRequest.set(request, capability);\n return Object.freeze({\n name: OFFICIAL_DEFAULT_OMIT_NAME,\n request,\n });\n };\n}\n\nexport function getOfficialDefaultOmitRequestCapability(\n request: unknown\n): OfficialDefaultOmitCapability | undefined {\n return isFunction(request) ? capabilitiesByRequest.get(request) : undefined;\n}\n\nexport function getOfficialDefaultOmitChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialDefaultOmitCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialDefaultOmitChain(\n chain: ResolvedExtensionChain,\n capability: OfficialDefaultOmitCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n","/**\n * CLIENT-LEVEL `omit` — `defaultOmit()({ user: { passwordHash: true } })`.\n *\n * A per-client DEFAULT, not a schema rule. It is applied by rewriting the\n * payload before validation: every node that will produce a row of a configured\n * model gains the configured `omit`, unless the caller already spoke about that\n * node's projection. From there it is an ordinary query-level `omit` and travels\n * the one path that exists (`withOmitProjection` desugars it into `select`).\n *\n * Why rewrite the ARGS instead of teaching the engine a second default? Because\n * the schemas are shared: two clients over the same models must accept exactly\n * the same payloads, and a per-client default that changed what VALIDATES would\n * break that. Rewriting args keeps the client option where it belongs — a\n * default for what a query did not say — and leaves one implementation of the\n * projection itself.\n *\n * PRECEDENCE, in the order the rules fire:\n * 1. an explicit `select` on the node overrides the CLIENT default: nothing\n * global is injected there, while a query-level `omit` still subtracts;\n * 2. the node's own `omit` wins per FIELD: `{ passwordHash: false }` re-includes\n * a globally omitted column, `{ other: true }` adds to the default;\n * 3. otherwise the client default applies as written.\n *\n * Model-level `.omit()` is above all three and is not represented here at all —\n * those fields have no `omit` key to name (see\n * `src/validation/model/core/projection.ts`).\n *\n * COST. A client without the official extension never builds a resolver or\n * calls `applyClientOmit`. With the extension, one shallow walk of the\n * `select`/`include` tree runs per query, copying only the nodes it changes.\n */\n\nimport { VibORMError, VibORMErrorCode } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n ResolvedRelationIndex,\n ResolvedSlot,\n ResolvedVariantEdge,\n} from \"@schema/validation/relation-resolution\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport { isRecord as isPlainRecord } from \"@validation/value-guards\";\nimport type { Operations } from \"./types\";\n\n/** Fields a client hides by default, per model key of the schema. */\nexport type ClientOmitConfig<S extends Record<string, AnyModel>> = {\n [K in keyof S]?: ClientModelOmit<S[K]>;\n};\n\n/**\n * The scalars of `M` a client may hide — every scalar except the ones the\n * MODEL already hides for good (naming one of those has no `omit` key to name;\n * see `@validation/model/core/projection`).\n *\n * The `any` arm is not decoration. A schema-generic extension sees\n * `Model<any>`, whose `scalars` is `any` — and the subtraction above would then\n * cancel to `never`, leaving `Partial<Record<never, true>>`, a config object\n * with no known properties. Answering `string` preserves the contextual\n * literal `true` until a concrete schema binds the official extension.\n */\ntype ProjectableKeysOf<M extends AnyModel> = 0 extends 1 &\n M[\"~\"][\"state\"][\"scalars\"]\n ? string\n : Extract<\n Exclude<\n keyof M[\"~\"][\"state\"][\"scalars\"],\n M[\"~\"][\"state\"][\"omit\"] extends Record<string, true>\n ? keyof M[\"~\"][\"state\"][\"omit\"]\n : never\n >,\n string\n >;\n\n/**\n * The fields one model hides by default, each flagged `true`.\n *\n * `true` only — not `boolean`. Two reasons, and they are the same reason:\n * - a `false` here would be a key that does nothing (the resolver only ever\n * acts on `=== true`), and a config key that silently does nothing is the\n * shape this codebase refuses; per-field re-inclusion belongs on the QUERY\n * (`omit: { passwordHash: false }`), which is where it can be undone;\n * - `boolean` as the contextual type widens the `true` a caller writes, and a\n * widened flag is a flag the RESULT TYPE cannot resolve — it would render\n * `passwordHash?: string` on a client that hides the column outright.\n */\nexport type ClientModelOmit<M extends AnyModel> = Partial<\n Record<ProjectableKeysOf<M>, true>\n>;\n\ntype ClientOmitKeys<Value> = Value extends unknown ? keyof Value : never;\n\ntype ClientOmitEntry<\n Given,\n ModelName extends PropertyKey,\n> = Given extends unknown\n ? ModelName extends keyof Given\n ? Given[ModelName]\n : never\n : never;\n\n/** Structural exactness for a direct client-default omit configuration. */\nexport type ExactClientOmitConfig<\n Given,\n S extends Record<string, AnyModel>,\n> = Record<Exclude<ClientOmitKeys<Given>, keyof S>, never> & {\n [ModelName in Extract<ClientOmitKeys<Given>, keyof S>]?: Record<\n Exclude<\n ClientOmitKeys<ClientOmitEntry<Given, ModelName>>,\n keyof ClientModelOmit<S[ModelName]>\n >,\n never\n >;\n};\n\n/**\n * Resolves a model to the fields this client hides by default, and carries the\n * one resolved topology index the recursion walks.\n *\n * The index travels WITH the resolver because the two are used together at every\n * node and are settled together when the official extension is applied: the\n * resolver answers \"which columns\", the index answers \"which model is on the\n * other side of this key\" — without invoking a target getter (§11.4.11).\n */\nexport interface ClientOmitResolver {\n /** The fields this client hides by default for one model. */\n readonly omit: (model: AnyModel) => Record<string, boolean> | undefined;\n readonly relations: ResolvedRelationIndex;\n}\n\nconst hasEntries = (value: Record<string, boolean>): boolean =>\n Object.keys(value).length > 0;\n\n/**\n * Build the model → default-omit lookup, or `undefined` when the client\n * configured nothing worth walking for. Keyed by model IDENTITY so a nested\n * relation resolves through its `ResolvedSlot` target without a name\n * round-trip.\n */\nexport const createClientOmitResolver = <S extends Record<string, AnyModel>>(\n schema: S,\n config: ClientOmitConfig<S>,\n relations: ResolvedRelationIndex\n): ClientOmitResolver | undefined => {\n const byModel = new Map<AnyModel, Record<string, boolean>>();\n for (const key of Object.keys(config)) {\n const model = Object.hasOwn(schema, key) ? schema[key] : undefined;\n const entry = config[key as keyof ClientOmitConfig<S>];\n // A config naming a model or field that does not exist is a typo the\n // resolver would otherwise carry silently. The official factory owns\n // structural exactness; this runtime boundary owns hostile JavaScript.\n if (!model) {\n throw new VibORMError(\n `Client 'omit' names model '${key}', which is not in the schema.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: key } }\n );\n }\n if (!isPlainRecord(entry)) continue;\n const projectable = new Set(projectableScalarNames(model));\n const flags: Record<string, boolean> = {};\n for (const field of Object.keys(entry)) {\n if (!projectable.has(field)) {\n throw new VibORMError(\n `Client 'omit' names field '${field}' on model '${key}', which is not a readable scalar of that model.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: key, field } }\n );\n }\n if (entry[field] === true) flags[field] = true;\n }\n if (hasEntries(flags)) byModel.set(model, flags);\n }\n if (byModel.size === 0) return undefined;\n return { omit: (model: AnyModel) => byModel.get(model), relations };\n};\n\n/**\n * The operations whose top-level payload is a model row (or rows). A bulk write\n * is NOT here: it answers `{ count }` unless the CALLER asked for a projection,\n * and a client default must never be what flips a return shape. Its nested\n * nodes are covered anyway — a bulk write projects scalars only.\n */\nexport const PROJECTING_OPERATIONS: ReadonlySet<string> = new Set([\n \"findFirst\",\n \"findFirstOrThrow\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"create\",\n \"update\",\n \"upsert\",\n \"delete\",\n]);\n\n/** A bulk write already carrying a projection: the caller opted into rows. */\nconst bulkWriteProjects = (\n operation: string,\n args: Record<string, unknown>\n): boolean =>\n (operation === \"createMany\" ||\n operation === \"updateMany\" ||\n operation === \"deleteMany\") &&\n args.omit !== undefined;\n\n/**\n * Rewrite one payload so every projecting node carries the client defaults.\n * Returns the SAME object when nothing changed, so an unaffected query is not\n * copied.\n */\nexport const applyClientOmit = (\n model: AnyModel,\n operation: Operations | string,\n args: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const projects =\n PROJECTING_OPERATIONS.has(operation) || bulkWriteProjects(operation, args);\n if (!projects) return args;\n return rewriteNode(model, args, resolve);\n};\n\n/**\n * One node of the projection tree. `select` present means the caller stated the\n * projection, so the client default is not injected. The node's own `omit`\n * remains for validation to subtract, and relation children are still visited.\n */\nconst rewriteNode = (\n model: AnyModel,\n node: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const selectValue = node.select;\n const includeValue = node.include;\n const hasSelect = isPlainRecord(selectValue);\n\n const nextSelect = hasSelect\n ? rewriteRelationMap(model, selectValue, resolve)\n : selectValue;\n const nextInclude = isPlainRecord(includeValue)\n ? rewriteRelationMap(model, includeValue, resolve)\n : includeValue;\n\n const defaults = hasSelect ? undefined : resolve.omit(model);\n const nextOmit = defaults ? mergeOmit(defaults, node.omit) : node.omit;\n\n if (\n nextSelect === selectValue &&\n nextInclude === includeValue &&\n nextOmit === node.omit\n ) {\n return node;\n }\n\n const next: Record<string, unknown> = { ...node };\n if (nextSelect !== selectValue) next.select = nextSelect;\n if (nextInclude !== includeValue) next.include = nextInclude;\n if (nextOmit !== node.omit) next.omit = nextOmit;\n return next;\n};\n\n/**\n * The client defaults with the caller's own `omit` layered on top, per field —\n * so `{ passwordHash: false }` re-includes exactly one globally hidden column\n * and leaves the rest hidden. Returns the caller's value untouched when it\n * already overrides every default (nothing to add).\n */\nconst mergeOmit = (\n defaults: Record<string, boolean>,\n local: unknown\n): Record<string, unknown> => {\n if (!isPlainRecord(local)) return { ...defaults };\n const merged: Record<string, unknown> = { ...defaults };\n for (const field of Object.keys(local)) merged[field] = local[field];\n return merged;\n};\n\n/**\n * Visit the relation entries of a `select`/`include` map. A bare `true` is\n * promoted to `{ omit: … }` only when the target model has defaults — otherwise\n * the shorthand is left exactly as written, which keeps the payload (and its\n * cache key) identical for the models nobody configured.\n */\nconst rewriteRelationMap = (\n model: AnyModel,\n map: Record<string, unknown>,\n resolve: ClientOmitResolver\n): Record<string, unknown> => {\n const slots = resolve.relations.get(model);\n let changed = false;\n const next: Record<string, unknown> = { ...map };\n\n for (const key of Object.keys(map)) {\n const resolved = slots?.get(key);\n if (!resolved) continue;\n const value = map[key];\n\n // ONE index, split here by the settled EDGE: a direct variant carrier spans\n // several targets and projects a tagged envelope; every other slot — an\n // ordinary pair, or a bound inverse view of one carrier member — reaches\n // exactly one model.\n const carrier = directVariantCarrier(resolved);\n if (carrier) {\n const rewritten = rewriteVariantCarrier(carrier, value, resolve);\n if (rewritten !== value) {\n next[key] = rewritten;\n changed = true;\n }\n continue;\n }\n\n const target = slotTarget(resolved, model);\n if (!target) continue;\n\n if (value === true) {\n const defaults = resolve.omit(target);\n if (!defaults) continue;\n next[key] = { omit: { ...defaults } };\n changed = true;\n continue;\n }\n if (!isPlainRecord(value)) continue;\n\n const rewritten = rewriteNode(target, value, resolve);\n if (rewritten !== value) {\n next[key] = rewritten;\n changed = true;\n }\n }\n\n return changed ? next : map;\n};\n\n/** The direct carrier edge of a variant slot — never a bound inverse's view. */\nexport const directVariantCarrier = (\n resolved: ResolvedSlot\n): ResolvedVariantEdge | undefined => {\n if (resolved.member) return undefined;\n const edge = resolved.edge;\n return edge.kind === \"variantRowCarrier\" ||\n edge.kind === \"variantJunctionCarrier\"\n ? edge\n : undefined;\n};\n\n/**\n * The SETTLED model on the other side of one slot.\n *\n * Every model here came out of the gate's own registration, so no getter is\n * invoked and no `targetEntries()` is walked: the edge already names both\n * endpoints, and a bound inverse names the carrier that holds the storage.\n */\nexport const slotTarget = (\n resolved: ResolvedSlot,\n source: AnyModel\n): AnyModel | undefined => {\n const edge = resolved.edge;\n if (edge.kind === \"foreignKey\" || edge.kind === \"junction\") {\n const [first, second] = edge.endpoints;\n return first.source === source && first.field === resolved.slot.field\n ? second.source\n : first.source;\n }\n return edge.carrier.source;\n};\n\n/**\n * WHERE a polymorphic arm lives depends on the slot's CARDINALITY, and getting\n * that wrong is not a missed default — it is a thrown query.\n *\n * A to-one slot's projection IS the discriminator map, so an arm is written at\n * the projection's top level. A collection's projection is an envelope whose\n * top level holds exactly two keys, `only` and `variants`; an arm written\n * beside them is an unknown key the strict envelope refuses. Since this rewrite\n * runs BEFORE validation, a top-level arm would make\n * `include: { items: true }` throw on any client that configures an `omit` for\n * a variant's target model — a client-option-shaped failure in a query that\n * never mentioned the option.\n */\nconst rewriteVariantCarrier = (\n edge: ResolvedVariantEdge,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown =>\n edge.kind === \"variantJunctionCarrier\"\n ? rewritePolymorphicCollection(edge, value, resolve)\n : rewritePolymorphicSlot(edge, value, resolve);\n\n/**\n * The arm a client default produces for one target, or `undefined` when that\n * target is unconfigured (leave the caller's payload — and its cache key —\n * exactly as written).\n */\nconst defaultedArm = (\n target: AnyModel,\n variant: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (isPlainRecord(variant)) {\n const rewritten = rewriteNode(target, variant, resolve);\n return rewritten === variant ? undefined : rewritten;\n }\n if (variant !== true && variant !== undefined) return undefined;\n const defaults = resolve.omit(target);\n return defaults ? { omit: { ...defaults } } : undefined;\n};\n\n/**\n * A to-one polymorphic projection object overrides individual variants; absent\n * keys still project that target's default scalars. Visit every configured\n * target so client defaults apply to both explicit and defaulted variants.\n */\nconst rewritePolymorphicSlot = (\n edge: Extract<ResolvedVariantEdge, { kind: \"variantRowCarrier\" }>,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (value !== true && !isPlainRecord(value)) return value;\n\n const projection: Record<string, unknown> =\n value === true ? {} : { ...value };\n let changed = false;\n\n for (const member of edge.members) {\n const variant = value === true ? undefined : value[member.variant];\n const arm = defaultedArm(member.targetModel, variant, resolve);\n if (arm === undefined) continue;\n projection[member.variant] = arm;\n changed = true;\n }\n\n return changed ? projection : value;\n};\n\n/**\n * A collection projection: arms go UNDER `variants`, and an allow-list is\n * obeyed rather than worked around.\n *\n * Synthesizing an arm for a variant `only` excludes would fabricate the exact\n * \"Variant 'x' is not in 'only'\" refusal the envelope raises — a client option\n * producing a parse error about a key the caller never wrote.\n */\nconst rewritePolymorphicCollection = (\n edge: Extract<ResolvedVariantEdge, { kind: \"variantJunctionCarrier\" }>,\n value: unknown,\n resolve: ClientOmitResolver\n): unknown => {\n if (value !== true && !isPlainRecord(value)) return value;\n\n const envelope = value === true ? undefined : value;\n const only = envelope?.only;\n const existing = envelope?.variants;\n // A malformed envelope is left ALONE: validation owns the message, and a\n // rewrite here would only add keys to a payload that is already failing.\n if (only !== undefined && !Array.isArray(only)) return value;\n if (existing !== undefined && !isPlainRecord(existing)) return value;\n const allowed = Array.isArray(only) ? new Set<unknown>(only) : undefined;\n\n const variants: Record<string, unknown> = { ...existing };\n let changed = false;\n\n for (const member of edge.members) {\n if (allowed && !allowed.has(member.variant)) continue;\n const arm = defaultedArm(\n member.topology.target.model,\n existing?.[member.variant],\n resolve\n );\n if (arm === undefined) continue;\n variants[member.variant] = arm;\n changed = true;\n }\n\n if (!changed) return value;\n return { ...envelope, variants };\n};\n","/**\n * `result`: fields a client computes on the rows it returns (Prisma's result\n * extensions).\n *\n * A computed field names what it reads (`needs`) and how (`compute`). It is\n * not a column: the payload is rewritten before validation so the engine reads\n * the fields it needs and never sees the computed one, and the rows are\n * finished after the operation settles — the field computed, the fields read\n * only for it removed. Both steps run only on a client whose chain declares\n * `result`; any other client builds and runs none of this.\n *\n * Which rows: every row of the model an operation returns, nested relation\n * rows included, the way a `select` or `include` reaches them. A field is\n * selected and omitted by its name, as a column is; a field may shadow a\n * scalar of the same name. A later extension's field may need an earlier\n * one's, even under the same name, and is computed after it. Filtering,\n * ordering, grouping and aggregating by a computed field stay refused: the\n * database never sees it. A variant relation's rows do not carry computed\n * fields; a recursive projection carries them at every level.\n */\n\nimport {\n directVariantCarrier,\n PROJECTING_OPERATIONS,\n slotTarget,\n} from \"@client/omit\";\nimport type { Schema } from \"@client/types\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { extensionError } from \"./definition\";\n\ntype Row = Record<string, unknown>;\n\n/** One computed field as a definition declares it, read once. */\nexport interface RuntimeComputedField {\n readonly needs: readonly string[];\n readonly compute: (row: Row) => unknown;\n}\n\n/** A definition's `result`: per model key (or `$allModels`), its fields. */\nexport type RuntimeResultContribution = Readonly<\n Record<string, Readonly<Record<string, RuntimeComputedField>>>\n>;\n\n/**\n * One model's computed field on the chain. Each need is a column's name, or\n * the index of the earlier computed field it reads.\n */\ninterface ResolvedComputedField {\n readonly name: string;\n readonly compute: (row: Row) => unknown;\n readonly needs: readonly (string | number)[];\n}\n\n/**\n * Per model name, every computed field the chain declares, in chain order: a\n * field's needs point only at columns and at fields before it.\n */\nexport type ResolvedResultFields = Readonly<\n Record<string, readonly ResolvedComputedField[]>\n>;\n\nconst ALL_MODELS = \"$allModels\";\n\n/** Read a definition's `result` once into a frozen snapshot. */\nexport function snapshotResult(\n component: unknown,\n extension: string,\n schema?: Schema\n): RuntimeResultContribution {\n function refuse(path: string, problem: string): never {\n return extensionError(\n `Extension \"${extension}\" result${path} ${problem}.`,\n extension\n );\n }\n if (!isRecord(component)) refuse(\"\", \"must be a model map\");\n const models: Record<\n string,\n Record<string, RuntimeComputedField>\n > = Object.create(null);\n for (const modelKey of Object.keys(component)) {\n if (modelKey !== ALL_MODELS && schema && !Object.hasOwn(schema, modelKey))\n refuse(\"\", `names unknown model \"${modelKey}\"`);\n const entries = component[modelKey];\n if (!isRecord(entries)) refuse(`.${modelKey}`, \"must be an object\");\n const fields: Record<string, RuntimeComputedField> = Object.create(null);\n for (const name of Object.keys(entries)) {\n const entry = entries[name];\n const compute = isRecord(entry) ? entry.compute : undefined;\n const needs = isRecord(entry) ? (entry.needs ?? {}) : undefined;\n if (!(isRecord(needs) && isFunction(compute)))\n refuse(\n `.${modelKey}.${name}`,\n \"must be an object with a compute function and a needs object\"\n );\n const read: string[] = [];\n for (const need of Object.keys(needs)) {\n if (typeof needs[need] !== \"boolean\")\n refuse(`.${modelKey}.${name}.needs.${need}`, \"must be a boolean\");\n if (needs[need]) read.push(need);\n }\n fields[name] = Object.freeze({\n needs: Object.freeze(read),\n compute: compute as RuntimeComputedField[\"compute\"],\n });\n }\n models[modelKey] = Object.freeze(fields);\n }\n return Object.freeze(models);\n}\n\n/**\n * The chain's computed fields with one extension's appended: `$allModels`\n * first, then the model's own, so a model's field can replace or need an\n * `$allModels` one. Every need is resolved here, against the model's\n * readable scalars and the fields before it.\n */\nexport function appendResultFields(\n previous: ResolvedResultFields | undefined,\n extension: string,\n contribution: RuntimeResultContribution,\n schema: Schema\n): ResolvedResultFields {\n const next: Record<string, readonly ResolvedComputedField[]> = {\n ...previous,\n };\n for (const modelName of Object.keys(schema)) {\n const model = schema[modelName]!;\n const fields = [...(next[modelName] ?? [])];\n const readable = new Set(projectableScalarNames(model));\n for (const key of [ALL_MODELS, modelName]) {\n const declared = contribution[key] ?? {};\n for (const name of Object.keys(declared)) {\n const at = `Extension \"${extension}\" result.${key}.${name}`;\n if (\n name === \"_count\" ||\n Object.hasOwn(model[\"~\"].state.relations, name)\n )\n extensionError(\n `${at} cannot be computed: \"${name}\" is a relation of model \"${modelName}\".`,\n extension\n );\n const needs = declared[name]!.needs.map((need) => {\n for (let earlier = fields.length - 1; earlier >= 0; earlier--) {\n if (fields[earlier]!.name === need) return earlier;\n }\n if (readable.has(need)) return need;\n return extensionError(\n `${at} needs \"${need}\", which is not a readable scalar or an earlier computed field of model \"${modelName}\".`,\n extension\n );\n });\n fields.push({ name, compute: declared[name]!.compute, needs });\n }\n }\n if (fields.length > 0) next[modelName] = fields;\n }\n return Object.freeze(next);\n}\n\n/**\n * One projection node's work on its rows, and its relations' nodes. A\n * recursive relation's node lists itself under the repeated key, so the\n * finish follows the tree the projection repeats.\n */\ninterface ResultNode {\n /** The model's computed fields; `outputs` indexes the ones returned. */\n readonly fields: readonly ResolvedComputedField[];\n readonly outputs: readonly number[];\n /** The columns the returned fields read, through earlier fields too. */\n readonly reads: readonly string[];\n readonly strip: readonly string[];\n readonly relations: (readonly [string, ResultNode])[];\n}\n\n/** A bulk write returns rows only when it carries a projection. */\nconst BULK_OPERATIONS = new Set([\"createMany\", \"updateMany\", \"deleteMany\"]);\n\n/**\n * Plan one operation: the payload the engine runs, and the function that\n * finishes its value. `undefined` when nothing this operation returns has a\n * computed field.\n */\nexport function planResultFields(\n fields: ResolvedResultFields,\n relations: ResolvedRelationIndex,\n model: AnyModel,\n operation: string,\n args: Row\n):\n | { readonly args: Row; readonly finish: (value: unknown) => unknown }\n | undefined {\n const returnsRows =\n PROJECTING_OPERATIONS.has(operation) ||\n (BULK_OPERATIONS.has(operation) &&\n (args.select !== undefined || args.omit !== undefined));\n if (!returnsRows) return undefined;\n const planned = planNode(fields, relations, model, args);\n if (planned === undefined) return undefined;\n const { node } = planned;\n return {\n args: planned.args ?? args,\n finish: (value) => finishValue(value, node),\n };\n}\n\nfunction planNode(\n fields: ResolvedResultFields,\n relations: ResolvedRelationIndex,\n model: AnyModel,\n args: Row | undefined\n): { readonly args: Row | undefined; readonly node: ResultNode } | undefined {\n const declared = fields[model[\"~\"].names.ts ?? \"\"];\n const select = isRecord(args?.select) ? args.select : undefined;\n const include = isRecord(args?.include) ? args.include : undefined;\n const omit = isRecord(args?.omit) ? args.omit : undefined;\n\n // The relations first: a node with no field of its own may still lead to\n // one that has.\n const nested: (readonly [string, ResultNode])[] = [];\n const projection = select ?? include;\n let nextProjection = projection;\n if (projection !== undefined) {\n const slots = relations.get(model);\n for (const key of Object.keys(projection)) {\n const resolved = slots?.get(key);\n const value = projection[key];\n if (!resolved || directVariantCarrier(resolved)) continue;\n if (value !== true && !isRecord(value)) continue;\n const target = slotTarget(resolved, model);\n if (!target) continue;\n const childArgs = value === true ? undefined : value;\n const child = planNode(fields, relations, target, childArgs);\n if (child === undefined) continue;\n nested.push([key, child.node]);\n if (childArgs?.recurse !== undefined)\n child.node.relations.push([key, child.node]);\n if (child.args !== childArgs) {\n if (nextProjection === projection) nextProjection = { ...projection };\n nextProjection![key] = child.args;\n }\n }\n }\n\n // The latest declaration of each name is the visible field.\n const visible = new Map<string, number>();\n for (const [index, field] of (declared ?? []).entries())\n visible.set(field.name, index);\n const wanted: number[] = [];\n // A payload that names a field it does not want still loses that key.\n let named = false;\n for (const [name, index] of visible) {\n named ||= (select ?? omit)?.[name] !== undefined;\n if ((!select || select[name] === true) && omit?.[name] !== true)\n wanted.push(index);\n }\n if (wanted.length === 0 && nested.length === 0 && !named) return undefined;\n\n // Every field the wanted ones read, computed first; the columns they read.\n const computing = new Set<number>();\n const reads = new Set<string>();\n const close = (index: number) => {\n if (computing.has(index)) return;\n computing.add(index);\n for (const need of declared![index]!.needs) {\n if (typeof need === \"number\") close(need);\n else reads.add(need);\n }\n };\n for (const index of wanted) close(index);\n const outputs = new Set(wanted.map((index) => declared![index]!.name));\n // The columns read only for a field: removed from the rows again.\n const strip = new Set<string>();\n\n let next = args;\n const rewrite = (key: string, value: Row) => {\n if (next === args) next = { ...args };\n next![key] = value;\n };\n // `omit` subtracts from either projection: a computed name leaves it (a\n // column it shadows stays omitted), and a column a field reads is read\n // anyway, then removed again.\n let nextOmit: Row | undefined;\n for (const name of visible.keys()) {\n if (omit?.[name] === undefined || readsColumn(model, name)) continue;\n nextOmit ??= { ...omit };\n delete nextOmit[name];\n }\n const kept = (field: string) =>\n (select ? select[field] === true : true) && omit?.[field] !== true;\n for (const field of reads) {\n if (!(kept(field) || outputs.has(field))) strip.add(field);\n if (omit?.[field] === true) {\n nextOmit ??= { ...omit };\n nextOmit[field] = false;\n }\n }\n if (nextOmit !== undefined) rewrite(\"omit\", nextOmit);\n if (select !== undefined) {\n const nextSelect: Row = { ...(nextProjection ?? select) };\n for (const name of visible.keys()) delete nextSelect[name];\n for (const field of reads) nextSelect[field] = true;\n if (!Object.values(nextSelect).some((value) => value !== false)) {\n const [first] = projectableScalarNames(model);\n if (first !== undefined) {\n nextSelect[first] = true;\n if (!outputs.has(first)) strip.add(first);\n }\n }\n rewrite(\"select\", nextSelect);\n } else if (nextProjection !== projection) {\n rewrite(\"include\", nextProjection!);\n }\n\n return {\n args: next,\n node: {\n fields: declared ?? [],\n outputs: wanted,\n reads: [...reads],\n strip: [...strip],\n relations: nested,\n },\n };\n}\n\nconst readsColumn = (model: AnyModel, name: string): boolean =>\n Object.hasOwn(model[\"~\"].state.scalars, name);\n\nfunction finishValue(value: unknown, node: ResultNode): unknown {\n if (Array.isArray(value)) return value.map((row) => finishRow(row, node));\n return finishRow(value, node);\n}\n\n/**\n * A copy of one row, its relations finished, the columns read only for a\n * field removed, and each field an enumerable getter, as Prisma's are: it is\n * computed on first read, once, from the values the call read (the row as\n * fetched, never the copy its caller may change: a JSON, date, list or binary\n * value a field reads is copied here, before the caller can edit it, and\n * only then), so a `compute` that throws\n * throws where the field is read and never fails the operation, nor a write\n * that already committed. A field assigned before it is read keeps the value\n * assigned.\n */\nfunction finishRow(value: unknown, node: ResultNode): unknown {\n if (!isRecord(value)) return value;\n const row: Row = { ...value };\n for (const [key, child] of node.relations) {\n if (row[key] !== undefined) row[key] = finishValue(row[key], child);\n }\n for (const key of node.strip) delete row[key];\n let fetched: Row = value;\n for (const column of node.reads) {\n const held = value[column];\n if (held === null || typeof held !== \"object\") continue;\n if (fetched === value) fetched = { ...value };\n fetched[column] = detached(held);\n }\n const values = new Map<number, unknown>();\n const computed = (index: number): unknown => {\n if (values.has(index)) return values.get(index);\n const field = node.fields[index]!;\n const input: Row = {};\n for (const need of field.needs) {\n if (typeof need === \"number\")\n input[node.fields[need]!.name] = computed(need);\n else input[need] = fetched[need];\n }\n const result = field.compute(input);\n values.set(index, result);\n return result;\n };\n for (const index of node.outputs) {\n const name = node.fields[index]!.name;\n const settle = (settled: unknown) => {\n Object.defineProperty(row, name, {\n value: settled,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n return settled;\n };\n Object.defineProperty(row, name, {\n get: () => settle(computed(index)),\n set: settle,\n enumerable: true,\n configurable: true,\n });\n }\n return row;\n}\n\nconst typedArraySlice = Object.getPrototypeOf(Uint8Array.prototype).slice as (\n this: ArrayBufferView\n) => ArrayBufferView;\n\n/**\n * A copy of a value the caller could edit: JSON objects and lists, dates and\n * binary or numeric arrays. A class instance (a `Decimal`) is immutable and\n * shared.\n */\nfunction detached(held: unknown): unknown {\n if (held === null || typeof held !== \"object\") return held;\n if (Array.isArray(held)) return held.map(detached);\n if (held instanceof Date) return new Date(held.getTime());\n if (ArrayBuffer.isView(held))\n return held instanceof DataView ? held : typedArraySlice.call(held);\n const prototype = Object.getPrototypeOf(held);\n if (prototype !== Object.prototype && prototype !== null) return held;\n const copy: Row = {};\n for (const key in held) copy[key] = detached((held as Row)[key]);\n return copy;\n}\n","import type { VibORMConfig } from \"@client/client\";\nimport type { ClientSchema } from \"@client/schema-links\";\nimport type { Operations, Schema } from \"@client/types\";\nimport type { AnyDriver } from \"@drivers/exports\";\nimport { ClientInitializationError } from \"@errors\";\nimport { ROUTED_OPERATIONS } from \"@query-engine/routed-operations\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { admitRows } from \"./admission\";\nimport type {\n ControlsContribution,\n DataContribution,\n DeletionContribution,\n RowsContribution,\n} from \"./controls\";\nimport type {\n EmptyClientExtensionState,\n ExtensionClientScope,\n ExtensionMethodDefinitionGuard,\n ExtensionMethodRecord,\n ExtensionModelDelegate,\n ExtensionStateConstraint,\n ResultConsumerContextOf,\n RuntimeClientMethodContribution,\n RuntimeModelMethodContribution,\n} from \"./methods\";\nimport type { ObserveHandler } from \"./observation\";\nimport type {\n GenericQueryHandler,\n QueryHandlerMap,\n RuntimeQueryContribution,\n} from \"./query\";\nimport type {\n GenericRequestHandler,\n RequestHandlerMap,\n RuntimeRequestContribution,\n} from \"./request\";\nimport { type RuntimeResultContribution, snapshotResult } from \"./result\";\nimport type { ResultDefinition, ResultInference } from \"./result-types\";\nimport type { StatementHandler } from \"./statement\";\n\ntype RuntimeExtensionFunction = (...args: never[]) => unknown;\n\n/**\n * One extension definition as the chain binds it: a host-owned frozen\n * snapshot of the six handler members, `rows` as admission left it (against\n * a schema), and `controls`, `deletion` and `data` as the definition wrote\n * them.\n */\nexport interface RuntimeExtensionDefinition {\n readonly name: string;\n readonly request?: RuntimeRequestContribution;\n readonly query?: RuntimeQueryContribution;\n readonly statement?: RuntimeExtensionFunction;\n readonly observe?: RuntimeExtensionFunction;\n readonly client?: RuntimeClientMethodContribution;\n readonly model?: RuntimeModelMethodContribution;\n readonly controls?: ControlsContribution;\n readonly rows?: RowsContribution;\n readonly deletion?: DeletionContribution;\n readonly data?: DataContribution;\n readonly result?: RuntimeResultContribution;\n}\n\nexport type ControlLiteral = string | number | boolean;\n\n/**\n * What `$extends` hands the chain. Schema-bound row/data/deletion model and\n * field names are checked before they can silently bind to no policy.\n * Handler members retain the hostile-definition boundary below.\n */\nexport type ExtensionDefinitionInput = Readonly<Record<string, unknown>> & {\n readonly controls?: ControlsContribution;\n readonly rows?: RowsContribution;\n readonly deletion?: DeletionContribution;\n readonly data?: DataContribution;\n};\n\nconst DEFINITION_KEYS = new Set([\n \"name\",\n \"request\",\n \"query\",\n \"statement\",\n \"observe\",\n \"client\",\n \"model\",\n \"controls\",\n \"rows\",\n \"deletion\",\n \"data\",\n \"result\",\n]);\n\nexport function extensionError(message: string, extension?: string): never {\n throw new ClientInitializationError(message, {\n meta: extension ? { extension } : undefined,\n });\n}\n\nfunction readOwnKeys(\n value: Record<string, unknown>,\n extension?: string\n): PropertyKey[] {\n try {\n return Reflect.ownKeys(value);\n } catch (cause) {\n throw new ClientInitializationError(\n extension\n ? `Extension \"${extension}\" members could not be inspected.`\n : \"Client extension members could not be inspected.\",\n {\n cause: errorCause(cause),\n meta: extension ? { extension } : undefined,\n }\n );\n }\n}\n\nfunction readOwn(\n value: Record<string, unknown>,\n key: string,\n extension?: string\n): unknown {\n try {\n return value[key];\n } catch (cause) {\n throw new ClientInitializationError(\n extension\n ? `Extension \"${extension}\" member \"${key}\" could not be read.`\n : `Client extension member \"${key}\" could not be read.`,\n {\n cause: errorCause(cause),\n meta: extension ? { extension } : undefined,\n }\n );\n }\n}\n\nfunction requireFunction(\n value: unknown,\n label: string,\n extension: string\n): RuntimeExtensionFunction {\n if (!isFunction(value)) {\n extensionError(\n `Extension \"${extension}\" ${label} must be a function.`,\n extension\n );\n }\n return value;\n}\n\nfunction snapshotOperationMap(\n component: unknown,\n label: \"request\" | \"query\",\n extension: string,\n schema?: Schema\n): RuntimeExtensionDefinition[\"request\"] {\n if (isFunction(component)) return component;\n if (!isRecord(component)) {\n extensionError(\n `Extension \"${extension}\" ${label} must be a function or model map.`,\n extension\n );\n }\n\n const models: Record<\n string,\n Readonly<Record<string, RuntimeExtensionFunction>>\n > = Object.create(null);\n for (const modelKey of readOwnKeys(component, extension)) {\n if (typeof modelKey !== \"string\") {\n extensionError(\n `Extension \"${extension}\" ${label} contains a non-string model key.`,\n extension\n );\n }\n if (schema && !Object.hasOwn(schema, modelKey)) {\n extensionError(\n `Extension \"${extension}\" ${label} names unknown model \"${modelKey}\".`,\n extension\n );\n }\n const handlers = readOwn(component, modelKey, extension);\n if (!isRecord(handlers)) {\n extensionError(\n `Extension \"${extension}\" ${label}.${modelKey} must be an operation map.`,\n extension\n );\n }\n const operations: Record<string, RuntimeExtensionFunction> =\n Object.create(null);\n for (const operationKey of readOwnKeys(handlers, extension)) {\n if (typeof operationKey !== \"string\") {\n extensionError(\n `Extension \"${extension}\" ${label}.${modelKey} contains a non-string operation key.`,\n extension\n );\n }\n if (!ROUTED_OPERATIONS.has(operationKey)) {\n extensionError(\n `Extension \"${extension}\" ${label}.${modelKey} names unknown operation \"${operationKey}\".`,\n extension\n );\n }\n operations[operationKey] = requireFunction(\n readOwn(handlers, operationKey, extension),\n `${label}.${modelKey}.${operationKey}`,\n extension\n );\n }\n models[modelKey] = Object.freeze(operations);\n }\n return Object.freeze(models);\n}\n\nfunction snapshotModelFactories(\n component: unknown,\n extension: string,\n schema?: Schema\n): RuntimeExtensionDefinition[\"model\"] {\n if (!isRecord(component)) {\n extensionError(\n `Extension \"${extension}\" model must be a model map.`,\n extension\n );\n }\n const factories: Record<string, RuntimeExtensionFunction> =\n Object.create(null);\n for (const modelKey of readOwnKeys(component, extension)) {\n if (typeof modelKey !== \"string\") {\n extensionError(\n `Extension \"${extension}\" model contains a non-string model key.`,\n extension\n );\n }\n if (schema && !Object.hasOwn(schema, modelKey)) {\n extensionError(\n `Extension \"${extension}\" model names unknown model \"${modelKey}\".`,\n extension\n );\n }\n factories[modelKey] = requireFunction(\n readOwn(component, modelKey, extension),\n `model.${modelKey}`,\n extension\n );\n }\n return Object.freeze(factories);\n}\n\n/** Refuse named policy facts that could otherwise silently bind to nothing. */\nfunction validateNamedPolicies(\n value: ExtensionDefinitionInput,\n schema: Schema | undefined,\n name: string\n): void {\n if (!schema) return;\n const components: (\"rows\" | \"data\" | \"deletion\")[] = [\n \"rows\",\n \"data\",\n \"deletion\",\n ];\n for (const component of components) {\n const declaration = readOwn(value, component, name);\n if (declaration === undefined) continue;\n if (!isRecord(declaration))\n extensionError(\n `Extension \"${name}\" ${component} must be an object.`,\n name\n );\n const models = readOwn(declaration, \"models\", name);\n if (!isRecord(models))\n extensionError(\n `Extension \"${name}\" ${component}.models must be an object.`,\n name\n );\n let expectedModes: readonly string[] | undefined;\n const defaultMode =\n component === \"rows\" ? readOwn(declaration, \"default\", name) : undefined;\n for (const modelName of readOwnKeys(models, name)) {\n if (typeof modelName !== \"string\" || !Object.hasOwn(schema, modelName))\n extensionError(\n `Extension \"${name}\" ${component} names unknown model \"${String(modelName)}\".`,\n name\n );\n const model = schema[modelName]!;\n const entry = readOwn(models, modelName, name);\n if (!isRecord(entry))\n extensionError(\n `Extension \"${name}\" ${component}.${modelName} must be an object.`,\n name\n );\n // A row predicate's fields are its admission's (`admission.ts`).\n const fields = (input: unknown): void => {\n if (input === undefined) return;\n if (!isRecord(input))\n extensionError(\n `Extension \"${name}\" ${component}.${modelName} fields must be an object.`,\n name\n );\n for (const key of readOwnKeys(input, name)) {\n if (\n typeof key !== \"string\" ||\n !Object.hasOwn(model[\"~\"].state.scalars, key)\n )\n extensionError(\n `Extension \"${name}\" ${component}.${modelName} names unknown field \"${String(key)}\".`,\n name\n );\n }\n };\n if (component === \"rows\") {\n const modes = readOwnKeys(entry, name).filter(\n (key): key is string => typeof key === \"string\"\n );\n const priorModes = expectedModes;\n if (\n typeof defaultMode !== \"string\" ||\n !modes.includes(defaultMode) ||\n (priorModes &&\n (priorModes.length !== modes.length ||\n modes.some((mode) => !priorModes.includes(mode))))\n )\n extensionError(\n `Extension \"${name}\" row models must share mode names and include the default mode.`,\n name\n );\n expectedModes ??= modes;\n for (const modeName of readOwnKeys(entry, name)) {\n if (typeof modeName !== \"string\")\n extensionError(\n `Extension \"${name}\" row mode must be a string.`,\n name\n );\n const mode = readOwn(entry, modeName, name);\n if (!isRecord(mode))\n extensionError(\n `Extension \"${name}\" row mode must be an object.`,\n name\n );\n }\n } else if (component === \"data\") {\n fields(readOwn(entry, \"create\", name));\n fields(readOwn(entry, \"update\", name));\n } else {\n const at = readOwn(entry, \"at\", name);\n if (\n at !== undefined &&\n (typeof at !== \"string\" ||\n !Object.hasOwn(model[\"~\"].state.scalars, at))\n )\n extensionError(\n `Extension \"${name}\" deletion.${modelName}.at names unknown scalar.`,\n name\n );\n fields(readOwn(entry, \"assign\", name));\n }\n }\n }\n}\n\n/**\n * Read a caller-owned definition once. The six handler members are validated\n * and frozen as host-owned snapshots, so a failed application cannot mutate\n * the supplied value; against a schema, every `rows` predicate is admitted\n * through its model's `where` schema; `controls`, `deletion` and `data` are\n * bound as written.\n */\nexport function normalizeExtensionDefinition(\n value: ExtensionDefinitionInput,\n schema?: Schema,\n registry?: SchemaRegistryLookup<Schema>\n): RuntimeExtensionDefinition {\n if (!isRecord(value)) {\n extensionError(\"Client extension must be an object.\");\n }\n const ownKeys = readOwnKeys(value);\n if (!ownKeys.includes(\"name\")) {\n extensionError(\"Client extension name must be a non-empty string.\");\n }\n const rawName = readOwn(value, \"name\");\n if (typeof rawName !== \"string\" || rawName.trim().length === 0) {\n extensionError(\"Client extension name must be a non-empty string.\");\n }\n const name = rawName;\n for (const key of ownKeys) {\n if (typeof key !== \"string\" || !DEFINITION_KEYS.has(key)) {\n extensionError(\n `Extension \"${name}\" has unknown member \"${String(key)}\".`,\n name\n );\n }\n }\n\n const rawRequest = ownKeys.includes(\"request\")\n ? readOwn(value, \"request\", name)\n : undefined;\n const request =\n rawRequest === undefined\n ? undefined\n : snapshotOperationMap(rawRequest, \"request\", name, schema);\n const rawQuery = ownKeys.includes(\"query\")\n ? readOwn(value, \"query\", name)\n : undefined;\n const query =\n rawQuery === undefined\n ? undefined\n : snapshotOperationMap(rawQuery, \"query\", name, schema);\n const rawStatement = ownKeys.includes(\"statement\")\n ? readOwn(value, \"statement\", name)\n : undefined;\n const statement =\n rawStatement === undefined\n ? undefined\n : requireFunction(rawStatement, \"statement\", name);\n const rawObserve = ownKeys.includes(\"observe\")\n ? readOwn(value, \"observe\", name)\n : undefined;\n const observe =\n rawObserve === undefined\n ? undefined\n : requireFunction(rawObserve, \"observe\", name);\n const rawClient = ownKeys.includes(\"client\")\n ? readOwn(value, \"client\", name)\n : undefined;\n const client =\n rawClient === undefined\n ? undefined\n : requireFunction(rawClient, \"client\", name);\n const rawModel = ownKeys.includes(\"model\")\n ? readOwn(value, \"model\", name)\n : undefined;\n const model =\n rawModel === undefined\n ? undefined\n : snapshotModelFactories(rawModel, name, schema);\n const rawResult = ownKeys.includes(\"result\")\n ? readOwn(value, \"result\", name)\n : undefined;\n const result =\n rawResult === undefined\n ? undefined\n : snapshotResult(rawResult, name, schema);\n const { controls, deletion, data } = value;\n validateNamedPolicies({ rows: value.rows, deletion, data }, schema, name);\n const rows =\n schema && value.rows\n ? admitRows(value.rows, schema, name, registry)\n : value.rows;\n\n return Object.freeze({\n name,\n ...(request ? { request } : {}),\n ...(query ? { query } : {}),\n ...(statement ? { statement } : {}),\n ...(observe ? { observe } : {}),\n ...(client ? { client } : {}),\n ...(model ? { model } : {}),\n ...(controls ? { controls } : {}),\n ...(rows ? { rows } : {}),\n ...(deletion ? { deletion } : {}),\n ...(data ? { data } : {}),\n ...(result ? { result } : {}),\n });\n}\n\ntype ExtensionConfig<S extends Schema> = {\n readonly schema: S;\n readonly driver: AnyDriver;\n};\n\n/**\n * A model factory, declared as a method so a factory typed against the client\n * it extends (`(delegate: M[K & keyof M]) => …`, generic over that client) is\n * compared in either direction rather than only contravariantly.\n */\ntype ModelMethodFactory<Delegate> = {\n factory(delegate: Delegate): ExtensionMethodRecord;\n}[\"factory\"];\n\n/**\n * One factory per schema model. A definition's model key is looked up here by\n * index, never by a conditional: a key outside the schema reads `never` (the\n * factory is refused where it is written), and a key set generic over the\n * client is substituted rather than deferred, so a plugin generic over `C`\n * type-checks and meets the schema check when it is applied.\n */\ntype ModelFactoryTable<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = {\n readonly [ModelName in keyof ClientSchema<C>]: ModelMethodFactory<\n ExtensionModelDelegate<C, X, ModelName>\n >;\n};\n\n/** The model keys a definition's own `model` map names. */\ntype DefinitionModelKeys<Self> = Self extends {\n readonly model?: infer Factories;\n}\n ? keyof Factories\n : never;\n\n/**\n * `Self` is the definition itself when `$extends` checks it (F-bounded), so\n * its model keys come from the definition; otherwise every schema model.\n */\nexport type ContextualExtensionDefinition<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n Self = unknown,\n> = ExtensionMembers<C, X> & {\n readonly result?: ResultDefinition<C>;\n readonly model?: unknown extends Self\n ? {\n readonly [ModelName in keyof ClientSchema<C>]?: ModelMethodFactory<\n ExtensionModelDelegate<C, X, ModelName>\n >;\n }\n : {\n readonly [ModelName in DefinitionModelKeys<Self>]?: ModelFactoryTable<\n C,\n X\n >[ModelName & keyof ClientSchema<C>];\n };\n};\n\ntype ExtensionMembers<\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = {\n readonly name: string;\n readonly request?: GenericRequestHandler | RequestHandlerMap<ClientSchema<C>>;\n readonly query?: GenericQueryHandler | QueryHandlerMap<C, X[\"rows\"]>;\n readonly statement?: StatementHandler;\n readonly observe?: ObserveHandler;\n readonly controls?: ControlsContribution;\n readonly rows?: RowsContribution;\n readonly deletion?: DeletionContribution;\n readonly data?: DataContribution;\n readonly client?: (\n scope: ExtensionClientScope<C, X>\n ) => ExtensionMethodRecord;\n};\n\ntype SchemaGenericExtensionDefinition = Omit<\n ContextualExtensionDefinition<\n ExtensionConfig<Schema>,\n EmptyClientExtensionState\n >,\n \"request\" | \"query\"\n> & {\n readonly request?: GenericRequestHandler;\n readonly query?: GenericQueryHandler;\n};\n\n/**\n * Public reusable extension definition.\n *\n * A schema with a string index has no exact model vocabulary, so its reusable\n * request/query contributions must use the polymorphic all-operation form.\n * Supplying a concrete schema retains its exact model and operation maps.\n */\nexport type ClientExtension<S extends Schema = Schema> = string extends keyof S\n ? SchemaGenericExtensionDefinition\n : ContextualExtensionDefinition<\n ExtensionConfig<S>,\n EmptyClientExtensionState\n >;\n\ntype DefinitionKeys = keyof ContextualExtensionDefinition<\n VibORMConfig,\n EmptyClientExtensionState\n>;\n\ndeclare const schemaBoundExtensionContext: unique symbol;\n\ntype SchemaBoundExtension<Definition> = Definition & {\n readonly [schemaBoundExtensionContext]: ResultConsumerContextOf<Definition>;\n};\n\ntype UnknownDefinitionKeys<Definition> = Record<\n Exclude<\n keyof Definition,\n DefinitionKeys | typeof schemaBoundExtensionContext\n >,\n never\n>;\n\ntype ConfigOmit<C extends VibORMConfig> = \"omit\" extends keyof C\n ? C[Extract<\"omit\", keyof C>]\n : undefined;\n\nexport type HasNamedClientOmit<C extends VibORMConfig> =\n string extends keyof NonNullable<ConfigOmit<C>>\n ? false\n : [Exclude<ConfigOmit<C>, undefined>] extends [never]\n ? false\n : true;\n\n/** Refuse replaying a schema-bound result consumer into an omitted client. */\nexport type SchemaBoundExtensionAdmission<\n Definition,\n C extends VibORMConfig,\n> = Definition extends {\n readonly [schemaBoundExtensionContext]: infer Context;\n}\n ? Context extends \"result-consuming\"\n ? HasNamedClientOmit<C> extends true\n ? { readonly [schemaBoundExtensionContext]: never }\n : unknown\n : unknown\n : unknown;\n\ntype OperationMapGuard<Map, S extends Schema> = Map extends CallableFunction\n ? unknown\n : Map extends object\n ? Record<Exclude<keyof Map, keyof S>, never> & {\n readonly [ModelName in keyof Map]: ModelName extends keyof S\n ? Map[ModelName] extends object\n ? Record<Exclude<keyof Map[ModelName], Operations>, never>\n : never\n : never;\n }\n : never;\n\ntype ComponentMapGuard<\n Definition,\n Key extends \"request\" | \"query\",\n S extends Schema,\n> = Definition extends { readonly [K in Key]: infer Component }\n ? { readonly [K in Key]: OperationMapGuard<Component, S> }\n : unknown;\n\n/** Policy model keys must be a subset of a concrete bound schema. */\ntype PolicyModelsGuard<\n Definition,\n S extends Schema,\n Key extends \"data\" | \"rows\" | \"deletion\",\n> = Definition extends {\n readonly [K in Key]: { readonly models: infer Models };\n}\n ? string extends keyof S\n ? unknown\n : [keyof Models] extends [keyof S]\n ? unknown\n : {\n readonly [K in Key]: { readonly models: Record<keyof Models, never> };\n }\n : unknown;\n\n/** Structural refusal for non-fresh extension definitions and contributions. */\nexport type ExactExtensionDefinition<\n Definition,\n C extends VibORMConfig,\n X extends ExtensionStateConstraint,\n> = UnknownDefinitionKeys<Definition> &\n ComponentMapGuard<Definition, \"request\", C[\"schema\"]> &\n ComponentMapGuard<Definition, \"query\", C[\"schema\"]> &\n PolicyModelsGuard<Definition, C[\"schema\"], \"data\"> &\n PolicyModelsGuard<Definition, C[\"schema\"], \"rows\"> &\n PolicyModelsGuard<Definition, C[\"schema\"], \"deletion\"> &\n ExtensionMethodDefinitionGuard<Definition, C, X>;\n\n// The definition is inferred from its declaration, never from a receiving\n// `$extends` overload's return context (which may be a client factory).\nexport type DefineExtensionBinder<S extends Schema> = <\n const Definition,\n Fields = unknown,\n>(\n definition: Definition &\n ContextualExtensionDefinition<\n ExtensionConfig<S>,\n EmptyClientExtensionState\n > &\n ExactExtensionDefinition<\n Definition,\n ExtensionConfig<S>,\n EmptyClientExtensionState\n > &\n ResultInference<ExtensionConfig<S>, Record<never, never>, Fields>\n) => SchemaBoundExtension<NoInfer<Definition>>;\n\nexport function defineExtension<\n const Definition extends SchemaGenericExtensionDefinition,\n>(\n definition: Definition &\n ExactExtensionDefinition<\n Definition,\n ExtensionConfig<Schema>,\n EmptyClientExtensionState\n >\n): NoInfer<Definition>;\nexport function defineExtension<S extends Schema>(): DefineExtensionBinder<S>;\nexport function defineExtension(\n ...definitions: [] | [definition: ClientExtension]\n): unknown {\n if (definitions.length === 0) {\n return (schemaDefinition: ExtensionDefinitionInput) =>\n normalizeExtensionDefinition(schemaDefinition);\n }\n return normalizeExtensionDefinition(definitions[0]);\n}\n","import {\n getOfficialCacheChainDefinition,\n getOfficialCacheQueryCapability,\n OFFICIAL_CACHE_NAME,\n officialCacheControls,\n registerOfficialCacheChain,\n} from \"@cache/capability\";\nimport {\n getOfficialDefaultOmitChainCapability,\n getOfficialDefaultOmitRequestCapability,\n OFFICIAL_DEFAULT_OMIT_NAME,\n registerOfficialDefaultOmitChain,\n} from \"@client/default-omit-extension\";\nimport type { Schema } from \"@client/types\";\nimport type { ModelStamps } from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport type { SchemaRegistryLookup } from \"@validation/types\";\nimport { isFunction } from \"@validation/value-guards\";\nimport {\n type DataContribution,\n type DeletionContribution,\n placeControls,\n type ResolvedControl,\n type RowsContribution,\n} from \"./controls\";\nimport {\n type ControlLiteral,\n type ExtensionDefinitionInput,\n extensionError,\n normalizeExtensionDefinition,\n type RuntimeExtensionDefinition,\n} from \"./definition\";\nimport type {\n RuntimeClientMethodContribution,\n RuntimeModelMethodContribution,\n} from \"./methods\";\nimport {\n getOfficialInstrumentationChainCapability,\n getTrustedProtectedObserverCapability,\n registerOfficialInstrumentationChain,\n} from \"./observation\";\nimport { appendResultFields, type ResolvedResultFields } from \"./result\";\nimport {\n bindRows,\n checkingLazyReferences,\n type RowsBinding,\n undeclaredControlReferencesOf,\n} from \"./rows\";\n\n/** The fixed name admission reserves for the official instrumentation extension. */\nexport const OFFICIAL_INSTRUMENTATION_NAME = \"viborm.instrumentation\";\n\nexport interface ResolvedExtensionHandler<\n Handler extends CallableFunction = CallableFunction,\n> {\n readonly extension: string;\n readonly handler: Handler;\n}\n\n/**\n * A request or query handler. The controls its extension declares travel\n * with it: the only ones its `context.controls` shows.\n */\nexport interface ResolvedOperationHandler<\n Handler extends CallableFunction = CallableFunction,\n> extends ResolvedExtensionHandler<Handler> {\n readonly controls?: readonly string[];\n}\n\n/** One precompiled handler array for each exact execution target. */\nexport interface ResolvedExtensionOperationLookup {\n readonly global: readonly ResolvedOperationHandler[];\n readonly models: Readonly<\n Record<\n string,\n Readonly<Record<string, readonly ResolvedOperationHandler[]>>\n >\n >;\n}\n\nexport interface ResolvedExtension {\n readonly name: string;\n readonly client?: RuntimeClientMethodContribution;\n readonly model?: RuntimeModelMethodContribution;\n}\n\n/** Who owns a request or query handler: its extension and that one's controls. */\ninterface OperationHandlerOwner {\n readonly name: string;\n readonly controls?: readonly string[];\n}\n\n/** A chain's controls, and the list one (model, operation) accepts. */\nexport interface ResolvedControls {\n /** Every control name on the chain: one name space. */\n readonly names: ReadonlySet<string>;\n /** Every control on the chain, in application order: the lists' one source. */\n readonly all: readonly ResolvedControl[];\n /**\n * The controls placed on one model's operation, in application order. Each\n * list is built the first time it is asked for and kept for the chain: a\n * client created per request asks for the one its call needs, never for\n * every operation of every model.\n */\n readonly placed: (\n model: string,\n operation: string\n ) => readonly ResolvedControl[];\n}\n\n/** What a delete of one managed model writes, and who declared it. */\nexport interface ResolvedDeletion {\n readonly extension: string;\n readonly at?: string;\n readonly assign: Readonly<Record<string, unknown>>;\n readonly removeWhen?: Readonly<Record<string, ControlLiteral>>;\n}\n\n/**\n * Absent on an unextended client; frozen whenever it exists, except the\n * `controls`, `rows`, `deletion` and `data` values a definition wrote, held\n * as written.\n */\nexport interface ResolvedExtensionChain {\n readonly controls?: ResolvedControls;\n /**\n * Every `rows` member, as declared (plain data): also a cached read's key,\n * so two chains whose `rows` differ never share an entry and two that\n * declare the same always do.\n */\n readonly rows?: readonly RowsContribution[];\n readonly deletion?: Readonly<Record<string, ResolvedDeletion>>;\n /** Per model, every extension's `data` fields: a later one wins a field. */\n readonly data?: Readonly<Record<string, ModelStamps>>;\n /**\n * Derived from `rows`, `deletion` and `data`: what each call's controls\n * resolve to.\n */\n readonly callRows?: RowsBinding;\n /** Per model, every extension's computed fields, in chain order. */\n readonly result?: ResolvedResultFields;\n readonly extensions: readonly ResolvedExtension[];\n readonly hasCache: boolean;\n readonly hasRequestHandlers: boolean;\n readonly hasQueryHandlers: boolean;\n readonly hasResultConsumers: boolean;\n readonly request: ResolvedExtensionOperationLookup;\n readonly query: ResolvedExtensionOperationLookup;\n readonly statement: readonly ResolvedExtensionHandler[];\n readonly observe: readonly ResolvedExtensionHandler[];\n}\n\n/** Return the precompiled array itself; lookup scans and merges nothing. */\nexport function lookupResolvedExtensionHandlers(\n chain: ResolvedExtensionChain | undefined,\n component: \"request\" | \"query\",\n model: string | undefined,\n operation: string\n): readonly ResolvedOperationHandler[] | undefined {\n if (chain === undefined) return undefined;\n const lookup = chain[component];\n const global = lookup.global.length === 0 ? undefined : lookup.global;\n if (model === undefined) {\n return component === \"query\" ? global : undefined;\n }\n return lookup.models[model]?.[operation] ?? global;\n}\n\n/** The controls one (model, operation) accepts; the shared empty list when none. */\nexport function lookupPlacedControls(\n chain: ResolvedExtensionChain | undefined,\n model: string,\n operation: string\n): readonly ResolvedControl[] {\n return chain?.controls?.placed(model, operation) ?? NO_CONTROLS;\n}\n\nconst NO_CONTROLS: readonly ResolvedControl[] = Object.freeze([]);\n\nfunction resolvedHandler(\n extension: Pick<ResolvedExtension, \"name\">,\n handler: CallableFunction\n): ResolvedExtensionHandler {\n return Object.freeze({ extension: extension.name, handler });\n}\n\nfunction resolvedOperationHandler(\n extension: OperationHandlerOwner,\n handler: CallableFunction\n): ResolvedOperationHandler {\n return Object.freeze(\n extension.controls === undefined\n ? { extension: extension.name, handler }\n : { extension: extension.name, handler, controls: extension.controls }\n );\n}\n\nfunction appendModelHandler(\n models: Record<string, Record<string, ResolvedOperationHandler[]>>,\n model: string,\n operation: string,\n handler: ResolvedOperationHandler,\n global: readonly ResolvedOperationHandler[]\n): void {\n const operations = (models[model] ??= Object.create(null));\n const handlers = (operations[operation] ??= [...global]);\n handlers.push(handler);\n}\n\nfunction appendGlobalHandler(\n models: Record<string, Record<string, ResolvedOperationHandler[]>>,\n handler: ResolvedOperationHandler\n): void {\n for (const operations of Object.values(models)) {\n for (const handlers of Object.values(operations)) handlers.push(handler);\n }\n}\n\nfunction appendOperationHandlers(\n previous: ResolvedExtensionOperationLookup | undefined,\n extension: OperationHandlerOwner,\n contribution: RuntimeExtensionDefinition[\"request\"]\n): ResolvedExtensionOperationLookup {\n if (contribution === undefined && previous !== undefined) return previous;\n\n const models: Record<\n string,\n Record<string, ResolvedOperationHandler[]>\n > = Object.create(null);\n const global: ResolvedOperationHandler[] = previous\n ? [...previous.global]\n : [];\n\n if (previous) {\n for (const [modelName, operationMap] of Object.entries(previous.models)) {\n const operations: Record<string, ResolvedOperationHandler[]> =\n Object.create(null);\n for (const [operation, handlers] of Object.entries(operationMap)) {\n operations[operation] = [...handlers];\n }\n models[modelName] = operations;\n }\n }\n\n if (contribution) {\n if (isFunction(contribution)) {\n const handler = resolvedOperationHandler(extension, contribution);\n global.push(handler);\n appendGlobalHandler(models, handler);\n } else {\n for (const [modelName, operationMap] of Object.entries(contribution)) {\n for (const [operation, handler] of Object.entries(operationMap)) {\n appendModelHandler(\n models,\n modelName,\n operation,\n resolvedOperationHandler(extension, handler),\n global\n );\n }\n }\n }\n }\n\n const frozenModels: Record<\n string,\n Readonly<Record<string, readonly ResolvedOperationHandler[]>>\n > = Object.create(null);\n for (const [modelName, operationMap] of Object.entries(models)) {\n const frozenOperations: Record<\n string,\n readonly ResolvedOperationHandler[]\n > = Object.create(null);\n for (const [operation, handlers] of Object.entries(operationMap)) {\n frozenOperations[operation] = Object.freeze(handlers);\n }\n frozenModels[modelName] = Object.freeze(frozenOperations);\n }\n return Object.freeze({\n global: Object.freeze(global),\n models: Object.freeze(frozenModels),\n });\n}\n\nfunction hasCompiledHandlers(\n lookup: ResolvedExtensionOperationLookup\n): boolean {\n if (lookup.global.length > 0) return true;\n for (const operations of Object.values(lookup.models)) {\n if (Object.keys(operations).length > 0) return true;\n }\n return false;\n}\n\nfunction appendFlatHandler(\n previous: readonly ResolvedExtensionHandler[] | undefined,\n extension: Pick<ResolvedExtension, \"name\">,\n handler: CallableFunction | undefined\n): readonly ResolvedExtensionHandler[] {\n if (handler === undefined) return previous ?? Object.freeze([]);\n const handlers = previous ? [...previous] : [];\n handlers.push(resolvedHandler(extension, handler));\n return Object.freeze(handlers);\n}\n\nfunction appendObserver(\n previous: readonly ResolvedExtensionHandler[] | undefined,\n extension: Pick<ResolvedExtension, \"name\">,\n handler: CallableFunction | undefined\n): readonly ResolvedExtensionHandler[] {\n if (handler === undefined) return previous ?? Object.freeze([]);\n const official = getTrustedProtectedObserverCapability(handler);\n if (official !== undefined && !official.observesLifecycle) {\n return previous ?? Object.freeze([]);\n }\n return appendFlatHandler(previous, extension, handler);\n}\n\n/**\n * Add one definition's controls to the chain's name space, then index every\n * control of the chain by operation, for every model and for each model some\n * control names. One name, one control: a call's argument is read once and\n * admitted against one declaration, so a second declaration of a name\n * (another extension's, or this one's `rows` control beside its own\n * `controls`) would refuse every call that passes either value, and a\n * binding would answer for both.\n */\nfunction appendControls(\n previous: ResolvedControls | undefined,\n declarations: readonly ResolvedControl[]\n): ResolvedControls {\n const names = new Set(previous?.names);\n for (const { name, extension } of declarations) {\n if (names.has(name)) {\n const owner = [...(previous?.all ?? []), ...declarations].find(\n (control) => control.name === name\n )!.extension;\n extensionError(\n `Extension \"${extension}\" declares control \"${name}\", which extension \"${owner}\" already declares.`,\n extension\n );\n }\n names.add(name);\n }\n const all = Object.freeze([\n ...(previous?.all ?? []),\n ...declarations.map((control) => Object.freeze(control)),\n ]);\n const lists = new Map<string, readonly ResolvedControl[]>();\n const placed = (\n model: string,\n operation: string\n ): readonly ResolvedControl[] => {\n const key = `${model}\\u0000${operation}`;\n let list = lists.get(key);\n if (list === undefined) {\n const found = all.filter(\n (control) =>\n control.operations.has(operation) &&\n (control.models === undefined || control.models.has(model))\n );\n list = found.length === 0 ? NO_CONTROLS : Object.freeze(found);\n lists.set(key, list);\n }\n return list;\n };\n return Object.freeze({ names, all, placed });\n}\n\nconst NO_ASSIGN: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/** One entry per managed model on the chain: a later entry replaces one. */\nfunction appendDeletion(\n previous: Readonly<Record<string, ResolvedDeletion>> | undefined,\n extension: string,\n deletion: DeletionContribution\n): Readonly<Record<string, ResolvedDeletion>> {\n const entries: Record<string, ResolvedDeletion> = Object.create(null);\n Object.assign(entries, previous);\n for (const [model, entry] of Object.entries(deletion.models)) {\n entries[model] = Object.freeze({\n extension,\n ...entry,\n assign: entry.assign ?? NO_ASSIGN,\n ...(deletion.removeWhen === undefined\n ? {}\n : { removeWhen: deletion.removeWhen }),\n });\n }\n return Object.freeze(entries);\n}\n\n/** One kind's fields with an extension's own merged in: it wins a field. */\nfunction withStamp(\n previous: Input | undefined,\n fields: Readonly<Record<string, unknown>> | undefined\n): Input | undefined {\n return fields === undefined\n ? previous\n : Object.freeze({ ...previous, ...fields });\n}\n\nfunction appendData(\n previous: Readonly<Record<string, ModelStamps>> | undefined,\n data: DataContribution\n): Readonly<Record<string, ModelStamps>> {\n const entries: Record<string, ModelStamps> = Object.create(null);\n Object.assign(entries, previous);\n for (const [model, entry] of Object.entries(data.models)) {\n const known = entries[model];\n entries[model] = Object.freeze({\n create: withStamp(known?.create, entry.create),\n update: withStamp(known?.update, entry.update),\n });\n }\n return Object.freeze(entries);\n}\n\n/** The cache's query leaves the chain's handlers; its control is its own. */\nfunction asOfficialCacheDefinition(\n definition: RuntimeExtensionDefinition\n): RuntimeExtensionDefinition {\n const { query: _officialCacheQuery, ...ordinaryDefinition } = definition;\n return Object.freeze({\n ...ordinaryDefinition,\n controls: officialCacheControls,\n });\n}\n\nfunction stripOfficialDefaultOmitRequest(\n definition: RuntimeExtensionDefinition\n): RuntimeExtensionDefinition {\n const { request: _officialDefaultOmitRequest, ...ordinaryDefinition } =\n definition;\n return Object.freeze(ordinaryDefinition);\n}\n\nfunction consumesOperationResults(\n definition: RuntimeExtensionDefinition\n): boolean {\n return (\n (definition.query !== undefined && !isFunction(definition.query)) ||\n definition.client !== undefined ||\n definition.model !== undefined\n );\n}\n\nfunction assertOfficialExtensionAdmission(options: {\n readonly definitionName: string;\n readonly officialName: string;\n readonly label: string;\n readonly hasIdentity: boolean;\n readonly isAlreadyPresent: boolean;\n readonly duplicateMessage: string;\n}): void {\n if (options.hasIdentity && options.isAlreadyPresent) {\n extensionError(options.duplicateMessage, options.definitionName);\n }\n if (options.hasIdentity && options.definitionName !== options.officialName) {\n extensionError(\n `The official ${options.label} extension name must be \"${options.officialName}\".`,\n options.definitionName\n );\n }\n if (!options.hasIdentity && options.definitionName === options.officialName) {\n extensionError(\n `Extension name \"${options.officialName}\" is reserved for the official ${options.label} extension.`,\n options.definitionName\n );\n }\n}\n\nexport function appendResolvedExtension(\n chain: ResolvedExtensionChain | undefined,\n value: ExtensionDefinitionInput,\n schema: Schema,\n registry?: SchemaRegistryLookup<Schema>\n): ResolvedExtensionChain {\n const definition = normalizeExtensionDefinition(value, schema, registry);\n const incomingCache = getOfficialCacheQueryCapability(definition.query);\n const existingOfficialCache = getOfficialCacheChainDefinition(chain);\n const incomingDefaultOmit = getOfficialDefaultOmitRequestCapability(\n definition.request\n );\n const existingDefaultOmit = getOfficialDefaultOmitChainCapability(chain);\n assertOfficialExtensionAdmission({\n definitionName: definition.name,\n officialName: OFFICIAL_CACHE_NAME,\n label: \"cache\",\n hasIdentity: incomingCache !== undefined,\n isAlreadyPresent: existingOfficialCache !== undefined,\n duplicateMessage:\n \"The official cache extension is already present on this client.\",\n });\n assertOfficialExtensionAdmission({\n definitionName: definition.name,\n officialName: OFFICIAL_DEFAULT_OMIT_NAME,\n label: \"default omit\",\n hasIdentity: incomingDefaultOmit !== undefined,\n // The generic duplicate-name check owns default-omit duplication after\n // instrumentation admission, preserving hostile hybrid error precedence.\n isAlreadyPresent: false,\n duplicateMessage: `Extension \"${OFFICIAL_DEFAULT_OMIT_NAME}\" is already present on this client.`,\n });\n if (incomingDefaultOmit !== undefined && chain?.hasResultConsumers === true) {\n extensionError(\n \"The default omit extension cannot follow an extension that defines model-mapped query, client, or model behavior.\",\n definition.name\n );\n }\n if (definition.rows !== undefined && chain?.hasResultConsumers === true) {\n extensionError(\n `Extension \"${definition.name}\" declares rows, which cannot follow an extension that defines model-mapped query, client, or model behavior.`,\n definition.name\n );\n }\n const incomingOfficial = getTrustedProtectedObserverCapability(\n definition.observe\n );\n const existingOfficial = getOfficialInstrumentationChainCapability(chain);\n assertOfficialExtensionAdmission({\n definitionName: definition.name,\n officialName: OFFICIAL_INSTRUMENTATION_NAME,\n label: \"instrumentation\",\n hasIdentity: incomingOfficial !== undefined,\n isAlreadyPresent: existingOfficial !== undefined,\n duplicateMessage:\n \"The official instrumentation extension is already present on this client.\",\n });\n if (\n chain?.extensions.some((extension) => extension.name === definition.name)\n ) {\n extensionError(\n `Extension \"${definition.name}\" is already present on this client.`,\n definition.name\n );\n }\n const effectiveDefinition =\n incomingCache === undefined\n ? incomingDefaultOmit === undefined\n ? definition\n : stripOfficialDefaultOmitRequest(definition)\n : asOfficialCacheDefinition(definition);\n const declaredControls =\n effectiveDefinition.controls === undefined &&\n effectiveDefinition.rows === undefined\n ? undefined\n : placeControls(effectiveDefinition);\n // A definition may name its own controls and those an earlier extension\n // declares: order owns a reference, so one value serves every extension.\n for (const control of undeclaredControlReferencesOf(effectiveDefinition)) {\n if (chain?.controls?.names.has(control) !== true) {\n extensionError(\n `Extension \"${definition.name}\" references undeclared control \"${control}\".`,\n definition.name\n );\n }\n }\n const resolved: ResolvedExtension = Object.freeze({\n name: definition.name,\n ...(effectiveDefinition.client === undefined\n ? {}\n : { client: effectiveDefinition.client }),\n ...(effectiveDefinition.model === undefined\n ? {}\n : { model: effectiveDefinition.model }),\n });\n const handlerOwner: OperationHandlerOwner =\n declaredControls === undefined\n ? resolved\n : {\n name: definition.name,\n controls: Object.freeze(\n declaredControls.map((control) => control.name)\n ),\n };\n const extensions = Object.freeze(\n chain ? [...chain.extensions, resolved] : [resolved]\n );\n const request = appendOperationHandlers(\n chain?.request,\n handlerOwner,\n effectiveDefinition.request\n );\n const query = appendOperationHandlers(\n chain?.query,\n handlerOwner,\n effectiveDefinition.query\n );\n const controls =\n declaredControls === undefined\n ? chain?.controls\n : appendControls(chain?.controls, declaredControls);\n // A lazy `verbs` entry's references are checked when it is resolved,\n // against what this chain declared here, as the loop above checks the rest.\n const ownControls = new Set([\n ...Object.keys(effectiveDefinition.controls ?? {}),\n ...(effectiveDefinition.rows ? [effectiveDefinition.rows.control] : []),\n ]);\n const declaredHere = chain?.controls?.names;\n const rows =\n effectiveDefinition.rows === undefined\n ? chain?.rows\n : Object.freeze([\n ...(chain?.rows ?? []),\n checkingLazyReferences(\n effectiveDefinition.rows,\n (control) =>\n ownControls.has(control) || declaredHere?.has(control) === true,\n (control) =>\n extensionError(\n `Extension \"${definition.name}\" references undeclared control \"${control}\".`,\n definition.name\n )\n ),\n ]);\n const deletion =\n effectiveDefinition.deletion === undefined\n ? chain?.deletion\n : appendDeletion(\n chain?.deletion,\n definition.name,\n effectiveDefinition.deletion\n );\n const data =\n effectiveDefinition.data === undefined\n ? chain?.data\n : appendData(chain?.data, effectiveDefinition.data);\n // The binding reads `required` from the controls, already appended: a\n // filter names only controls its own or an earlier extension declares, so\n // a later definition that declares only controls changes nothing it binds.\n const callRows =\n rows === chain?.rows && deletion === chain?.deletion && data === chain?.data\n ? chain?.callRows\n : bindRows(rows, deletion, data, controls);\n const result =\n effectiveDefinition.result === undefined\n ? chain?.result\n : appendResultFields(\n chain?.result,\n definition.name,\n effectiveDefinition.result,\n schema\n );\n const resolvedChain = Object.freeze({\n ...(controls === undefined ? {} : { controls }),\n ...(rows === undefined ? {} : { rows }),\n ...(deletion === undefined ? {} : { deletion }),\n ...(data === undefined ? {} : { data }),\n ...(callRows === undefined ? {} : { callRows }),\n ...(result === undefined ? {} : { result }),\n extensions,\n hasCache: incomingCache !== undefined || chain?.hasCache === true,\n hasRequestHandlers: hasCompiledHandlers(request),\n hasQueryHandlers: hasCompiledHandlers(query),\n hasResultConsumers:\n chain?.hasResultConsumers === true ||\n consumesOperationResults(effectiveDefinition),\n request,\n query,\n statement: appendFlatHandler(\n chain?.statement,\n resolved,\n effectiveDefinition.statement\n ),\n observe: appendObserver(\n chain?.observe,\n resolved,\n effectiveDefinition.observe\n ),\n });\n const official = incomingOfficial ?? existingOfficial;\n if (official !== undefined) {\n registerOfficialInstrumentationChain(resolvedChain, official);\n }\n const officialCache = incomingCache ?? existingOfficialCache;\n if (officialCache !== undefined) {\n registerOfficialCacheChain(resolvedChain, officialCache);\n }\n const officialDefaultOmit = incomingDefaultOmit ?? existingDefaultOmit;\n if (officialDefaultOmit !== undefined) {\n registerOfficialDefaultOmitChain(resolvedChain, officialDefaultOmit);\n }\n return resolvedChain;\n}\n"],"mappings":"0ZA6BA,SAAgB,mBACd,EAC4B,CAC5B,GAAI,CACF,IAAM,EAAY,EAAO,QAAQ,UACjC,OAAO,OAAO,OAAO,CACnB,QAAS,EAAO,QAChB,WAAY,EAAO,WACnB,GAAI,IAAc,IAAA,GAAY,EAAE,CAAG,CAAE,YAAW,CACjD,CAAC,MACI,CAGN,QC/BJ,MAAa,EAA6B,qBAqBpC,EAAwB,IAAI,QAI5B,EAAsB,IAAI,QAKhC,SAAS,mBAAmB,EAAiB,EAAwB,CACnE,MAAM,IAAI,EAA0B,EAAS,CAC3C,MAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAW,EAAM,CAC3D,CAAC,CAGJ,SAAS,QAAQ,EAAe,EAA8B,CAC5D,GAAI,CACF,OAAO,QAAQ,QAAQ,EAAM,OACtB,EAAO,CACd,mBACE,gBAAgB,EAAM,kCACtB,EACD,EAIL,SAASA,UACP,EACA,EACA,EACS,CACT,GAAI,CACF,OAAO,EAAM,SACN,EAAO,CACd,mBACE,gBAAgB,EAAM,WAAW,EAAI,sBACrC,EACD,yBAIL,SAAS,sBACP,EACA,EACkC,CAClC,GAAI,CACF,OAAO,EAAS,EAAM,OACf,EAAO,CACd,mBAAmB,gBAAgB,EAAM,0BAA2B,EAAM,EAI9E,SAAS,eAAe,EAA0C,CAC3D,sBAAsB,EAAO,gBAAgB,EAChD,mBAAmB,gDAAgD,CAErE,IAAM,EAGF,OAAO,OAAO,KAAK,CACvB,IAAK,IAAM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,EAAqC,EAAe,EAAS,CAE/D,IAAM,EAAgB,GAAiB,EACnC,IAAkB,IAAA,IACpB,EAA2B,EAAe,EAAc,CAE1D,IAAM,EAAsB,GAAuB,EAInD,OAHI,IAAwB,IAAA,IAC1B,iCAAiC,EAAe,EAAoB,CAE/D"}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./hydration-
|
|
2
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./hydration-BflrXEIQ.mjs";import{i as n}from"./validator-CQOw7G3q.mjs";import{a as r,n as i,o as a,s as o,t as s}from"./client-aU3YhZ6G.mjs";import{a as c}from"./identity-CmRos0Yf.mjs";import{t as l}from"./every-CzF00eDV.mjs";import{t as u}from"./version-n393hhwM.mjs";import{i as d,n as f,r as p}from"./utils-DkAxKcDD.mjs";import{t as m}from"./fs-estate-N_F2YqYa.mjs";import{Command as h,InvalidArgumentError as g}from"commander";import{resolve as _}from"node:path";import{writeFile as v}from"node:fs/promises";import{cancel as y,confirm as b,isCancel as x,note as S,outro as C}from"@clack/prompts";const needsRepair=e=>e.type===`decimal`?!e.checked:e.noncanonical!==0,describeAudit=e=>{let t=`[storage] "${e.table}"."${e.column}"`;if((e.type===`decimal`?e.declared:e.noncanonical)===null)return`${t}: the column is missing; typed queries that use it fail.\n Create it through viborm push or migrate.`;if(e.type===`decimal`)return`${t}: declared ${e.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;let n=e.type===`time`?`Time`:`DateTime`,r=e.list?"Rewrite each row through the typed client (`update`), which stores canonical members":`Repair with sqliteCanonical${n}Expression from viborm/migrations`;return`${t}: ${e.noncanonical} row(s) of noncanonical ${n} text compare and sort wrongly.\n ${r}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`},describe=e=>[`[${e.code}] ${e.message}`,e.repair].filter(Boolean).join(`
|
|
3
3
|
`);async function runCheck(e){await d({config:e.config,skipValidation:!0},e.json,async r=>{let{models:i}=r;t(i);let a=n(i),s=e.db?await o({$driver:r.driver,$schema:i}):void 0,c=s?.filter(needsRepair)??[];if(e.json)process.stdout.write(`${JSON.stringify(s?{...a,storage:s}:a,null,2)}\n`);else{for(let e of a.errors)process.stderr.write(`error ${describe(e)}\n`);for(let e of a.warnings)process.stderr.write(`warning ${describe(e)}\n`);for(let e of c)process.stderr.write(`error ${describeAudit(e)}\n`);process.stdout.write(a.valid?`Schema valid (${Object.keys(i).length} models).\n`:`Schema invalid: ${a.errors.length} error(s).\n`),s&&process.stdout.write(`Storage audited: ${s.length} column(s), ${c.length} need repair.\n`)}(!a.valid||c.length>0)&&(process.exitCode=1)})}function createCheckCommand(){return new h(`check`).description(`Validate the schema, so clients can be created with skipSchemaValidation`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--json`,`Print machine-readable JSON`).option(`--db`,`Also audit SQLite storage: DateTime/Time text and decimal columns`).action(runCheck)}const w=createCheckCommand(),T=/^[0-9a-f]{8,63}$/;function positiveInteger(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new g(`must be a positive safe integer`);return t}function selector(e){if(e)return c(e)?{id:e}:T.test(e)?{prefix:e}:{name:e}}const approveDestructive=e=>e.type===`destructive`?e.proceed():void 0,confirmDestructive=async e=>{if(e.type!==`destructive`)return;let t=await b({message:`${e.description} — approve?`,initialValue:!1});return!x(t)&&t?e.proceed():e.reject()};function generateResolver(e,t){if(e.migrations?.resolve)return e.migrations.resolve;if(t.acceptDataLoss)return approveDestructive;if(!(t.dryRun||t.json||!process.stdin.isTTY))return confirmDestructive}async function withMigrations(e,t,n){await d({config:e.opts().config},t.json,async e=>{let r=_(t.dir??e.migrations?.dir??`./migrations`),i=e.migrations?.storage??m(r);await n(s(e.client,{storage:i,...e.migrations?.tables===void 0?{}:{tables:e.migrations.tables}}),e,i)})}function createMigrateCommand(){let e=new h(`migrate`).description(`Manage the authenticated migration estate`).option(`--config <path>`,`Path to viborm.config.ts`);return e.command(`generate`).description(`Publish a new estate state from the current schema`).option(`-n, --name <name>`,`Human-readable state label`).option(`-d, --dir <dir>`,`Estate directory`).option(`--from <stateId>`,`Parent state id, or empty for the virtual root`).option(`--custom <path>`,`Compile a TypeScript manual migration author`).option(`--review <path>`,`Write labelled forward/check/rollback review SQL`).option(`--dry-run`,`Preview without publishing`).option(`--low-lock`,`PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps`).option(`--accept-data-loss`,`Approve destructive changes (drops, type changes) for this generate`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async(e,n)=>{let i=t.from===void 0?void 0:t.from===``||t.from===`empty`?null:c(t.from)?t.from:(await e.show(selector(t.from))).stateId,a;if(t.custom){let n=await f(_(t.custom)),r=(Object.hasOwn(n,`default`)?n.default:void 0)??n.migration;if(!r)throw Error(`A custom migration module must export a default migration or author function`);let o=await e.graph(),s=Object.freeze(i===void 0?o.leaves.length===0?[null]:[...o.leaves]:[i]);a=typeof r==`function`?await r(s):r}let o=generateResolver(n,t),s=await e.generate({name:t.name,from:i,dryRun:t.dryRun,...t.lowLock?{lowLock:!0}:{},...o?{resolve:o}:{},...a?{manualMigration:a}:{}});if(t.json)p(s,!0);else{process.stdout.write(`${s.outcome}: ${s.name??`No schema changes`}${s.stateId?` (${s.stateId})`:``}\n`);for(let e of s.operationsByParent??[])process.stdout.write(`Parent ${e.fromState??`empty`}:\n${e.operations.map(r).join(`
|
|
4
4
|
`)}\n`);for(let e of s.warnings??[])process.stderr.write(`warning: ${e}\n`);(s.reviewSql||s.sql)&&process.stdout.write(`${s.reviewSql||s.sql}\n`)}t.review&&s.reviewSql&&await v(_(t.review),s.reviewSql,`utf8`)})}),e.command(`check`).description(`Validate estate artifacts without touching the database`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{let n=await e.check();p(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`list`).description(`List estate states`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.list(),!!t.json)})}),e.command(`show`).description(`Show one estate state`).argument(`<state>`,`State id, unambiguous prefix, or name`).option(`-d, --dir <dir>`,`Estate directory`).option(`--sql`,`Print labelled forward/check/rollback review SQL`).option(`--review <path>`,`Write review SQL to this file`).option(`--json`,`Print machine-readable output`).action(async(t,n)=>{await withMigrations(e,n,async(e,r,o)=>{let s=await e.show(selector(t));if(!(n.sql||n.review)){p(s,!!n.json);return}let c=await a(o),l=c.states.get(s.stateId),u=l&&c.sql.get(l.sqlHash);if(!(l&&u))throw Error(`The authenticated state SQL is unavailable`);let d=i(l.parents,l.destinationChecks,u);n.json?p({...s,reviewSql:d},!0):(p(s,!1),process.stdout.write(d)),n.review&&await v(_(n.review),d,`utf8`)})}),e.command(`graph`).description(`Print estate roots and leaves`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.graph(),!!t.json)})}),e.command(`status`).description(`Show marker, pending path, and unfinished attempts`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.status(),!!t.json)})}),e.command(`verify`).description(`Lock and compare the live schema to the marker`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{let n=await e.verify();p(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`log`).description(`Print the append-only ledger`).option(`-d, --dir <dir>`,`Estate directory`).option(`--limit <n>`,`Maximum events`,positiveInteger).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{let n=await e.log();p(t.limit?n.slice(-t.limit):n,!!t.json)})}),e.command(`apply`).description(`Apply estate states to the target`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state id, prefix, or name`).option(`--via <stateId...>`,`Force a path through these states`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.apply({to:selector(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e.command(`down`).description(`Roll back along the recorded arrival path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Roll back to this state`).option(`--steps <n>`,`Number of states to roll back`,positiveInteger).option(`--accept-data-loss`,`Approve destructive changes the rollback makes to populated tables`).option(`--expect-revision <n>`,`Refuse unless the marker is at this revision`,positiveInteger).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async(e,n)=>{if(t.to!==void 0&&t.steps!==void 0)throw Error(`down accepts --to or --steps, not both`);let r=generateResolver(n,t),i={dryRun:t.dryRun,...r?{resolve:r}:{},...t.expectRevision===void 0?{}:{expectRevision:t.expectRevision}},a=await e.down(t.to?{to:selector(t.to),...i}:{steps:t.steps,...i});if(!a.preview||t.json)p(a,!!t.json);else{for(let e of a.edges)process.stdout.write(e.sql);a.refusal&&process.stderr.write(`down would refuse: ${a.refusal.code}: ${a.refusal.message}\n`)}a.preview&&a.refusal&&(process.exitCode=1)})}),e.command(`baseline`).description(`Adopt an existing database as a known estate state`).requiredOption(`--to <selector>`,`Existing estate state to adopt`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.baseline({to:selector(t.to),via:t.via}),!!t.json)})}),e.command(`reanchor`).description(`After a restore left the history older than the database, move the marker to the state the live schema matches`).option(`--to <selector>`,`Adopt this state as the new baseline`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{p(await e.reanchor({to:selector(t.to),via:t.via}),!!t.json)})}),e.command(`resolve`).description(`Resolve an unfinished attempt after live proof`).option(`-d, --dir <dir>`,`Estate directory`).option(`--complete`,`Mark complete when destination proof holds`).option(`--rolled-back`,`Mark rolled back when origin proof holds`).option(`--retry`,`Retry from the first proven incomplete step`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{if([t.complete,t.rolledBack,t.retry].filter(Boolean).length!==1)throw Error(`resolve requires exactly one of --complete, --rolled-back, or --retry`);let n=t.complete?`complete`:t.rolledBack?`rolled-back`:`retry`;p(await e.resolve({outcome:n}),!!t.json)})}),e.command(`reset`).description(`Clear managed objects and replay from empty to a selected state`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state after rebuild`).option(`--via <stateId...>`,`Force a rebuild path`).option(`--confirm`,`Confirm destructive reset (not required for dry-run)`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await withMigrations(e,t,async e=>{if(!(t.dryRun||t.confirm))throw Error(`Reset requires --confirm; inspect --dry-run first`);p(await e.reset({to:selector(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e}const E=createMigrateCommand();function printPlan(e){let t=e.operations.length===0?[`No schema changes.`]:e.operations.map(e=>`[${e.risk}] ${e.label} (${e.id})`),n=e.statements.map((e,t)=>`${t+1}. ${e.sql}${e.parameters.length===0?``:`\n parameters: ${JSON.stringify(e.parameters)}`}`);S([`Target: ${JSON.stringify(e.target)}`,`Plan: ${e.planHash}`,...t,...n.length===0?[]:[``,`SQL:`,...n]].join(`
|
|
5
5
|
`),`Push plan`)}async function runPush(e){await d({config:e.config},e.json,async t=>{let n=t.migrations?.tables===void 0?s(t.client):s(t.client,{tables:t.migrations.tables}),r=await n.push({dryRun:!0,...e.forceReset===!0?{forceReset:!0}:{},...t.migrations?.resolve?{resolve:t.migrations.resolve}:{}});if(!e.json&&t.driver?.dialect===`sqlite`&&[`sqlite3`,`bun-sqlite`,`bun-sql`].includes(t.driver.driverName)&&(await t.driver._executeRaw(`PRAGMA database_list`)).rows.some(e=>e.name===`main`&&e.file===``)&&process.stderr.write(`warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.
|