viborm 1.2.1 → 1.2.2

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.
Files changed (61) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/bun-sql.d.mts +1 -1
  3. package/dist/bun-sqlite.d.mts +1 -1
  4. package/dist/cache/cloudflare-kv.d.mts +1 -1
  5. package/dist/cache/memory.d.mts +1 -1
  6. package/dist/cache.d.mts +1 -1
  7. package/dist/cli.mjs +1 -1
  8. package/dist/{client-XQSEkF90.d.mts → client-BKKA2CQj.d.mts} +1 -1
  9. package/dist/{client-CCgfcp5A.mjs → client-D291xo5z.mjs} +20 -20
  10. package/dist/client-D291xo5z.mjs.map +1 -0
  11. package/dist/client.d.mts +1 -1
  12. package/dist/config.d.mts +1 -1
  13. package/dist/d1.d.mts +1 -1
  14. package/dist/driver.d.mts +1 -1
  15. package/dist/every-BJLkY4qm.mjs +2 -0
  16. package/dist/{every-4KE0p2Gw.mjs.map → every-BJLkY4qm.mjs.map} +1 -1
  17. package/dist/{index-Likdf5qP.d.mts → index-BaK35ze2.d.mts} +48 -25
  18. package/dist/index.d.mts +1 -1
  19. package/dist/instrumentation.d.mts +1 -1
  20. package/dist/instrumentation.mjs +1 -1
  21. package/dist/{libsql-Bu_IdFU1.mjs → libsql-IdshHiw4.mjs} +3 -3
  22. package/dist/libsql-IdshHiw4.mjs.map +1 -0
  23. package/dist/libsql.d.mts +1 -1
  24. package/dist/{memory-D4yxtCPK.mjs → memory-DSEeJ7ps.mjs} +2 -2
  25. package/dist/{memory-D4yxtCPK.mjs.map → memory-DSEeJ7ps.mjs.map} +1 -1
  26. package/dist/migrations/mysql.d.mts +4 -4
  27. package/dist/migrations/mysql.mjs +1 -1
  28. package/dist/migrations/postgres.d.mts +4 -4
  29. package/dist/migrations/postgres.mjs +1 -1
  30. package/dist/migrations/sqlite.d.mts +4 -4
  31. package/dist/migrations/sqlite.mjs +1 -1
  32. package/dist/migrations/tenant.d.mts +2 -2
  33. package/dist/migrations/tenant.mjs +1 -1
  34. package/dist/migrations.d.mts +4 -4
  35. package/dist/migrations.mjs +1 -1
  36. package/dist/{mysql-CibPaHSp.mjs → mysql-B7VGoX6t.mjs} +3 -3
  37. package/dist/mysql-B7VGoX6t.mjs.map +1 -0
  38. package/dist/mysql2.d.mts +1 -1
  39. package/dist/neon-http.d.mts +1 -1
  40. package/dist/{object-store-CbjhsBQ3.d.mts → object-store-DCxwbkys.d.mts} +3 -3
  41. package/dist/pg.d.mts +1 -1
  42. package/dist/pglite.d.mts +1 -1
  43. package/dist/planetscale.d.mts +1 -1
  44. package/dist/{planner-CwFUkNHP.d.mts → planner-BKHHRpvB.d.mts} +1 -1
  45. package/dist/{postgres-oqNW9xqo.mjs → postgres-CeSmp2Tj.mjs} +4 -4
  46. package/dist/postgres-CeSmp2Tj.mjs.map +1 -0
  47. package/dist/postgres.d.mts +1 -1
  48. package/dist/schema/json.d.mts +1 -1
  49. package/dist/schema.d.mts +1 -1
  50. package/dist/soft-delete.d.mts +1 -1
  51. package/dist/sqlite3.d.mts +1 -1
  52. package/dist/validation.d.mts +1 -1
  53. package/dist/version-DxmSsAcv.mjs +2 -0
  54. package/dist/{version-B4VuToLC.mjs.map → version-DxmSsAcv.mjs.map} +1 -1
  55. package/package.json +2 -2
  56. package/dist/client-CCgfcp5A.mjs.map +0 -1
  57. package/dist/every-4KE0p2Gw.mjs +0 -2
  58. package/dist/libsql-Bu_IdFU1.mjs.map +0 -1
  59. package/dist/mysql-CibPaHSp.mjs.map +0 -1
  60. package/dist/postgres-oqNW9xqo.mjs.map +0 -1
  61. package/dist/version-B4VuToLC.mjs +0 -2
package/dist/client.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as Schema, At as getOperationPayloadSchema, B as LinkedClientConfig, C as Client, D as OperationPayloadSchema, E as OperationPayload, F as GroupByResultType, Ft as ExtendedClient, H as RelationLinks, Hn as IndexDefinition, Ht as defaultOmit, I as InferSelectInclude, Jt as defineExtension, Kt as PlacedControl, L as ClientSchema, M as AggregateResultType, Mt as renderSchemaType, N as BatchPayload, Nt as validateOperationPayload, O as OperationResult, P as CountResultType, R as FlatSchema, S as CachedClient, T as MutationOperations, Un as IndexOptions, V as Links, Xt as StatementHandler, Yt as StatementContext, _ as ObservationCompletion, _n as isPendingOperation, en as ExtensionCacheState, et as VibSchema, gn as UnwrapPendingOperations, hn as UnwrapPendingOperation, in as RawOperation, j as ValidatedOperationPayload, jt as renderOperationResultType, k as Operations, lr as ObjectSchema, mn as PendingOperation, nn as ExtensionResultConsumerState, qt as ClientExtension, v as ObservationUnit, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, z as Linked } from "./index-Likdf5qP.mjs";
1
+ import { A as Schema, At as getOperationPayloadSchema, B as LinkedClientConfig, C as Client, D as OperationPayloadSchema, E as OperationPayload, F as GroupByResultType, Ft as ExtendedClient, H as RelationLinks, Hn as IndexDefinition, Ht as defaultOmit, I as InferSelectInclude, Jt as defineExtension, Kt as PlacedControl, L as ClientSchema, M as AggregateResultType, Mt as renderSchemaType, N as BatchPayload, Nt as validateOperationPayload, O as OperationResult, P as CountResultType, R as FlatSchema, S as CachedClient, T as MutationOperations, Un as IndexOptions, V as Links, Xt as StatementHandler, Yt as StatementContext, _ as ObservationCompletion, _n as isPendingOperation, en as ExtensionCacheState, et as VibSchema, gn as UnwrapPendingOperations, hn as UnwrapPendingOperation, in as RawOperation, j as ValidatedOperationPayload, jt as renderOperationResultType, k as Operations, lr as ObjectSchema, mn as PendingOperation, nn as ExtensionResultConsumerState, qt as ClientExtension, v as ObservationUnit, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, z as Linked } from "./index-BaK35ze2.mjs";
2
2
  export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type CountResultType, type ExtendedClient, type ExtensionCacheState, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedControl, type RawOperation, type RelationLinks, type Schema, type StatementContext, type StatementHandler, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, defineExtension, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ResolveCallback, t as MigrationClient } from "./planner-CwFUkNHP.mjs";
1
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-BKHHRpvB.mjs";
2
2
  import { n as MigrationStorageWriter } from "./contract-CIIqgFyb.mjs";
3
3
 
4
4
  //#region src/cli/utils.d.ts
package/dist/d1.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, On as BatchQuery, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as QueryExecutionContext, kn as CommittedBatchNotification, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-Likdf5qP.mjs";
1
+ import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, On as BatchQuery, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as QueryExecutionContext, kn as CommittedBatchNotification, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-BaK35ze2.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
package/dist/driver.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { An as Dialect, Mn as QueryResult, On as BatchQuery, Pi as isRetryableError, _i as CheckConstraintError, bi as UniqueConstraintError, ei as TransactionError, f as SQLITE_MIGRATION_CAPABILITY, h as DriverResultParser, jn as QueryExecutionContext, l as AnyDriver, li as QueryError, ni as ConnectionError, p as SqliteMigrationCapability, ri as FeatureNotSupportedError, u as Driver, vi as ForeignKeyError, wn as sqliteResultParser, yi as NotNullConstraintError } from "./index-Likdf5qP.mjs";
1
+ import { An as Dialect, Mn as QueryResult, On as BatchQuery, Pi as isRetryableError, _i as CheckConstraintError, bi as UniqueConstraintError, ei as TransactionError, f as SQLITE_MIGRATION_CAPABILITY, h as DriverResultParser, jn as QueryExecutionContext, l as AnyDriver, li as QueryError, ni as ConnectionError, p as SqliteMigrationCapability, ri as FeatureNotSupportedError, u as Driver, vi as ForeignKeyError, wn as sqliteResultParser, yi as NotNullConstraintError } from "./index-BaK35ze2.mjs";
2
2
  export { type AnyDriver, type BatchQuery, CheckConstraintError, ConnectionError, type Dialect, Driver, type DriverResultParser, FeatureNotSupportedError, ForeignKeyError, NotNullConstraintError, QueryError, type QueryExecutionContext, type QueryResult, SQLITE_MIGRATION_CAPABILITY, type SqliteMigrationCapability, TransactionError, UniqueConstraintError, isRetryableError, sqliteResultParser };
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./client-D291xo5z.mjs";import{n,t as r}from"./libsql-IdshHiw4.mjs";import{t as i}from"./mysql-B7VGoX6t.mjs";import{t as a}from"./postgres-CeSmp2Tj.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i)}export{registerEveryMigrationDriver as t};
2
+ //# sourceMappingURL=every-BJLkY4qm.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"every-4KE0p2Gw.mjs","names":[],"sources":["../src/migrations/dialects/every.ts"],"sourcesContent":["/**\n * Every dialect's migration driver. Callers register from their own entry\n * statement (`viborm/migrations`, the CLI), so the registration stays with\n * the entry a bundler keeps.\n */\n\nimport { registerMigrationDriver } from \"../drivers\";\nimport { libsqlMigrationDriver } from \"../drivers/libsql\";\nimport { mysqlMigrationDriver } from \"../drivers/mysql\";\nimport { postgresMigrationDriver } from \"../drivers/postgres\";\nimport { sqlite3MigrationDriver } from \"../drivers/sqlite\";\n\nexport function registerEveryMigrationDriver(): void {\n registerMigrationDriver(postgresMigrationDriver);\n registerMigrationDriver(sqlite3MigrationDriver);\n registerMigrationDriver(libsqlMigrationDriver);\n registerMigrationDriver(mysqlMigrationDriver);\n}\n"],"mappings":"oNAYA,SAAgB,8BAAqC,CACnD,EAAwB,EAAwB,CAChD,EAAwB,EAAuB,CAC/C,EAAwB,EAAsB,CAC9C,EAAwB,EAAqB"}
1
+ {"version":3,"file":"every-BJLkY4qm.mjs","names":[],"sources":["../src/migrations/dialects/every.ts"],"sourcesContent":["/**\n * Every dialect's migration driver. Callers register from their own entry\n * statement (`viborm/migrations`, the CLI), so the registration stays with\n * the entry a bundler keeps.\n */\n\nimport { registerMigrationDriver } from \"../drivers\";\nimport { libsqlMigrationDriver } from \"../drivers/libsql\";\nimport { mysqlMigrationDriver } from \"../drivers/mysql\";\nimport { postgresMigrationDriver } from \"../drivers/postgres\";\nimport { sqlite3MigrationDriver } from \"../drivers/sqlite\";\n\nexport function registerEveryMigrationDriver(): void {\n registerMigrationDriver(postgresMigrationDriver);\n registerMigrationDriver(sqlite3MigrationDriver);\n registerMigrationDriver(libsqlMigrationDriver);\n registerMigrationDriver(mysqlMigrationDriver);\n}\n"],"mappings":"oNAYA,SAAgB,8BAAqC,CACnD,EAAwB,EAAwB,CAChD,EAAwB,EAAuB,CAC/C,EAAwB,EAAsB,CAC9C,EAAwB,EAAqB"}
@@ -10930,15 +10930,16 @@ type NoExtraClauseKeys<Given, Allowed, Always extends PropertyKey = never> = Giv
10930
10930
  * The root-reported walks (WHERE model keys, nested write data) follow the
