viborm 1.4.0 → 1.4.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 (164) hide show
  1. package/dist/{adapter-namespace-BLejG8FA.mjs → adapter-namespace-NnXlXR8c.mjs} +2 -2
  2. package/dist/{adapter-namespace-BLejG8FA.mjs.map → adapter-namespace-NnXlXR8c.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/builder-BxCr9ANq.mjs +2 -0
  6. package/dist/builder-BxCr9ANq.mjs.map +1 -0
  7. package/dist/bun-sql.d.mts +1 -1
  8. package/dist/bun-sql.mjs +1 -1
  9. package/dist/bun-sqlite.d.mts +1 -1
  10. package/dist/bun-sqlite.mjs +1 -1
  11. package/dist/cache/cloudflare-kv.d.mts +1 -1
  12. package/dist/cache/cloudflare-kv.mjs +1 -1
  13. package/dist/cache/memory.d.mts +1 -1
  14. package/dist/cache/memory.mjs +1 -1
  15. package/dist/cache.d.mts +1 -1
  16. package/dist/cache.mjs +1 -1
  17. package/dist/{chain-D5J9hIw-.mjs → chain-C4EUyLzF.mjs} +2 -2
  18. package/dist/{chain-D5J9hIw-.mjs.map → chain-C4EUyLzF.mjs.map} +1 -1
  19. package/dist/cli.mjs +1 -1
  20. package/dist/{client-BzgBm_86.d.mts → client-D-XiaClb.d.mts} +1 -1
  21. package/dist/client-DACEO6tS.mjs +2 -0
  22. package/dist/client-DACEO6tS.mjs.map +1 -0
  23. package/dist/{client-aU3YhZ6G.mjs → client-sAey5P-I.mjs} +2 -2
  24. package/dist/{client-aU3YhZ6G.mjs.map → client-sAey5P-I.mjs.map} +1 -1
  25. package/dist/client.d.mts +1 -1
  26. package/dist/client.mjs +1 -1
  27. package/dist/config.d.mts +1 -1
  28. package/dist/config.mjs +1 -1
  29. package/dist/current-C2fZL9Ln.mjs +2 -0
  30. package/dist/current-C2fZL9Ln.mjs.map +1 -0
  31. package/dist/d1.d.mts +1 -1
  32. package/dist/d1.mjs +1 -1
  33. package/dist/d1.mjs.map +1 -1
  34. package/dist/{datetime-physical-codec-lX7IJBlz.mjs → datetime-physical-codec-CFoeuitT.mjs} +2 -2
  35. package/dist/{datetime-physical-codec-lX7IJBlz.mjs.map → datetime-physical-codec-CFoeuitT.mjs.map} +1 -1
  36. package/dist/{driver-u2qJicrE.mjs → driver-BqD-3_jO.mjs} +2 -2
  37. package/dist/{driver-u2qJicrE.mjs.map → driver-BqD-3_jO.mjs.map} +1 -1
  38. package/dist/driver-DseQwbsu.mjs +2 -0
  39. package/dist/driver-DseQwbsu.mjs.map +1 -0
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-CEQMQEdt.mjs +2 -0
  43. package/dist/{every-CzF00eDV.mjs.map → every-CEQMQEdt.mjs.map} +1 -1
  44. package/dist/execution-context-asSCmyas.mjs +2 -0
  45. package/dist/execution-context-asSCmyas.mjs.map +1 -0
  46. package/dist/{geo-area-codec-BmMmWgU_.mjs → geo-area-codec-4W5b7whM.mjs} +2 -2
  47. package/dist/{geo-area-codec-BmMmWgU_.mjs.map → geo-area-codec-4W5b7whM.mjs.map} +1 -1
  48. package/dist/geo-point-codec-pAWYj5ZZ.mjs +2 -0
  49. package/dist/geo-point-codec-pAWYj5ZZ.mjs.map +1 -0
  50. package/dist/{hydration-BflrXEIQ.mjs → hydration-Az2rjp5a.mjs} +2 -2
  51. package/dist/{hydration-BflrXEIQ.mjs.map → hydration-Az2rjp5a.mjs.map} +1 -1
  52. package/dist/{identifier-conversion-Dc0Rf4Gi.mjs → identifier-conversion-ufaCNi9E.mjs} +2 -2
  53. package/dist/{identifier-conversion-Dc0Rf4Gi.mjs.map → identifier-conversion-ufaCNi9E.mjs.map} +1 -1
  54. package/dist/{index-B4IWFJfv.d.mts → index-Ci8b13Lm.d.mts} +52 -6
  55. package/dist/index.d.mts +1 -1
  56. package/dist/index.mjs +1 -1
  57. package/dist/instrumentation.d.mts +1 -1
  58. package/dist/instrumentation.mjs +1 -1
  59. package/dist/instrumentation.mjs.map +1 -1
  60. package/dist/{key-B89Z4vxn.mjs → key-CyLRw0ne.mjs} +2 -2
  61. package/dist/{key-B89Z4vxn.mjs.map → key-CyLRw0ne.mjs.map} +1 -1
  62. package/dist/{libsql-CrDXsfpL.mjs → libsql-DPrXWc_J.mjs} +2 -2
  63. package/dist/{libsql-CrDXsfpL.mjs.map → libsql-DPrXWc_J.mjs.map} +1 -1
  64. package/dist/libsql.d.mts +1 -1
  65. package/dist/libsql.mjs +1 -1
  66. package/dist/libsql.mjs.map +1 -1
  67. package/dist/{memory-TXO4KgBy.mjs → memory-DiTWROVS.mjs} +2 -2
  68. package/dist/{memory-TXO4KgBy.mjs.map → memory-DiTWROVS.mjs.map} +1 -1
  69. package/dist/migrations/mysql.d.mts +4 -4
  70. package/dist/migrations/mysql.mjs +1 -1
  71. package/dist/migrations/postgres.d.mts +4 -4
  72. package/dist/migrations/postgres.mjs +1 -1
  73. package/dist/migrations/sqlite.d.mts +4 -4
  74. package/dist/migrations/sqlite.mjs +1 -1
  75. package/dist/migrations/tenant.d.mts +2 -2
  76. package/dist/migrations/tenant.mjs +1 -1
  77. package/dist/migrations.d.mts +4 -4
  78. package/dist/migrations.mjs +1 -1
  79. package/dist/{mysql-adapter-C5CMIYRS.mjs → mysql-adapter-B1U35CJn.mjs} +2 -2
  80. package/dist/{mysql-adapter-C5CMIYRS.mjs.map → mysql-adapter-B1U35CJn.mjs.map} +1 -1
  81. package/dist/{mysql-C2vOPcuA.mjs → mysql-fJlFIW7m.mjs} +2 -2
  82. package/dist/{mysql-C2vOPcuA.mjs.map → mysql-fJlFIW7m.mjs.map} +1 -1
  83. package/dist/mysql2.d.mts +1 -1
  84. package/dist/mysql2.mjs +1 -1
  85. package/dist/neon-http.d.mts +1 -1
  86. package/dist/neon-http.mjs +1 -1
  87. package/dist/{object-store-uRqi0URP.d.mts → object-store-H7fJwgPR.d.mts} +3 -3
  88. package/dist/permissions.d.mts +1 -1
  89. package/dist/permissions.mjs +1 -1
  90. package/dist/pg.d.mts +1 -1
  91. package/dist/pg.mjs +1 -1
  92. package/dist/pg.mjs.map +1 -1
  93. package/dist/pglite.d.mts +1 -1
  94. package/dist/pglite.mjs +1 -1
  95. package/dist/{physical-uJfmo4-Z.mjs → physical-C4D-979R.mjs} +2 -2
  96. package/dist/{physical-uJfmo4-Z.mjs.map → physical-C4D-979R.mjs.map} +1 -1
  97. package/dist/planetscale.d.mts +1 -1
  98. package/dist/planetscale.mjs +1 -1
  99. package/dist/planetscale.mjs.map +1 -1
  100. package/dist/{planner-SzkGh-3T.d.mts → planner-CUcPdJwD.d.mts} +1 -1
  101. package/dist/{postgres-BSmy1PYR.mjs → postgres-DD92WdFu.mjs} +2 -2
  102. package/dist/{postgres-BSmy1PYR.mjs.map → postgres-DD92WdFu.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-BAqRfWl1.mjs → postgres-adapter-B7hzWhky.mjs} +2 -2
  104. package/dist/{postgres-adapter-BAqRfWl1.mjs.map → postgres-adapter-B7hzWhky.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-B1RyJlWL.mjs → postgres-adapter-CJmoxTW7.mjs} +2 -2
  106. package/dist/{postgres-adapter-B1RyJlWL.mjs.map → postgres-adapter-CJmoxTW7.mjs.map} +1 -1
  107. package/dist/postgres.d.mts +1 -1
  108. package/dist/postgres.mjs +1 -1
  109. package/dist/postgres.mjs.map +1 -1
  110. package/dist/{provider-limits-V09frtmK.mjs → provider-limits-D0ECF7_Q.mjs} +2 -2
  111. package/dist/{provider-limits-V09frtmK.mjs.map → provider-limits-D0ECF7_Q.mjs.map} +1 -1
  112. package/dist/result-shape-ic2j3Tze.mjs +2 -0
  113. package/dist/result-shape-ic2j3Tze.mjs.map +1 -0
  114. package/dist/{rows-BiaiswSV.mjs → rows-YyvK9MDz.mjs} +2 -2
  115. package/dist/{rows-BiaiswSV.mjs.map → rows-YyvK9MDz.mjs.map} +1 -1
  116. package/dist/{scalar-Cm7nMFmO.mjs → scalar-Dyns7kc7.mjs} +2 -2
  117. package/dist/{scalar-Cm7nMFmO.mjs.map → scalar-Dyns7kc7.mjs.map} +1 -1
  118. package/dist/schema/json.d.mts +1 -1
  119. package/dist/schema/json.mjs +1 -1
  120. package/dist/{schema-tGtziyCJ.mjs → schema-CUm_yh6L.mjs} +2 -2
  121. package/dist/{schema-tGtziyCJ.mjs.map → schema-CUm_yh6L.mjs.map} +1 -1
  122. package/dist/{schema-introspection-C1-XrQP4.mjs → schema-introspection-LpRNeSG2.mjs} +2 -2
  123. package/dist/{schema-introspection-C1-XrQP4.mjs.map → schema-introspection-LpRNeSG2.mjs.map} +1 -1
  124. package/dist/schema.d.mts +1 -1
  125. package/dist/schema.mjs +1 -1
  126. package/dist/soft-delete.d.mts +1 -1
  127. package/dist/{sqlite-adapter-CoDeF2h2.mjs → sqlite-adapter-CLWY4B8w.mjs} +2 -2
  128. package/dist/sqlite-adapter-CLWY4B8w.mjs.map +1 -0
  129. package/dist/{sqlite-utils-C0TyzOys.mjs → sqlite-utils-C5_KQPZn.mjs} +2 -2
  130. package/dist/{sqlite-utils-C0TyzOys.mjs.map → sqlite-utils-C5_KQPZn.mjs.map} +1 -1
  131. package/dist/sqlite3.d.mts +1 -1
  132. package/dist/sqlite3.mjs +1 -1
  133. package/dist/{to-many-Btc9X5Ga.mjs → to-many-DxQuOBuq.mjs} +2 -2
  134. package/dist/{to-many-Btc9X5Ga.mjs.map → to-many-DxQuOBuq.mjs.map} +1 -1
  135. package/dist/{utils-DkAxKcDD.mjs → utils-CQ2nQwwO.mjs} +2 -2
  136. package/dist/{utils-DkAxKcDD.mjs.map → utils-CQ2nQwwO.mjs.map} +1 -1
  137. package/dist/{v-514RME2X.mjs → v-BcroBusN.mjs} +2 -2
  138. package/dist/{v-514RME2X.mjs.map → v-BcroBusN.mjs.map} +1 -1
  139. package/dist/{validation-C7Z6wTJa.mjs → validation-CjWRiLWU.mjs} +2 -2
  140. package/dist/{validation-C7Z6wTJa.mjs.map → validation-CjWRiLWU.mjs.map} +1 -1
  141. package/dist/validation.d.mts +1 -1
  142. package/dist/validation.mjs +1 -1
  143. package/dist/{validator-CQOw7G3q.mjs → validator-yrGnrsAo.mjs} +2 -2
  144. package/dist/{validator-CQOw7G3q.mjs.map → validator-yrGnrsAo.mjs.map} +1 -1
  145. package/dist/version-DLtcW9kn.mjs +2 -0
  146. package/dist/{version-n393hhwM.mjs.map → version-DLtcW9kn.mjs.map} +1 -1
  147. package/package.json +15 -15
  148. package/dist/builder-BS8EW4BQ.mjs +0 -2
  149. package/dist/builder-BS8EW4BQ.mjs.map +0 -1
  150. package/dist/client-Bhl2mWam.mjs +0 -2
  151. package/dist/client-Bhl2mWam.mjs.map +0 -1
  152. package/dist/current-oXcxSCBQ.mjs +0 -2
  153. package/dist/current-oXcxSCBQ.mjs.map +0 -1
  154. package/dist/driver-CQQbCQh9.mjs +0 -2
  155. package/dist/driver-CQQbCQh9.mjs.map +0 -1
  156. package/dist/every-CzF00eDV.mjs +0 -2
  157. package/dist/execution-context-rJXTRVrJ.mjs +0 -2
  158. package/dist/execution-context-rJXTRVrJ.mjs.map +0 -1
  159. package/dist/geo-point-codec-D95uXgDF.mjs +0 -2
  160. package/dist/geo-point-codec-D95uXgDF.mjs.map +0 -1
  161. package/dist/result-shape-Fi1-Fvri.mjs +0 -2
  162. package/dist/result-shape-Fi1-Fvri.mjs.map +0 -1
  163. package/dist/sqlite-adapter-CoDeF2h2.mjs.map +0 -1
  164. package/dist/version-n393hhwM.mjs +0 -2
package/dist/client.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { $t as ExtensionResultConsumerState, A as Schema, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Gt as defineExtension, Ht as PlacedControl, I as Links, Kt as StatementContext, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Rt as defaultOmit, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Wn as IndexDefinition, Wt as ClientExtension, Y as VibSchema, Zt as ExtensionCacheState, _ as ObservationCompletion, _n as UnwrapPendingOperation, an as InferSelectInclude, dr as ObjectSchema, gn as PendingOperation, in as GroupByResultType, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as BatchPayload, on as RawOperation, qt as StatementHandler, rn as CountResultType, tn as AggregateResultType, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation } from "./index-B4IWFJfv.mjs";
1
+ import { $t as ExtensionResultConsumerState, A as Schema, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Gt as defineExtension, Ht as PlacedControl, I as Links, Kt as StatementContext, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Rt as defaultOmit, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Wn as IndexDefinition, Wt as ClientExtension, Y as VibSchema, Zt as ExtensionCacheState, _ as ObservationCompletion, _n as UnwrapPendingOperation, an as InferSelectInclude, dr as ObjectSchema, gn as PendingOperation, in as GroupByResultType, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as BatchPayload, on as RawOperation, qt as StatementHandler, rn as CountResultType, tn as AggregateResultType, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation } from "./index-Ci8b13Lm.mjs";
2
2
  export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type ClientTypeState, 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/client.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,u as t}from"./chain-D5J9hIw-.mjs";import{d as n,m as r}from"./result-shape-Fi1-Fvri.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-C1-XrQP4.mjs";export{n as PendingOperation,t as defaultOmit,e as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
1
+ import{a as e,u as t}from"./chain-C4EUyLzF.mjs";import{d as n,m as r}from"./result-shape-ic2j3Tze.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-LpRNeSG2.mjs";export{n as PendingOperation,t as defaultOmit,e as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ResolveCallback, t as MigrationClient } from "./planner-SzkGh-3T.mjs";
1
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-CUcPdJwD.mjs";
2
2
  import { n as MigrationStorageWriter } from "./contract-Dw0FR78e.mjs";
3
3
 
4
4
  //#region src/cli/utils.d.ts
package/dist/config.mjs CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./utils-DkAxKcDD.mjs";export{e as defineConfig};
1
+ import{t as e}from"./utils-CQ2nQwwO.mjs";export{e as defineConfig};
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";let t;function currentInstant(){return t===void 0&&(t=new Date().toISOString(),queueMicrotask(()=>{t=void 0})),t}function currentTemporalValue(e){let t=currentInstant();return e===`date`?t.slice(0,10):e===`time`?t.slice(11,19):t}export{currentTemporalValue as t};
2
+ //# sourceMappingURL=current-C2fZL9Ln.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"current-C2fZL9Ln.mjs","names":[],"sources":["../src/schema/scalars/datetime/current.ts"],"sourcesContent":["/** The wall-clock value shared by temporal `now` and `updatedAt` generators. */\nexport type TemporalKind = \"datetime\" | \"date\" | \"time\";\n\n/**\n * The instant every generator of the current synchronous run reads.\n *\n * A call's input is admitted in one synchronous run, and each `now` and\n * `updatedAt` field generates its value there, one after another: read\n * separately, a create's `createdAt` and `updatedAt` could straddle a\n * millisecond and differ. The first read of a run takes the clock and the\n * rest reuse it, until the run's microtasks run.\n */\nlet runInstant: string | undefined;\n\nfunction currentInstant(): string {\n if (runInstant === undefined) {\n runInstant = new Date().toISOString();\n queueMicrotask(() => {\n runInstant = undefined;\n });\n }\n return runInstant;\n}\n\n/**\n * Read the host wall clock (once per synchronous run) and spell it in one\n * temporal scalar's logical input language.\n */\nexport function currentTemporalValue(kind: TemporalKind): string {\n const timestamp = currentInstant();\n if (kind === \"date\") return timestamp.slice(0, 10);\n if (kind === \"time\") return timestamp.slice(11, 19);\n return timestamp;\n}\n"],"mappings":"yCAYA,IAAI,EAEJ,SAAS,gBAAyB,CAOhC,OANI,IAAe,IAAA,KACjB,EAAa,IAAI,MAAM,CAAC,aAAa,CACrC,mBAAqB,CACnB,EAAa,IAAA,IACb,EAEG,EAOT,SAAgB,qBAAqB,EAA4B,CAC/D,IAAM,EAAY,gBAAgB,CAGlC,OAFI,IAAS,OAAe,EAAU,MAAM,EAAG,GAAG,CAC9C,IAAS,OAAe,EAAU,MAAM,GAAI,GAAG,CAC5C"}
package/dist/d1.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-B4IWFJfv.mjs";
1
+ import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-Ci8b13Lm.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
package/dist/d1.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,n}from"./normalized-result-BF7gr4_b.mjs";import{m as r}from"./error-mapping-6op318w6.mjs";import{p as i}from"./validation-gwZYm3Yn.mjs";import{a,n as o,r as s}from"./client-Bhl2mWam.mjs";import{c,t as l}from"./driver-CQQbCQh9.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-C0TyzOys.mjs";import{t as p}from"./sql-statement-tokens-4J5l5Lyt.mjs";import{t as m}from"./sqlite-adapter-CoDeF2h2.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,n){if(!t(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(t))||!t(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(n,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0,compoundSelectTerms:5,relationsPerStatement:256});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,t){return this.executeTypedStatement(e,t,async(e,t,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,t,r,i);return n(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(t).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,n}from"./normalized-result-BF7gr4_b.mjs";import{m as r}from"./error-mapping-6op318w6.mjs";import{p as i}from"./validation-gwZYm3Yn.mjs";import{a,n as o,r as s}from"./client-DACEO6tS.mjs";import{c,t as l}from"./driver-DseQwbsu.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-C5_KQPZn.mjs";import{t as p}from"./sql-statement-tokens-4J5l5Lyt.mjs";import{t as m}from"./sqlite-adapter-CLWY4B8w.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,n){if(!t(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(t))||!t(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(n,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0,compoundSelectTerms:5,relationsPerStatement:256,countsCascadedChanges:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,t){return this.executeTypedStatement(e,t,async(e,t,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,t,r,i);return n(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(t).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
2
2
  //# sourceMappingURL=d1.mjs.map
package/dist/d1.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`. D1 compiles\n // with an expression depth of 100 (\"Expression tree is too large\"):\n // relation filters nest as derived tables and conjunctions as balanced\n // trees (d1-permissions-verbs W-W3, W-W7). D1 refuses a statement over 100 KB: a\n // relation body a statement repeats is stated once (d1-permissions-placement\n // W-P10's update form), and a compound SELECT over 5 terms (\"too many terms\n // in compound SELECT\", witnessed by d1-permissions-statement-budget W-K2f).\n // D1 bounds no relations: it takes PostgreSQL's (256, Neki's) because\n // below it walks kept in place serve a few rows faster (a take-10 read at\n // 50x the permissions fixture: 0.6 ms, 5.2 ms as reaching sets), and above\n // it the compact form keeps the largest reads well inside 100 KB.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n deepExpressions: false,\n sharedRelationBodies: true,\n compoundSelectTerms: 5,\n relationsPerStatement: 256,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\n}\n"],"mappings":"scAOA,MAAM,EAAe,IAAI,IAAI,CAAC,UAAW,SAAU,SAAS,CAAC,CACvD,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,UACA,SACA,QACA,SACA,SACA,SACA,OACA,MACA,UACA,UACA,WACA,YACA,SACD,CAAC,CACI,EAAwB,IAAI,IAAI,CACpC,sBACA,qBACA,eACA,2BACA,qBACA,qBACA,4BACD,CAAC,CACI,EAAyB,IAAI,IAAI,CAAC,WAAW,CAAC,CAC9C,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAGtE,SAAgB,8BACd,EAC2B,CAC3B,IAAM,EAAW,EAA2B,EAAI,CAChD,GAAI,CAAC,EAAU,MAAO,UACtB,IAAM,EAAW,gBAAgB,EAAS,CACpC,EAAU,GAAU,MAe1B,OAdK,EACD,EAAa,IAAI,EAAQ,CACpB,OAEL,EAAkB,IAAI,EAAQ,CACzB,EACJ,MAAM,EAAS,MAAQ,EAAE,CACzB,KAAM,GAAU,EAAM,OAAS,QAAU,EAAM,QAAU,YAAY,CACpE,OACA,UAEF,IAAY,SACP,eAAe,EAAS,CAE1B,EAAgB,IAAI,EAAQ,CAAG,UAAY,UAd7B,UAkBvB,SAAgB,wBAAwB,EAAsB,CAC5D,IAAM,EAAU,gBAAgB,EAA2B,EAAI,CAAC,EAAE,MAClE,OAAO,IAAY,UAAY,IAAY,UAG7C,SAAS,gBACP,EACgE,CAChE,IAAM,EAAQ,IAAW,GACzB,GAAI,CAAC,GAAS,EAAM,OAAS,OAAQ,OACrC,GAAI,EAAM,QAAU,OAAQ,MAAO,CAAE,MAAO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AAM,SAAW,EAC1C,GAAI,CACF,IAAM,EAAS,EAAM,OAAS,oBAAoB,EAAM,OAAO,CAAG,EAAE,CACpE,EAAW,KAAK,EAAO,QAAQ,EAAM,IAAI,CAAC,KAAK,GAAG,EAAO,CAAC,OACnD,EAAO,CACd,MAAM,KAAK,0BACT,EACA,EAAM,IACN,KAAK,6BAA6B,EAAM,CACxC,EACA,GACD,EAKL,IAAM,EAAmB,MAAM,EAAO,MAAS,EAAW,CAG1D,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,kBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,IAAM,EAA+B,EAAE,CACvC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,OAAQ,GAAS,EAAG,CACtD,IAAM,EAAQ,EAAQ,GACtB,GAAI,CAAC,EACH,MAAM,kBACJ,EACA,oDAAoD,IACrD,CAEH,EAAW,KACT,kBACE,EAAQ,GACR,EAAM,IACN,EAAM,SAAW,EACjB,GACD,CACF,CAEH,OAAO,IAQX,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,YAAa,EAIrB,OAAO,EAA6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
1
+ {"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`. D1 compiles\n // with an expression depth of 100 (\"Expression tree is too large\"):\n // relation filters nest as derived tables and conjunctions as balanced\n // trees (d1-permissions-verbs W-W3, W-W7). D1 refuses a statement over 100 KB: a\n // relation body a statement repeats is stated once (d1-permissions-placement\n // W-P10's update form), and a compound SELECT over 5 terms (\"too many terms\n // in compound SELECT\", witnessed by d1-permissions-statement-budget W-K2f).\n // D1 bounds no relations: it takes PostgreSQL's (256, Neki's) because\n // below it walks kept in place serve a few rows faster (a take-10 read at\n // 50x the permissions fixture: 0.6 ms, 5.2 ms as reaching sets), and above\n // it the compact form keeps the largest reads well inside 100 KB.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n deepExpressions: false,\n sharedRelationBodies: true,\n compoundSelectTerms: 5,\n relationsPerStatement: 256,\n countsCascadedChanges: true,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\n}\n"],"mappings":"scAOA,MAAM,EAAe,IAAI,IAAI,CAAC,UAAW,SAAU,SAAS,CAAC,CACvD,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,UACA,SACA,QACA,SACA,SACA,SACA,OACA,MACA,UACA,UACA,WACA,YACA,SACD,CAAC,CACI,EAAwB,IAAI,IAAI,CACpC,sBACA,qBACA,eACA,2BACA,qBACA,qBACA,4BACD,CAAC,CACI,EAAyB,IAAI,IAAI,CAAC,WAAW,CAAC,CAC9C,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAGtE,SAAgB,8BACd,EAC2B,CAC3B,IAAM,EAAW,EAA2B,EAAI,CAChD,GAAI,CAAC,EAAU,MAAO,UACtB,IAAM,EAAW,gBAAgB,EAAS,CACpC,EAAU,GAAU,MAe1B,OAdK,EACD,EAAa,IAAI,EAAQ,CACpB,OAEL,EAAkB,IAAI,EAAQ,CACzB,EACJ,MAAM,EAAS,MAAQ,EAAE,CACzB,KAAM,GAAU,EAAM,OAAS,QAAU,EAAM,QAAU,YAAY,CACpE,OACA,UAEF,IAAY,SACP,eAAe,EAAS,CAE1B,EAAgB,IAAI,EAAQ,CAAG,UAAY,UAd7B,UAkBvB,SAAgB,wBAAwB,EAAsB,CAC5D,IAAM,EAAU,gBAAgB,EAA2B,EAAI,CAAC,EAAE,MAClE,OAAO,IAAY,UAAY,IAAY,UAG7C,SAAS,gBACP,EACgE,CAChE,IAAM,EAAQ,IAAW,GACzB,GAAI,CAAC,GAAS,EAAM,OAAS,OAAQ,OACrC,GAAI,EAAM,QAAU,OAAQ,MAAO,CAAE,MAAO,EAAG,MAAO,EAAM,MAAO,CACnE,IAAM,EAAQ,EAAS,WACpB,EAAO,IACN,EAAa,GAAK,E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,OAAO,CAAG,EAAE,CACpE,EAAW,KAAK,EAAO,QAAQ,EAAM,IAAI,CAAC,KAAK,GAAG,EAAO,CAAC,OACnD,EAAO,CACd,MAAM,KAAK,0BACT,EACA,EAAM,IACN,KAAK,6BAA6B,EAAM,CACxC,EACA,GACD,EAKL,IAAM,EAAmB,MAAM,EAAO,MAAS,EAAW,CAG1D,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,kBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,IAAM,EAA+B,EAAE,CACvC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,OAAQ,GAAS,EAAG,CACtD,IAAM,EAAQ,EAAQ,GACtB,GAAI,CAAC,EACH,MAAM,kBACJ,EACA,oDAAoD,IACrD,CAEH,EAAW,KACT,kBACE,EAAQ,GACR,EAAM,IACN,EAAM,SAAW,EACjB,GACD,CACF,CAEH,OAAO,IAQX,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,YAAa,EAIrB,OAAO,EAA6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-D95uXgDF.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function digitsAt(e,t,n){let r=0;for(let i=t;i<t+n;i+=1){let t=e.charCodeAt(i)-48;if(t<0||t>9)return-1;r=r*10+t}return r}function decodeCanonicalTimestamp(e){if(e.length!==24||e.charCodeAt(4)!==45||e.charCodeAt(7)!==45||e.charCodeAt(10)!==84||e.charCodeAt(13)!==58||e.charCodeAt(16)!==58||e.charCodeAt(19)!==46||e.charCodeAt(23)!==90)return!1;let t=digitsAt(e,0,4),n=digitsAt(e,5,2),o=digitsAt(e,8,2),s=digitsAt(e,11,2),c=digitsAt(e,14,2),l=digitsAt(e,17,2),u=digitsAt(e,20,3);if(t<100||n<0||o<0||s<0||c<0||l<0||u<0)return!1;if(!(a(t,n,o)&&r(s,c,l)))return;let d=Date.UTC(t,n-1,o,s,c,l,u);return i(d)?new Date(d):void 0}function decodeProviderTimestamp(e){let t=decodeCanonicalTimestamp(e);if(t!==!1)return t;let n=c.exec(e);if(!n)return;let o=n[13]?1-Number(n[1]):Number(n[1]),s=Number(n[2]),l=Number(n[3]),u=Number(n[4]),d=Number(n[5]),f=Number(n[6]),p=Number(n[10]??0),m=Number(n[11]??0),h=Number(n[12]??0);if(!(a(o,s,l)&&r(u,d,f))||p>23||m>59||h>59)return;let g=new Date(0);g.setUTCFullYear(o,s-1,l),g.setUTCHours(u,d,f,Number((n[7]??``).padEnd(3,`0`).slice(0,3)));let _=(p*3600+m*60+h)*1e3,v=g.getTime()-(n[9]===`-`?-_:_);return i(v)?new Date(v):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
2
- //# sourceMappingURL=datetime-physical-codec-lX7IJBlz.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-pAWYj5ZZ.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function digitsAt(e,t,n){let r=0;for(let i=t;i<t+n;i+=1){let t=e.charCodeAt(i)-48;if(t<0||t>9)return-1;r=r*10+t}return r}function decodeCanonicalTimestamp(e){if(e.length!==24||e.charCodeAt(4)!==45||e.charCodeAt(7)!==45||e.charCodeAt(10)!==84||e.charCodeAt(13)!==58||e.charCodeAt(16)!==58||e.charCodeAt(19)!==46||e.charCodeAt(23)!==90)return!1;let t=digitsAt(e,0,4),n=digitsAt(e,5,2),o=digitsAt(e,8,2),s=digitsAt(e,11,2),c=digitsAt(e,14,2),l=digitsAt(e,17,2),u=digitsAt(e,20,3);if(t<100||n<0||o<0||s<0||c<0||l<0||u<0)return!1;if(!(a(t,n,o)&&r(s,c,l)))return;let d=Date.UTC(t,n-1,o,s,c,l,u);return i(d)?new Date(d):void 0}function decodeProviderTimestamp(e){let t=decodeCanonicalTimestamp(e);if(t!==!1)return t;let n=c.exec(e);if(!n)return;let o=n[13]?1-Number(n[1]):Number(n[1]),s=Number(n[2]),l=Number(n[3]),u=Number(n[4]),d=Number(n[5]),f=Number(n[6]),p=Number(n[10]??0),m=Number(n[11]??0),h=Number(n[12]??0);if(!(a(o,s,l)&&r(u,d,f))||p>23||m>59||h>59)return;let g=new Date(0);g.setUTCFullYear(o,s-1,l),g.setUTCHours(u,d,f,Number((n[7]??``).padEnd(3,`0`).slice(0,3)));let _=(p*3600+m*60+h)*1e3,v=g.getTime()-(n[9]===`-`?-_:_);return i(v)?new Date(v):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
2
+ //# sourceMappingURL=datetime-physical-codec-CFoeuitT.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"datetime-physical-codec-lX7IJBlz.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * The canonical stored spelling `YYYY-MM-DDTHH:MM:SS.sssZ` (what the\n * DateTime boundary writes), read by character: `false` for any other\n * spelling, and for a year below 100, which `Date.UTC` would read as 19xx.\n * The general grammar reads both; the domain rules are the same.\n */\nfunction decodeCanonicalTimestamp(value: string): Date | undefined | false {\n if (\n value.length !== 24 ||\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n value.charCodeAt(10) !== 84 || // T\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 || // :\n value.charCodeAt(19) !== 46 || // .\n value.charCodeAt(23) !== 90 // Z\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n const millisecond = digitsAt(value, 20, 3);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0 ||\n millisecond < 0\n )\n return false;\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch = Date.UTC(\n year,\n month - 1,\n day,\n hour,\n minute,\n second,\n millisecond\n );\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const canonical = decodeCanonicalTimestamp(value);\n if (canonical !== false) return canonical;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,uBACd,EACA,EACiB,CACjB,GAAI,IAAS,OAAQ,OAAO,EAC5B,IAAM,EAAoB,KAAK,MAAM,EAAI,CACzC,OAAO,IAAS,cACZ,EACA,EAAoB,EAAuB,EAcjD,SAAgB,uBACd,EACA,EACkB,CAClB,IAAM,EAAW,eAAe,EAAM,CACtC,GAAI,IAAa,IAAA,GAAW,OAC5B,IAAM,EACJ,IAAS,cACL,EACA,KAAK,OAAO,EAAW,GAAyB,EAAqB,CACtE,KAAkB,EAAkB,CACzC,OAAO,IAAI,KAAK,EAAkB,CAGpC,MAAM,EACJ,mIAGF,SAAS,SAAS,EAAe,EAAY,EAAuB,CAClE,IAAI,EAAS,EACb,IAAK,IAAI,EAAQ,EAAI,EAAQ,EAAK,EAAO,GAAS,EAAG,CACnD,IAAM,EAAQ,EAAM,WAAW,EAAM,CAAG,GACxC,GAAI,EAAQ,GAAK,EAAQ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OAAO,EAAM,GAAG,CACzB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAa,OAAO,EAAM,KAAO,EAAE,CACnC,EAAe,OAAO,EAAM,KAAO,EAAE,CACrC,EAAe,OAAO,EAAM,KAAO,EAAE,CAC3C,GACE,EACE,EAAwB,EAAM,EAAO,EAAI,EACzC,EAAgB,EAAM,EAAQ,EAAO,GAEvC,EAAa,IACb,EAAe,IACf,EAAe,GAEf,OACF,IAAM,EAAS,IAAI,KAAK,EAAE,CAE1B,EAAO,eAAe,EAAM,EAAQ,EAAG,EAAI,CAC3C,EAAO,YACL,EACA,EACA,EACA,QAAQ,EAAM,IAAM,IAAI,OAAO,EAAG,IAAI,CAAC,MAAM,EAAG,EAAE,CAAC,CACpD,CACD,IAAM,GAAU,EAAa,KAAO,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
1
+ {"version":3,"file":"datetime-physical-codec-CFoeuitT.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The digits `value` holds at `[at, at + count)`, or -1 where one is not a digit. */\nfunction digitsAt(value: string, at: number, count: number): number {\n let parsed = 0;\n for (let index = at; index < at + count; index += 1) {\n const digit = value.charCodeAt(index) - 48;\n if (digit < 0 || digit > 9) return -1;\n parsed = parsed * 10 + digit;\n }\n return parsed;\n}\n\n/**\n * The canonical stored spelling `YYYY-MM-DDTHH:MM:SS.sssZ` (what the\n * DateTime boundary writes), read by character: `false` for any other\n * spelling, and for a year below 100, which `Date.UTC` would read as 19xx.\n * The general grammar reads both; the domain rules are the same.\n */\nfunction decodeCanonicalTimestamp(value: string): Date | undefined | false {\n if (\n value.length !== 24 ||\n value.charCodeAt(4) !== 45 || // -\n value.charCodeAt(7) !== 45 || // -\n value.charCodeAt(10) !== 84 || // T\n value.charCodeAt(13) !== 58 || // :\n value.charCodeAt(16) !== 58 || // :\n value.charCodeAt(19) !== 46 || // .\n value.charCodeAt(23) !== 90 // Z\n )\n return false;\n const year = digitsAt(value, 0, 4);\n const month = digitsAt(value, 5, 2);\n const day = digitsAt(value, 8, 2);\n const hour = digitsAt(value, 11, 2);\n const minute = digitsAt(value, 14, 2);\n const second = digitsAt(value, 17, 2);\n const millisecond = digitsAt(value, 20, 3);\n if (\n year < 100 ||\n month < 0 ||\n day < 0 ||\n hour < 0 ||\n minute < 0 ||\n second < 0 ||\n millisecond < 0\n )\n return false;\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n )\n )\n return undefined;\n const epoch = Date.UTC(\n year,\n month - 1,\n day,\n hour,\n minute,\n second,\n millisecond\n );\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const canonical = decodeCanonicalTimestamp(value);\n if (canonical !== false) return canonical;\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,uBACd,EACA,EACiB,CACjB,GAAI,IAAS,OAAQ,OAAO,EAC5B,IAAM,EAAoB,KAAK,MAAM,EAAI,CACzC,OAAO,IAAS,cACZ,EACA,EAAoB,EAAuB,EAcjD,SAAgB,uBACd,EACA,EACkB,CAClB,IAAM,EAAW,eAAe,EAAM,CACtC,GAAI,IAAa,IAAA,GAAW,OAC5B,IAAM,EACJ,IAAS,cACL,EACA,KAAK,OAAO,EAAW,GAAyB,EAAqB,CACtE,KAAkB,EAAkB,CACzC,OAAO,IAAI,KAAK,EAAkB,CAGpC,MA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,GAAI,CAAC,EAAO,OACZ,IAAM,EAAO,EAAM,IAAM,EAAI,OAAO,EAAM,GAAG,CAAG,OAAO,EAAM,GAAG,CAC1D,EAAQ,OAAO,EAAM,GAAG,CACxB,EAAM,OAAO,EAAM,GAAG,CACtB,EAAO,OAAO,EAAM,GAAG,CACvB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAS,OAAO,EAAM,GAAG,CACzB,EAAa,OAAO,EAAM,KAAO,EAAE,CACnC,EAAe,OAAO,EAAM,KAAO,EAAE,CACrC,EAAe,OAAO,EAAM,KAAO,EAAE,CAC3C,GACE,EACE,EAAwB,EAAM,EAAO,EAAI,EACzC,EAAgB,EAAM,EAAQ,EAAO,GAEvC,EAAa,IACb,EAAe,IACf,EAAe,GAEf,OACF,IAAM,EAAS,IAAI,KAAK,EAAE,CAE1B,EAAO,eAAe,EAAM,EAAQ,EAAG,EAAI,CAC3C,EAAO,YACL,EACA,EACA,EACA,QAAQ,EAAM,IAAM,IAAI,OAAO,EAAG,IAAI,CAAC,MAAM,EAAG,EAAE,CAAC,CACpD,CACD,IAAM,GAAU,EAAa,KAAO,EAAe,GAAK,GAAgB,IAClE,EAAQ,EAAO,SAAS,EAAI,EAAM,KAAO,IAAM,CAAC,EAAS,GAC/D,OAAO,EAAkB,EAAM,CAAG,IAAI,KAAK,EAAM,CAAG,IAAA,GAItD,MAAa,oBAAuB,GAClC,IAAI,KAAK,EAAI,CAAC,aAAa,CAAC,MAAM,EAAG,GAAG,CAAC,QAAQ,IAAK,IAAI"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,r as n}from"./cache-CIPRF-pz.mjs";import{n as r}from"./v-514RME2X.mjs";import{n as i,r as a,t as o}from"./key-B89Z4vxn.mjs";import{d as s,f as c,t as l}from"./observation-Co72iCd1.mjs";import{o as u}from"./execution-context-rJXTRVrJ.mjs";import{t as d}from"./clock-CJotKAxc.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),v),e=>parseTTL(e)),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||l(u(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,i,o,s){let c=a(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,o,s,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,s,o,u);if(n){let a=this.clock.now()-n.createdAt;if(!(a>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&a<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,o,s,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let a=await r();return this.#r(l,a,i,o,s,u,d),recordCacheOutcome(i.executionContext,`miss`),a};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,o,c,l,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=u(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),s=o.snapshot(t);await this.#c(n,s,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,l,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():s({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=u(t)?.observe;if(a===void 0||a.length===0)return n();let o=e===`clear`||e===`delete`;return s({kind:`cache`,operation:o?`invalidate`:e},o?c(a):a,n,void 0,()=>Object.freeze(o?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${o}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let r=e.startsWith(`${o}:`)?e:e?`${o}:${e}`:o;if(r===i||r.startsWith(`${i}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return r}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
- //# sourceMappingURL=driver-u2qJicrE.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,r as n}from"./cache-CIPRF-pz.mjs";import{n as r}from"./v-BcroBusN.mjs";import{n as i,r as a,t as o}from"./key-CyLRw0ne.mjs";import{d as s,f as c,t as l}from"./observation-Co72iCd1.mjs";import{s as u}from"./execution-context-asSCmyas.mjs";import{t as d}from"./clock-CJotKAxc.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),v),e=>parseTTL(e)),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||l(u(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,i,o,s){let c=a(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,o,s,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,s,o,u);if(n){let a=this.clock.now()-n.createdAt;if(!(a>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&a<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,o,s,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let a=await r();return this.#r(l,a,i,o,s,u,d),recordCacheOutcome(i.executionContext,`miss`),a};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,o,c,l,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=u(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),s=o.snapshot(t);await this.#c(n,s,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,l,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():s({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=u(t)?.observe;if(a===void 0||a.length===0)return n();let o=e===`clear`||e===`delete`;return s({kind:`cache`,operation:o?`invalidate`:e},o?c(a):a,n,void 0,()=>Object.freeze(o?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${o}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let r=e.startsWith(`${o}:`)?e:e?`${o}:${e}`:o;if(r===i||r.startsWith(`${i}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return r}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
+ //# sourceMappingURL=driver-BqD-3_jO.mjs.map