10931
10931
  * LITERAL the caller wrote, key each spelled object against a key set read
10932
10932
  * from the model's state, and report what is left as ONE `UnknownClauseKey` on
10933
- * the root clause. Both descend only REQUIRED keys (`RequiredSpelledKeys`),
10934
- * never a payload's own optional ones, which is what expands the recursive
10935
- * payloads (see above): a held value typed as the payload spells none, and
10936
- * following its optional relation keys enumerated every path through the
10937
- * model graph (TS2589 in 1.2.0). Cycle detection uses the exact
10938
- * spelled-value/model pair, never a numeric depth cap, so a value whose type
10939
- * requires a recursive key stops at its first repeat. `NoInfer` keeps that
10940
- * comparison from inferring through a relinked model (a mapped type), which
10941
- * would walk its whole relation graph.
10933
+ * the root clause. Neither follows a payload's own optional keys, which is
10934
+ * what expands the recursive payloads (see above): following them through a
10935
+ * held value typed as the payload enumerated every path through the model
10936
+ * graph (TS2589 in 1.2.0). The write walk descends only REQUIRED keys
10937
+ * (`RequiredSpelledKeys`); the WHERE walk descends every key of a finite
10938
+ * value and stops at the payload (`WhereWalkKeys`). Cycle detection uses the
10939
+ * exact spelled-value/model pair, never a numeric depth cap, so a held
10940
+ * recursive type stops at its first repeat. `NoInfer` keeps that comparison
10941
+ * from inferring through a relinked model (a mapped type), which would walk
10942
+ * its whole relation graph.
10942
10943
  */
10943
10944
  type SameValue<A, B$1> = (<T$1>() => T$1 extends NoInfer<A> ? 1 : 2) extends (<T$1>() => T$1 extends NoInfer<B$1> ? 1 : 2) ? true : false;
10944
10945
  type SeenValue<Given, M$1, Seen> = true extends (Seen extends unknown ? SameValue<readonly [Given, M$1], Seen> : never) ? true : false;
@@ -10954,7 +10955,25 @@ type QuantifiedWhereUnknownKeys<Given, R$1 extends AnyRelation, Seen, Q$1 extend
10954
10955
  * is sealed exactly as on the select side.
10955
10956
  */
10956
10957
  type RelationWhereUnknownKeys<Given, R$1 extends AnyRelation, Seen> = TargetKind<R$1> extends "model" ? "recurse" extends SpelledClauseKeys<Given> ? QuantifiedWhereUnknownKeys<Given, R$1, Seen, "some" | "every" | "none"> | MisspelledRecurrenceKeys<ValueAt<Given, "recurse">> : Cardinality<R$1> extends "one" ? [Extract<SpelledClauseKeys<Given>, "is" | "isNot">] extends [never] ? WhereUnknownKeys<Given, GetTargetModel<R$1>, Seen> : QuantifiedWhereUnknownKeys<Given, R$1, Seen, "is" | "isNot"> : QuantifiedWhereUnknownKeys<Given, R$1, Seen, "some" | "every" | "none"> : never;
10957
- type WhereUnknownKeys<Given, M$1 extends Model$1<any>, Seen = never, Allowed extends PropertyKey = WhereModelKeys<M$1>> = Given extends readonly unknown[] ? WhereUnknownKeys<Given[number], M$1, Seen, Allowed> : Given extends object ? string extends keyof Given ? never : Exclude<keyof Given, Allowed> | (SeenValue<Given, M$1, Seen> extends true ? never : { [K in Extract<RequiredSpelledKeys<Given>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>]: K extends WhereLogicalKeys<M$1> ? WhereUnknownKeys<NonNullable<Given[K]>, M$1, Seen | readonly [Given, M$1]> : K extends keyof M$1["~"]["state"]["relations"] ? RelationWhereUnknownKeys<NonNullable<Given[K]>, M$1["~"]["state"]["relations"][K], Seen | readonly [Given, M$1]> : never }[Extract<RequiredSpelledKeys<Given>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>]) : never;
10958
+ /**
10959
+ * The misspelled model keys of one WHERE value, at every depth it names. An
10960
+ * `any` value states no key and is not walked: its array arm would unwrap it
10961
+ * to itself until TS2589.
10962
+ */
10963
+ type WhereUnknownKeys<Given, M$1 extends Model$1<any>, Seen = never, Allowed extends PropertyKey = WhereModelKeys<M$1>> = 0 extends 1 & Given ? never : Given extends readonly unknown[] ? WhereUnknownKeys<Given[number], M$1, Seen, Allowed> : Given extends object ? string extends keyof Given ? never : Exclude<keyof Given, Allowed> | (SeenValue<Given, M$1, Seen> extends true ? never : { [K in Extract<WhereWalkKeys<Given, M$1>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>]: K extends WhereLogicalKeys<M$1> ? WhereUnknownKeys<NonNullable<Given[K]>, M$1, Seen | readonly [Given, M$1]> : K extends keyof M$1["~"]["state"]["relations"] ? RelationWhereUnknownKeys<NonNullable<Given[K]>, M$1["~"]["state"]["relations"][K], Seen | readonly [Given, M$1]> : never }[Extract<WhereWalkKeys<Given, M$1>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>]) : never;
10964
+ /**
10965
+ * The keys of one WHERE object the walk descends. A value whose type states
10966
+ * every key of the model's WHERE is the client's own payload, under any of its
10967
+ * spellings (`Parameters<…>`, `ModelCoreInput<…, "where">`, `InferDatabase`'s
10968
+ * `Where`, an `AND` element, a quantifier's target) or spread into a literal:
10969
+ * only what its type requires was written, and following its optional
10970
+ * relation keys would enumerate every path through the model graph (TS2589 in
10971
+ * 1.2.0). Any other value is finite, so every key it names is walked,
10972
+ * optional ones included: a held filter's and a conditional spread's. A
10973
+ * relation filter typed by a type parameter is refused there, as under a
10974
+ * required key: its keys cannot be read.
10975
+ */
10976
+ type WhereWalkKeys<Given, M$1 extends Model$1<any>> = [Exclude<WhereModelKeys<M$1>, keyof Given>] extends [never] ? RequiredSpelledKeys<Given> : keyof Given;
10958
10977
  /**
10959
10978
  * The data objects one relation's write verbs carry: `create`,
10960
10979
  * `createMany.data`, `connectOrCreate.create`, `upsert.create` / `.update`,
@@ -10977,6 +10996,12 @@ type UpdateFormData<Update, TargetKeys> = Update extends {
10977
10996
  * `N extends { select?: { title?: true } }` unprovable.
10978
10997
  */
10979
10998
  type RequiredSpelledKeys<Given> = Given extends object ? keyof { [K in keyof Given as Record<never, never> extends Pick<Given, K> ? never : K]: 0 } : never;
10999
+ /**
11000
+ * Every key an object names beside an index signature, optional ones
11001
+ * included, in the key-remapped form that resolves a generic node through its
11002
+ * constraint.
11003
+ */
11004
+ type WrittenKeys<Given> = Given extends object ? keyof { [K in keyof Given as string extends K ? never : K]: 0 } : never;
10980
11005
  /**
10981
11006
  * The keys nested write data spells that its model does not declare, at
10982
11007
  * every depth below the root data (whose own keys `DirectWriteKeysGuard`
@@ -10999,13 +11024,12 @@ type SpelledClause<Arg, Clause extends PropertyKey> = [Arg] extends [{ [Key in C
10999
11024
  * `where` walks model field names through relation and logical filters,
11000
11025
  * `data` / `create` / `update` walk nested write data. A clause spelling no
11001
11026
  * relation or logical group has nothing below its root to walk. A `where`
11002
- * that IS the payload type is not walked either. `Parameters<…>` instantiates
11003
- * this guard with the payload as the argument, where a unique `where` is
11004
- * required and is a union of arms that each require their key; walking them
11005
- * costs one `Parameters<…>` read of a `findUnique` about 12k instantiations at
11006
- * 50 models (measured for 1.2.1).
11027
+ * typed as the payload stops at its root (`WhereWalkKeys`), which is what
11028
+ * `Parameters<…>` hands this guard: it instantiates the argument with the
11029
+ * payload, where a unique `where` is required and is a union of arms that
11030
+ * each require their key.
11007
11031
  */
11008
- type NestedClauseGuard<Arg, Payload, M$1 extends Model$1<any>, Clause extends "where" | "data" | "create" | "update"> = Clause extends keyof Arg ? SpelledClause<Arg, Clause> extends true ? Clause extends keyof Payload ? [Extract<SpelledClauseKeys<ElementOf<NonNullable<Arg[Clause]>>>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>] extends [never] ? unknown : (Clause extends "where" ? SameValue<NonNullable<Arg[Clause]>, NonNullable<Payload[Clause]>> extends true ? never : WhereUnknownKeys<NonNullable<Arg[Clause]>, M$1, never, ClauseKeys<NonNullable<Payload[Clause]>>> : NestedWriteUnknownKeys<NonNullable<Arg[Clause]>, M$1>) extends infer Extra ? [Extra] extends [never] ? unknown : { [Key in Clause]?: UnknownClauseKey<Extra> } : unknown : unknown : unknown : unknown;
11032
+ type NestedClauseGuard<Arg, Payload, M$1 extends Model$1<any>, Clause extends "where" | "data" | "create" | "update"> = Clause extends keyof Arg ? SpelledClause<Arg, Clause> extends true ? Clause extends keyof Payload ? [Extract<SpelledClauseKeys<ElementOf<NonNullable<Arg[Clause]>>>, WhereLogicalKeys<M$1> | keyof M$1["~"]["state"]["relations"]>] extends [never] ? unknown : (Clause extends "where" ? WhereUnknownKeys<NonNullable<Arg[Clause]>, M$1, never, ClauseKeys<NonNullable<Payload[Clause]>>> : NestedWriteUnknownKeys<NonNullable<Arg[Clause]>, M$1>) extends infer Extra ? [Extra] extends [never] ? unknown : { [Key in Clause]?: UnknownClauseKey<Extra> } : unknown : unknown : unknown : unknown;
11009
11033
  /**
11010
11034
  * A root WHERE operator bag, sealed at the bag: an object spelled for a
11011
11035
  * scalar is keyed against every key the field's object arms declare, so
@@ -11129,9 +11153,7 @@ type RecursiveNodeObjectGuard<Node, T$1> = ExclusiveSelection<Node> & ("recurse"
11129
11153
  select?: RecursiveProjectionGuard<Node["select"], T$1> & ProjectionKeySeal<Node["select"], T$1, "select">;
11130
11154
  } : unknown) & ("include" extends keyof Node ? {
11131
11155
  include?: RecursiveProjectionGuard<Node["include"], T$1> & ProjectionKeySeal<Node["include"], T$1, "include">;
11132
- } : unknown) & ([Node] extends [{
11133
- where: unknown;
11134
- }] ? {
11156
+ } : unknown) & ("where" extends keyof Node ? {
11135
11157
  where?: NodeWhereSeal<Node["where"], T$1>;
11136
11158
  } : unknown) & ("variants" extends keyof Node ? {
11137
11159
  variants?: RecursiveProjectionGuard<Node["variants"], never>;
@@ -11144,13 +11166,14 @@ type RecursiveNodeObjectGuard<Node, T$1> = ExclusiveSelection<Node> & ("recurse"
11144
11166
  */
11145
11167
  type RecursiveProjectionGuard<Clause, T$1, Skipped extends PropertyKey = never> = { [Key in Exclude<SpelledClauseKeys<NonNullable<Clause>>, Skipped>]?: boolean | RecursiveNodeGuard<ValueAt<NonNullable<Clause>, Key>, RelationTarget<T$1, Key>> };
11146
11168
  /**
11147
- * A model-target node's `select` / `include` keys, beside `_count`. Only the
11148
- * keys the value requires are spelled: a held node (typed as the payload, as
11149
- * `Parameters<…>` reads it) is a union of the ordinary and the recursive
11150
- * node, and the recursive arm's projection carries the asking key as an
11151
- * optional refused member nobody wrote.
11169
+ * A model-target node's `select` / `include` keys, beside `_count`: every
11170
+ * key the value names, optional ones included, is refused as `?: undefined`.
11171
+ * That is the type of the one unknown key nobody wrote: a held node (typed as
11172
+ * the payload, as `Parameters<…>` reads it) is a union of the ordinary and the
11173
+ * recursive node, and the recursive arm's projection carries the asking key as
11174
+ * a refused `?: undefined` member.
11152
11175
  */
11153
- type ProjectionKeySeal<Clause, T$1, Kind$1 extends "select" | "include"> = [T$1] extends [never] ? unknown : T$1 extends Model$1<any> ? Record<Exclude<RequiredSpelledKeys<NonNullable<Clause>>, "_count" | keyof T$1["~"]["state"][Kind$1 extends "select" ? "shape" : "relations"]>, never> : unknown;
11176
+ type ProjectionKeySeal<Clause, T$1, Kind$1 extends "select" | "include"> = [T$1] extends [never] ? unknown : T$1 extends Model$1<any> ? { [Key in Exclude<WrittenKeys<NonNullable<Clause>>, "_count" | keyof T$1["~"]["state"][Kind$1 extends "select" ? "shape" : "relations"]>]?: undefined } : unknown;
11154
11177
  /** A model-target node's `where`, walked as the root WHERE is. */
11155
11178
  type NodeWhereSeal<Where, T$1> = [T$1] extends [never] ? unknown : T$1 extends Model$1<any> ? WhereUnknownKeys<NonNullable<Where>, T$1> extends infer Extra ? [Extra] extends [never] ? unknown : UnknownClauseKey<Extra> : unknown : unknown;
11156
11179
  type ScalarStateOf<Field, Kind$1 extends ScalarType> = Field extends {
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $n as GeneratorDefaultBrand, $r as InvalidTransactionInputError, $t as EmptyClientExtensionState, Ai as CacheOperationNotCacheableError, At as getOperationPayloadSchema, B as LinkedClientConfig, Bi as GeoBounds, Bn as isFieldRef, Br as JsonNullSentinel, Bt as VibORMConfig, Ci as isForeignKeyError, Cr as IsoTimestampSchema, Ct as BooleanScalar, Di as CacheConfigurationError, Dr as BooleanSchema, Dt as ModelToManyRelation, Ei as isValueTooLongError, Et as ReferencesStage, Fi as isVibORMError, Fn as StringSchema, Fr as AnyJsonNullSentinel, Ft as ExtendedClient, G as VariantToOneRelation, Gn as InitialModelState, Gr as Getter, Gt as NoControls, H as RelationLinks, Hi as GeoPolygon, Hn as IndexDefinition, Ii as toPrismaErrorCode, In as AnyFieldRef, Ir as AnyNull, It as ExtendedOperationResult, Jn as ModelState, Jr as RelationCardinality, Jt as defineExtension, K as Scalar, Kn as Model, Kt as PlacedControl, L as ClientSchema, Li as wrapError, Ln as FieldRef, Lr as DbNull, Lt as ExtensionState, Mi as VibORMError, Mt as renderSchemaType, Ni as VibORMErrorCode, Nt as validateOperationPayload, Oi as CacheInvalidKeyError, Ot as s, Pi as isRetryableError, Qr as isValidationError, Qt as ClientExtensionState, R as FlatSchema, Ri as DiagnosticDisclosure, Rn as ModelFieldRefs, Rr as JsonNull, Si as isCheckConstraintError, Sr as IsoTimeSchema, St as DateScalar, Ti as isUniqueConstraintError, Tr as EnumSchema, Tt as ModelToOneRelation, U as ModelShape, Ui as DecimalDescriptor, Un as IndexOptions, V as Links, Vi as GeoPoint, Vn as AnyModel, Vr as isJsonNullSentinel, Vt as createClient, W as VariantToManyRelation, Wi as Decimal, Wr as AnyRelation, Xn as DecimalSchema, Xr as ValidationError, Xt as StatementHandler, Yn as UpdateState, Yr as RelationSlot, Yt as StatementContext, Zn as AutoGenerate, Zr as ValidationErrorSource, Zt as AccumulatedExtensionState, _ as ObservationCompletion, _i as CheckConstraintError, _n as isPendingOperation, _r as JsonValue, _t as IntScalar, ai as NestedWriteError, an as validateSchema, bi as UniqueConstraintError, bt as TimeScalar, ci as QueryEngineError, cn as isSchemaValidationError, cr as PointSchema, di as isClientInitializationError, dn as ValidationResult, dt as NumericScalar, ei as TransactionError, en as ExtensionCacheState, er as InitialScalarState, et as VibSchema, fi as isNotFoundError, fr as IntegerSchema, ft as VectorScalar, gi as isMigrationError, gn as UnwrapPendingOperations, gr as JsonSchema, gt as JsonScalar, hi as MigrationError, hn as UnwrapPendingOperation, hr as InputJsonValue, ht as NumberScalar, ii as NestedWriteAssertionError, in as RawOperation, ji as PrismaErrorCode, jr as BigIntSchema, jt as renderOperationResultType, ki as CacheInvalidTTLError, kr as BlobSchema, kt as getSchemas, li as QueryError, ln as SchemaValidationIssue, lr as ObjectSchema, mi as isUnsupportedOperationError, mn as PendingOperation, mt as PointScalar, ni as ConnectionError, nn as ExtensionResultConsumerState, oi as NotFoundError, on as validateSchemaOrThrow, or as VectorSchema, pi as isPendingOperationError, pr as NumberSchema, pt as StringScalar, q as BigIntScalar, qn as ModelInternal, qr as ReferentialAction, qt as ClientExtension, ri as FeatureNotSupportedError, rn as MergeExtensionState, rr as UpdateState$1, si as PendingOperationError, sn as SchemaValidationError, ti as ClientInitializationError, tn as ExtensionContributionState, tr as ScalarState, ui as UnsupportedOperationError, un as Severity, v as ObservationUnit, vi as ForeignKeyError, vt as EnumScalar, wi as isNotNullConstraintError, wt as BlobScalar, xi as ValueTooLongError, xr as IsoDateSchema, xt as DateTimeScalar, y as ObserveHandler, yi as NotNullConstraintError, yt as DecimalScalar, z as Linked, zi as GeoArea, zn as createModelFieldRefs, zr as JsonNullKind, zt as VibORMClient } from "./index-Likdf5qP.mjs";
1
+ import { $n as GeneratorDefaultBrand, $r as InvalidTransactionInputError, $t as EmptyClientExtensionState, Ai as CacheOperationNotCacheableError, At as getOperationPayloadSchema, B as LinkedClientConfig, Bi as GeoBounds, Bn as isFieldRef, Br as JsonNullSentinel, Bt as VibORMConfig, Ci as isForeignKeyError, Cr as IsoTimestampSchema, Ct as BooleanScalar, Di as CacheConfigurationError, Dr as BooleanSchema, Dt as ModelToManyRelation, Ei as isValueTooLongError, Et as ReferencesStage, Fi as isVibORMError, Fn as StringSchema, Fr as AnyJsonNullSentinel, Ft as ExtendedClient, G as VariantToOneRelation, Gn as InitialModelState, Gr as Getter, Gt as NoControls, H as RelationLinks, Hi as GeoPolygon, Hn as IndexDefinition, Ii as toPrismaErrorCode, In as AnyFieldRef, Ir as AnyNull, It as ExtendedOperationResult, Jn as ModelState, Jr as RelationCardinality, Jt as defineExtension, K as Scalar, Kn as Model, Kt as PlacedControl, L as ClientSchema, Li as wrapError, Ln as FieldRef, Lr as DbNull, Lt as ExtensionState, Mi as VibORMError, Mt as renderSchemaType, Ni as VibORMErrorCode, Nt as validateOperationPayload, Oi as CacheInvalidKeyError, Ot as s, Pi as isRetryableError, Qr as isValidationError, Qt as ClientExtensionState, R as FlatSchema, Ri as DiagnosticDisclosure, Rn as ModelFieldRefs, Rr as JsonNull, Si as isCheckConstraintError, Sr as IsoTimeSchema, St as DateScalar, Ti as isUniqueConstraintError, Tr as EnumSchema, Tt as ModelToOneRelation, U as ModelShape, Ui as DecimalDescriptor, Un as IndexOptions, V as Links, Vi as GeoPoint, Vn as AnyModel, Vr as isJsonNullSentinel, Vt as createClient, W as VariantToManyRelation, Wi as Decimal, Wr as AnyRelation, Xn as DecimalSchema, Xr as ValidationError, Xt as StatementHandler, Yn as UpdateState, Yr as RelationSlot, Yt as StatementContext, Zn as AutoGenerate, Zr as ValidationErrorSource, Zt as AccumulatedExtensionState, _ as ObservationCompletion, _i as CheckConstraintError, _n as isPendingOperation, _r as JsonValue, _t as IntScalar, ai as NestedWriteError, an as validateSchema, bi as UniqueConstraintError, bt as TimeScalar, ci as QueryEngineError, cn as isSchemaValidationError, cr as PointSchema, di as isClientInitializationError, dn as ValidationResult, dt as NumericScalar, ei as TransactionError, en as ExtensionCacheState, er as InitialScalarState, et as VibSchema, fi as isNotFoundError, fr as IntegerSchema, ft as VectorScalar, gi as isMigrationError, gn as UnwrapPendingOperations, gr as JsonSchema, gt as JsonScalar, hi as MigrationError, hn as UnwrapPendingOperation, hr as InputJsonValue, ht as NumberScalar, ii as NestedWriteAssertionError, in as RawOperation, ji as PrismaErrorCode, jr as BigIntSchema, jt as renderOperationResultType, ki as CacheInvalidTTLError, kr as BlobSchema, kt as getSchemas, li as QueryError, ln as SchemaValidationIssue, lr as ObjectSchema, mi as isUnsupportedOperationError, mn as PendingOperation, mt as PointScalar, ni as ConnectionError, nn as ExtensionResultConsumerState, oi as NotFoundError, on as validateSchemaOrThrow, or as VectorSchema, pi as isPendingOperationError, pr as NumberSchema, pt as StringScalar, q as BigIntScalar, qn as ModelInternal, qr as ReferentialAction, qt as ClientExtension, ri as FeatureNotSupportedError, rn as MergeExtensionState, rr as UpdateState$1, si as PendingOperationError, sn as SchemaValidationError, ti as ClientInitializationError, tn as ExtensionContributionState, tr as ScalarState, ui as UnsupportedOperationError, un as Severity, v as ObservationUnit, vi as ForeignKeyError, vt as EnumScalar, wi as isNotNullConstraintError, wt as BlobScalar, xi as ValueTooLongError, xr as IsoDateSchema, xt as DateTimeScalar, y as ObserveHandler, yi as NotNullConstraintError, yt as DecimalScalar, z as Linked, zi as GeoArea, zn as createModelFieldRefs, zr as JsonNullKind, zt as VibORMClient } from "./index-BaK35ze2.mjs";
2
2
  import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-BvfwUKIh.mjs";
3
3
  export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
@@ -1,4 +1,4 @@
1
- import { Mi as VibORMError, Ri as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-Likdf5qP.mjs";
1
+ import { Mi as VibORMError, Ri as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-BaK35ze2.mjs";
2
2
 
3
3
  //#region src/instrumentation/types.d.ts
4
4
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{t as r,u as i}from"./chain-Dh0FV72b.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-AdXAoy6l.mjs";import{c as g,s as _,u as ee}from"./observation-DUSm7oXK.mjs";import{t as te}from"./version-B4VuToLC.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:r,correlationId:a}=t;return{...createDriverAttributes(i(e)),...n?{[E]:n}:{},...r?{[D]:r}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),i=function officialInstrumentationObserver(){};return $.set(n,t),ee(i,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:r,observe:i})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`)throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{t as r,u as i}from"./chain-Dh0FV72b.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-AdXAoy6l.mjs";import{c as g,s as _,u as ee}from"./observation-DUSm7oXK.mjs";import{t as te}from"./version-DxmSsAcv.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:r,correlationId:a}=t;return{...createDriverAttributes(i(e)),...n?{[E]:n}:{},...r?{[D]:r}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),i=function officialInstrumentationObserver(){};return $.set(n,t),ee(i,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:r,observe:i})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`)throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
2
2
  //# sourceMappingURL=instrumentation.mjs.map
@@ -1,4 +1,4 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{E as r,P as i}from"./geo-point-codec-lhxH42SK.mjs";import{s as a}from"./v-D5Z06FKN.mjs";import{i as o}from"./datetime-physical-codec-oIhiYZEP.mjs";import{o as s}from"./native-types-veeTk36s.mjs";import{a as c,t as l}from"./physical-6V_LNU3L.mjs";import{$ as u,O as d,P as f,Q as p,X as m,Y as h,Z as g,_,at as v,c as y,ct as b,d as x,et as S,f as C,h as w,it as T,m as E,nt as D,ot as O,rt as k,st as A,tt as j,x as M,z as N}from"./client-CCgfcp5A.mjs";import{t as P}from"./batch-refs-4L8ECdPU.mjs";import{o as F}from"./identifier-conversion-GgbwHc2G.mjs";function escapeIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function int(e){return Number(e)}const I=/^WHERE\s+([\s\S]+)$/i,L=/^(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|0x[\da-f]+|'(?:[^']|'')*'|x'[\da-f]*'|"(?:[^"]|"")*"|[a-z_][\w$]*)$/i;function columnDefault(e){if(e!==null)return L.test(e)?e:`(${e})`}const R=/\bAUTOINCREMENT\b/i;function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function sqliteEnumCheckSuffix(e,t){if(!e)return;let n=escapeIdentifier(t),r=e.match(RegExp(`CHECK\\(\\s*${escapeRegExp(n)}\\s+IN\\s*\\((\\s*(?:'(?:[^']|'')*'\\s*,\\s*)*'(?:[^']|'')*'\\s*)\\)\\s*\\)`,`i`))?.[1];if(!r)return;let i=[],a=/'((?:[^']|'')*)'/g,o=a.exec(r);for(;o;){let e=o[1];e!==void 0&&i.push(e.replace(/''/g,`'`)),o=a.exec(r)}if(i.length!==0)return` CHECK(${n} IN (${i.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `)}))`}function partialIndexPredicate(e){if(!e)return;let t=0,n=0,r=-1;for(;n<e.length;){let i=b(e,n);if(i!==n){n=i;continue}let a=e[n];if(a===`(`)t++;else if(a===`)`&&(t--,t===0)){r=n;break}n++}if(r!==-1)return I.exec(e.slice(r+1).trimStart())?.[1]}async function introspect(e,r,i=!1){let a=await e(`
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{E as r,P as i}from"./geo-point-codec-lhxH42SK.mjs";import{s as a}from"./v-D5Z06FKN.mjs";import{i as o}from"./datetime-physical-codec-oIhiYZEP.mjs";import{o as s}from"./native-types-veeTk36s.mjs";import{a as c,t as l}from"./physical-6V_LNU3L.mjs";import{$ as u,O as d,P as f,Q as p,X as m,Y as h,Z as g,_,at as v,c as y,ct as b,d as x,et as S,f as C,h as w,it as T,m as E,nt as D,ot as O,rt as k,st as A,tt as j,x as M,z as N}from"./client-D291xo5z.mjs";import{t as P}from"./batch-refs-4L8ECdPU.mjs";import{o as F}from"./identifier-conversion-GgbwHc2G.mjs";function escapeIdentifier(e){return`"${e.replace(/"/g,`""`)}"`}function int(e){return Number(e)}const I=/^WHERE\s+([\s\S]+)$/i,L=/^(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|0x[\da-f]+|'(?:[^']|'')*'|x'[\da-f]*'|"(?:[^"]|"")*"|[a-z_][\w$]*)$/i;function columnDefault(e){if(e!==null)return L.test(e)?e:`(${e})`}const R=/\bAUTOINCREMENT\b/i;function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function sqliteEnumCheckSuffix(e,t){if(!e)return;let n=escapeIdentifier(t),r=e.match(RegExp(`CHECK\\(\\s*${escapeRegExp(n)}\\s+IN\\s*\\((\\s*(?:'(?:[^']|'')*'\\s*,\\s*)*'(?:[^']|'')*'\\s*)\\)\\s*\\)`,`i`))?.[1];if(!r)return;let i=[],a=/'((?:[^']|'')*)'/g,o=a.exec(r);for(;o;){let e=o[1];e!==void 0&&i.push(e.replace(/''/g,`'`)),o=a.exec(r)}if(i.length!==0)return` CHECK(${n} IN (${i.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `)}))`}function partialIndexPredicate(e){if(!e)return;let t=0,n=0,r=-1;for(;n<e.length;){let i=b(e,n);if(i!==n){n=i;continue}let a=e[n];if(a===`(`)t++;else if(a===`)`&&(t--,t===0)){r=n;break}n++}if(r!==-1)return I.exec(e.slice(r+1).trimStart())?.[1]}async function introspect(e,r,i=!1){let a=await e(`
2
2
  SELECT name, sql
3
3
  FROM sqlite_master
4
4
  WHERE type = 'table'
@@ -6,6 +6,6 @@ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs"
6
6
  AND name <> ?
7
7
  ${i?`AND name NOT GLOB '_cf_*'`:``}
8
8
  ORDER BY name
9
- `,[P]),o=[];for(let i of a.rows){let a=i.name,s=r===void 0||r.includes(a),c=v(i.sql??``);if(s&&c.some(e=>T(e.text).includes(`AS`)))throw new n(`SQLite table "${a}" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`generated columns`}});if(s&&T((i.sql??``).split(`(`)[0]).includes(`VIRTUAL`))throw new n(`SQLite virtual table "${a}" cannot be faithfully reconstructed. Synchronization refuses before effects.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`virtual table`}});let l=await e(`PRAGMA table_info(${escapeIdentifier(a)})`),d=i.sql,f=R.test(d??``),p=await e(`PRAGMA index_list(${escapeIdentifier(a)})`),m=await e(`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?`,[a]),g=new Map(m.rows.map(e=>[e.name,e.sql])),_=await e(`PRAGMA foreign_key_list(${escapeIdentifier(a)})`),y=[],b=[];for(let e of l.rows){let t=int(e.pk),n=e.type||`TEXT`,r=int(e.notnull)===0&&t===0,i=S(d,{name:e.name,type:n,nullable:r},escapeIdentifier);y.push({name:e.name,geoPointEncoding:i,type:i?u:`${n}${sqliteEnumCheckSuffix(d,e.name)??``}`,nullable:r,default:columnDefault(e.dflt_value),autoIncrement:t===1&&f,decimal:h(d,{name:e.name,type:e.type,nullable:r},escapeIdentifier)}),t>0&&b.push({name:e.name,position:t})}if(s&&c.reduce((e,t)=>e+T(t.text).filter(e=>e===`CHECK`).length,0)!==y.reduce((e,t)=>e+Number(t.decimal!==void 0)+Number(t.geoPointEncoding!==void 0)+Number(sqliteEnumCheckSuffix(d,t.name)!==void 0),0)&&!w(a,d))throw new n(`SQLite table "${a}" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`CHECK constraints`}});let x;b.length>0&&(b.sort((e,t)=>e.position-t.position),x={name:`${a}_pkey`,columns:b.map(e=>e.name)});let C=[],E=[];for(let i of p.rows){let o=(await e(`PRAGMA index_xinfo(${escapeIdentifier(i.name)})`)).rows.filter(e=>int(e.key)===1);if(o.length===0||o.some(e=>int(e.cid)<0||e.name===null||int(e.desc)!==0||e.coll!==`BINARY`)){if(r===void 0||r.includes(a))throw new n(`SQLite index "${a}.${i.name}" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Manage its table outside this synchronization scope until a faithful declaration is available.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:a,indexName:i.name}});continue}if(i.origin===`pk`)continue;let s=o.sort((e,t)=>int(e.seqno)-int(t.seqno)).flatMap(e=>e.name===null?[]:[e.name]),c=int(i.unique)===1;c&&i.origin===`u`?E.push({name:i.name,columns:s}):C.push({name:i.name,columns:s,unique:c,where:partialIndexPredicate(g.get(i.name)??null)})}let D=new Map;for(let e of _.rows){let t=int(e.id),n=D.get(t)||[];n.push(e),D.set(t,n)}let O=[];for(let[e,t]of D){let n=t.sort((e,t)=>int(e.seq)-int(t.seq)),r=n[0];r&&O.push({name:`${a}_fk_${e}`,columns:n.map(e=>e.from),referencedTable:r.table,referencedColumns:n.map(e=>e.to),onDelete:F(r.on_delete),onUpdate:F(r.on_update)})}o.push({name:a,columns:y,primaryKey:x,indexes:C,foreignKeys:O,uniqueConstraints:E})}return{tables:o,enums:[]}}const z=/^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\()/i,B=`__new_`,V=/^CREATE\s+TABLE\s+/i,H=/^ALTER\s+TABLE\s+/i,U=/^\s+RENAME\s+TO\s+/i,W=/^CREATE\s+(?:TEMP(?:ORARY)?\s+)?(TRIGGER|VIEW)\s+(?:IF\s+NOT\s+EXISTS\s+)?/i,G=/^DROP\s+(?:TRIGGER|VIEW)\s+(?:IF\s+EXISTS\s+)?/i,K=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?/i,q=/^\s*\./,J=/^(?:add|all|alter|and|as|autoincrement|between|case|check|collate|commit|constraint|create|default|deferrable|delete|distinct|drop|else|escape|except|exists|foreign|from|group|having|in|index|insert|intersect|into|is|isnull|join|limit|not|nothing|notnull|null|on|or|order|primary|references|returning|select|set|table|then|to|transaction|union|unique|update|using|values|when|where)$/,Y=/\s+CHECK\s*\(/,X=/CHAR|CLOB|TEXT/,Z=/REAL|FLOA|DOUB/;function lostDependents(e,t){let n=new Map(t.map(e=>[e.name.toLowerCase(),e])),r=new Map,i=[];for(let t of e){let e=t.trim(),a=b(e,0);for(;a>0;)e=e.slice(a).trimStart(),a=b(e,0);let o=V.exec(e),s=H.exec(e),c=W.exec(e),l=G.exec(e),u=K.exec(e),d=o??s??c??l??u,f=d&&readObjectName(e,d[0].length);if(!f)continue;let p=f.value.toLowerCase();if(c){let t=c[1].toLowerCase();n.set(p,{type:t,name:f.value,sql:e})}else if(l)n.delete(p);else if(u){let e=(r.get(p)??f.value).toLowerCase();for(let[t,r]of n)r.type===`trigger`&&r.table===e&&n.delete(t)}else if(o&&p.startsWith(B)){let e=f.value.slice(6),t=r.get(e.toLowerCase())??e,a=[e.toLowerCase(),t.toLowerCase()];for(let[e,r]of n){let o=r.sql??``;a.some(e=>sqlNamesTable(o,r.name,e))&&(i.push({table:t,dependent:r}),n.delete(e))}}else if(s&&!p.startsWith(B)){let t=U.exec(e.slice(f.end)),n=t&&A(e,f.end+t[0].length);n&&r.set(n.value.toLowerCase(),r.get(p)??f.value)}}return i}function readObjectName(e,t){let n=A(e,t),r=n?q.exec(e.slice(n.end)):null;return n&&r?A(e,n.end+r[0].length):n}function sqlNamesTable(e,t,n){let r=!0,i=0;for(;i<e.length;){let a=e.charAt(i),o='"`['.includes(a)||O(a)?A(e,i):void 0;if(o){let e=o.value.toLowerCase();if(r&&e===t.toLowerCase())r=!1;else if(e===n&&(o.quoted||!J.test(e)))return!0;i=o.end}else i=Math.max(b(e,i),i+1)}return!1}function sqliteAffinity(e){let t=e.toUpperCase().split(Y)[0].trim();return t.includes(`INT`)?`INTEGER`:X.test(t)?`TEXT`:t===``||t.includes(`BLOB`)?`BLOB`:Z.test(t)?`REAL`:`NUMERIC`}function sqliteConvertingAffinity(e,t){let n=sqliteAffinity(t.type);if(n!==sqliteAffinity(e.type))return n===`INTEGER`||n===`REAL`||n===`TEXT`?n:void 0}function applyToTable(e,t){if(!(`tableName`in t)||t.tableName!==e.name)return e;switch(t.type){case`addColumn`:return{...e,columns:[...e.columns,t.column]};case`dropColumn`:return{...e,columns:e.columns.filter(e=>e.name!==t.columnName)};case`alterColumn`:return{...e,columns:e.columns.map(e=>e.name===t.columnName?t.to:e)};case`createIndex`:return{...e,indexes:[...e.indexes,t.index]};case`dropIndex`:return{...e,indexes:e.indexes.filter(e=>e.name!==t.indexName)};case`addForeignKey`:return{...e,foreignKeys:[...e.foreignKeys,t.fk]};case`dropForeignKey`:return{...e,foreignKeys:e.foreignKeys.filter(e=>e.name!==t.fkName)};case`addUniqueConstraint`:return{...e,uniqueConstraints:[...e.uniqueConstraints,t.constraint]};case`dropUniqueConstraint`:return{...e,uniqueConstraints:e.uniqueConstraints.filter(e=>e.name!==t.constraintName)};case`addPrimaryKey`:return{...e,primaryKey:t.primaryKey};case`dropPrimaryKey`:return{...e,primaryKey:void 0};default:return e}}function replaySchemaTables(e,t){let n=[...e];for(let e of t){if(e.type===`createTable`){n=[...n,e.table];continue}if(e.type===`dropTable`){n=n.filter(t=>t.name!==e.tableName);continue}if(e.type===`renameTable`||e.type===`renameColumn`){n=d({tables:n},e).tables;continue}n=n.map(t=>applyToTable(t,e))}return n}function sqliteTableBearsRelations(e,t,n,r=[]){if(n&&n.foreignKeys.length>0)return!0;let i=replaySchemaTables(t,r);for(let t of i)if(t.name===e&&t.foreignKeys.length>0||t.foreignKeys.some(t=>t.referencedTable===e))return!0;return!1}var SQLite3MigrationDriver=class extends E{dialect=`sqlite`;driverName=`sqlite3`;finalizeTable(e){let r=e.columns.filter(e=>e.autoIncrement);if(r.length>0&&(r.length!==1||e.primaryKey?.columns.length!==1||e.primaryKey.columns[0]!==r[0].name||r[0].type.toUpperCase()!==`INTEGER`||r[0].nullable))throw new n(`SQLite table "${e.name}" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,t.INVALID_INPUT,{meta:{table:e.name}});return e}getIrreversibleRollbackReason(e){return e.type===`alterColumn`&&k(e.from)===`binary64`&&k(e.to)===`legacy`?`Rollback cannot downgrade GeoPoint column "${e.tableName}.${e.columnName}" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`:super.getIrreversibleRollbackReason(e)}capabilities={supportsNativeEnums:!1,supportsAddEnumValueInTransaction:!0,supportsIndexTypes:[`btree`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!1,introspectionReadsConstraintNames:!1};async preflightSchemaRequirements(e,r,i){let a=[...new Set(e.flatMap(e=>e.tables.map(e=>e.name)))];if(a.length===0&&i.length===0)return;let o=await r(`SELECT type, name, sql, lower(tbl_name) AS "table" FROM sqlite_master WHERE type IN ('view', 'trigger')`),s=o.rows.find(e=>e.type===`view`&&a.includes(e.name));if(s)throw new n(`SQLite relation "${s.name}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:s.name,feature:`view`}});let c=lostDependents(i,o.rows);if(c.length>0)throw new n(`This migration rebuilds SQLite ${c.map(({table:e,dependent:t})=>`table "${e}", which ${t.type} "${t.name}" depends on`).join(`; `)}. A rebuild drops the table, which silently drops its triggers and breaks every view or trigger that reads it. The migration is refused before any statement runs, so the schema and data are unchanged. Drop them before this change (a SQL step earlier in the same migration path counts) and recreate them after it.`,t.MIGRATION_INVALID_STATE,{meta:{table:c[0].table,dependents:c.map(({dependent:e})=>`${e.type}:${e.name}`),feature:`table recreation`}})}introspect(e){let t=this.executionDriver?.driverName;return introspect(e,this.target?.tables,t===`d1`)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:c(n,r,`sqlite`);if(i)return i.columnType;let a=s(r,`sqlite`);return a&&!t.array?a.type:f({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,r){if(r.type===`datetime`&&r.autoGenerate?.kind===`now`){let t=l(e[`~`].nativeType);return t===`julianDay`?`(julianday('now'))`:t===`epochMillis`?`(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))`:`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`}if(r.autoGenerate?.kind===`now`){if(r.type===`date`)return`(strftime('%Y-%m-%d','now'))`;if(r.type===`time`)return`(strftime('%H:%M:%f','now'))`}let i=r.hasDefault&&!r.autoGenerate&&!r.array&&(r.type===`datetime`||r.type===`time`)?this.literalDefaultValue(r):void 0;if(r.type===`datetime`&&r.array!==!0&&r.autoGenerate===void 0&&r.hasDefault&&typeof i==`string`){let t=o(i,l(e[`~`].nativeType));return typeof t==`string`?this.escapeValue(t):String(t)}if(r.type===`time`&&!r.array&&!r.autoGenerate&&r.hasDefault&&typeof i==`string`){let e=a(i);if(!(`value`in e))throw new n(`Invalid Time literal default`,t.MIGRATION_INVALID_STATE);return this.escapeValue(e.value)}return super.getDefaultExpression(e,r)}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){let r=n.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `);return`TEXT CHECK(${this.escapeIdentifier(t)} IN (${r}))`}generateColumnDef(e,r){if(e.autoIncrement&&e.type.toUpperCase()!==`INTEGER`)throw new n(`SQLite auto-increment requires INTEGER type. Column "${e.name}" has type "${e.type}" which is not compatible with auto-increment. Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}});if(e.autoIncrement)return`${this.escapeIdentifier(e.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;let i=[this.escapeIdentifier(e.name),e.type];e.nullable||i.push(`NOT NULL`),e.default!==void 0&&i.push(`DEFAULT ${e.default}`),e.type.toUpperCase()===u&&i.push(D(e,e=>this.escapeIdentifier(e),k(e)));let a=p(e);return e.decimal&&a&&i.push(m(e,e.decimal,a,e=>this.escapeIdentifier(e))),i.join(` `)}compileTableRecreation(e,r,i,a,o,s){let c=[],l=`${B}${e}`,u=new Map(i.columns.map(e=>[e.name,e])),d=new Map;for(let[e,t]of o??[])d.set(t,e);let f=r.columns.some(e=>{let t=d.get(e.name)??e.name;return this.decimalConversionKind(u.get(t),e)===`list`}),p=`__viborm_source`;c.push(`PRAGMA foreign_keys=OFF`),c.push(this.generateCreateTableDef({...r,name:l},a));let m=[];for(let i of r.columns){let r=d.get(i.name)??i.name,a=u.get(r);if(a!==void 0){let t=f?`${this.escapeIdentifier(p)}.${this.escapeIdentifier(r)}`:this.escapeIdentifier(r);m.push({source:s?.get(i.name)??this.copySourceExpression(e,r,a,i,t),target:i.name})}else if(!i.nullable&&i.default===void 0)throw new n(`Cannot add NOT NULL column "${i.name}" without a default value during table recreation. SQLite requires a default value or nullable column for table recreation.`,t.FEATURE_NOT_SUPPORTED)}if(m.length>0){let t=m.map(e=>e.source).join(`, `),n=m.map(e=>this.escapeIdentifier(e.target)).join(`, `);c.push(`INSERT INTO ${this.escapeIdentifier(l)} (${n}) SELECT ${t} FROM ${this.escapeIdentifier(e)}`+(f?` AS ${this.escapeIdentifier(p)}`:``))}c.push(`DROP TABLE ${this.escapeIdentifier(e)}`),c.push(`ALTER TABLE ${this.escapeIdentifier(l)} RENAME TO ${this.escapeIdentifier(e)}`);for(let t of r.indexes)c.push(this.generateCreateIndex({type:`createIndex`,tableName:e,index:t},a));return c.push(`PRAGMA foreign_keys=ON`),this.filterStatements(c)}copySourceExpression(e,a,o,s,c){if(s.geoPointEncoding===`binary64`&&o!==void 0&&k(o)===`legacy`)return`CASE WHEN ${c} IS NULL THEN NULL ELSE ${j(c)} END`;let l=s.dateTime;if(l!==void 0){let i=this.sqliteDateTimeSourceForm(o);if(i===void 0)throw new n(`The declared change to "${e}"."${a}" would adopt ${o?.decimal===void 0?`${o?.type??`unknown`} storage`:`a fixed-decimal domain at ${r(o.decimal)}`} as a SQLite DateTime. Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:a,feature:`SQLite DateTime storage conversion`,dialect:`sqlite`}});return x(c,i,l,o?.dateTime!==void 0)}let u=s.decimal,d=p(s),f=o?.decimal;if(u===void 0&&o!==void 0&&f!==void 0)return this.descaledDecimalSource(e,a,{...o,decimal:f},s.type,c);if(u===void 0||d===void 0){let e=o&&sqliteConvertingAffinity(o,s);return e===void 0?c:`CASE WHEN ${c} IS NULL THEN NULL WHEN CAST(${c} AS ${e}) = ${c} THEN CAST(${c} AS ${e}) ELSE ${y} END`}if(f===void 0){if(!(d===`scalar`&&o?.type.toUpperCase()===`INTEGER`))throw new n(`The declared change to "${e}"."${a}" would adopt unmarked ${o?.type??`unknown`} storage as a fixed-decimal ${d}. Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:a,feature:`decimal storage adoption`,dialect:`sqlite`}});return g(c,void 0,u,`scalar`)}if(i(f,u))return c;let m=this.decimalConversionKind(o,s);return m===void 0?c:g(c,f,u,m)}descaledDecimalSource(e,i,a,o,s){let c=p(a);if(c===`scalar`&&sqliteAffinity(o)===`INTEGER`){let e=10n**BigInt(a.decimal.scale);return`CASE WHEN ${s} IS NULL THEN NULL WHEN typeof(${s}) = 'integer' AND ${s} % ${e} = 0 THEN ${s} / ${e} ELSE ${y} END`}throw new n(`The declared change to "${e}"."${i}" would copy a fixed-decimal ${c??`column`} at ${r(a.decimal)} into ${o} storage that declares no decimal domain. SQLite stores the decimal as its scaled integer coefficient, and only a scalar copied into INTEGER storage can be descaled exactly. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:i,feature:`decimal storage conversion`,dialect:`sqlite`}})}sqliteDateTimeSourceForm(e){if(e?.dateTime!==void 0)return e.dateTime;if(e?.decimal===void 0)switch(e?.type.toUpperCase()){case`TEXT`:return`text`;case`INTEGER`:return`epochMillis`;case`REAL`:return`julianDay`;default:return}}decimalConversionKind(e,t){let n=e?.decimal,r=t.decimal;if(e===void 0||n===void 0||r===void 0||i(n,r))return;let a=p(t);if(!(a===void 0||p(e)!==a))return a}assertDomainReconstructionAdmitted(e,i,a,o,s){let c,l;if(s===`decimal`){if(i.decimal===void 0)return;c=`a fixed-decimal column at ${r(i.decimal)}`,l=`decimal descriptor conversion`}else{if(i.dateTime===void 0)return;c=`a SQLite DateTime column in ${i.dateTime} storage`,l=`SQLite DateTime storage conversion`}let u=this.executionDriver;if(u&&_(u)&&sqliteTableBearsRelations(e,o.currentSchema?.tables??[],a,o.precedingOperations))throw new n(`Rebuilding "${e}"."${i.name}", ${c}, recreates the whole table, and the driver "${u.driverName}" runs migrations without a transaction (D1 runs them as one native batch). Without a transaction, \`PRAGMA foreign_keys=OFF\` cannot be proven before the rebuild drops a table that still has references, nor the drop rolled back — and a pragma that did not take raises on one referential action and silently deletes or nulls child rows on another. The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver with transactions.`,t.FEATURE_NOT_SUPPORTED,{meta:{driver:u.driverName,table:e,column:i.name,feature:l}})}generateCreateTableDef(e,t){let n=[];for(let r of e.columns)n.push(this.generateColumnDef(r,t));if(e.primaryKey&&!(e.primaryKey.columns.length===1&&e.columns.find(t=>t.name===e.primaryKey.columns[0]&&t.type.toUpperCase()===`INTEGER`&&t.autoIncrement))){let t=e.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);n.push(`PRIMARY KEY (${t})`)}for(let t of e.uniqueConstraints){let e=t.columns.map(e=>this.escapeIdentifier(e)).join(`, `);n.push(t.name.startsWith(`sqlite_autoindex_`)?`UNIQUE (${e})`:`CONSTRAINT ${this.escapeIdentifier(t.name)} UNIQUE (${e})`)}for(let t of e.foreignKeys){let e=t.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=t.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(t.name)} `;i+=`FOREIGN KEY (${e}) `,i+=`REFERENCES ${this.escapeIdentifier(t.referencedTable)} (${r})`,t.onDelete&&t.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(t.onDelete)}`),t.onUpdate&&t.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(t.onUpdate)}`),n.push(i)}return`CREATE TABLE ${this.escapeIdentifier(e.name)} (\n ${n.join(`,
9
+ `,[P]),o=[];for(let i of a.rows){let a=i.name,s=r===void 0||r.includes(a),c=v(i.sql??``);if(s&&c.some(e=>T(e.text).includes(`AS`)))throw new n(`SQLite table "${a}" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`generated columns`}});if(s&&T((i.sql??``).split(`(`)[0]).includes(`VIRTUAL`))throw new n(`SQLite virtual table "${a}" cannot be faithfully reconstructed. Synchronization refuses before effects.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`virtual table`}});let l=await e(`PRAGMA table_info(${escapeIdentifier(a)})`),d=i.sql,f=R.test(d??``),p=await e(`PRAGMA index_list(${escapeIdentifier(a)})`),m=await e(`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?`,[a]),g=new Map(m.rows.map(e=>[e.name,e.sql])),_=await e(`PRAGMA foreign_key_list(${escapeIdentifier(a)})`),y=[],b=[];for(let e of l.rows){let t=int(e.pk),n=e.type||`TEXT`,r=int(e.notnull)===0&&t===0,i=S(d,{name:e.name,type:n,nullable:r},escapeIdentifier);y.push({name:e.name,geoPointEncoding:i,type:i?u:`${n}${sqliteEnumCheckSuffix(d,e.name)??``}`,nullable:r,default:columnDefault(e.dflt_value),autoIncrement:t===1&&f,decimal:h(d,{name:e.name,type:e.type,nullable:r},escapeIdentifier)}),t>0&&b.push({name:e.name,position:t})}if(s&&c.reduce((e,t)=>e+T(t.text).filter(e=>e===`CHECK`).length,0)!==y.reduce((e,t)=>e+Number(t.decimal!==void 0)+Number(t.geoPointEncoding!==void 0)+Number(sqliteEnumCheckSuffix(d,t.name)!==void 0),0)&&!w(a,d))throw new n(`SQLite table "${a}" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,t.MIGRATION_INVALID_STATE,{meta:{table:a,feature:`CHECK constraints`}});let x;b.length>0&&(b.sort((e,t)=>e.position-t.position),x={name:`${a}_pkey`,columns:b.map(e=>e.name)});let C=[],E=[];for(let i of p.rows){let o=(await e(`PRAGMA index_xinfo(${escapeIdentifier(i.name)})`)).rows.filter(e=>int(e.key)===1);if(o.length===0||o.some(e=>int(e.cid)<0||e.name===null||int(e.desc)!==0||e.coll!==`BINARY`)){if(r===void 0||r.includes(a))throw new n(`SQLite index "${a}.${i.name}" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Manage its table outside this synchronization scope until a faithful declaration is available.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:a,indexName:i.name}});continue}if(i.origin===`pk`)continue;let s=o.sort((e,t)=>int(e.seqno)-int(t.seqno)).flatMap(e=>e.name===null?[]:[e.name]),c=int(i.unique)===1;c&&i.origin===`u`?E.push({name:i.name,columns:s}):C.push({name:i.name,columns:s,unique:c,where:partialIndexPredicate(g.get(i.name)??null)})}let D=new Map;for(let e of _.rows){let t=int(e.id),n=D.get(t)||[];n.push(e),D.set(t,n)}let O=[];for(let[e,t]of D){let n=t.sort((e,t)=>int(e.seq)-int(t.seq)),r=n[0];r&&O.push({name:`${a}_fk_${e}`,columns:n.map(e=>e.from),referencedTable:r.table,referencedColumns:n.map(e=>e.to),onDelete:F(r.on_delete),onUpdate:F(r.on_update)})}o.push({name:a,columns:y,primaryKey:x,indexes:C,foreignKeys:O,uniqueConstraints:E})}return{tables:o,enums:[]}}const z=/^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\()/i,B=`__new_`,V=/^CREATE\s+TABLE\s+/i,H=/^ALTER\s+TABLE\s+/i,U=/^\s+RENAME\s+TO\s+/i,W=/^CREATE\s+(?:TEMP(?:ORARY)?\s+)?(TRIGGER|VIEW)\s+(?:IF\s+NOT\s+EXISTS\s+)?/i,G=/^DROP\s+(?:TRIGGER|VIEW)\s+(?:IF\s+EXISTS\s+)?/i,K=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?/i,q=/^\s*\./,J=/^(?:add|all|alter|and|as|autoincrement|between|case|check|collate|commit|constraint|create|default|deferrable|delete|distinct|drop|else|escape|except|exists|foreign|from|group|having|in|index|insert|intersect|into|is|isnull|join|limit|not|nothing|notnull|null|on|or|order|primary|references|returning|select|set|table|then|to|transaction|union|unique|update|using|values|when|where)$/,Y=/\s+CHECK\s*\(/,X=/CHAR|CLOB|TEXT/,Z=/REAL|FLOA|DOUB/;function lostDependents(e,t){let n=new Map(t.map(e=>[e.name.toLowerCase(),e])),r=new Map,i=[];for(let t of e){let e=t.trim(),a=b(e,0);for(;a>0;)e=e.slice(a).trimStart(),a=b(e,0);let o=V.exec(e),s=H.exec(e),c=W.exec(e),l=G.exec(e),u=K.exec(e),d=o??s??c??l??u,f=d&&readObjectName(e,d[0].length);if(!f)continue;let p=f.value.toLowerCase();if(c){let t=c[1].toLowerCase();n.set(p,{type:t,name:f.value,sql:e})}else if(l)n.delete(p);else if(u){let e=(r.get(p)??f.value).toLowerCase();for(let[t,r]of n)r.type===`trigger`&&r.table===e&&n.delete(t)}else if(o&&p.startsWith(B)){let e=f.value.slice(6),t=r.get(e.toLowerCase())??e,a=[e.toLowerCase(),t.toLowerCase()];for(let[e,r]of n){let o=r.sql??``;a.some(e=>sqlNamesTable(o,r.name,e))&&(i.push({table:t,dependent:r}),n.delete(e))}}else if(s&&!p.startsWith(B)){let t=U.exec(e.slice(f.end)),n=t&&A(e,f.end+t[0].length);n&&r.set(n.value.toLowerCase(),r.get(p)??f.value)}}return i}function readObjectName(e,t){let n=A(e,t),r=n?q.exec(e.slice(n.end)):null;return n&&r?A(e,n.end+r[0].length):n}function sqlNamesTable(e,t,n){let r=!0,i=0;for(;i<e.length;){let a=e.charAt(i),o='"`['.includes(a)||O(a)?A(e,i):void 0;if(o){let e=o.value.toLowerCase();if(r&&e===t.toLowerCase())r=!1;else if(e===n&&(o.quoted||!J.test(e)))return!0;i=o.end}else i=Math.max(b(e,i),i+1)}return!1}function sqliteAffinity(e){let t=e.toUpperCase().split(Y)[0].trim();return t.includes(`INT`)?`INTEGER`:X.test(t)?`TEXT`:t===``||t.includes(`BLOB`)?`BLOB`:Z.test(t)?`REAL`:`NUMERIC`}function sqliteConvertingAffinity(e,t){let n=sqliteAffinity(t.type);if(n!==sqliteAffinity(e.type))return n===`INTEGER`||n===`REAL`||n===`TEXT`?n:void 0}function applyToTable(e,t){if(!(`tableName`in t)||t.tableName!==e.name)return e;switch(t.type){case`addColumn`:return{...e,columns:[...e.columns,t.column]};case`dropColumn`:return{...e,columns:e.columns.filter(e=>e.name!==t.columnName)};case`alterColumn`:return{...e,columns:e.columns.map(e=>e.name===t.columnName?t.to:e)};case`createIndex`:return{...e,indexes:[...e.indexes,t.index]};case`dropIndex`:return{...e,indexes:e.indexes.filter(e=>e.name!==t.indexName)};case`addForeignKey`:return{...e,foreignKeys:[...e.foreignKeys,t.fk]};case`dropForeignKey`:return{...e,foreignKeys:e.foreignKeys.filter(e=>e.name!==t.fkName)};case`addUniqueConstraint`:return{...e,uniqueConstraints:[...e.uniqueConstraints,t.constraint]};case`dropUniqueConstraint`:return{...e,uniqueConstraints:e.uniqueConstraints.filter(e=>e.name!==t.constraintName)};case`addPrimaryKey`:return{...e,primaryKey:t.primaryKey};case`dropPrimaryKey`:return{...e,primaryKey:void 0};default:return e}}function replaySchemaTables(e,t){let n=[...e];for(let e of t){if(e.type===`createTable`){n=[...n,e.table];continue}if(e.type===`dropTable`){n=n.filter(t=>t.name!==e.tableName);continue}if(e.type===`renameTable`||e.type===`renameColumn`){n=d({tables:n},e).tables;continue}n=n.map(t=>applyToTable(t,e))}return n}function sqliteTableBearsRelations(e,t,n,r=[]){if(n&&n.foreignKeys.length>0)return!0;let i=replaySchemaTables(t,r);for(let t of i)if(t.name===e&&t.foreignKeys.length>0||t.foreignKeys.some(t=>t.referencedTable===e))return!0;return!1}var SQLite3MigrationDriver=class extends E{dialect=`sqlite`;driverName=`sqlite3`;finalizeTable(e){let r=e.columns.filter(e=>e.autoIncrement);if(r.length>0&&(r.length!==1||e.primaryKey?.columns.length!==1||e.primaryKey.columns[0]!==r[0].name||r[0].type.toUpperCase()!==`INTEGER`||r[0].nullable))throw new n(`SQLite table "${e.name}" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,t.INVALID_INPUT,{meta:{table:e.name}});return e}getIrreversibleRollbackReason(e){return e.type===`alterColumn`&&k(e.from)===`binary64`&&k(e.to)===`legacy`?`Rollback cannot downgrade GeoPoint column "${e.tableName}.${e.columnName}" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`:super.getIrreversibleRollbackReason(e)}capabilities={supportsNativeEnums:!1,supportsAddEnumValueInTransaction:!0,supportsIndexTypes:[`btree`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!1,introspectionReadsConstraintNames:!1};async preflightSchemaRequirements(e,r,i){let a=[...new Set(e.flatMap(e=>e.tables.map(e=>e.name)))];if(a.length===0&&i.length===0)return!1;let o=await r(`SELECT type, name, sql, lower(tbl_name) AS "table" FROM sqlite_master WHERE type IN ('view', 'trigger')`),s=o.rows.find(e=>e.type===`view`&&a.includes(e.name));if(s)throw new n(`SQLite relation "${s.name}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:s.name,feature:`view`}});let c=lostDependents(i,o.rows);if(c.length>0)throw new n(`This migration rebuilds SQLite ${c.map(({table:e,dependent:t})=>`table "${e}", which ${t.type} "${t.name}" depends on`).join(`; `)}. A rebuild drops the table, which silently drops its triggers and breaks every view or trigger that reads it. The migration is refused before any statement runs, so the schema and data are unchanged. Drop them before this change (a SQL step earlier in the same migration path counts) and recreate them after it.`,t.MIGRATION_INVALID_STATE,{meta:{table:c[0].table,dependents:c.map(({dependent:e})=>`${e.type}:${e.name}`),feature:`table recreation`}});return!1}introspect(e){let t=this.executionDriver?.driverName;return introspect(e,this.target?.tables,t===`d1`)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:c(n,r,`sqlite`);if(i)return i.columnType;let a=s(r,`sqlite`);return a&&!t.array?a.type:f({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,r){if(r.type===`datetime`&&r.autoGenerate?.kind===`now`){let t=l(e[`~`].nativeType);return t===`julianDay`?`(julianday('now'))`:t===`epochMillis`?`(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))`:`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`}if(r.autoGenerate?.kind===`now`){if(r.type===`date`)return`(strftime('%Y-%m-%d','now'))`;if(r.type===`time`)return`(strftime('%H:%M:%f','now'))`}let i=r.hasDefault&&!r.autoGenerate&&!r.array&&(r.type===`datetime`||r.type===`time`)?this.literalDefaultValue(r):void 0;if(r.type===`datetime`&&r.array!==!0&&r.autoGenerate===void 0&&r.hasDefault&&typeof i==`string`){let t=o(i,l(e[`~`].nativeType));return typeof t==`string`?this.escapeValue(t):String(t)}if(r.type===`time`&&!r.array&&!r.autoGenerate&&r.hasDefault&&typeof i==`string`){let e=a(i);if(!(`value`in e))throw new n(`Invalid Time literal default`,t.MIGRATION_INVALID_STATE);return this.escapeValue(e.value)}return super.getDefaultExpression(e,r)}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){let r=n.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `);return`TEXT CHECK(${this.escapeIdentifier(t)} IN (${r}))`}generateColumnDef(e,r){if(e.autoIncrement&&e.type.toUpperCase()!==`INTEGER`)throw new n(`SQLite auto-increment requires INTEGER type. Column "${e.name}" has type "${e.type}" which is not compatible with auto-increment. Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}});if(e.autoIncrement)return`${this.escapeIdentifier(e.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;let i=[this.escapeIdentifier(e.name),e.type];e.nullable||i.push(`NOT NULL`),e.default!==void 0&&i.push(`DEFAULT ${e.default}`),e.type.toUpperCase()===u&&i.push(D(e,e=>this.escapeIdentifier(e),k(e)));let a=p(e);return e.decimal&&a&&i.push(m(e,e.decimal,a,e=>this.escapeIdentifier(e))),i.join(` `)}compileTableRecreation(e,r,i,a,o,s){let c=[],l=`${B}${e}`,u=new Map(i.columns.map(e=>[e.name,e])),d=new Map;for(let[e,t]of o??[])d.set(t,e);let f=r.columns.some(e=>{let t=d.get(e.name)??e.name;return this.decimalConversionKind(u.get(t),e)===`list`}),p=`__viborm_source`;c.push(`PRAGMA foreign_keys=OFF`),c.push(this.generateCreateTableDef({...r,name:l},a));let m=[];for(let i of r.columns){let r=d.get(i.name)??i.name,a=u.get(r);if(a!==void 0){let t=f?`${this.escapeIdentifier(p)}.${this.escapeIdentifier(r)}`:this.escapeIdentifier(r);m.push({source:s?.get(i.name)??this.copySourceExpression(e,r,a,i,t),target:i.name})}else if(!i.nullable&&i.default===void 0)throw new n(`Cannot add NOT NULL column "${i.name}" without a default value during table recreation. SQLite requires a default value or nullable column for table recreation.`,t.FEATURE_NOT_SUPPORTED)}if(m.length>0){let t=m.map(e=>e.source).join(`, `),n=m.map(e=>this.escapeIdentifier(e.target)).join(`, `);c.push(`INSERT INTO ${this.escapeIdentifier(l)} (${n}) SELECT ${t} FROM ${this.escapeIdentifier(e)}`+(f?` AS ${this.escapeIdentifier(p)}`:``))}c.push(`DROP TABLE ${this.escapeIdentifier(e)}`),c.push(`ALTER TABLE ${this.escapeIdentifier(l)} RENAME TO ${this.escapeIdentifier(e)}`);for(let t of r.indexes)c.push(this.generateCreateIndex({type:`createIndex`,tableName:e,index:t},a));return c.push(`PRAGMA foreign_keys=ON`),this.filterStatements(c)}copySourceExpression(e,a,o,s,c){if(s.geoPointEncoding===`binary64`&&o!==void 0&&k(o)===`legacy`)return`CASE WHEN ${c} IS NULL THEN NULL ELSE ${j(c)} END`;let l=s.dateTime;if(l!==void 0){let i=this.sqliteDateTimeSourceForm(o);if(i===void 0)throw new n(`The declared change to "${e}"."${a}" would adopt ${o?.decimal===void 0?`${o?.type??`unknown`} storage`:`a fixed-decimal domain at ${r(o.decimal)}`} as a SQLite DateTime. Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:a,feature:`SQLite DateTime storage conversion`,dialect:`sqlite`}});return x(c,i,l,o?.dateTime!==void 0)}let u=s.decimal,d=p(s),f=o?.decimal;if(u===void 0&&o!==void 0&&f!==void 0)return this.descaledDecimalSource(e,a,{...o,decimal:f},s.type,c);if(u===void 0||d===void 0){let e=o&&sqliteConvertingAffinity(o,s);return e===void 0?c:`CASE WHEN ${c} IS NULL THEN NULL WHEN CAST(${c} AS ${e}) = ${c} THEN CAST(${c} AS ${e}) ELSE ${y} END`}if(f===void 0){if(!(d===`scalar`&&o?.type.toUpperCase()===`INTEGER`))throw new n(`The declared change to "${e}"."${a}" would adopt unmarked ${o?.type??`unknown`} storage as a fixed-decimal ${d}. Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:a,feature:`decimal storage adoption`,dialect:`sqlite`}});return g(c,void 0,u,`scalar`)}if(i(f,u))return c;let m=this.decimalConversionKind(o,s);return m===void 0?c:g(c,f,u,m)}descaledDecimalSource(e,i,a,o,s){let c=p(a);if(c===`scalar`&&sqliteAffinity(o)===`INTEGER`){let e=10n**BigInt(a.decimal.scale);return`CASE WHEN ${s} IS NULL THEN NULL WHEN typeof(${s}) = 'integer' AND ${s} % ${e} = 0 THEN ${s} / ${e} ELSE ${y} END`}throw new n(`The declared change to "${e}"."${i}" would copy a fixed-decimal ${c??`column`} at ${r(a.decimal)} into ${o} storage that declares no decimal domain. SQLite stores the decimal as its scaled integer coefficient, and only a scalar copied into INTEGER storage can be descaled exactly. The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e,column:i,feature:`decimal storage conversion`,dialect:`sqlite`}})}sqliteDateTimeSourceForm(e){if(e?.dateTime!==void 0)return e.dateTime;if(e?.decimal===void 0)switch(e?.type.toUpperCase()){case`TEXT`:return`text`;case`INTEGER`:return`epochMillis`;case`REAL`:return`julianDay`;default:return}}decimalConversionKind(e,t){let n=e?.decimal,r=t.decimal;if(e===void 0||n===void 0||r===void 0||i(n,r))return;let a=p(t);if(!(a===void 0||p(e)!==a))return a}assertDomainReconstructionAdmitted(e,i,a,o,s){let c,l;if(s===`decimal`){if(i.decimal===void 0)return;c=`a fixed-decimal column at ${r(i.decimal)}`,l=`decimal descriptor conversion`}else{if(i.dateTime===void 0)return;c=`a SQLite DateTime column in ${i.dateTime} storage`,l=`SQLite DateTime storage conversion`}let u=this.executionDriver;if(u&&_(u)&&sqliteTableBearsRelations(e,o.currentSchema?.tables??[],a,o.precedingOperations))throw new n(`Rebuilding "${e}"."${i.name}", ${c}, recreates the whole table, and the driver "${u.driverName}" runs migrations without a transaction (D1 runs them as one native batch). Without a transaction, \`PRAGMA foreign_keys=OFF\` cannot be proven before the rebuild drops a table that still has references, nor the drop rolled back — and a pragma that did not take raises on one referential action and silently deletes or nulls child rows on another. The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver with transactions.`,t.FEATURE_NOT_SUPPORTED,{meta:{driver:u.driverName,table:e,column:i.name,feature:l}})}generateCreateTableDef(e,t){let n=[];for(let r of e.columns)n.push(this.generateColumnDef(r,t));if(e.primaryKey&&!(e.primaryKey.columns.length===1&&e.columns.find(t=>t.name===e.primaryKey.columns[0]&&t.type.toUpperCase()===`INTEGER`&&t.autoIncrement))){let t=e.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);n.push(`PRIMARY KEY (${t})`)}for(let t of e.uniqueConstraints){let e=t.columns.map(e=>this.escapeIdentifier(e)).join(`, `);n.push(t.name.startsWith(`sqlite_autoindex_`)?`UNIQUE (${e})`:`CONSTRAINT ${this.escapeIdentifier(t.name)} UNIQUE (${e})`)}for(let t of e.foreignKeys){let e=t.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=t.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(t.name)} `;i+=`FOREIGN KEY (${e}) `,i+=`REFERENCES ${this.escapeIdentifier(t.referencedTable)} (${r})`,t.onDelete&&t.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(t.onDelete)}`),t.onUpdate&&t.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(t.onUpdate)}`),n.push(i)}return`CREATE TABLE ${this.escapeIdentifier(e.name)} (\n ${n.join(`,
10
10
  `)}\n)`}getCurrentTable(e,t){return replaySchemaTables(t.currentSchema?.tables??[],t.precedingOperations??[]).find(t=>t.name===e)}generateCreateTable(e,t){let{table:n}=e,r=[this.generateCreateTableDef(n,t)];for(let e of n.indexes)r.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return r}generateDropTable(e,t){return`DROP TABLE ${this.escapeIdentifier(e.tableName)}`}generateRenameTable(e,t){return`ALTER TABLE ${this.escapeIdentifier(e.from)} RENAME TO ${this.escapeIdentifier(e.to)}`}generateAddColumn(e,r){if(e.column.default!==void 0&&z.test(e.column.default)){let i=this.getCurrentTable(e.tableName,r);if(!i)throw new n(`Cannot add computed default: table "${e.tableName}" is absent`,t.MIGRATION_INVALID_STATE);return this.compileTableRecreation(e.tableName,{...i,columns:[...i.columns,e.column]},i,r)}let i=this.generateColumnDef(e.column,r);return`ALTER TABLE ${this.escapeIdentifier(e.tableName)} ADD COLUMN ${i}`}generateDropColumn(e,t){return`ALTER TABLE ${this.escapeIdentifier(e.tableName)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,r){let i=this.getCurrentTable(e.tableName,r),a=i?.columns.find(t=>t.name===e.from),o=`ALTER TABLE ${this.escapeIdentifier(e.tableName)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`;if(i===void 0||a?.decimal===void 0)return o;let s=d({tables:[i]},e).tables[0];if(s===void 0)throw new n(`Cannot rename column: table "${e.tableName}" disappeared from the current schema.`,t.INTERNAL_ERROR,{meta:{table:e.tableName,column:e.from}});return this.assertDomainReconstructionAdmitted(e.tableName,a,s,r,`decimal`),[o,...this.compileTableRecreation(e.tableName,s,s,r)]}generateAlterColumn(e,t){return this.compileAlterColumnByRecreation(e,t,!0)}compileAlterColumnByRecreation(e,t,n){let r=[e];if(n&&t.followingOperations){let compatible=t=>t?.type===`alterColumn`&&t.tableName===e.tableName&&M(t)===M(e),n=[];for(let e of[...t.precedingOperations??[]].reverse()){if(!compatible(e))break;n.unshift(e)}let i=[];for(let e of t.followingOperations){if(!compatible(e))break;i.push(e)}let a=[...n,e,...i];if(new Set(a.map(e=>e.columnName)).size===a.length){if(n.length>0)return[];r.push(...i)}}let i=this.getCurrentTable(e.tableName,t);if(!i)throw Error(`Cannot alter column: table "${e.tableName}" not found in current schema. Supply the current schema when compiling this operation.`);let a=new Map(r.map(e=>[e.columnName,e.to])),o=i.columns.map(e=>a.get(e.name)??e),s={...i,columns:o};for(let n of r)N(n.from,n.to)?this.assertDomainReconstructionAdmitted(e.tableName,n.to,s,t,`decimal`):C(n.from.dateTime,n.to.dateTime)&&this.assertDomainReconstructionAdmitted(e.tableName,n.to,s,t,`dateTime`);return this.compileTableRecreation(e.tableName,s,i,t)}generateCreateIndex(e,t){let{tableName:n,index:r}=e;this.validateIndexType(r.type,r.name);let i=r.unique?`UNIQUE `:``,a=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `),o=r.where?` WHERE ${r.where}`:``;return`CREATE ${i}INDEX ${this.escapeIdentifier(r.name)} ON ${this.escapeIdentifier(n)} (${a})${o}`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)}`}generateAddForeignKey(e,t){return this.recreateWith(e.tableName,t,`add foreign key`,t=>({...t,foreignKeys:[...t.foreignKeys,e.fk]}))}generateDropForeignKey(e,t){return this.recreateWith(e.tableName,t,`drop foreign key`,t=>({...t,foreignKeys:t.foreignKeys.filter(t=>t.name!==e.fkName)}))}recreateWith(e,t,n,r){let i=this.getCurrentTable(e,t);if(!i)throw Error(`Cannot ${n}: table "${e}" not found in current schema. Supply the current schema when compiling this operation.`);return this.compileTableRecreation(e,r(i),i,t)}generateAddUniqueConstraint(e,t){return this.recreateWith(e.tableName,t,`add unique constraint`,t=>({...t,uniqueConstraints:[...t.uniqueConstraints,e.constraint]}))}generateDropUniqueConstraint(e,t){return this.recreateWith(e.tableName,t,`drop unique constraint`,t=>({...t,uniqueConstraints:t.uniqueConstraints.filter(t=>t.name!==e.constraintName)}))}generateAddPrimaryKey(e,t){return this.recreateWith(e.tableName,t,`add primary key`,t=>({...t,primaryKey:e.primaryKey}))}generateDropPrimaryKey(e,t){return this.recreateWith(e.tableName,t,`drop primary key`,e=>({...e,primaryKey:void 0}))}generateCreateEnum(e,t){return`-- SQLite: enum CHECK constraint is part of column definition`}generateDropEnum(e,r){let{enumName:i,dependentColumns:a}=e;if(!a||a.length===0)return`-- SQLite: no dependent columns for enum "${i}"`;let o=[];for(let e of a){let a=this.getCurrentTable(e.tableName,r);if(!a)throw new n(`Table "${e.tableName}" not found for enum "${i}"`,t.INTERNAL_ERROR);let s=a.columns.map(t=>t.name===e.columnName&&t.type.includes(`CHECK`)?{...t,type:`TEXT`}:t),c={...a,columns:s};o.push(...this.compileTableRecreation(e.tableName,c,a,r))}return o}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e,a=[];if(!r||r.length===0)return`-- SQLite: no new values provided for enum "${n}"`;if(!i||i.length===0)return`-- SQLite: no dependent columns found for enum "${n}"`;let o=r.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `);for(let n of i){let r=this.getCurrentTable(n.tableName,t);if(!r){a.push(`-- SQLite: table "${n.tableName}" not found`);continue}let i=`TEXT CHECK(${this.escapeIdentifier(n.columnName)} IN (${o}))`,s=r.columns.map(e=>e.name===n.columnName?{...e,type:i}:e),c={...r,columns:s},l=this.escapeIdentifier(n.columnName),u=this.enumReplacementCases(e,n.tableName,n.columnName),d=u.length===0?void 0:new Map([[n.columnName,`CASE ${l} ${u.join(` `)} ELSE ${l} END`]]);a.push(...this.compileTableRecreation(n.tableName,c,r,t,void 0,d))}return a}generateAcquireLock(e){return null}generateReleaseLock(e){return null}generateInventoryTables(){return{sql:`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name`,params:[]}}generateInventoryEnums(){return null}};const Q=new SQLite3MigrationDriver;var LibSQLMigrationDriver=class extends SQLite3MigrationDriver{driverName=`libsql`;capabilities={supportsNativeEnums:!1,supportsAddEnumValueInTransaction:!0,supportsIndexTypes:[`btree`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!1,introspectionReadsConstraintNames:!1};generateAlterColumn(e,t){if(N(e.from,e.to)||C(e.from.dateTime,e.to.dateTime))return this.compileAlterColumnByRecreation(e,t,!1);let{tableName:n,columnName:r,to:i}=e;return`ALTER TABLE ${this.escapeIdentifier(n)} ALTER COLUMN ${this.escapeIdentifier(r)} TO ${this.generateColumnDef(i,t)}`}buildColumnDefWithReferences(e,t){let n=[this.escapeIdentifier(e.name),e.type];e.nullable||n.push(`NOT NULL`),e.default!==void 0&&n.push(`DEFAULT ${e.default}`),e.type.toUpperCase()===u&&n.push(D(e,e=>this.escapeIdentifier(e),k(e)));let r=p(e);return e.decimal&&r&&n.push(m(e,e.decimal,r,e=>this.escapeIdentifier(e))),t&&(n.push(`REFERENCES ${this.escapeIdentifier(t.refTable)}(${this.escapeIdentifier(t.refCol)})`),t.onDelete&&t.onDelete!==`noAction`&&n.push(`ON DELETE ${this.formatReferentialAction(t.onDelete)}`),t.onUpdate&&t.onUpdate!==`noAction`&&n.push(`ON UPDATE ${this.formatReferentialAction(t.onUpdate)}`)),n.join(` `)}generateAddForeignKey(e,t){let{tableName:n,fk:r}=e;if(r.columns.length>1)return super.generateAddForeignKey(e,t);let i=r.columns[0],a=r.referencedColumns[0];if(!(i&&a))throw Error(`Invalid foreign key: columns array is empty for table "${n}".`);let o=this.getCurrentTable(n,t);if(!o)throw Error(`Cannot add foreign key: table "${n}" not found in current schema. Pass currentSchema in DDLContext.`);let s=o.columns.find(e=>e.name===i);if(!s)throw Error(`Cannot add foreign key: column "${i}" not found in table "${n}".`);return`ALTER TABLE ${this.escapeIdentifier(n)} ALTER COLUMN ${this.escapeIdentifier(i)} TO ${this.buildColumnDefWithReferences(s,{refTable:r.referencedTable,refCol:a,onDelete:r.onDelete,onUpdate:r.onUpdate})}`}generateDropForeignKey(e,t){let n=this.getCurrentTable(e.tableName,t);if(!n)throw Error(`Cannot drop foreign key: table "${e.tableName}" not found in current schema. Supply the current schema when compiling this operation.`);let r=n.foreignKeys.find(t=>t.name===e.fkName);if(!r)throw Error(`Cannot drop foreign key: constraint "${e.fkName}" not found in table "${e.tableName}".`);if(r.columns.length>1)return super.generateDropForeignKey(e,t);let i=r.columns[0];if(!i)throw Error(`Invalid foreign key: columns array is empty for constraint "${e.fkName}".`);let a=n.columns.find(e=>e.name===i);if(!a)throw Error(`Cannot drop foreign key: column "${i}" not found in table "${e.tableName}".`);return`ALTER TABLE ${this.escapeIdentifier(e.tableName)} ALTER COLUMN ${this.escapeIdentifier(i)} TO ${this.buildColumnDefWithReferences(a)}`}};const $=new LibSQLMigrationDriver;export{Q as n,$ as t};
11
- //# sourceMappingURL=libsql-Bu_IdFU1.mjs.map
11
+ //# sourceMappingURL=libsql-IdshHiw4.mjs.map