@tempoxyz/id 0.0.0-pr-349.sha-e0d3dfc → 0.0.0-pr-357.sha-e757593

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 (341) hide show
  1. package/README.md +0 -3
  2. package/dist/app/server/assets/Grant-D_tun0mF.js.map +1 -1
  3. package/dist/app/server/index.js +4 -4
  4. package/dist/app/server/index.js.map +1 -1
  5. package/dist/cli/Cli.d.ts +1 -8
  6. package/dist/cli/Cli.d.ts.map +1 -1
  7. package/dist/cli/Cli.js +6 -9
  8. package/dist/cli/Cli.js.map +1 -1
  9. package/dist/cli/Session.d.ts +1 -1
  10. package/dist/cli/Session.d.ts.map +1 -1
  11. package/dist/cli/Session.js +1 -1
  12. package/dist/cli/Session.js.map +1 -1
  13. package/dist/cli/bin.js +4 -23
  14. package/dist/cli/bin.js.map +1 -1
  15. package/dist/client/Actions.d.ts +1 -2
  16. package/dist/client/Actions.d.ts.map +1 -1
  17. package/dist/client/Actions.js +0 -1
  18. package/dist/client/Actions.js.map +1 -1
  19. package/dist/client/Auth.d.ts +1 -1
  20. package/dist/client/Auth.d.ts.map +1 -1
  21. package/dist/client/Auth.js.map +1 -1
  22. package/dist/client/Authorization.d.ts +8 -4
  23. package/dist/client/Authorization.d.ts.map +1 -1
  24. package/dist/client/Authorization.js +1 -1
  25. package/dist/client/Authorization.js.map +1 -1
  26. package/dist/client/actions/email.d.ts +1 -1
  27. package/dist/client/actions/email.d.ts.map +1 -1
  28. package/dist/client/actions/passkey.d.ts +1 -1
  29. package/dist/client/actions/passkey.d.ts.map +1 -1
  30. package/dist/client/actions/redirect.d.ts +1 -1
  31. package/dist/client/actions/redirect.d.ts.map +1 -1
  32. package/dist/client/internal/api.d.ts +1 -1
  33. package/dist/client/internal/api.d.ts.map +1 -1
  34. package/dist/client/internal/api.js +1 -1
  35. package/dist/client/internal/api.js.map +1 -1
  36. package/dist/client/viem/Actions.d.ts +3 -3
  37. package/dist/client/viem/Actions.d.ts.map +1 -1
  38. package/dist/client/viem/Actions.js +4 -4
  39. package/dist/client/viem/Actions.js.map +1 -1
  40. package/dist/client/viem/Decorator.d.ts +2 -2
  41. package/dist/client/viem/internal/client.d.ts +3 -3
  42. package/dist/client/viem/internal/client.d.ts.map +1 -1
  43. package/dist/client/viem/internal/client.js +2 -2
  44. package/dist/client/viem/internal/client.js.map +1 -1
  45. package/dist/client.d.ts +0 -1
  46. package/dist/client.d.ts.map +1 -1
  47. package/dist/client.js +0 -1
  48. package/dist/client.js.map +1 -1
  49. package/dist/internal/Apps.d.ts +1 -2
  50. package/dist/internal/Apps.d.ts.map +1 -1
  51. package/dist/internal/Apps.js +5 -10
  52. package/dist/internal/Apps.js.map +1 -1
  53. package/dist/internal/ErrorResponse.d.ts +0 -20
  54. package/dist/internal/ErrorResponse.d.ts.map +1 -1
  55. package/dist/internal/ErrorResponse.js +0 -35
  56. package/dist/internal/ErrorResponse.js.map +1 -1
  57. package/dist/internal/RequestId.d.ts +1 -7
  58. package/dist/internal/RequestId.d.ts.map +1 -1
  59. package/dist/internal/RequestId.js.map +1 -1
  60. package/dist/internal/Timing.d.ts +1 -4
  61. package/dist/internal/Timing.d.ts.map +1 -1
  62. package/dist/internal/Timing.js.map +1 -1
  63. package/package.json +1 -7
  64. package/src/cli/Cli.ts +5 -13
  65. package/src/cli/Session.ts +2 -2
  66. package/src/cli/bin.ts +4 -26
  67. package/src/client/Actions.ts +1 -2
  68. package/src/client/Auth.ts +0 -4
  69. package/src/client/Authorization.ts +8 -4
  70. package/src/client/actions/email.ts +1 -1
  71. package/src/client/actions/passkey.ts +1 -1
  72. package/src/client/actions/redirect.ts +1 -1
  73. package/src/client/internal/api.ts +2 -2
  74. package/src/client/viem/Actions.ts +5 -5
  75. package/src/client/viem/Decorator.ts +2 -2
  76. package/src/client/viem/internal/client.ts +5 -5
  77. package/src/client.ts +0 -1
  78. package/src/internal/Apps.ts +4 -17
  79. package/src/internal/ErrorResponse.ts +0 -41
  80. package/src/internal/OpenApi.ts +7 -57
  81. package/src/internal/RequestId.ts +2 -8
  82. package/src/internal/Timing.ts +1 -4
  83. package/src/types/app.d.ts +0 -14
  84. package/dist/Admin.d.ts +0 -79
  85. package/dist/Admin.d.ts.map +0 -1
  86. package/dist/Admin.js +0 -93
  87. package/dist/Admin.js.map +0 -1
  88. package/dist/admin/Env.d.ts +0 -68
  89. package/dist/admin/Env.d.ts.map +0 -1
  90. package/dist/admin/Env.js +0 -2
  91. package/dist/admin/Env.js.map +0 -1
  92. package/dist/admin/app/client/.assetsignore +0 -2
  93. package/dist/admin/app/client/assets/Client-BrjXsLWn.js +0 -2
  94. package/dist/admin/app/client/assets/Client-DdghQm8N.css +0 -1
  95. package/dist/admin/app/client/assets/GeistMono-Variable-BRXCGrxA.woff2 +0 -0
  96. package/dist/admin/app/client/assets/Inter-cyrillic-e3OmmzmJ.woff2 +0 -0
  97. package/dist/admin/app/client/assets/Inter-cyrillic-ext-DOWZeO4Q.woff2 +0 -0
  98. package/dist/admin/app/client/assets/Inter-greek-BD3ujQlX.woff2 +0 -0
  99. package/dist/admin/app/client/assets/Inter-greek-ext-CXEwbus4.woff2 +0 -0
  100. package/dist/admin/app/client/assets/Inter-latin-BDFm4vTb.woff2 +0 -0
  101. package/dist/admin/app/client/assets/Inter-latin-ext-E7a9JEPe.woff2 +0 -0
  102. package/dist/admin/app/client/assets/Inter-symbols-DEch7Rxr.woff2 +0 -0
  103. package/dist/admin/app/client/assets/Inter-vietnamese-Bg9723vR.woff2 +0 -0
  104. package/dist/admin/app/client/assets/___dev-EY7r7Loc.css +0 -1
  105. package/dist/admin/app/client/assets/___dev.sign-in-ClQvgAau.js +0 -1
  106. package/dist/admin/app/client/assets/index-Cbo1RPkb.css +0 -1
  107. package/dist/admin/app/client/assets/index-DAKRgvN1.js +0 -13
  108. package/dist/admin/app/client/assets/reset-co-CHrff.css +0 -1
  109. package/dist/admin/app/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  110. package/dist/admin/app/client/assets/routes-BEUY7mCO.css +0 -1
  111. package/dist/admin/app/client/assets/routes-DM0o3oBQ.js +0 -1
  112. package/dist/admin/app/client/assets/shadowDom-DMRd3g4s.js +0 -1
  113. package/dist/admin/app/server/.vite/manifest.json +0 -359
  114. package/dist/admin/app/server/assets/Client-D4wNQeJd.js +0 -3
  115. package/dist/admin/app/server/assets/Client-D4wNQeJd.js.map +0 -1
  116. package/dist/admin/app/server/assets/GeistMono-Variable-BRXCGrxA.woff2 +0 -0
  117. package/dist/admin/app/server/assets/Inter-cyrillic-e3OmmzmJ.woff2 +0 -0
  118. package/dist/admin/app/server/assets/Inter-cyrillic-ext-DOWZeO4Q.woff2 +0 -0
  119. package/dist/admin/app/server/assets/Inter-greek-BD3ujQlX.woff2 +0 -0
  120. package/dist/admin/app/server/assets/Inter-greek-ext-CXEwbus4.woff2 +0 -0
  121. package/dist/admin/app/server/assets/Inter-latin-BDFm4vTb.woff2 +0 -0
  122. package/dist/admin/app/server/assets/Inter-latin-ext-E7a9JEPe.woff2 +0 -0
  123. package/dist/admin/app/server/assets/Inter-symbols-DEch7Rxr.woff2 +0 -0
  124. package/dist/admin/app/server/assets/Inter-vietnamese-Bg9723vR.woff2 +0 -0
  125. package/dist/admin/app/server/assets/___dev-EY7r7Loc.css +0 -1
  126. package/dist/admin/app/server/assets/___dev.sign-in-DUf_NQPU.js +0 -2
  127. package/dist/admin/app/server/assets/___dev.sign-in-DUf_NQPU.js.map +0 -1
  128. package/dist/admin/app/server/assets/_tanstack-start-manifest_v-C8ysuxtN.js +0 -1
  129. package/dist/admin/app/server/assets/arktype-aI7TBD0R-D1R3Byo5.js +0 -2
  130. package/dist/admin/app/server/assets/arktype-aI7TBD0R-D1R3Byo5.js.map +0 -1
  131. package/dist/admin/app/server/assets/async-local-storage-DUe1175v.js +0 -2
  132. package/dist/admin/app/server/assets/async-local-storage-DUe1175v.js.map +0 -1
  133. package/dist/admin/app/server/assets/convert-BIC8n32x.js +0 -2
  134. package/dist/admin/app/server/assets/convert-BIC8n32x.js.map +0 -1
  135. package/dist/admin/app/server/assets/cookie-BOmgOR30.js +0 -2
  136. package/dist/admin/app/server/assets/cookie-BOmgOR30.js.map +0 -1
  137. package/dist/admin/app/server/assets/cookie-DdghQm8N.css +0 -1
  138. package/dist/admin/app/server/assets/default-u_dwuiYb-D6RfpcBr.js +0 -2
  139. package/dist/admin/app/server/assets/default-u_dwuiYb-D6RfpcBr.js.map +0 -1
  140. package/dist/admin/app/server/assets/effect-QlVUlMFu-Bs0PyUhN.js +0 -2
  141. package/dist/admin/app/server/assets/effect-QlVUlMFu-Bs0PyUhN.js.map +0 -1
  142. package/dist/admin/app/server/assets/empty-plugin-adapters-BaGcmrjC.js +0 -2
  143. package/dist/admin/app/server/assets/empty-plugin-adapters-BaGcmrjC.js.map +0 -1
  144. package/dist/admin/app/server/assets/esm-C6SW--yt.js +0 -4
  145. package/dist/admin/app/server/assets/esm-C6SW--yt.js.map +0 -1
  146. package/dist/admin/app/server/assets/index-CLddUTqr-ComTZ4bq.js +0 -2
  147. package/dist/admin/app/server/assets/index-CLddUTqr-ComTZ4bq.js.map +0 -1
  148. package/dist/admin/app/server/assets/index-DZEfthgZ-BxnrPO8Q.js +0 -2
  149. package/dist/admin/app/server/assets/index-DZEfthgZ-BxnrPO8Q.js.map +0 -1
  150. package/dist/admin/app/server/assets/reset-co-CHrff.css +0 -1
  151. package/dist/admin/app/server/assets/rolldown-runtime-BWaJ3C7D.js +0 -1
  152. package/dist/admin/app/server/assets/router-Cbo1RPkb.css +0 -1
  153. package/dist/admin/app/server/assets/router-Dqhrc0PX.js +0 -2
  154. package/dist/admin/app/server/assets/router-Dqhrc0PX.js.map +0 -1
  155. package/dist/admin/app/server/assets/routes-BEUY7mCO.css +0 -1
  156. package/dist/admin/app/server/assets/routes-CxbX5JNu.js +0 -2
  157. package/dist/admin/app/server/assets/routes-CxbX5JNu.js.map +0 -1
  158. package/dist/admin/app/server/assets/server-tS2GlQUk.js +0 -77
  159. package/dist/admin/app/server/assets/server-tS2GlQUk.js.map +0 -1
  160. package/dist/admin/app/server/assets/shadowDom-CvS1DzWo.js +0 -2
  161. package/dist/admin/app/server/assets/shadowDom-CvS1DzWo.js.map +0 -1
  162. package/dist/admin/app/server/assets/standard-json-DY77efq0.js +0 -2
  163. package/dist/admin/app/server/assets/standard-json-DY77efq0.js.map +0 -1
  164. package/dist/admin/app/server/assets/standard-json-ig2t0wRt.js +0 -2
  165. package/dist/admin/app/server/assets/standard-json-ig2t0wRt.js.map +0 -1
  166. package/dist/admin/app/server/assets/standard-json-t-LNckA6.js +0 -2
  167. package/dist/admin/app/server/assets/standard-json-t-LNckA6.js.map +0 -1
  168. package/dist/admin/app/server/assets/standard-openapi-CONmVRl8.js +0 -2
  169. package/dist/admin/app/server/assets/standard-openapi-CONmVRl8.js.map +0 -1
  170. package/dist/admin/app/server/assets/start-C63VetBp.js +0 -2
  171. package/dist/admin/app/server/assets/start-C63VetBp.js.map +0 -1
  172. package/dist/admin/app/server/assets/sury-CWZTCd75-DP9TvBrs.js +0 -2
  173. package/dist/admin/app/server/assets/sury-CWZTCd75-DP9TvBrs.js.map +0 -1
  174. package/dist/admin/app/server/assets/typebox-Dei93FPO-D_lCVdAz.js +0 -2
  175. package/dist/admin/app/server/assets/typebox-Dei93FPO-D_lCVdAz.js.map +0 -1
  176. package/dist/admin/app/server/assets/valibot--1zFm7rT-BKGsXNQL.js +0 -2
  177. package/dist/admin/app/server/assets/valibot--1zFm7rT-BKGsXNQL.js.map +0 -1
  178. package/dist/admin/app/server/assets/valibot-D_HTw1Gn-BNmO9Liy.js +0 -2
  179. package/dist/admin/app/server/assets/valibot-D_HTw1Gn-BNmO9Liy.js.map +0 -1
  180. package/dist/admin/app/server/assets/worker-entry-DcGlpZzO.js +0 -93
  181. package/dist/admin/app/server/assets/worker-entry-DcGlpZzO.js.map +0 -1
  182. package/dist/admin/app/server/assets/zod-Bwrt9trS-DuX8BREF.js +0 -2
  183. package/dist/admin/app/server/assets/zod-Bwrt9trS-DuX8BREF.js.map +0 -1
  184. package/dist/admin/app/server/assets/zod-DSgpEGAE-BF9ADewr.js +0 -2
  185. package/dist/admin/app/server/assets/zod-DSgpEGAE-BF9ADewr.js.map +0 -1
  186. package/dist/admin/app/server/index.js +0 -1
  187. package/dist/admin/app/server/wrangler.json +0 -1
  188. package/dist/admin/dev/Session.d.ts +0 -135
  189. package/dist/admin/dev/Session.d.ts.map +0 -1
  190. package/dist/admin/dev/Session.js +0 -160
  191. package/dist/admin/dev/Session.js.map +0 -1
  192. package/dist/admin/index.d.ts +0 -15
  193. package/dist/admin/index.d.ts.map +0 -1
  194. package/dist/admin/index.js +0 -15
  195. package/dist/admin/index.js.map +0 -1
  196. package/dist/cli/AdminApi.d.ts +0 -46
  197. package/dist/cli/AdminApi.d.ts.map +0 -1
  198. package/dist/cli/AdminApi.js +0 -82
  199. package/dist/cli/AdminApi.js.map +0 -1
  200. package/dist/client/Admin.d.ts +0 -71
  201. package/dist/client/Admin.d.ts.map +0 -1
  202. package/dist/client/Admin.js +0 -29
  203. package/dist/client/Admin.js.map +0 -1
  204. package/dist/client/actions/admin/apps.d.ts +0 -142
  205. package/dist/client/actions/admin/apps.d.ts.map +0 -1
  206. package/dist/client/actions/admin/apps.js +0 -133
  207. package/dist/client/actions/admin/apps.js.map +0 -1
  208. package/dist/client/actions/admin.d.ts +0 -6
  209. package/dist/client/actions/admin.d.ts.map +0 -1
  210. package/dist/client/actions/admin.js +0 -6
  211. package/dist/client/actions/admin.js.map +0 -1
  212. package/src/Admin.ts +0 -184
  213. package/src/admin/Api.ts +0 -253
  214. package/src/admin/Env.ts +0 -73
  215. package/src/admin/app/.void/env.d.ts +0 -17
  216. package/src/admin/app/.void/preview-deploy-config.json +0 -1
  217. package/src/admin/app/.void/tanstack-start-trigger-wrapper.ts +0 -12
  218. package/src/admin/app/.void/tsconfig.json +0 -5
  219. package/src/admin/app/.void-wrangler.jsonc +0 -1
  220. package/src/admin/app/components/CodeInput.tsx +0 -153
  221. package/src/admin/app/dist/client/.assetsignore +0 -2
  222. package/src/admin/app/dist/client/assets/Client-BrjXsLWn.js +0 -2
  223. package/src/admin/app/dist/client/assets/Client-DdghQm8N.css +0 -1
  224. package/src/admin/app/dist/client/assets/GeistMono-Variable-BRXCGrxA.woff2 +0 -0
  225. package/src/admin/app/dist/client/assets/Inter-cyrillic-e3OmmzmJ.woff2 +0 -0
  226. package/src/admin/app/dist/client/assets/Inter-cyrillic-ext-DOWZeO4Q.woff2 +0 -0
  227. package/src/admin/app/dist/client/assets/Inter-greek-BD3ujQlX.woff2 +0 -0
  228. package/src/admin/app/dist/client/assets/Inter-greek-ext-CXEwbus4.woff2 +0 -0
  229. package/src/admin/app/dist/client/assets/Inter-latin-BDFm4vTb.woff2 +0 -0
  230. package/src/admin/app/dist/client/assets/Inter-latin-ext-E7a9JEPe.woff2 +0 -0
  231. package/src/admin/app/dist/client/assets/Inter-symbols-DEch7Rxr.woff2 +0 -0
  232. package/src/admin/app/dist/client/assets/Inter-vietnamese-Bg9723vR.woff2 +0 -0
  233. package/src/admin/app/dist/client/assets/___dev-EY7r7Loc.css +0 -1
  234. package/src/admin/app/dist/client/assets/___dev.sign-in-ClQvgAau.js +0 -1
  235. package/src/admin/app/dist/client/assets/index-Cbo1RPkb.css +0 -1
  236. package/src/admin/app/dist/client/assets/index-DAKRgvN1.js +0 -13
  237. package/src/admin/app/dist/client/assets/reset-co-CHrff.css +0 -1
  238. package/src/admin/app/dist/client/assets/rolldown-runtime-WkwZ5CU-.js +0 -1
  239. package/src/admin/app/dist/client/assets/routes-BEUY7mCO.css +0 -1
  240. package/src/admin/app/dist/client/assets/routes-DM0o3oBQ.js +0 -1
  241. package/src/admin/app/dist/client/assets/shadowDom-DMRd3g4s.js +0 -1
  242. package/src/admin/app/dist/server/.vite/manifest.json +0 -359
  243. package/src/admin/app/dist/server/assets/Client-D4wNQeJd.js +0 -3
  244. package/src/admin/app/dist/server/assets/Client-D4wNQeJd.js.map +0 -1
  245. package/src/admin/app/dist/server/assets/GeistMono-Variable-BRXCGrxA.woff2 +0 -0
  246. package/src/admin/app/dist/server/assets/Inter-cyrillic-e3OmmzmJ.woff2 +0 -0
  247. package/src/admin/app/dist/server/assets/Inter-cyrillic-ext-DOWZeO4Q.woff2 +0 -0
  248. package/src/admin/app/dist/server/assets/Inter-greek-BD3ujQlX.woff2 +0 -0
  249. package/src/admin/app/dist/server/assets/Inter-greek-ext-CXEwbus4.woff2 +0 -0
  250. package/src/admin/app/dist/server/assets/Inter-latin-BDFm4vTb.woff2 +0 -0
  251. package/src/admin/app/dist/server/assets/Inter-latin-ext-E7a9JEPe.woff2 +0 -0
  252. package/src/admin/app/dist/server/assets/Inter-symbols-DEch7Rxr.woff2 +0 -0
  253. package/src/admin/app/dist/server/assets/Inter-vietnamese-Bg9723vR.woff2 +0 -0
  254. package/src/admin/app/dist/server/assets/___dev-EY7r7Loc.css +0 -1
  255. package/src/admin/app/dist/server/assets/___dev.sign-in-DUf_NQPU.js +0 -2
  256. package/src/admin/app/dist/server/assets/___dev.sign-in-DUf_NQPU.js.map +0 -1
  257. package/src/admin/app/dist/server/assets/_tanstack-start-manifest_v-C8ysuxtN.js +0 -1
  258. package/src/admin/app/dist/server/assets/arktype-aI7TBD0R-D1R3Byo5.js +0 -2
  259. package/src/admin/app/dist/server/assets/arktype-aI7TBD0R-D1R3Byo5.js.map +0 -1
  260. package/src/admin/app/dist/server/assets/async-local-storage-DUe1175v.js +0 -2
  261. package/src/admin/app/dist/server/assets/async-local-storage-DUe1175v.js.map +0 -1
  262. package/src/admin/app/dist/server/assets/convert-BIC8n32x.js +0 -2
  263. package/src/admin/app/dist/server/assets/convert-BIC8n32x.js.map +0 -1
  264. package/src/admin/app/dist/server/assets/cookie-BOmgOR30.js +0 -2
  265. package/src/admin/app/dist/server/assets/cookie-BOmgOR30.js.map +0 -1
  266. package/src/admin/app/dist/server/assets/cookie-DdghQm8N.css +0 -1
  267. package/src/admin/app/dist/server/assets/default-u_dwuiYb-D6RfpcBr.js +0 -2
  268. package/src/admin/app/dist/server/assets/default-u_dwuiYb-D6RfpcBr.js.map +0 -1
  269. package/src/admin/app/dist/server/assets/effect-QlVUlMFu-Bs0PyUhN.js +0 -2
  270. package/src/admin/app/dist/server/assets/effect-QlVUlMFu-Bs0PyUhN.js.map +0 -1
  271. package/src/admin/app/dist/server/assets/empty-plugin-adapters-BaGcmrjC.js +0 -2
  272. package/src/admin/app/dist/server/assets/empty-plugin-adapters-BaGcmrjC.js.map +0 -1
  273. package/src/admin/app/dist/server/assets/esm-C6SW--yt.js +0 -4
  274. package/src/admin/app/dist/server/assets/esm-C6SW--yt.js.map +0 -1
  275. package/src/admin/app/dist/server/assets/index-CLddUTqr-ComTZ4bq.js +0 -2
  276. package/src/admin/app/dist/server/assets/index-CLddUTqr-ComTZ4bq.js.map +0 -1
  277. package/src/admin/app/dist/server/assets/index-DZEfthgZ-BxnrPO8Q.js +0 -2
  278. package/src/admin/app/dist/server/assets/index-DZEfthgZ-BxnrPO8Q.js.map +0 -1
  279. package/src/admin/app/dist/server/assets/reset-co-CHrff.css +0 -1
  280. package/src/admin/app/dist/server/assets/rolldown-runtime-BWaJ3C7D.js +0 -1
  281. package/src/admin/app/dist/server/assets/router-Cbo1RPkb.css +0 -1
  282. package/src/admin/app/dist/server/assets/router-Dqhrc0PX.js +0 -2
  283. package/src/admin/app/dist/server/assets/router-Dqhrc0PX.js.map +0 -1
  284. package/src/admin/app/dist/server/assets/routes-BEUY7mCO.css +0 -1
  285. package/src/admin/app/dist/server/assets/routes-CxbX5JNu.js +0 -2
  286. package/src/admin/app/dist/server/assets/routes-CxbX5JNu.js.map +0 -1
  287. package/src/admin/app/dist/server/assets/server-tS2GlQUk.js +0 -77
  288. package/src/admin/app/dist/server/assets/server-tS2GlQUk.js.map +0 -1
  289. package/src/admin/app/dist/server/assets/shadowDom-CvS1DzWo.js +0 -2
  290. package/src/admin/app/dist/server/assets/shadowDom-CvS1DzWo.js.map +0 -1
  291. package/src/admin/app/dist/server/assets/standard-json-DY77efq0.js +0 -2
  292. package/src/admin/app/dist/server/assets/standard-json-DY77efq0.js.map +0 -1
  293. package/src/admin/app/dist/server/assets/standard-json-ig2t0wRt.js +0 -2
  294. package/src/admin/app/dist/server/assets/standard-json-ig2t0wRt.js.map +0 -1
  295. package/src/admin/app/dist/server/assets/standard-json-t-LNckA6.js +0 -2
  296. package/src/admin/app/dist/server/assets/standard-json-t-LNckA6.js.map +0 -1
  297. package/src/admin/app/dist/server/assets/standard-openapi-CONmVRl8.js +0 -2
  298. package/src/admin/app/dist/server/assets/standard-openapi-CONmVRl8.js.map +0 -1
  299. package/src/admin/app/dist/server/assets/start-C63VetBp.js +0 -2
  300. package/src/admin/app/dist/server/assets/start-C63VetBp.js.map +0 -1
  301. package/src/admin/app/dist/server/assets/sury-CWZTCd75-DP9TvBrs.js +0 -2
  302. package/src/admin/app/dist/server/assets/sury-CWZTCd75-DP9TvBrs.js.map +0 -1
  303. package/src/admin/app/dist/server/assets/typebox-Dei93FPO-D_lCVdAz.js +0 -2
  304. package/src/admin/app/dist/server/assets/typebox-Dei93FPO-D_lCVdAz.js.map +0 -1
  305. package/src/admin/app/dist/server/assets/valibot--1zFm7rT-BKGsXNQL.js +0 -2
  306. package/src/admin/app/dist/server/assets/valibot--1zFm7rT-BKGsXNQL.js.map +0 -1
  307. package/src/admin/app/dist/server/assets/valibot-D_HTw1Gn-BNmO9Liy.js +0 -2
  308. package/src/admin/app/dist/server/assets/valibot-D_HTw1Gn-BNmO9Liy.js.map +0 -1
  309. package/src/admin/app/dist/server/assets/worker-entry-DcGlpZzO.js +0 -93
  310. package/src/admin/app/dist/server/assets/worker-entry-DcGlpZzO.js.map +0 -1
  311. package/src/admin/app/dist/server/assets/zod-Bwrt9trS-DuX8BREF.js +0 -2
  312. package/src/admin/app/dist/server/assets/zod-Bwrt9trS-DuX8BREF.js.map +0 -1
  313. package/src/admin/app/dist/server/assets/zod-DSgpEGAE-BF9ADewr.js +0 -2
  314. package/src/admin/app/dist/server/assets/zod-DSgpEGAE-BF9ADewr.js.map +0 -1
  315. package/src/admin/app/dist/server/index.js +0 -1
  316. package/src/admin/app/dist/server/wrangler.json +0 -1
  317. package/src/admin/app/env.ts +0 -11
  318. package/src/admin/app/lib/Client.ts +0 -38
  319. package/src/admin/app/package.json +0 -8
  320. package/src/admin/app/routeTree.gen.ts +0 -86
  321. package/src/admin/app/router.tsx +0 -19
  322. package/src/admin/app/routes/[_]dev.sign-in.tsx +0 -93
  323. package/src/admin/app/routes/__root.tsx +0 -97
  324. package/src/admin/app/routes/index.tsx +0 -20
  325. package/src/admin/app/screens/Dashboard.tsx +0 -84
  326. package/src/admin/app/screens/dev/SignIn.tsx +0 -213
  327. package/src/admin/app/server.ts +0 -129
  328. package/src/admin/app/tsconfig.json +0 -7
  329. package/src/admin/app/vite.config.ts +0 -52
  330. package/src/admin/app/void.config.ts +0 -17
  331. package/src/admin/app/zyzz.config.ts +0 -25
  332. package/src/admin/apps.ts +0 -472
  333. package/src/admin/dev/Session.ts +0 -332
  334. package/src/admin/dev/signIn.ts +0 -381
  335. package/src/admin/index.ts +0 -14
  336. package/src/admin/session.ts +0 -60
  337. package/src/cli/AdminApi.ts +0 -134
  338. package/src/client/Admin.ts +0 -76
  339. package/src/client/actions/admin/apps.ts +0 -257
  340. package/src/client/actions/admin.ts +0 -5
  341. package/src/internal/AdminApps.ts +0 -64
@@ -1,93 +0,0 @@
1
- import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-BWaJ3C7D.js";import{a,c as o,d as s,f as c,i as l,l as u,n as d,o as f,r as p,s as m,t as h,u as g}from"./cookie-BOmgOR30.js";import{n as _}from"./index-CLddUTqr-ComTZ4bq.js";import{n as ee}from"./index-DZEfthgZ-BxnrPO8Q.js";import"cloudflare:workers";import{AsyncLocalStorage as te}from"node:async_hooks";import*as ne from"events";import*as re from"util";import*as ie from"util/types";import*as ae from"crypto";import*as oe from"dns";import*as se from"fs";import*as ce from"net";import*as le from"tls";import*as ue from"path";import*as de from"stream";import*as fe from"string_decoder";function pe(e){return Error(`[unenv] ${e} is not implemented yet!`)}var me=globalThis.performance?.timeOrigin??Date.now(),he=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-me,ge={name:`node`,entryType:`node`,startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},_e=class{__unenv__=!0;detail;entryType=`event`;name;startTime;constructor(e,t){this.name=e,this.startTime=t?.startTime||he(),this.detail=t?.detail}get duration(){return he()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},ve=class extends _e{entryType=`mark`;constructor(){super(...arguments)}get duration(){return 0}},ye=class extends _e{entryType=`measure`},be=class extends _e{entryType=`resource`;serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType=``;name=``;nextHopProtocol=``;redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},xe=class{__unenv__=!0;getEntries(){return[]}getEntriesByName(e,t){return[]}getEntriesByType(e){return[]}},Se=class{__unenv__=!0;timeOrigin=me;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(e,t){throw pe(`Performance.timerify`)}get nodeTiming(){return ge}eventLoopUtilization(){return{}}markResourceTiming(){return new be(``)}onresourcetimingbufferfull=null;now(){return this.timeOrigin===me?he():Date.now()-this.timeOrigin}clearMarks(e){this._entries=e?this._entries.filter(t=>t.name!==e):this._entries.filter(e=>e.entryType!==`mark`)}clearMeasures(e){this._entries=e?this._entries.filter(t=>t.name!==e):this._entries.filter(e=>e.entryType!==`measure`)}clearResourceTimings(){this._entries=this._entries.filter(e=>e.entryType!==`resource`||e.entryType!==`navigation`)}getEntries(){return this._entries}getEntriesByName(e,t){return this._entries.filter(n=>n.name===e&&(!t||n.entryType===t))}getEntriesByType(e){return this._entries.filter(t=>t.entryType===e)}mark(e,t){let n=new ve(e,t);return this._entries.push(n),n}measure(e,t,n){let r,i;typeof t==`string`?(r=this.getEntriesByName(t,`mark`)[0]?.startTime,i=this.getEntriesByName(n,`mark`)[0]?.startTime):(r=Number.parseFloat(t?.start)||this.now(),i=Number.parseFloat(t?.end)||this.now());let a=new ye(e,{startTime:r,detail:{start:r,end:i}});return this._entries.push(a),a}setResourceTimingBufferSize(e){this._resourceTimingBufferSize=e}addEventListener(e,t,n){throw pe(`Performance.addEventListener`)}removeEventListener(e,t,n){throw pe(`Performance.removeEventListener`)}dispatchEvent(e){throw pe(`Performance.dispatchEvent`)}toJSON(){return this}},Ce=class{__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(e){this._callback=e}takeRecords(){return[]}disconnect(){throw pe(`PerformanceObserver.disconnect`)}observe(e){throw pe(`PerformanceObserver.observe`)}bind(e){return e}runInAsyncScope(e,t,...n){return e.call(t,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},we=globalThis.performance&&`addEventListener`in globalThis.performance?globalThis.performance:new Se;if(!(`__unenv__`in we)){let e=Se.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!==`constructor`&&!(t in we)){let n=Object.getOwnPropertyDescriptor(e,t);n&&Object.defineProperty(we,t,n)}}globalThis.performance=we,globalThis.Performance=Se,globalThis.PerformanceEntry=_e,globalThis.PerformanceMark=ve,globalThis.PerformanceMeasure=ye,globalThis.PerformanceObserver=Ce,globalThis.PerformanceObserverEntryList=xe,globalThis.PerformanceResourceTiming=be;var Te=[`__VOID_`,`__PROJECT_`],Ee=[`ISR_CACHE`];function De(e){return e.__VOID_ISR_DEPLOYMENT_ID!=null}var Oe=Symbol.for(`void.envContext.v1`),ke=globalThis;ke[Oe]??=new te;var Ae=ke[Oe],je;typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`&&import(`cloudflare:workers`).then(e=>{je=Me(e.env)??void 0}).catch(()=>{});function Me(e){return typeof e!=`object`||!e||`then`in e&&typeof e.then==`function`?null:e}function Ne(){return Me(globalThis.__env__)}function Pe(){return Ae.getStore()??Ne()??je??(()=>{throw Error(`env: Cloudflare env is unavailable. Use void runtime bindings inside Nuxt/SvelteKit/Analog server request handlers or Worker handlers.`)})()}var Fe=Symbol.for(`void.runtimeRequestScope.v1`),Ie=globalThis;Ie[Fe]??=new te,Ie[Fe];function Le(e,t){return Te.some(t=>e.startsWith(t))?!0:De(t)&&Ee.includes(e)}function Re(e){return new Proxy(e,{get(e,t,n){if(!(typeof t==`string`&&Le(t,e)))return Reflect.get(e,t,n)},has(e,t){return typeof t==`string`&&Le(t,e)?!1:Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e).filter(t=>typeof t!=`string`||!Le(t,e))},getOwnPropertyDescriptor(e,t){if(!(typeof t==`string`&&Le(t,e)))return Reflect.getOwnPropertyDescriptor(e,t)}})}function ze(){return Re(Pe())}var Be=`<redacted>`,Ve=`VOID_ENV_UNMASK`;function He(e,t,n={}){return n.unmask||typeof e!=`string`||e.length===0?t:t.split(e).join(Be)}var Ue=null;function We(){if(Ue!==null)return Ue;try{Ue=globalThis.process?.env?.[Ve]===`1`}catch{Ue=!1}return Ue&&console.error(`[void/env] ${Ve}=1 is set — env validation errors will include raw values. Unset it before sharing logs.`),Ue}var Ge=Symbol.for(`void.env.registry`),Ke=globalThis,qe=Ke[Ge]??={schema:null,hasDefineEnvBeenCalled:!1,bootValidation:null},Je=new WeakMap,Ye=[];function Xe(e){let t=Je.get(e);return t||(t=new Map,Je.set(e,t),Ye.push(t)),t}function Ze(){return Object.fromEntries(Object.entries({BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!0,TSS_DEV_SERVER:`false`,TSS_DEV_SSR_STYLES_BASEPATH:`/`,TSS_DEV_SSR_STYLES_ENABLED:`true`,TSS_DISABLE_CSRF_MIDDLEWARE_WARNING:`false`,TSS_INLINE_CSS_ENABLED:`false`,TSS_ROUTER_BASEPATH:``,TSS_SERVER_FN_BASE:`/_serverFn/`}).filter(([e])=>e.startsWith(`VITE_`)))}var Qe=class extends Error{key;issues;constructor(e,t){super(`Invalid env "${e}": ${t.map(e=>e.message).join(`, `)}`),this.name=`EnvValidationError`,this.key=e,this.issues=t}};function $e(e){let t=Pe();if(Le(e,t))return;let n=ze(),r=Ze(),i=Object.hasOwn(r,e)?r[e]:n[e];if(!qe.schema)return i;let a=qe.schema[e];if(!a)return i;let o=Xe(t);if(o.has(e))return o.get(e);let s=a[`~standard`].validate(i);if(s instanceof Promise)throw Error(`env: Async validator for '${e}' cannot be resolved synchronously. Proxy property access is synchronous, so async Standard Schema validators must be pre-resolved by calling \`_validateEnvOnce(env)\` at worker boot (Void splices this into the generated entry) or by awaiting \`validateAllEnv(env)\` before the first \`env.${e}\` read. Once pre-validated, the resolved value is cached and served synchronously here.`);if(s.issues){let t=We();throw new Qe(e,s.issues.map(e=>({...e,message:He(i,e.message,{unmask:t})})))}return o.set(e,s.value),s.value}new Proxy({},{get(e,t){if(typeof t!=`symbol`)return $e(t)},has(e,t){return typeof t==`symbol`?!1:Object.hasOwn(Ze(),t)||Reflect.has(ze(),t)},ownKeys(){return[...new Set([...Reflect.ownKeys(ze()),...Object.keys(Ze())])]},getOwnPropertyDescriptor(e,t){if(typeof t!=`symbol`)return{enumerable:!0,configurable:!0,value:$e(String(t))}}});var et=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},tt=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},nt=Symbol(),rt=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),it=1e4,at=e=>`headers`in e,ot=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(at(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?st(e,{all:n,dot:r}):{}};async function st(e,t){if(!at(e)&&e.bodyCache.formData)return ct(await e.bodyCache.formData,t);let n=at(e)?e.headers:e.raw.headers,r=rt(await e.arrayBuffer(),n.get(`Content-Type`)||``);at(e)||(e.bodyCache.formData=r);let i=await r;return i?ct(i,t):{}}function ct(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?lt(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(ut(n,e,t,r),delete n[e])}),n}var lt=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},ut=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,34);a.length>33&&dt(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=it&&dt(),i[e]=Object.create(null)),i=i[e])})},dt=()=>{throw Error(`Nesting limit exceeded`)},ft=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&c(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=c(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return m(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return ot(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let r in t)return t[r].then(t=>{r===`json`&&(t=JSON.stringify(t));let i=r===`formData`?void 0:n.headers.get(`content-type`);return new Response(t,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[nt](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},pt={Stringify:1,BeforeStream:2,Stream:3},mt=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},ht=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>ht(e,t,!1,r,i))).then(()=>i[0]));return n?mt(await o,a):o},gt=`text/plain; charset=UTF-8`,_t=(e,t)=>({"Content-Type":e,...t}),vt=(e,t)=>new Response(e,t),yt=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new ft(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=vt(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=vt(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=vt(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return vt(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,_t(gt,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,_t(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,_t(`text/html; charset=UTF-8`,n));return typeof e==`object`?ht(e,pt.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>vt(),this.#c(this))},bt=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],xt=`Can not add a route since the matcher is already built.`,St=class extends Error{},Ct=`__COMPOSED_HANDLER`,wt=e=>e.text(`404 Not Found`,404),Tt=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},Et=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...bt,`all`].forEach(e=>{this[e]=(t,...n)=>{let r=e.toUpperCase();return typeof t==`string`?this.#e=t:this.#r(r,this.#e,t),n.forEach(e=>{this.#r(r,this.#e,e)}),this}}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat()){let e=t.toUpperCase();for(let t of n)this.#r(e,this.#e,t)}}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??l:a}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=wt;errorHandler=Tt;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Tt?r=e.handler:(r=async(n,r)=>(await et([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Ct]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=u(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=u(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,u(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){t=u(this._basePath,t);let i={basePath:r===void 0?this._basePath:u(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new yt(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=et(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${u(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Dt=()=>Object.create(null),Ot=[];function kt(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Ot];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var At=`[^/]+`,jt=`(?:|/.*)`,Mt=Symbol(),Nt=new Set(`.\\+*[^]$()`);function Pt(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Ft=class e{#e;#t;#n=Dt();insert(t,n,r,i,a){let o=this;for(let n=0,a=t.length;n<a;n++){let s=t[n],c=s.length===1?s===`*`?n===a-1?[``,``,`.*`]:[``,``,At]:null:s===`/*`?[``,``,jt]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||`[^/]+`;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))||n.length===1&&Nt.has(n)))throw Mt;if(l=o.#n[n],!l){if(n!==`.*`&&n!==`(?:|/.*)`){for(let e in o.#n)if((n.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw Mt}l=o.#n[n]=new e}t!==``&&(l.#t??=i.varIndex++,r.push([t,l.#t]))}else if(l=o.#n[s],!l){for(let e in o.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw Mt;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw Mt;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Pt).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Nt.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},It=class{#e={varIndex:0};#t=new Ft;#n=0;paths=Dt();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Lt=Dt();function Rt(e){return Lt[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?jt:e===`*`?`.*`:`/:${At}`)}$`)}function zt(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(Rt(n).test(t))return[...e[n]]}var Bt=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Dt()},this.#t={ALL:Dt()},this.#n={ALL:new It}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===Mt?new St(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(xt);if(!r[e]){this.#n[e]=new It;for(let t of[r,i]){t[e]=Dt();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=Rt(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=zt(r[e],t)||zt(r.ALL,t)||[]);for(let o of[r,i])for(let r of a)for(let i in o[r])e.test(i)&&o[r][i].push([n,t]);return}let o=p(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=zt(r[t],e)||zt(r.ALL,e)||[]),i[t][e].push([n,e])}match=kt;buildAllMatchers(){let e=Dt();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Lt=Dt(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Dt(),a=[],[o,s,c]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],o=r.paths[t];o?a[o[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=c[o[1][n][1]],e),Dt())]):i[t]=[n.map(([e])=>[e,Dt()]),Ot]}return[o,s.map(e=>a[e]),i]}},Vt=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(xt);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof St)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},Ht=Dt(),Ut=0,Wt=class e{#e=[];#t=Dt();#n=[];#r;#i=Ht;insert(t,n,r){let i=this,a=s(n),o=new Set,c=0;for(let t of a){let n=a[++c],r=f(t,n)||(n===void 0&&t&&t.indexOf(`*`)===t.length-1?t:null),s=Array.isArray(r),l=s?r[0]:r||t,u=i.#t[l]||=new e;r&&!u.#r&&(u.#r=r,i.#n.push(u)),i=u,s&&o.add(r[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...o],score:++Ut}})}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL;if(s){s.params=Dt(),e.push(s);for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e];s.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=Ht;let r=[this],i=g(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r of p.#n){let f=r.#r,m=p.#i===Ht?{}:{...p.#i};if(typeof f==`string`){(f===`*`||l.startsWith(f.slice(0,-1)))&&(this.#a(n,r,e,p.#i),f===`*`&&(r.#i=m,d.push(r)));continue}let[,h,g]=f;if(l||g!==!0){if(g!==!0){if(!s){s=[];let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let l=t.slice(s[c]),u=g.exec(l);if(u){m[h]=u[0],this.#a(n,r,e,p.#i,m),u[0].length===l.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,p.#i,m);for(let e in r.#t){r.#i=m;let e=u[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,r,e,m,p.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,m,p.#i)):(r.#i=m,d.push(r)))}}}let f=a.shift();r=f?d.concat(f):d}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},Gt=class{name=`TrieRouter`;#e=new Wt;add(e,t,n){for(let r of p(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},Kt=class extends Et{constructor(e={}){super(e),this.router=e.router??new Vt({routers:[new Bt,new Gt]})}},qt=e=>e,Jt={error:{color:31,label:`ERROR`},info:{color:32,label:` INFO`},warn:{color:33,label:` WARN`}};function Yt(e,t={prefix:``}){return Object.entries(e).flatMap(e=>{let n=`${t.prefix}${e[0]}`,r=e[1];return typeof r==`object`&&r&&!Array.isArray(r)?Yt(r,{prefix:`${n}.`}):[[n,r]]})}function Xt(e,t){let{message:n,...r}=e,i=Jt[t.level],a=Yt(r);return[[`\x1b[2m${new Date().toISOString().slice(11,23)}\x1b[0m`,`\x1b[1;${i.color}m${i.label}\x1b[0m`,`\x1b[1m${String(n)}\x1b[0m`,...a.filter(e=>!e[0].endsWith(`stack`)).map(e=>`\x1b[3m${e[0]}\x1b[0m\x1b[2m=\x1b[0m${Zt(e[1])}`)].join(` `),...a.filter(e=>e[0].endsWith(`stack`)).flatMap(e=>String(e[1]).split(`
2
- `)).map(e=>e.replace(/\/node_modules\/\.pnpm\/[^/]+\/node_modules\//,`/node_modules/`).replace(/\((?:\/[^()]*?)?\/((?:node_modules|src)\/[^()]*)\)/,`($1)`)).map(e=>`\x1b[2m ${e}\x1b[0m`)].join(`
3
- `)}function Zt(e){let t=String(e);return/[\s"=]/.test(t)||t===``?JSON.stringify(t):t}function Qt(){return!1}function $t(...e){console.error(sn(on(...e),{level:`error`}))}function en(...e){console.info(sn(on(...e),{level:`info`}))}function tn(e){return e.req.matchedRoutes.find(e=>!e.path.includes(`*`))?.path??`/*`}function nn(...e){console.warn(sn(on(...e),{level:`warn`}))}function rn(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function an(e,t={depth:0}){if(!(e instanceof Error))return{name:`NonError`,type:typeof e};let n=(()=>{let t=cn(e,{key:`shortMessage`});if(typeof t==`string`)return t;let n=cn(e,{key:`query`});return typeof n==`string`&&Array.isArray(Reflect.get(e,`params`))?`Failed query: ${n}`:e.message})(),r=cn(e,{key:`status`});return rn({cause:e.cause!==void 0&&t.depth<3?an(e.cause,{depth:t.depth+1}):void 0,code:cn(e,{key:`code`}),details:e.name===`RpcRequestError`?cn(e,{key:`details`}):void 0,message:n,name:e.name,stack:e.stack?.split(`
4
- `).filter(e=>/^\s+at /.test(e)).map(e=>e.trim()).join(`
5
- `),status:typeof r==`number`?r:void 0})}function on(...e){let[t,n]=e.length===2?e:[void 0,e[0]],{error:r,fields:i,message:a}=n;return rn({...i,error:r===void 0?void 0:an(r),message:a,request:t?rn({id:t.get(`requestId`),method:t.req.method,path:tn(t)}):void 0})}function sn(e,t){return Qt()?Xt(e,t):e}function cn(e,t){let n=Reflect.get(e,t.key);return typeof n==`string`||typeof n==`number`?n:void 0}var ln=!1;async function v(e,t,n,r){let i=e.var.timing,a=performance.now(),o={closed:1/0,...r?{description:r}:{},duration:0,name:n,opened:i.events++,start:a-i.start};i.spans.push(o);try{return await t}finally{o.closed=i.events++,o.duration=performance.now()-a}}var un=qt(async(e,t)=>{let n=!ln;ln=!0;let r={events:0,spans:[],start:performance.now()};e.set(`timing`,r),await t();let i=performance.now()-r.start,a=dn(r.spans);e.res.headers.append(`server-timing`,[`total;dur=${fn(i)}`,...n?[`cold`]:[],...a.map(pn)].join(`, `)),!Qt()&&en({fields:{duration:fn(i),errorCode:e.var.refusal?.error,method:e.req.method,reason:e.var.refusal?.reason,requestId:e.var.requestId,route:tn(e),spans:a.map(e=>`${e.name};dur=${fn(e.duration)};start=${fn(e.start)}`).join(`, `),status:e.res.status},message:`The Worker timed a request.`})});function dn(e){return e.map((e,t)=>({settles:e.opened-t,span:e})).toSorted((e,t)=>e.settles===t.settles?e.span.closed===t.span.closed?e.span.opened-t.span.opened:e.span.closed>t.span.closed?-1:1:e.settles-t.settles).map(e=>e.span)}function fn(e){return Math.round(e*10)/10}function pn(e){let t=`${e.name};dur=${fn(e.duration)}`;return e.description?`${t};desc="${e.description.replace(/["\\]/g,`\\$&`)}"`:t}var mn=i(((e,t)=>{t.exports=ne.default})),hn=i((e=>{e.parse=function(e,n){return new t(e,n).parse()};var t=class e{constructor(e,t){this.source=e,this.transform=t||n,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e===`\\`?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var t;(this.recorded.length>0||e)&&(t=this.recorded.join(``),t===`NULL`&&!e&&(t=null),t!==null&&(t=this.transform(t)),this.entries.push(t),this.recorded=[])}consumeDimensions(){if(this.source[0]===`[`)for(;!this.isEof()&&this.nextCharacter().value!==`=`;);}parse(t){var n,r,i;for(this.consumeDimensions();!this.isEof();)if(n=this.nextCharacter(),n.value===`{`&&!i)this.dimension++,this.dimension>1&&(r=new e(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(n.value===`}`&&!i){if(this.dimension--,!this.dimension&&(this.newEntry(),t))return this.entries}else n.value===`"`&&!n.escaped?(i&&this.newEntry(!0),i=!i):n.value===`,`&&!i?this.newEntry():this.record(n.value);if(this.dimension!==0)throw Error(`array dimension not balanced`);return this.entries}};function n(e){return e}})),gn=i(((e,t)=>{var n=hn();t.exports={create:function(e,t){return{parse:function(){return n.parse(e,t)}}}}})),_n=i(((e,t)=>{var n=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,r=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,i=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,a=/^-?infinity$/;t.exports=function(e){if(a.test(e))return Number(e.replace(`i`,`I`));var t=n.exec(e);if(!t)return o(e)||null;var r=!!t[8],i=parseInt(t[1],10);r&&(i=c(i));var u=parseInt(t[2],10)-1,d=t[3],f=parseInt(t[4],10),p=parseInt(t[5],10),m=parseInt(t[6],10),h=t[7];h=h?1e3*parseFloat(h):0;var g,_=s(e);return _==null?(g=new Date(i,u,d,f,p,m,h),l(i)&&g.setFullYear(i)):(g=new Date(Date.UTC(i,u,d,f,p,m,h)),l(i)&&g.setUTCFullYear(i),_!==0&&g.setTime(g.getTime()-_)),g};function o(e){var t=r.exec(e);if(t){var n=parseInt(t[1],10);t[4]&&(n=c(n));var i=parseInt(t[2],10)-1,a=t[3],o=new Date(n,i,a);return l(n)&&o.setFullYear(n),o}}function s(e){if(e.endsWith(`+00`))return 0;var t=i.exec(e.split(` `)[1]);if(t){var n=t[1];if(n===`Z`)return 0;var r=n===`-`?-1:1;return(parseInt(t[2],10)*3600+parseInt(t[3]||0,10)*60+parseInt(t[4]||0,10))*r*1e3}}function c(e){return-(e-1)}function l(e){return e>=0&&e<100}})),vn=i(((e,t)=>{t.exports=r;var n=Object.prototype.hasOwnProperty;function r(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)n.call(r,i)&&(e[i]=r[i])}return e}})),yn=i(((e,t)=>{var n=vn();t.exports=r;function r(e){if(!(this instanceof r))return new r(e);n(this,g(e))}var i=[`seconds`,`minutes`,`hours`,`days`,`months`,`years`];r.prototype.toPostgres=function(){var e=i.filter(this.hasOwnProperty,this);return this.milliseconds&&e.indexOf(`seconds`)<0&&e.push(`seconds`),e.length===0?`0`:e.map(function(e){var t=this[e]||0;return e===`seconds`&&this.milliseconds&&(t=(t+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,``)),t+` `+e},this).join(` `)};var a={years:`Y`,months:`M`,days:`D`,hours:`H`,minutes:`M`,seconds:`S`},o=[`years`,`months`,`days`],s=[`hours`,`minutes`,`seconds`];r.prototype.toISOString=r.prototype.toISO=function(){var e=o.map(n,this).join(``),t=s.map(n,this).join(``);return`P`+e+`T`+t;function n(e){var t=this[e]||0;return e===`seconds`&&this.milliseconds&&(t=(t+this.milliseconds/1e3).toFixed(6).replace(/0+$/,``)),t+a[e]}};var c=`([+-]?\\d+)`,l=c+`\\s+years?`,u=c+`\\s+mons?`,d=c+`\\s+days?`,f=new RegExp([l,u,d,`([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?`].map(function(e){return`(`+e+`)?`}).join(`\\s*`)),p={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},m=[`hours`,`minutes`,`seconds`,`milliseconds`];function h(e){var t=e+`000000`.slice(e.length);return parseInt(t,10)/1e3}function g(e){if(!e)return{};var t=f.exec(e),n=t[8]===`-`;return Object.keys(p).reduce(function(e,r){var i=t[p[r]];return!i||(i=r===`milliseconds`?h(i):parseInt(i,10),!i)||(n&&~m.indexOf(r)&&(i*=-1),e[r]=i),e},{})}})),bn=i(((e,t)=>{var n=Buffer.from||Buffer;t.exports=function(e){if(/^\\x/.test(e))return n(e.substr(2),`hex`);for(var t=``,r=0;r<e.length;)if(e[r]!==`\\`)t+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))t+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var i=1;r+i<e.length&&e[r+i]===`\\`;)i++;for(var a=0;a<Math.floor(i/2);++a)t+=`\\`;r+=Math.floor(i/2)*2}return n(t,`binary`)}})),xn=i(((e,t)=>{var n=hn(),r=gn(),i=_n(),a=yn(),o=bn();function s(e){return function(t){return t===null?t:e(t)}}function c(e){return e===null?e:e===`TRUE`||e===`t`||e===`true`||e===`y`||e===`yes`||e===`on`||e===`1`}function l(e){return e?n.parse(e,c):null}function u(e){return parseInt(e,10)}function d(e){return e?n.parse(e,s(u)):null}function f(e){return e?n.parse(e,s(function(e){return ne(e).trim()})):null}var p=function(e){return e?r.create(e,function(e){return e!==null&&(e=ie(e)),e}).parse():null},m=function(e){return e?r.create(e,function(e){return e!==null&&(e=parseFloat(e)),e}).parse():null},h=function(e){return e?r.create(e).parse():null},g=function(e){return e?r.create(e,function(e){return e!==null&&(e=i(e)),e}).parse():null},_=function(e){return e?r.create(e,function(e){return e!==null&&(e=a(e)),e}).parse():null},ee=function(e){return e?n.parse(e,s(o)):null},te=function(e){return parseInt(e,10)},ne=function(e){var t=String(e);return/^\d+$/.test(t)?t:e},re=function(e){return e?n.parse(e,s(JSON.parse)):null},ie=function(e){return e[0]===`(`?(e=e.substring(1,e.length-1).split(`,`),{x:parseFloat(e[0]),y:parseFloat(e[1])}):null},ae=function(e){if(e[0]!==`<`&&e[1]!==`(`)return null;for(var t=`(`,n=``,r=!1,i=2;i<e.length-1;i++)r||(t+=e[i]),e[i]===`)`?r=!0:r&&e[i]!==`,`&&(n+=e[i]);var a=ie(t);return a.radius=parseFloat(n),a};t.exports={init:function(e){e(20,ne),e(21,te),e(23,te),e(26,te),e(700,parseFloat),e(701,parseFloat),e(16,c),e(1082,i),e(1114,i),e(1184,i),e(600,ie),e(651,h),e(718,ae),e(1e3,l),e(1001,ee),e(1005,d),e(1007,d),e(1028,d),e(1016,f),e(1017,p),e(1021,m),e(1022,m),e(1231,m),e(1014,h),e(1015,h),e(1008,h),e(1009,h),e(1040,h),e(1041,h),e(1115,g),e(1182,g),e(1185,g),e(1186,a),e(1187,_),e(17,o),e(114,JSON.parse.bind(JSON)),e(3802,JSON.parse.bind(JSON)),e(199,re),e(3807,re),e(3907,h),e(2951,h),e(791,h),e(1183,h),e(1270,h)}}})),Sn=i(((e,t)=>{var n=1e6;function r(e){var t=e.readInt32BE(0),r=e.readUInt32BE(4),i=``;t<0&&(t=~t+(r===0),r=~r+1>>>0,i=`-`);var a=``,o=t%n,s,c,l,u,d;if(t=t/n>>>0,s=4294967296*o+r,r=s/n>>>0,c=``+(s-n*r),r===0&&t===0)return i+c+a;for(l=``,u=6-c.length,d=0;d<u;d++)l+=`0`;if(a=l+c+a,o=t%n,t=t/n>>>0,s=4294967296*o+r,r=s/n>>>0,c=``+(s-n*r),r===0&&t===0)return i+c+a;for(l=``,u=6-c.length,d=0;d<u;d++)l+=`0`;if(a=l+c+a,o=t%n,t=t/n>>>0,s=4294967296*o+r,r=s/n>>>0,c=``+(s-n*r),r===0&&t===0)return i+c+a;for(l=``,u=6-c.length,d=0;d<u;d++)l+=`0`;return a=l+c+a,o=t%n,s=4294967296*o+r,c=``+s%n,i+c+a}t.exports=r})),Cn=i(((e,t)=>{var n=Sn(),r=function(e,t,n,r,i){n||=0,r||=!1,i||=function(e,t,n){return e*2**n+t};var a=n>>3,o=function(e){return r?~e&255:e},s=255,c=8-n%8;t<c&&(s=255<<8-t&255,c=t),n&&(s>>=n%8);var l=0;n%8+t>=8&&(l=i(0,o(e[a])&s,c));for(var u=t+n>>3,d=a+1;d<u;d++)l=i(l,o(e[d]),8);var f=(t+n)%8;return f>0&&(l=i(l,o(e[u])>>8-f,f)),l},i=function(e,t,n){var i=2**(n-1)-1,a=r(e,1),o=r(e,n,1);if(o===0)return 0;var s=1,c=r(e,t,n+1,!1,function(e,t,n){e===0&&(e=1);for(var r=1;r<=n;r++)s/=2,(t&1<<n-r)>0&&(e+=s);return e});return o==2**(n+1)-1?c===0?a===0?1/0:-1/0:NaN:(a===0?1:-1)*2**(o-i)*c},a=function(e){return r(e,1)==1?-1*(r(e,15,1,!0)+1):r(e,15,1)},o=function(e){return r(e,1)==1?-1*(r(e,31,1,!0)+1):r(e,31,1)},s=function(e){return i(e,23,8)},c=function(e){return i(e,52,11)},l=function(e){var t=r(e,16,32);if(t==49152)return NaN;for(var n=1e4**r(e,16,16),i=0,a=r(e,16),o=0;o<a;o++)i+=r(e,16,64+16*o)*n,n/=1e4;var s=10**r(e,16,48);return(t===0?1:-1)*Math.round(i*s)/s},u=function(e,t){var n=r(t,1),i=r(t,63,1),a=new Date((n===0?1:-1)*i/1e3+9466848e5);return e||a.setTime(a.getTime()+a.getTimezoneOffset()*6e4),a.usec=i%1e3,a.getMicroSeconds=function(){return this.usec},a.setMicroSeconds=function(e){this.usec=e},a.getUTCMicroSeconds=function(){return this.usec},a},d=function(e){var t=r(e,32);r(e,32,32);for(var n=r(e,32,64),i=96,a=[],o=0;o<t;o++)a[o]=r(e,32,i),i+=32,i+=32;var s=function(t){var n=r(e,32,i);if(i+=32,n==4294967295)return null;var a;if(t==23||t==20)return a=r(e,n*8,i),i+=n*8,a;if(t==25)return a=e.toString(this.encoding,i>>3,(i+=n<<3)>>3),a;console.log(`ERROR: ElementType not implemented: `+t)},c=function(e,t){var n=[],r;if(e.length>1){var i=e.shift();for(r=0;r<i;r++)n[r]=c(e,t);e.unshift(i)}else for(r=0;r<e[0];r++)n[r]=s(t);return n};return c(a,n)},f=function(e){return e.toString(`utf8`)},p=function(e){return e===null?null:r(e,8)>0};t.exports={init:function(e){e(20,n),e(21,a),e(23,o),e(26,o),e(1700,l),e(700,s),e(701,c),e(16,p),e(1114,u.bind(null,!1)),e(1184,u.bind(null,!0)),e(1e3,d),e(1007,d),e(1016,d),e(1008,d),e(1009,d),e(25,f)}}})),wn=i(((e,t)=>{t.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}})),Tn=i((e=>{var t=xn(),n=Cn(),r=gn(),i=wn();e.getTypeParser=s,e.setTypeParser=c,e.arrayParser=r,e.builtins=i;var a={text:{},binary:{}};function o(e){return String(e)}function s(e,t){return t||=`text`,a[t]&&a[t][e]||o}function c(e,t,n){typeof t==`function`&&(n=t,t=`text`),a[t][e]=n}t.init(function(e,t){a.text[e]=t}),n.init(function(e,t){a.binary[e]=t})})),En=i(((e,t)=>{var n;try{n=process.platform===`win32`?process.env.USERNAME:process.env.USER}catch{}t.exports={host:`localhost`,user:n,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:``,ssl:!1,sslnegotiation:void 0,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var r=Tn(),i=r.getTypeParser(20,`text`),a=r.getTypeParser(1016,`text`);t.exports.__defineSetter__(`parseInt8`,function(e){r.setTypeParser(20,`text`,e?r.getTypeParser(23,`text`):i),r.setTypeParser(1016,`text`,e?r.getTypeParser(1007,`text`):a)})})),Dn=i(((e,t)=>{t.exports=re.default})),On=i(((e,t)=>{t.exports=ie.default})),kn=i(((e,t)=>{var n=En(),r=Dn(),{isDate:i}=On(),a=r.deprecate(()=>{},`Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.`,`PG_INVALID_DATE`);function o(e){return`"`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)+`"`}function s(e){let t=`{`;for(let n=0;n<e.length;n++){n>0&&(t+=`,`);let r=e[n];r==null?t+=`NULL`:Array.isArray(r)?t+=s(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),t+=`\\\\x`+r.toString(`hex`)):t+=o(c(r))}return t+=`}`,t}var c=function(e,t){return e==null?null:typeof e==`object`?e instanceof Buffer?e:ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):i(e)?(isNaN(e.getTime())&&a(),n.parseInputDatesAsUTC?d(e):u(e)):Array.isArray(e)?s(e):l(e,t):e.toString()};function l(e,t){if(e&&typeof e.toPostgres==`function`){if(t||=[],t.indexOf(e)!==-1)throw Error(`circular reference detected while preparing "`+e+`" for query`);return t.push(e),c(e.toPostgres(c),t)}return JSON.stringify(e)}function u(e){let t=-e.getTimezoneOffset(),n=e.getFullYear(),r=n<1;r&&(n=Math.abs(n)+1);let i=String(n).padStart(4,`0`)+`-`+String(e.getMonth()+1).padStart(2,`0`)+`-`+String(e.getDate()).padStart(2,`0`)+`T`+String(e.getHours()).padStart(2,`0`)+`:`+String(e.getMinutes()).padStart(2,`0`)+`:`+String(e.getSeconds()).padStart(2,`0`)+`.`+String(e.getMilliseconds()).padStart(3,`0`);return t<0?(i+=`-`,t*=-1):i+=`+`,i+=String(Math.floor(t/60)).padStart(2,`0`)+`:`+String(t%60).padStart(2,`0`),r&&(i+=` BC`),i}function d(e){let t=e.getUTCFullYear(),n=t<1;n&&(t=Math.abs(t)+1);let r=String(t).padStart(4,`0`)+`-`+String(e.getUTCMonth()+1).padStart(2,`0`)+`-`+String(e.getUTCDate()).padStart(2,`0`)+`T`+String(e.getUTCHours()).padStart(2,`0`)+`:`+String(e.getUTCMinutes()).padStart(2,`0`)+`:`+String(e.getUTCSeconds()).padStart(2,`0`)+`.`+String(e.getUTCMilliseconds()).padStart(3,`0`);return r+=`+00:00`,n&&(r+=` BC`),r}function f(e,t,n){return e=typeof e==`string`?{text:e}:p(e),t&&(typeof t==`function`?e.callback=t:e.values=t),n&&(e.callback=n),e}function p(e){return e==null?e:Object.defineProperties(Object.create(Object.getPrototypeOf(e)),Object.getOwnPropertyDescriptors(e))}t.exports={prepareValue:function(e){return c(e)},normalizeQueryConfig:f,escapeIdentifier:function(e){return`"`+e.replace(/"/g,`""`)+`"`},escapeLiteral:function(e){let t=!1,n=`'`;if(e==null||typeof e!=`string`)return`''`;for(let r=0;r<e.length;r++){let i=e[r];i===`'`?n+=i+i:i===`\\`?(n+=i+i,t=!0):n+=i}return n+=`'`,t===!0&&(n=` E`+n),n}}})),An=i(((e,t)=>{t.exports=ae.default})),jn=i(((e,t)=>{var n=An();t.exports={postgresMd5PasswordHash:c,randomBytes:o,deriveKey:f,sha256:l,hashByName:u,hmacSha256:d,md5:s};var r=n.webcrypto||globalThis.crypto,i=r.subtle,a=new TextEncoder;function o(e){return r.getRandomValues(Buffer.alloc(e))}async function s(e){try{return n.createHash(`md5`).update(e,`utf-8`).digest(`hex`)}catch{let t=typeof e==`string`?a.encode(e):e,n=await i.digest(`MD5`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}}async function c(e,t,n){let r=await s(t+e);return`md5`+await s(Buffer.concat([Buffer.from(r),n]))}async function l(e){return await i.digest(`SHA-256`,e)}async function u(e,t){return await i.digest(e,t)}async function d(e,t){let n=await i.importKey(`raw`,e,{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return await i.sign(`HMAC`,n,a.encode(t))}async function f(e,t,n){let r=await i.importKey(`raw`,a.encode(e),`PBKDF2`,!1,[`deriveBits`]),o={name:`PBKDF2`,hash:`SHA-256`,salt:t,iterations:n};return await i.deriveBits(o,r,256,[`deriveBits`])}})),Mn=i(((e,t)=>{function n(e,t){return Error(`SASL channel binding: `+e+` when parsing public certificate `+t.toString(`base64`))}function r(e,t){let r=e[t++];if(r<128)return{length:r,index:t};let i=r&127;if(i>4)throw n(`bad length`,e);r=0;for(let n=0;n<i;n++)r=r<<8|e[t++];return{length:r,index:t}}function i(e,t){if(e[t++]!==6)throw n(`non-OID data`,e);let{length:i,index:a}=r(e,t);t=a;let o=t+i,s=e[t++],c=(s/40|0)+`.`+s%40;for(;t<o;){let n=0;for(;t<o;){let r=e[t++];if(n=n<<7|r&127,r<128)break}c+=`.`+n}return{oid:c,index:t}}function a(e,t){if(e[t++]!==48)throw n(`non-sequence data`,e);return r(e,t)}function o(e,t){t===void 0&&(t=0),t=a(e,t).index;let{length:o,index:s}=a(e,t);t=s+o,t=a(e,t).index;let{oid:c,index:l}=i(e,t);switch(c){case`1.2.840.113549.1.1.4`:return`MD5`;case`1.2.840.113549.1.1.5`:return`SHA-1`;case`1.2.840.113549.1.1.11`:return`SHA-256`;case`1.2.840.113549.1.1.12`:return`SHA-384`;case`1.2.840.113549.1.1.13`:return`SHA-512`;case`1.2.840.113549.1.1.14`:return`SHA-224`;case`1.2.840.113549.1.1.15`:return`SHA512-224`;case`1.2.840.113549.1.1.16`:return`SHA512-256`;case`1.2.840.10045.4.1`:return`SHA-1`;case`1.2.840.10045.4.3.1`:return`SHA-224`;case`1.2.840.10045.4.3.2`:return`SHA-256`;case`1.2.840.10045.4.3.3`:return`SHA-384`;case`1.2.840.10045.4.3.4`:return`SHA-512`;case`1.2.840.113549.1.1.10`:{if(t=l,t=a(e,t).index,e[t++]!==160)throw n(`non-tag data`,e);t=r(e,t).index,t=a(e,t).index;let{oid:o}=i(e,t);switch(o){case`1.2.840.113549.2.5`:return`MD5`;case`1.3.14.3.2.26`:return`SHA-1`;case`2.16.840.1.101.3.4.2.1`:return`SHA-256`;case`2.16.840.1.101.3.4.2.2`:return`SHA-384`;case`2.16.840.1.101.3.4.2.3`:return`SHA-512`}throw n(`unknown hash OID `+o,e)}case`1.3.101.110`:case`1.3.101.112`:return`SHA-512`;case`1.3.101.111`:case`1.3.101.113`:throw n(`Ed448 certificate channel binding is not currently supported by Postgres`)}throw n(`unknown OID `+c,e)}t.exports={signatureAlgorithmHashFromCertificate:o}})),Nn=i(((e,t)=>{var n=jn(),{signatureAlgorithmHashFromCertificate:r}=Mn();function i(e){return e.replace(/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g,` `).replace(/[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g,``).normalize(`NFKC`)}var a=1e5;function o(e,t,r=a){let i=[`SCRAM-SHA-256`];t&&i.unshift(`SCRAM-SHA-256-PLUS`);let o=i.find(t=>e.includes(t));if(!o)throw Error(`SASL: Only mechanism(s) `+i.join(` and `)+` are supported`);if(o===`SCRAM-SHA-256-PLUS`&&typeof t.getPeerCertificate!=`function`)throw Error(`SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate`);let s=n.randomBytes(18).toString(`base64`);return{mechanism:o,clientNonce:s,response:(o===`SCRAM-SHA-256-PLUS`?`p=tls-server-end-point`:t?`y`:`n`)+`,,n=*,r=`+s,message:`SASLInitialResponse`,scramMaxIterations:r}}async function s(e,t,o,s){if(e.message!==`SASLInitialResponse`)throw Error(`SASL: Last message was not SASLInitialResponse`);if(typeof t!=`string`)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string`);if(t===``)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string`);if(typeof o!=`string`)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string`);let c=f(o);if(!c.nonce.startsWith(e.clientNonce))throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce`);if(c.nonce.length===e.clientNonce.length)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short`);let l=typeof e.scramMaxIterations==`number`?e.scramMaxIterations:a;if(l!==0&&c.iteration>l)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count `+c.iteration+` exceeds scramMaxIterations of `+l);let u=`n=*,r=`+e.clientNonce,d=`r=`+c.nonce+`,s=`+c.salt+`,i=`+c.iteration,p=s?`eSws`:`biws`;if(e.mechanism===`SCRAM-SHA-256-PLUS`){let e=s.getPeerCertificate().raw,t=r(e);(t===`MD5`||t===`SHA-1`)&&(t=`SHA-256`);let i=await n.hashByName(t,e);p=Buffer.concat([Buffer.from(`p=tls-server-end-point,,`),Buffer.from(i)]).toString(`base64`)}let h=`c=`+p+`,r=`+c.nonce,g=u+`,`+d+`,`+h,_=Buffer.from(c.salt,`base64`),ee=await n.deriveKey(i(t),_,c.iteration),te=await n.hmacSha256(ee,`Client Key`),ne=await n.sha256(te),re=await n.hmacSha256(ne,g),ie=m(Buffer.from(te),Buffer.from(re)).toString(`base64`),ae=await n.hmacSha256(ee,`Server Key`),oe=await n.hmacSha256(ae,g);e.message=`SASLResponse`,e.serverSignature=Buffer.from(oe).toString(`base64`),e.response=h+`,p=`+ie}function c(e,t){if(e.message!==`SASLResponse`)throw Error(`SASL: Last message was not SASLResponse`);if(typeof t!=`string`)throw Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string`);let{serverSignature:n}=p(t);if(n!==e.serverSignature)throw Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match`)}function l(e){if(typeof e!=`string`)throw TypeError(`SASL: text must be a string`);return e.split(``).map((t,n)=>e.charCodeAt(n)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function u(e){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(e)}function d(e){if(typeof e!=`string`)throw TypeError(`SASL: attribute pairs text must be a string`);return new Map(e.split(`,`).map(e=>{if(!/^.=/.test(e))throw Error(`SASL: Invalid attribute pair entry`);return[e[0],e.substring(2)]}))}function f(e){let t=d(e),n=t.get(`r`);if(!n)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing`);if(!l(n))throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters`);let r=t.get(`s`);if(!r)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing`);if(!u(r))throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64`);let i=t.get(`i`);if(!i)throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing`);if(!/^[1-9][0-9]*$/.test(i))throw Error(`SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count`);return{nonce:n,salt:r,iteration:parseInt(i,10)}}function p(e){let t=d(e),n=t.get(`e`),r=t.get(`v`);if(n)throw Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${n}"`);if(!r)throw Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing`);if(!u(r))throw Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64`);return{serverSignature:r}}function m(e,t){if(!Buffer.isBuffer(e))throw TypeError(`first argument must be a Buffer`);if(!Buffer.isBuffer(t))throw TypeError(`second argument must be a Buffer`);if(e.length!==t.length)throw Error(`Buffer lengths must match`);if(e.length===0)throw Error(`Buffers cannot be empty`);return Buffer.from(e.map((n,r)=>e[r]^t[r]))}t.exports={startSession:o,continueSession:s,finalizeSession:c,DEFAULT_MAX_SCRAM_ITERATIONS:a}})),Pn=i(((e,t)=>{var n=Tn();function r(e){this._types=e||n,this.text={},this.binary={}}r.prototype.getOverrides=function(e){switch(e){case`text`:return this.text;case`binary`:return this.binary;default:return{}}},r.prototype.setTypeParser=function(e,t,n){typeof t==`function`&&(n=t,t=`text`),this.getOverrides(t)[e]=n},r.prototype.getTypeParser=function(e,t){return t||=`text`,this.getOverrides(t)[e]||this._types.getTypeParser(e,t)},t.exports=r})),Fn=i(((e,t)=>{t.exports=oe.default})),In=i(((e,t)=>{t.exports=se.default})),Ln=i(((e,t)=>{function n(e,t={}){if(e.charAt(0)===`/`){let t=e.split(` `);return{host:t[0],database:t[1]}}let n=Object.create(null),r,i=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(e)&&(e=encodeURI(e).replace(/%25(\d\d)/g,`%$1`));try{try{r=new URL(e,`postgres://base`)}catch{r=new URL(e.replace(`@/`,`@___DUMMY___/`),`postgres://base`),i=!0}}catch(e){throw e.input&&=`*****REDACTED*****`,e}for(let e of r.searchParams.entries())n[e[0]]=e[1];if(n.user=n.user||decodeURIComponent(r.username),n.password=n.password||decodeURIComponent(r.password),r.protocol==`socket:`)return n.host=decodeURI(r.pathname),n.database=r.searchParams.get(`db`),n.client_encoding=r.searchParams.get(`encoding`),n;let a=(i?``:r.hostname).replace(/^\[(.+)\]$/,`$1`);n.host?a&&/^%2f/i.test(a)&&(r.pathname=a+r.pathname):n.host=decodeURIComponent(a),n.port||=r.port;let s=r.pathname.slice(1)||null;n.database=s?decodeURI(s):null,(n.ssl===`true`||n.ssl===`1`)&&(n.ssl=!0),n.ssl===`0`&&(n.ssl=!1),(n.sslcert||n.sslkey||n.sslrootcert||n.sslmode)&&(n.ssl={}),n.sslnegotiation===`direct`&&n.ssl===void 0&&(n.ssl=!0);let c=n.sslcert||n.sslkey||n.sslrootcert?In():null;if(n.sslcert&&(n.ssl.cert=c.readFileSync(n.sslcert).toString()),n.sslkey&&(n.ssl.key=c.readFileSync(n.sslkey).toString()),n.sslrootcert&&(n.ssl.ca=c.readFileSync(n.sslrootcert).toString()),t.useLibpqCompat&&n.uselibpqcompat)throw Error(`Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.`);if(n.uselibpqcompat===`true`||t.useLibpqCompat)switch(n.sslmode){case`disable`:n.ssl=!1;break;case`prefer`:n.ssl.rejectUnauthorized=!1;break;case`require`:n.sslrootcert?n.ssl.checkServerIdentity=function(){}:n.ssl.rejectUnauthorized=!1;break;case`verify-ca`:if(!n.ssl.ca)throw Error(`SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.`);n.ssl.checkServerIdentity=function(){}}else switch(n.sslmode){case`disable`:n.ssl=!1;break;case`prefer`:case`require`:case`verify-ca`:case`verify-full`:n.sslmode!==`verify-full`&&o(n.sslmode);break;case`no-verify`:n.ssl.rejectUnauthorized=!1}return n}function r(e){return Object.entries(e).reduce((e,[t,n])=>(n!=null&&(e[t]=n),e),Object.create(null))}function i(e){return Object.entries(e).reduce((e,[t,n])=>{if(t===`ssl`){let i=n;typeof i==`boolean`&&(e[t]=i),typeof i==`object`&&(e[t]=r(i))}else if(n!=null){if(t===`port`){if(n!==``){let r=parseInt(n,10);if(isNaN(r))throw Error(`Invalid ${t}: ${n}`);e[t]=r}}else e[t]=n}return e},Object.create(null))}function a(e){return i(n(e))}function o(e){!o.warned&&typeof process<`u`&&process.emitWarning&&(o.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
6
- In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
7
-
8
- To prepare for this change:
9
- - If you want the current behavior, explicitly use 'sslmode=verify-full'
10
- - If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${e}'
11
-
12
- See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}t.exports=n,n.parse=n,n.toClientConfig=i,n.parseIntoClientConfig=a})),Rn=i(((e,t)=>{var n=Fn(),r=En(),i=Ln().parse,a=function(e,t,n){return t[e]?t[e]:(n===void 0?n=process.env[`PG`+e.toUpperCase()]:n===!1||(n=process.env[n]),n||r[e])},o=function(){switch(process.env.PGSSLMODE){case`disable`:return!1;case`prefer`:case`require`:case`verify-ca`:case`verify-full`:return!0;case`no-verify`:return{rejectUnauthorized:!1}}return r.ssl},s=function(e){return`'`+(``+e).replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)+`'`},c=function(e,t,n){let r=t[n];r!=null&&e.push(n+`=`+s(r))};t.exports=class{constructor(e){if(e=typeof e==`string`?i(e):e||{},e.connectionString&&(e=Object.assign({},e,i(e.connectionString))),this.user=a(`user`,e),this.database=a(`database`,e),this.database===void 0&&(this.database=this.user),this.port=parseInt(a(`port`,e),10),this.host=a(`host`,e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:a(`password`,e)}),this.binary=a(`binary`,e),this.options=a(`options`,e),this.ssl=e.ssl===void 0?o():e.ssl,typeof this.ssl==`string`&&this.ssl===`true`&&(this.ssl=!0),this.ssl===`no-verify`&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.sslnegotiation=a(`sslnegotiation`,e,`PGSSLNEGOTIATION`),this.sslnegotiation!==void 0&&this.sslnegotiation!==`postgres`&&this.sslnegotiation!==`direct`)throw Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation===`direct`&&!this.ssl)throw Error(`sslnegotiation=direct requires SSL to be enabled`);this.client_encoding=a(`client_encoding`,e),this.replication=a(`replication`,e),this.isDomainSocket=!(this.host||``).indexOf(`/`),this.application_name=a(`application_name`,e,`PGAPPNAME`),this.fallback_application_name=a(`fallback_application_name`,e,!1),this.statement_timeout=a(`statement_timeout`,e,!1),this.lock_timeout=a(`lock_timeout`,e,!1),this.idle_in_transaction_session_timeout=a(`idle_in_transaction_session_timeout`,e,!1),this.query_timeout=a(`query_timeout`,e,!1),this.connect_timeout=e.connectionTimeoutMillis===void 0?process.env.PGCONNECT_TIMEOUT||0:Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis==`number`&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let t=[];c(t,this,`user`),c(t,this,`password`),c(t,this,`port`),c(t,this,`application_name`),c(t,this,`fallback_application_name`),c(t,this,`connect_timeout`),c(t,this,`options`);let r=typeof this.ssl==`object`?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(c(t,r,`sslmode`),c(t,r,`sslca`),c(t,r,`sslkey`),c(t,r,`sslcert`),c(t,r,`sslrootcert`),c(t,this,`sslnegotiation`),this.database&&t.push(`dbname=`+s(this.database)),this.replication&&t.push(`replication=`+s(this.replication)),this.host&&t.push(`host=`+s(this.host)),this.isDomainSocket)return e(null,t.join(` `));this.client_encoding&&t.push(`client_encoding=`+s(this.client_encoding)),n.lookup(this.host,function(n,r){return n?e(n,null):(t.push(`hostaddr=`+s(r)),e(null,t.join(` `)))})}}})),zn=i(((e,t)=>{var n=Tn(),r=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;t.exports=class{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,this.rowAsArray=e===`array`,this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let t;t=e.text?r.exec(e.text):r.exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++){let r=e[n];r===null?t[n]=null:t[n]=this._parsers[n](r)}return t}parseRow(e){let t={...this._prebuiltEmptyResultObject};for(let n=0,r=e.length;n<r;n++){let r=e[n],i=this.fields[n].name;if(r!==null){let e=this.fields[n].format===`binary`?Buffer.from(r):r;t[i]=this._parsers[n](e)}else t[i]=null}return t}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=Array(e.length));let t=Object.create(null);for(let r=0;r<e.length;r++){let i=e[r];t[i.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(i.dataTypeID,i.format||`text`):this._parsers[r]=n.getTypeParser(i.dataTypeID,i.format||`text`)}this._prebuiltEmptyResultObject={...t}}}})),Bn=i(((e,t)=>{var{EventEmitter:n}=mn(),r=zn(),i=kn();t.exports=class extends n{constructor(e,t,n){super(),e=i.normalizeQueryConfig(e,t,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||``,this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new r(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode===`extended`||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new r(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners(`row`).length}handleDataRow(e){let t;if(!this._canceledDueToError){try{t=this._result.parseRow(e.fields)}catch(e){this._canceledDueToError=e;return}this.emit(`row`,t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,t){if(this._canceledDueToError&&=(e=this._canceledDueToError,!1),this.callback)return this.callback(e);this.emit(`error`,e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(e){process.nextTick(()=>{throw e})}this.emit(`end`,this._results)}submit(e){if(typeof this.text!=`string`&&typeof this.name!=`string`)return Error(`A query must have either text or a name. Supplying neither is unsupported.`);let t=e.parsedStatements[this.name]||e.submittedNamedStatements[this.name];if(this.text&&t&&this.text!==t)return Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return Error(`Query values must be an array`);if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&(e.parsedStatements[this.name]!==void 0||e.submittedNamedStatements[this.name]!==void 0)}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,t){e.execute({portal:this.portal,rows:t}),t?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||(e.parse({text:this.text,name:this.name,types:this.types}),this.name&&(e.submittedNamedStatements[this.name]=this.text));try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:i.prepareValue})}catch(t){e.close({type:`S`,name:this.name}),e.sync(),this.handleError(t,e);return}e.describe({type:`P`,name:this.portal||``}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail(`No source stream defined`)}handleCopyData(e,t){}}})),Vn=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoticeMessage=e.DataRowMessage=e.CommandCompleteMessage=e.ReadyForQueryMessage=e.NotificationResponseMessage=e.BackendKeyDataMessage=e.AuthenticationMD5Password=e.ParameterStatusMessage=e.ParameterDescriptionMessage=e.RowDescriptionMessage=e.Field=e.CopyResponse=e.CopyDataMessage=e.DatabaseError=e.copyDone=e.emptyQuery=e.replicationStart=e.portalSuspended=e.noData=e.closeComplete=e.bindComplete=e.parseComplete=void 0,e.parseComplete={name:`parseComplete`,length:5},e.bindComplete={name:`bindComplete`,length:5},e.closeComplete={name:`closeComplete`,length:5},e.noData={name:`noData`,length:5},e.portalSuspended={name:`portalSuspended`,length:5},e.replicationStart={name:`replicationStart`,length:4},e.emptyQuery={name:`emptyQuery`,length:4},e.copyDone={name:`copyDone`,length:4},e.DatabaseError=class extends Error{constructor(e,t,n){super(e),this.length=t,this.name=n}},e.CopyDataMessage=class{constructor(e,t){this.length=e,this.chunk=t,this.name=`copyData`}},e.CopyResponse=class{constructor(e,t,n,r){this.length=e,this.name=t,this.binary=n,this.columnTypes=Array(r)}},e.Field=class{constructor(e,t,n,r,i,a,o){this.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=r,this.dataTypeSize=i,this.dataTypeModifier=a,this.format=o}},e.RowDescriptionMessage=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name=`rowDescription`,this.fields=Array(this.fieldCount)}},e.ParameterDescriptionMessage=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name=`parameterDescription`,this.dataTypeIDs=Array(this.parameterCount)}},e.ParameterStatusMessage=class{constructor(e,t,n){this.length=e,this.parameterName=t,this.parameterValue=n,this.name=`parameterStatus`}},e.AuthenticationMD5Password=class{constructor(e,t){this.length=e,this.salt=t,this.name=`authenticationMD5Password`}},e.BackendKeyDataMessage=class{constructor(e,t,n){this.length=e,this.processID=t,this.secretKey=n,this.name=`backendKeyData`}},e.NotificationResponseMessage=class{constructor(e,t,n,r){this.length=e,this.processId=t,this.channel=n,this.payload=r,this.name=`notification`}},e.ReadyForQueryMessage=class{constructor(e,t){this.length=e,this.status=t,this.name=`readyForQuery`}},e.CommandCompleteMessage=class{constructor(e,t){this.length=e,this.text=t,this.name=`commandComplete`}},e.DataRowMessage=class{constructor(e,t){this.length=e,this.fields=t,this.name=`dataRow`,this.fieldCount=t.length}},e.NoticeMessage=class{constructor(e,t){this.length=e,this.message=t,this.name=`notice`}}})),Hn=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Writer=void 0,e.Writer=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let t=this.buffer,n=t.length+(t.length>>1)+e;this.buffer=Buffer.allocUnsafe(n),t.copy(this.buffer,0,0,this.offset)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{let t=Buffer.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,`utf-8`),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=``){let t=Buffer.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}addInt32PrefixedString(e){let t=Buffer.byteLength(e);this.ensure(4+t);let n=this.buffer,r=this.offset;return n[r++]=t>>>24&255,n[r++]=t>>>16&255,n[r++]=t>>>8&255,n[r++]=t>>>0&255,n.write(e,r,`utf-8`),this.offset=r+t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}reserveUnsafe(e){let t=this.offset;return this.ensure(e),this.offset+=e,t}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),t}clear(){this.offset=5,this.headerPosition=0}}})),Un=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.serialize=void 0;var t=Hn(),n=new t.Writer,r=e=>{n.addInt16(3).addInt16(0);for(let t of Object.keys(e))n.addCString(t).addCString(e[t]);n.addCString(`client_encoding`).addCString(`UTF8`);let r=n.addCString(``).flush(),i=r.length+4;return new t.Writer().addInt32(i).add(r).flush()},i=()=>{let e=Buffer.allocUnsafe(8);return e.writeInt32BE(8,0),e.writeInt32BE(80877103,4),e},a=e=>n.addCString(e).flush(112),o=function(e,t){return n.addCString(e).addInt32PrefixedString(t),n.flush(112)},s=function(e){return n.addString(e).flush(112)},c=e=>n.addCString(e).flush(81),l=[],u=e=>{let t=e.name||``;t.length>63&&(console.error(`Warning! Postgres only supports 63 characters for query names.`),console.error(`You supplied %s (%s)`,t,t.length),console.error(`This can cause conflicts and silent errors executing queries`));let r=e.types||l,i=r.length,a=n.addCString(t).addCString(e.text).addInt16(i);for(let e=0;e<i;e++)a.addInt32(r[e]);return n.flush(80)},d=function(e,t,r){let i=e.length;for(let a=0;a<i;a++){let i=t?t(e[a],a):e[a],o=0;i==null?n.addInt32(-1):i instanceof Buffer?(o=1,n.addInt32(i.length),n.add(i)):n.addInt32PrefixedString(i);let s=n.buffer;s[r++]=0,s[r++]=o}},f=(e={})=>{let t=e.portal||``,r=e.statement||``,i=e.binary||!1,a=e.values||l,o=a.length;n.addCString(t).addCString(r),n.addInt16(o);let s=n.reserveUnsafe(o*2);n.addInt16(o);try{d(a,e.valueMapper,s)}catch(e){throw n.clear(),e}return n.addInt16(1),n.addInt16(+!!i),n.flush(66)},p=Buffer.from([69,0,0,0,9,0,0,0,0,0]),m=e=>{if(!e||!e.portal&&!e.rows)return p;let t=e.portal||``,n=e.rows||0,r=Buffer.byteLength(t),i=4+r+1+4,a=Buffer.allocUnsafe(1+i);return a[0]=69,a.writeInt32BE(i,1),a.write(t,5,`utf-8`),a[r+5]=0,a.writeUInt32BE(n,a.length-4),a},h=(e,t)=>{let n=Buffer.allocUnsafe(16);return n.writeInt32BE(16,0),n.writeInt16BE(1234,4),n.writeInt16BE(5678,6),n.writeInt32BE(e,8),n.writeInt32BE(t,12),n},g=(e,t)=>{let n=4+Buffer.byteLength(t)+1,r=Buffer.allocUnsafe(1+n);return r[0]=e,r.writeInt32BE(n,1),r.write(t,5,`utf-8`),r[n]=0,r},_=n.addCString(`P`).flush(68),ee=n.addCString(`S`).flush(68),te=e=>e.name?g(68,`${e.type}${e.name||``}`):e.type===`P`?_:ee,ne=e=>g(67,`${e.type}${e.name||``}`),re=e=>n.add(e).flush(100),ie=e=>g(102,e),ae=e=>Buffer.from([e,0,0,0,4]),oe=ae(72),se=ae(83),ce=ae(88),le=ae(99);e.serialize={startup:r,password:a,requestSsl:i,sendSASLInitialResponseMessage:o,sendSCRAMClientFinalMessage:s,query:c,parse:u,bind:f,execute:m,describe:te,close:ne,flush:()=>oe,sync:()=>se,end:()=>ce,copyData:re,copyDone:()=>le,copyFail:ie,cancel:h}})),Wn=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferReader=void 0,e.BufferReader=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding=`utf-8`}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++];);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}}})),Gn=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Parser=void 0;var t=Vn(),n=Wn(),r=1,i=5,a=-1,o=Buffer.allocUnsafe(0);e.Parser=class{constructor(e){if(this.buffer=o,this.bufferLength=0,this.bufferOffset=0,this.reader=new n.BufferReader,e?.mode===`binary`)throw Error(`Binary mode not supported yet`);this.mode=e?.mode||`text`}parse(e,t){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,a=this.bufferOffset;for(;a+i<=n;){let e=this.buffer[a],o=this.buffer.readUInt32BE(a+r),s=r+o;if(s+a<=n)t(this.handlePacket(a+i,e,o,this.buffer)),a+=s;else break}a===n?(this.buffer=o,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-a,this.bufferOffset=a)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let e;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)e=this.buffer;else{let n=this.buffer.byteLength*2;for(;t>=n;)n*=2;e=Buffer.allocUnsafe(n)}this.buffer.copy(e,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=e,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,n,r,i){let{reader:a}=this;a.setBuffer(e,i);let f;switch(n){case 50:f=t.bindComplete;break;case 49:f=t.parseComplete;break;case 51:f=t.closeComplete;break;case 110:f=t.noData;break;case 115:f=t.portalSuspended;break;case 99:f=t.copyDone;break;case 87:f=t.replicationStart;break;case 73:f=t.emptyQuery;break;case 68:f=_(a);break;case 67:f=c(a);break;case 90:f=s(a);break;case 65:f=p(a);break;case 82:f=ne(a,r);break;case 83:f=ee(a);break;case 75:f=te(a);break;case 69:f=re(a,`error`);break;case 78:f=re(a,`notice`);break;case 84:f=m(a);break;case 116:f=g(a);break;case 71:f=u(a);break;case 72:f=d(a);break;case 100:f=l(a,r);break;default:return new t.DatabaseError(`received invalid response: `+n.toString(16),r,`error`)}return a.setBuffer(0,o),f.length=r,f}};var s=e=>{let n=e.string(1);return new t.ReadyForQueryMessage(a,n)},c=e=>{let n=e.cstring();return new t.CommandCompleteMessage(a,n)},l=(e,n)=>{let r=e.bytes(n-4);return new t.CopyDataMessage(a,r)},u=e=>f(e,`copyInResponse`),d=e=>f(e,`copyOutResponse`),f=(e,n)=>{let r=e.byte()!==0,i=e.int16(),o=new t.CopyResponse(a,n,r,i);for(let t=0;t<i;t++)o.columnTypes[t]=e.int16();return o},p=e=>{let n=e.int32(),r=e.cstring(),i=e.cstring();return new t.NotificationResponseMessage(a,n,r,i)},m=e=>{let n=e.int16(),r=new t.RowDescriptionMessage(a,n);for(let t=0;t<n;t++)r.fields[t]=h(e);return r},h=e=>{let n=e.cstring(),r=e.uint32(),i=e.int16(),a=e.uint32(),o=e.int16(),s=e.int32(),c=e.int16()===0?`text`:`binary`;return new t.Field(n,r,i,a,o,s,c)},g=e=>{let n=e.int16(),r=new t.ParameterDescriptionMessage(a,n);for(let t=0;t<n;t++)r.dataTypeIDs[t]=e.uint32();return r},_=e=>{let n=e.int16(),r=Array(n);for(let t=0;t<n;t++){let n=e.int32();r[t]=n===-1?null:e.string(n)}return new t.DataRowMessage(a,r)},ee=e=>{let n=e.cstring(),r=e.cstring();return new t.ParameterStatusMessage(a,n,r)},te=e=>{let n=e.int32(),r=e.int32();return new t.BackendKeyDataMessage(a,n,r)},ne=(e,n)=>{let r=e.int32(),i={name:`authenticationOk`,length:n};switch(r){case 0:break;case 3:i.length===8&&(i.name=`authenticationCleartextPassword`);break;case 5:if(i.length===12){i.name=`authenticationMD5Password`;let n=e.bytes(4);return new t.AuthenticationMD5Password(a,n)}break;case 10:{i.name=`authenticationSASL`,i.mechanisms=[];let t;do t=e.cstring(),t&&i.mechanisms.push(t);while(t)}break;case 11:i.name=`authenticationSASLContinue`,i.data=e.string(n-8);break;case 12:i.name=`authenticationSASLFinal`,i.data=e.string(n-8);break;default:throw Error(`Unknown authenticationOk message type `+r)}return i},re=(e,n)=>{let r={},i=e.string(1);for(;i!==`\0`;)r[i]=e.cstring(),i=e.string(1);let o=r.M,s=n===`notice`?new t.NoticeMessage(a,o):new t.DatabaseError(o,a,n);return s.severity=r.S,s.code=r.C,s.detail=r.D,s.hint=r.H,s.position=r.P,s.internalPosition=r.p,s.internalQuery=r.q,s.where=r.W,s.schema=r.s,s.table=r.t,s.column=r.c,s.dataType=r.d,s.constraint=r.n,s.file=r.F,s.line=r.L,s.routine=r.R,s}})),Kn=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DatabaseError=e.serialize=void 0,e.parse=i;var t=Vn();Object.defineProperty(e,"DatabaseError",{enumerable:!0,get:function(){return t.DatabaseError}});var n=Un();Object.defineProperty(e,"serialize",{enumerable:!0,get:function(){return n.serialize}});var r=Gn();function i(e,t){let n=new r.Parser;return e.on(`data`,e=>n.parse(e,t)),new Promise(t=>e.on(`end`,()=>t()))}})),qn=i(((e,t)=>{t.exports=ce.default})),Jn=i(((e,t)=>{t.exports=le.default})),Yn=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CloudflareSocket=void 0;var t=mn();e.CloudflareSocket=class extends t.EventEmitter{constructor(e){super(),this.ssl=e,this.writable=!1,this.destroyed=!1,this._upgrading=!1,this._upgraded=!1,this._cfSocket=null,this._cfWriter=null,this._cfReader=null}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}async connect(e,t,n){try{n&&this.once(`connect`,n);let r=this.ssl?{secureTransport:`starttls`}:{},i=(await import(`cloudflare:sockets`)).connect;return this._cfSocket=i(`${t}:${e}`,r),this._cfWriter=this._cfSocket.writable.getWriter(),this._addClosedHandler(),this._cfReader=this._cfSocket.readable.getReader(),this.ssl?this._listenOnce().catch(e=>this.emit(`error`,e)):this._listen().catch(e=>this.emit(`error`,e)),await this._cfWriter.ready,this.writable=!0,this.emit(`connect`),this}catch(e){this.emit(`error`,e)}}async _listen(){for(;;){let{done:e,value:t}=await this._cfReader.read();if(e)break;this.emit(`data`,Buffer.from(t))}}async _listenOnce(){let{done:e,value:t}=await this._cfReader.read();this.emit(`data`,Buffer.from(t))}write(e,t=`utf8`,n=()=>{}){let r=typeof t==`function`?`utf8`:t;return typeof t==`function`&&(n=t),e.length===0?n():(typeof e==`string`&&(e=Buffer.from(e,r)),this._cfWriter.write(e).then(()=>{n()},e=>{n(e)}),!0)}end(e=Buffer.alloc(0),t=`utf8`,n=()=>{}){return this.write(e,t,e=>{let t=this._cfSocket;(t?.close())?.then(()=>{this._cfSocket===t&&(this._cfSocket=null,this.emit(`close`))}).catch(e=>this.emit(`error`,e)),n&&n(e)}),this}destroy(e){return this.destroyed=!0,this.end()}startTls(e){this._upgraded?this.emit(`error`,"Cannot call `startTls()` more than once on a socket"):(this._cfWriter.releaseLock(),this._cfReader.releaseLock(),this._upgrading=!0,this._cfSocket=this._cfSocket.startTls(e),this._cfWriter=this._cfSocket.writable.getWriter(),this._cfReader=this._cfSocket.readable.getReader(),this._addClosedHandler(),this._listen().catch(e=>this.emit(`error`,e)))}_addClosedHandler(){let e=this._cfSocket;e.closed.then(()=>{this._upgrading?(this._upgrading=!1,this._upgraded=!0):this._cfSocket===e&&(this._cfSocket=null,this.emit(`close`))}).catch(e=>this.emit(`error`,e))}}})),Xn=i(((e,t)=>{var{getStream:n,getSecureStream:r}=s();t.exports={getStream:n,getSecureStream:r};function i(){function e(e){return new(qn()).Socket}function t(e){return Jn().connect(e)}return{getStream:e,getSecureStream:t}}function a(){function e(e){let{CloudflareSocket:t}=Yn();return new t(e)}function t(e){return e.socket.startTls(e),e.socket}return{getStream:e,getSecureStream:t}}function o(){if(typeof navigator==`object`&&navigator!==null&&typeof navigator.userAgent==`string`)return navigator.userAgent===`Cloudflare-Workers`;if(typeof Response==`function`){let e=new Response(null,{cf:{thing:!0}});if(typeof e.cf==`object`&&e.cf!==null&&e.cf.thing)return!0}return!1}function s(){return o()?a():i()}})),Zn=i(((e,t)=>{var n=mn().EventEmitter,{parse:r,serialize:i}=Kn(),a=Xn(),{getStream:o}=a,s=i.flush(),c=i.sync(),l=i.end();t.exports=class extends n{constructor(e){super(),e||={},this.stream=e.stream||o(e.ssl),typeof this.stream==`function`&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.submittedNamedStatements={},this.ssl=e.ssl||!1,this.sslNegotiation=e.sslNegotiation||`postgres`,this._ending=!1,this._emitMessage=!1;let t=this;this.on(`newListener`,function(e){e===`message`&&(t._emitMessage=!0)})}connect(e,t){let n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,t),this.stream.once(`connect`,function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit(`connect`)});let r=function(e){(!n._ending||e.code!==`ECONNRESET`&&e.code!==`EPIPE`)&&n.emit(`error`,e)};if(this.stream.on(`error`,r),this.stream.on(`close`,function(){n.emit(`end`)}),!this.ssl)return this.attachListeners(this.stream);if(this.sslNegotiation===`direct`)return this.stream.once(`connect`,function(){n.upgradeToSSL(t,r)});this.stream.once(`data`,function(e){switch(e.toString(`utf8`)){case`S`:break;case`N`:return n.stream.end(),n.emit(`error`,Error(`The server does not support SSL connections`));default:return n.stream.end(),n.emit(`error`,Error(`There was an error establishing an SSL connection`))}n.upgradeToSSL(t,r)})}upgradeToSSL(e,t){let n=this,r={socket:n.stream,host:e};n.ssl!==!0&&(Object.assign(r,n.ssl),`key`in n.ssl&&(r.key=n.ssl.key)),n.sslNegotiation===`direct`&&(r.ALPNProtocols=[`postgresql`]);let i=qn();i.isIP&&i.isIP(e)===0&&(r.servername=e);try{n.stream=a.getSecureStream(r)}catch(e){return n.emit(`error`,e)}n.attachListeners(n.stream),n.stream.on(`error`,t),n.emit(`sslconnect`)}attachListeners(e){r(e,e=>{let t=e.name===`error`?`errorMessage`:e.name;this._emitMessage&&this.emit(`message`,e),this.emit(t,e)})}requestSsl(){this.stream.write(i.requestSsl())}startup(e){this.stream.write(i.startup(e))}cancel(e,t){this._send(i.cancel(e,t))}password(e){this._send(i.password(e))}sendSASLInitialResponseMessage(e,t){this._send(i.sendSASLInitialResponseMessage(e,t))}sendSCRAMClientFinalMessage(e){this._send(i.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(i.query(e))}parse(e){this._send(i.parse(e))}bind(e){this._send(i.bind(e))}execute(e){this._send(i.execute(e))}flush(){this.stream.writable&&this.stream.write(s)}sync(){this._send(c)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable)this.stream.end();else return this.stream.write(l,()=>{this.stream.end()})}close(e){this._send(i.close(e))}describe(e){this._send(i.describe(e))}sendCopyFromChunk(e){this._send(i.copyData(e))}endCopyFrom(){this._send(i.copyDone())}sendCopyFail(e){this._send(i.copyFail(e))}}})),Qn=i(((e,t)=>{t.exports=ue.default})),$n=i(((e,t)=>{t.exports=de.default})),er=i(((e,t)=>{t.exports=fe.default})),tr=i(((e,t)=>{var{Transform:n}=$n(),{StringDecoder:r}=er(),i=Symbol(`last`),a=Symbol(`decoder`);function o(e,t,n){let r;if(this.overflow){if(r=this[a].write(e).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[i]+=this[a].write(e),r=this[i].split(this.matcher);this[i]=r.pop();for(let e=0;e<r.length;e++)try{c(this,this.mapper(r[e]))}catch(e){return n(e)}this.overflow=this[i].length>this.maxLength,this.overflow&&!this.skipOverflow?n(Error(`maximum buffer reached`)):n()}function s(e){if(this[i]+=this[a].end(),this[i])try{c(this,this.mapper(this[i]))}catch(t){return e(t)}e()}function c(e,t){t!==void 0&&e.push(t)}function l(e){return e}function u(e,t,c){switch(e||=/\r?\n/,t||=l,c||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(c=e,e=/\r?\n/);break;case 2:typeof e==`function`?(c=t,t=e,e=/\r?\n/):typeof t==`object`&&(c=t,t=l)}c=Object.assign({},c),c.autoDestroy=!0,c.transform=o,c.flush=s,c.readableObjectMode=!0;let u=new n(c);return u[i]=``,u[a]=new r(`utf8`),u.matcher=e,u.mapper=t,u.maxLength=c.maxLength,u.skipOverflow=c.skipOverflow||!1,u.overflow=!1,u._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},u}t.exports=u})),nr=i(((e,t)=>{var n=Qn(),r=$n().Stream,i=tr(),a=Dn(),o=5432,s=process.platform===`win32`,c=process.stderr,l=56,u=7,d=61440,f=32768;function p(e){return(e&d)==f}var m=[`host`,`port`,`database`,`user`,`password`],h=m.length,g=m[h-1];function _(){if(c instanceof r&&!0===c.writable){var e=Array.prototype.slice.call(arguments).concat(`
13
- `);c.write(a.format.apply(a,e))}}Object.defineProperty(t.exports,"isWin",{get:function(){return s},set:function(e){s=e}}),t.exports.warnTo=function(e){var t=c;return c=e,t},t.exports.getFileName=function(e){var t=e||process.env;return t.PGPASSFILE||(s?n.join(t.APPDATA||`./`,`postgresql`,`pgpass.conf`):n.join(t.HOME||`./`,`.pgpass`))},t.exports.usePgPass=function(e,t){return Object.prototype.hasOwnProperty.call(process.env,`PGPASSWORD`)?!1:s?!0:(t||=`<unkn>`,p(e.mode)?e.mode&(l|u)?(_(`WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less`,t),!1):!0:(_(`WARNING: password file "%s" is not a plain file`,t),!1))};var ee=t.exports.match=function(e,t){return m.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(e[r]||o)===Number(t[r])?n&&!0:n&&(t[r]===`*`||t[r]===e[r])},!0)};t.exports.getPassword=function(e,t,n){var r,a=t.pipe(i());function o(t){var n=te(t);n&&ne(n)&&ee(e,n)&&(r=n[g],a.end())}var s=function(){t.destroy(),n(r)},c=function(e){t.destroy(),_(`WARNING: error on reading file: %s`,e),n(void 0)};t.on(`error`,c),a.on(`data`,o).on(`end`,s).on(`error`,c)};var te=t.exports.parseLine=function(e){if(e.length<11||e.match(/^\s+#/))return null;for(var t=``,n=``,r=0,i=0,a={},o=!1,s=function(t,n,r){var i=e.substring(n,r);Object.hasOwnProperty.call(process.env,`PGPASS_NO_DEESCAPE`)||(i=i.replace(/\\([:\\])/g,`$1`)),a[m[t]]=i},c=0;c<e.length-1;c+=1){if(t=e.charAt(c+1),n=e.charAt(c),o=r==h-1,o){s(r,i);break}c>=0&&t==`:`&&n!==`\\`&&(s(r,i,c+1),i=c+2,r+=1)}return a=Object.keys(a).length===h?a:null,a},ne=t.exports.isValidEntry=function(e){for(var t={0:function(e){return e.length>0},1:function(e){return e===`*`||(e=Number(e),isFinite(e)&&e>0&&e<9007199254740992&&Math.floor(e)===e)},2:function(e){return e.length>0},3:function(e){return e.length>0},4:function(e){return e.length>0}},n=0;n<m.length;n+=1){var r=t[n];if(!r(e[m[n]]||``))return!1}return!0}})),rr=i(((e,t)=>{Qn();var n=In(),r=nr();t.exports=function(e,t){var i=r.getFileName();n.stat(i,function(a,o){if(a||!r.usePgPass(o,i))return t(void 0);var s=n.createReadStream(i);r.getPassword(e,s,t)})},t.exports.warnTo=r.warnTo})),ir=i(((e,t)=>{var n=mn().EventEmitter,r=kn(),i=Dn(),a=Nn(),o=Pn(),s=Rn(),c=Bn(),l=En(),u=Zn(),d=jn(),f=i.deprecate(()=>{},`Client.activeQuery is deprecated and will be removed in pg@9.0`),p=i.deprecate(()=>{},`Client.queryQueue is deprecated and will be removed in pg@9.0.`),m=i.deprecate(()=>{},`pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code.`),h=i.deprecate(()=>{},`Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0.`),g=i.deprecate(()=>{},`Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.`);function _(e,t){if(typeof e==`number`)return Number.isFinite(e)?e:t;if(typeof e==`string`&&e.trim()!==``){let n=Number(e);return Number.isFinite(n)?n:t}return t}var ee=class extends n{constructor(e){super(),this.connectionParameters=new s(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let t=e||{};t.Promise&&h(),this._Promise=t.Promise||global.Promise,this._types=new o(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!t.enableChannelBinding,this.scramMaxIterations=_(t.scramMaxIterations,a.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=t.connection||new u({stream:t.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||`utf8`}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!t.pipeline,this.binary=t.binary||l.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||`postgres`,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return f(),this._activeQuery}set activeQuery(e){f(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=t=>{process.nextTick(()=>{t.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._sentQueryQueue.forEach(t),this._sentQueryQueue.length=0,this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let t=Error(`Client has already been connected. You cannot reuse a client.`);process.nextTick(()=>{e(t)})}else this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(Error(`timeout expired`))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf(`/`)===0?n.connect(this.host+`/.s.PGSQL.`+this.port):n.connect(this.port,this.host),n.on(`connect`,function(){t.ssl?t.sslNegotiation!==`direct`&&n.requestSsl():n.startup(t.getStartupConf())}),n.on(`sslconnect`,function(){n.startup(t.getStartupConf())}),this._attachListeners(n),n.once(`end`,()=>{let e=this._ending?Error(`Connection terminated`):Error(`Connection terminated unexpectedly`);clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(e),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(e):this._handleErrorEvent(e):this._connectionError||this._handleErrorEvent(e)),process.nextTick(()=>{this.emit(`end`)})})}connect(e){if(e)this._connect(e);else return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})}_attachListeners(e){e.on(`authenticationCleartextPassword`,this._handleAuthCleartextPassword.bind(this)),e.on(`authenticationMD5Password`,this._handleAuthMD5Password.bind(this)),e.on(`authenticationSASL`,this._handleAuthSASL.bind(this)),e.on(`authenticationSASLContinue`,this._handleAuthSASLContinue.bind(this)),e.on(`authenticationSASLFinal`,this._handleAuthSASLFinal.bind(this)),e.on(`backendKeyData`,this._handleBackendKeyData.bind(this)),e.on(`error`,this._handleErrorEvent.bind(this)),e.on(`errorMessage`,this._handleErrorMessage.bind(this)),e.on(`readyForQuery`,this._handleReadyForQuery.bind(this)),e.on(`notice`,this._handleNotice.bind(this)),e.on(`rowDescription`,this._handleRowDescription.bind(this)),e.on(`dataRow`,this._handleDataRow.bind(this)),e.on(`portalSuspended`,this._handlePortalSuspended.bind(this)),e.on(`emptyQuery`,this._handleEmptyQuery.bind(this)),e.on(`commandComplete`,this._handleCommandComplete.bind(this)),e.on(`parseComplete`,this._handleParseComplete.bind(this)),e.on(`copyInResponse`,this._handleCopyInResponse.bind(this)),e.on(`copyData`,this._handleCopyData.bind(this)),e.on(`notification`,this._handleNotification.bind(this))}_getPassword(e){let t=this.connection;if(typeof this.password==`function`)this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(n=>{if(n!==void 0){if(typeof n!=`string`){t.emit(`error`,TypeError(`Password must be a string`));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(e=>{t.emit(`error`,e)});else if(this.password!==null)e();else try{rr()(this.connectionParameters,t=>{t!==void 0&&(m(),this.connectionParameters.password=this.password=t),e()})}catch(e){this.emit(`error`,e)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let t=await d.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(e){this.emit(`error`,e)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=a.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(e){this.connection.emit(`error`,e)}})}async _handleAuthSASLContinue(e){try{await a.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(e){this.connection.emit(`error`,e)}}_handleAuthSASLFinal(e){try{a.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(e){this.connection.emit(`error`,e)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&=(this._connectionCallback(null,this),null),this.emit(`connect`));let t=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit(`error`,e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit(`error`,e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();t?(this._activeQuery=null,t.name&&delete this.connection.submittedNamedStatements[t.name],t.handleError(e,this.connection)):this._handleErrorEvent(e)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected rowDescription message from backend.`);this._handleErrorEvent(e)}else t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected dataRow message from backend.`);this._handleErrorEvent(e)}else t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected portalSuspended message from backend.`);this._handleErrorEvent(e)}else t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected emptyQuery message from backend.`);this._handleErrorEvent(e)}else t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected commandComplete message from backend.`);this._handleErrorEvent(e)}else t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let e=Error(`Received unexpected parseComplete message from backend.`);this._handleErrorEvent(e)}else e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected copyInResponse message from backend.`);this._handleErrorEvent(e)}else t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected copyData message from backend.`);this._handleErrorEvent(e)}else t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit(`notification`,e)}_handleNotice(e){this.emit(`notice`,e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=``+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){let t=this.connection;this.host&&this.host.indexOf(`/`)===0?t.connect(this.host+`/.s.PGSQL.`+this.port):t.connect(this.port,this.host),t.on(`connect`,function(){t.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(t)===-1?e._sentQueryQueue.indexOf(t)!==-1&&(t.callback=()=>{}):e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return r.escapeIdentifier(e)}escapeLiteral(e){return r.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline)this._pulsePipelinedQueryQueue();else if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit(`drain`))}}_pulsePipelinedQueryQueue(){if(this._connected&&this._queryable){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let t=e.submit(this.connection);t?process.nextTick(()=>{e.handleError(t,this.connection)}):this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit(`drain`)}}query(e,t,n){let r,i;if(e==null)throw TypeError(`Client was passed a null or undefined query`);if(typeof e.submit==`function`)i=r=e,r.callback||(typeof t==`function`?r.callback=t:n&&(r.callback=n));else if(r=new c(e,t,n),!r.callback)i=new this._Promise((e,t)=>{r.callback=(n,r)=>n?t(n):e(r)}).catch(e=>{throw Error.captureStackTrace(e),e});else if(typeof r.callback!=`function`)throw TypeError(`callback is not a function`);let a=e.query_timeout||this.connectionParameters.query_timeout;if(a){let e=r.callback||(()=>{}),t=setTimeout(()=>{let t=Error(`Query read timeout`);process.nextTick(()=>{r.handleError(t,this.connection)}),e(t),r.callback=()=>{};let n=this._queryQueue.indexOf(r);if(n>-1)this._queryQueue.splice(n,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},a);r.callback=(n,r)=>{clearTimeout(t),e(n,r)}}if(this.binary&&!r.binary&&(r.binary=!0),r._result&&!r._result._types&&(r._result._types=this._types),this.pipeline){let t=typeof e.submit==`function`&&!(r instanceof c)?`Custom query classes such as pg-cursor and pg-query-stream are`:r.rows?"The `rows` option is":null;if(t)return process.nextTick(()=>{r.handleError(Error(`${t} not supported in pipeline mode`),this.connection)}),i}return this._queryable?this._ending?(process.nextTick(()=>{r.handleError(Error(`Client was closed and is not queryable`),this.connection)}),i):(this._queryQueue.length>0&&!this.pipeline&&g(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(process.nextTick(()=>{r.handleError(Error(`Client has encountered a connection error and is not queryable`),this.connection)}),i)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended){if(e){e();return}return this._Promise.resolve()}if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once(`drain`,()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once(`end`,e);else return new this._Promise(e=>{this.connection.once(`end`,e)})}get queryQueue(){return p(),this._queryQueue}};ee.Query=c,t.exports=ee})),ar=i(((e,t)=>{var n=mn().EventEmitter,r=function(){},i=(e,t)=>{let n=e.findIndex(t);return n===-1?void 0:e.splice(n,1)[0]},a=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},o=class{constructor(e){this.callback=e}};function s(){throw Error(`Release called on client which has already been released to the pool.`)}function c(e,t){if(t)return{callback:t,result:void 0};let n,r;return{callback:function(e,t){e?n(e):r(t)},result:new e(function(e,t){r=e,n=t}).catch(e=>{throw Error.captureStackTrace(e),e})}}function l(e,t){return function n(r){r.client=t,t.removeListener(`error`,n),t.on(`error`,()=>{e.log(`additional client error after disconnection due to error`,r)}),e._remove(t),e.emit(`error`,r,t)}}t.exports=class extends n{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&`password`in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||t||fr().Client,this.Promise=this.options.Promise||global.Promise,this.options.idleTimeoutMillis===void 0&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let t=this.Promise;return typeof t.try==`function`?t.try(e):new t(t=>t(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log(`pulse queue`),this.ended){this.log(`pulse queue ended`);return}if(this.ending){this.log(`pulse queue on ending`),this._idle.length&&this._idle.slice().map(e=>{this._remove(e.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log(`no queued requests`);return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let r=t.idleListener;return this._acquireClient(n,e,r,!1)}if(!this._isFull())return this.newClient(e);throw Error(`unexpected condition`)}_remove(e,t){let n=i(this._idle,t=>t.client===e);n!==void 0&&clearTimeout(n.timeoutId),this._clients=this._clients.filter(t=>t!==e);let r=this;e.end(()=>{r.emit(`remove`,e),typeof t==`function`&&t()})}connect(e){if(this.ending){let t=Error(`Cannot use a pool after calling end on the pool`);return e?e(t):this.Promise.reject(t)}let t=c(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new o(t.callback)),n;let e=(e,n,r)=>{clearTimeout(a),t.callback(e,n,r)},r=new o(e),a=setTimeout(()=>{i(this._pendingQueue,t=>t.callback===e),r.timedOut=!0,t.callback(Error(`timeout exceeded when trying to connect`))},this.options.connectionTimeoutMillis);return a.unref&&a.unref(),this._pendingQueue.push(r),n}return this.newClient(new o(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=l(this,t);this.log(`checking client timeout`);let i,a=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{t.connection?(this.log(`ending client due to timeout`),a=!0,t.connection.stream.destroy()):t.isConnected()||(this.log(`ending client due to timeout`),a=!0,t.end())},this.options.connectionTimeoutMillis)),this.log(`connecting new client`),t.connect(o=>{if(i&&clearTimeout(i),t.on(`error`,n),o)this.log(`client failed to connect`,o),this._clients=this._clients.filter(e=>e!==t),a&&(o=Error(`Connection terminated due to connection timeout`,{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,r);else{if(this.log(`new client connected`),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},n=>{this._clients=this._clients.filter(e=>e!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(n,void 0,r)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,n){if(this.options.maxLifetimeSeconds!==0){let t=setTimeout(()=>{this.log(`ending client due to expired lifetime`),this._expired.add(e),this._idle.findIndex(t=>t.client===e)!==-1&&this._acquireClient(e,new o((e,t,n)=>n()),n,!1)},this.options.maxLifetimeSeconds*1e3);t.unref(),e.once(`end`,()=>clearTimeout(t))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,i){i&&this.emit(`connect`,e),this.emit(`acquire`,e),e.release=this._releaseOnce(e,n),e.removeListener(`error`,n),t.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,n=>{if(n)return e.release(n),t.callback(n,void 0,r);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return r=>{n&&s(),n=!0,this._release(e,t,r)}}_release(e,t,n){if(e.on(`error`,t),e._poolUseCount=(e._poolUseCount||0)+1,this.emit(`release`,n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log(`remove expended client`),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log(`remove expired client`),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let r;this.options.idleTimeoutMillis&&this._isAboveMin()&&(r=setTimeout(()=>{this._isAboveMin()&&(this.log(`remove idle client`),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&r.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new a(e,t,r)),this._pulseQueue()}query(e,t,n){if(typeof e==`function`){let t=c(this.Promise,e);return setImmediate(function(){return t.callback(Error(`Passing a function as the first parameter to pool.query is not supported`))}),t.result}typeof t==`function`&&(n=t,t=void 0);let r=c(this.Promise,n);return n=r.callback,this.connect((r,i)=>{if(r)return n(r);let a=!1,o=e=>{a||(a=!0,i.release(e),n(e))};i.once(`error`,o),this.log(`dispatching query`);try{i.query(e,t,(e,t)=>{if(this.log(`query dispatched`),i.removeListener(`error`,o),!a)return a=!0,i.release(e),e?n(e):n(void 0,t)})}catch(e){return i.release(e),n(e)}}),r.result}end(e){if(this.log(`ending`),this.ending){let t=Error(`Called end on pool more than once`);return e?e(t):this.Promise.reject(t)}this.ending=!0;let t=c(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+ +!!this._expired.has(t),0)}get totalCount(){return this._clients.length}}})),or=r({default:()=>sr}),sr,cr=n(()=>{throw sr={},Error(`Could not resolve "pg-native" imported by "pg". Is it installed?`)}),lr=i(((e,t)=>{var n=mn().EventEmitter,r=Dn(),i=kn(),a=t.exports=function(e,t,r){n.call(this),e=i.normalizeQueryConfig(e,t,r),this.text=e.text,this.values=e.values,this.name=e.name,this.queryMode=e.queryMode,this.callback=e.callback,this.state=`new`,this._arrayMode=e.rowMode===`array`,this._emitRowEvents=!1,this.on(`newListener`,function(e){e===`row`&&(this._emitRowEvents=!0)}.bind(this))};r.inherits(a,n);var o={sqlState:`code`,statementPosition:`position`,messagePrimary:`message`,messageDetail:`detail`,messageHint:`hint`,context:`where`,schemaName:`schema`,tableName:`table`,columnName:`column`,dataTypeName:`dataType`,constraintName:`constraint`,sourceFile:`file`,sourceLine:`line`,sourceFunction:`routine`};a.prototype.handleError=function(e){let t=this.native&&this.native.pq.resultErrorFields();if(t)for(let n in t){let r=o[n]||n;e[r]=t[n]}this.callback?this.callback(e):this.emit(`error`,e),this.state=`error`},a.prototype.then=function(e,t){return this._getPromise().then(e,t)},a.prototype.catch=function(e){return this._getPromise().catch(e)},a.prototype._getPromise=function(){return this._promise||=new Promise(function(e,t){this._once(`end`,e),this._once(`error`,t)}.bind(this)),this._promise},a.prototype.submit=function(e){this.state=`running`;let t=this;this.native=e.native,e.native.arrayMode=this._arrayMode;let n=function(n,r,i){if(e.native.arrayMode=!1,setImmediate(function(){t.emit(`_done`)}),n)return t.handleError(n);t._emitRowEvents&&(i.length>1?r.forEach((e,n)=>{e.forEach(e=>{t.emit(`row`,e,i[n])})}):r.forEach(function(e){t.emit(`row`,e,i)})),t.state=`end`,t.emit(`end`,i),t.callback&&t.callback(null,i)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error(`Warning! Postgres only supports 63 characters for query names.`),console.error(`You supplied %s (%s)`,this.name,this.name.length),console.error(`This can cause conflicts and silent errors executing queries`));let r=(this.values||[]).map(i.prepareValue);if(e.namedQueries[this.name]!==void 0){if(this.text&&e.namedQueries[this.name]!==this.text){let e=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(e)}return e.native.execute(this.name,r,n)}return e.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(e.namedQueries[t.name]=t.text,t.native.execute(t.name,r,n))})}if(this.values){if(!Array.isArray(this.values))return n(Error(`Query values must be an array`));let t=this.values.map(i.prepareValue);e.native.query(this.text,t,n)}else this.queryMode===`extended`?e.native.query(this.text,[],n):e.native.query(this.text,n)}})),ur=i(((e,n)=>{var r=Dn(),i;try{i=(cr(),t(or))}catch(e){throw e}var a=Pn(),o=mn().EventEmitter,s=Dn(),c=Rn(),l=lr(),u=r.deprecate(()=>{},`Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.`),d=n.exports=function(e){o.call(this),e||={},this._Promise=e.Promise||global.Promise,this._types=new a(e.types),this.native=new i({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!e.pipeline,this._pipelineInFlight=!1;let t=this.connectionParameters=new c(e);e.nativeConnectionString&&(t.nativeConnectionString=e.nativeConnectionString),this.user=t.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:t.password}),this.database=t.database,this.host=t.host,this.port=t.port,this.namedQueries={}};d.Query=l,s.inherits(d,o),d.prototype._errorAllQueries=function(e){let t=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(e)})};this._hasActiveQuery()&&(t(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0},d.prototype._connect=function(e){let t=this;this._connecting?process.nextTick(()=>e(Error(`Client has already been connected. You cannot reuse a client.`))):(this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(t.connectionParameters.nativeConnectionString&&(r=t.connectionParameters.nativeConnectionString),n)return e(n);t.native.connect(r,function(n){if(n)return t.native.end(),e(n);t._connected=!0,t.native.on(`error`,function(e){t._queryable=!1,t._errorAllQueries(e),t.emit(`error`,e)}),t.native.on(`notification`,function(e){t.emit(`notification`,{channel:e.relname,payload:e.extra})}),t.emit(`connect`),t._pulseQueryQueue(!0),e(null,this)})}))},d.prototype.connect=function(e){if(e)this._connect(e);else return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})},d.prototype.query=function(e,t,n){let r,i,a,o,s;if(e==null)throw TypeError(`Client was passed a null or undefined query`);if(typeof e.submit==`function`)a=e.query_timeout||this.connectionParameters.query_timeout,i=r=e,typeof t==`function`&&(e.callback=t);else if(a=e.query_timeout||this.connectionParameters.query_timeout,r=new l(e,t,n),!r.callback){let e,t;i=new this._Promise((n,r)=>{e=n,t=r}).catch(e=>{throw Error.captureStackTrace(e),e}),r.callback=(n,r)=>n?t(n):e(r)}return a&&(s=r.callback||(()=>{}),o=setTimeout(()=>{let e=Error(`Query read timeout`);process.nextTick(()=>{r.handleError(e,this.connection)}),s(e),r.callback=()=>{};let t=this._queryQueue.indexOf(r);t>-1&&this._queryQueue.splice(t,1),this._pulseQueryQueue()},a),r.callback=(e,t)=>{clearTimeout(o),s(e,t)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(Error(`Client was closed and is not queryable`))}),i):(this._queryQueue.length>0&&!this.pipeline&&u(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(Error(`Client has encountered a connection error and is not queryable`))}),i)},d.prototype.end=function(e){let t=this;this._ending=!0,this._connecting&&!this._connected&&this.once(`connect`,()=>{this.end(()=>{})});let n;e||(n=new this._Promise(function(t,n){e=e=>e?n(e):t()}));let r=function(){t.native.end(function(){t._connected=!1,t._errorAllQueries(Error(`Connection terminated`)),process.nextTick(()=>{t.emit(`end`),e&&e()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once(`drain`,r):r(),n},d.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!==`error`&&this._activeQuery.state!==`end`},d.prototype._pulseQueryQueue=function(e){if(!this._connected)return;if(this.pipeline&&!e)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let t=this._queryQueue.shift();if(!t){e||this.emit(`drain`);return}this._activeQuery=t,t.submit(this);let n=this;t.once(`_done`,function(){n._pulseQueryQueue()})},d.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit(`drain`);return}this._pipelineInFlight=!0;let e=this,t=[],n=[],r=kn();for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0,n.push(e);let i=e.values?e.values.map(r.prepareValue):null,a={text:e.text,name:e.name,arrayMode:e._arrayMode};i&&(a.values=i),e.name&&this.namedQueries[e.name]&&(a._alreadyPrepared=!0),t.push(a)}this.native.pipeline(t,function(t,r){if(e._pipelineInFlight=!1,t){e._connected=!1,e._queryable=!1;for(let r=0;r<n.length;r++){let i=n[r];i.native=e.native,i.handleError(t)}e._errorAllQueries(t),e.emit(`error`,t),e.emit(`end`)}else{for(let t=0;t<n.length;t++){let i=n[t],a=r[t];i.native=e.native,a.err?i.handleError(a.err):(i.name&&(e.namedQueries[i.name]=i.text),i.state=`end`,i.emit(`end`,a.result),i.callback&&i.callback(null,a.result)),setImmediate(function(){i.emit(`_done`)})}e._pulsePipelinedQueryQueue()}})},d.prototype.cancel=function(e){this._activeQuery===e?this.native.cancel(function(){}):this._queryQueue.indexOf(e)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(e),1)},d.prototype.ref=function(){},d.prototype.unref=function(){},d.prototype.setTypeParser=function(e,t,n){return this._types.setTypeParser(e,t,n)},d.prototype.getTypeParser=function(e,t){return this._types.getTypeParser(e,t)},d.prototype.isConnected=function(){return this._connected},d.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}})),dr=i(((e,t)=>{t.exports=ur()})),fr=i(((e,t)=>{var n=ir(),r=En(),i=Zn(),a=zn(),o=kn(),s=ar(),c=Pn(),{DatabaseError:l}=Kn(),{escapeIdentifier:u,escapeLiteral:d}=kn(),f=e=>class extends s{constructor(t){super(t,e)}},p=function(e){this.defaults=r,this.Client=e,this.Query=this.Client.Query,this.Pool=f(this.Client),this._pools=[],this.Connection=i,this.types=Tn(),this.DatabaseError=l,this.TypeOverrides=c,this.escapeIdentifier=u,this.escapeLiteral=d,this.Result=a,this.utils=o},m=n,h=!1;try{h=!!process.env.NODE_PG_FORCE_NATIVE}catch{}h&&(m=dr()),t.exports=new p(m),Object.defineProperty(t.exports,"native",{configurable:!0,enumerable:!1,get(){let e=null;try{e=new p(dr())}catch(e){if(e.code!==`MODULE_NOT_FOUND`)throw e}return Object.defineProperty(t.exports,"native",{value:e}),e}})})),pr=e(fr(),1);pr.default.Client,pr.default.Pool,pr.default.Connection,pr.default.types,pr.default.Query,pr.default.DatabaseError,pr.default.escapeIdentifier,pr.default.escapeLiteral,pr.default.Result,pr.default.TypeOverrides,pr.default.defaults;var mr=pr.default,y=Symbol.for(`drizzle:entityKind`);function b(e,t){if(!e||typeof e!=`object`)return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,y))throw Error(`Class "${t.name??`<unknown>`}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(y in n&&n[y]===t[y])return!0;n=Object.getPrototypeOf(n)}return!1}var hr=class{static[y]=`ConsoleLogWriter`;write(e){console.log(e)}},gr=class{static[y]=`DefaultLogger`;writer;constructor(e){this.writer=e?.writer??new hr}logQuery(e,t){let n=t.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),r=n.length?` -- params: [${n.join(`, `)}]`:``;this.writer.write(`Query: ${e}${r}`)}},_r=class{static[y]=`NoopLogger`;logQuery(){}},vr=class{static[y]=`QueryPromise`;[Symbol.toStringTag]=`QueryPromise`;catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}},x=class{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[y]=`Column`;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}},yr=class{static[y]=`ColumnBuilder`;config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===``&&(this.config.name=e)}},br=Symbol.for(`drizzle:Name`),xr=class{static[y]=`PgForeignKeyBuilder`;reference;_onUpdate=`no action`;_onDelete=`no action`;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?`no action`:e,this}onDelete(e){return this._onDelete=e===void 0?`no action`:e,this}build(e){return new Sr(e,this)}},Sr=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[y]=`PgForeignKey`;reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[br],...r,n[0].table[br],...i];return e??`${a.join(`_`)}_fk`}};function Cr(e,...t){return e(...t)}function wr(e){return new Dr(e)}function Tr(e,t){return`${e[br]}_${t.join(`_`)}_unique`}var Er=class{constructor(e,t){this.name=t,this.columns=e}static[y]=`PgUniqueConstraintBuilder`;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new Or(e,this.columns,this.nullsNotDistinctConfig,this.name)}},Dr=class{static[y]=`PgUniqueOnConstraintBuilder`;name;constructor(e){this.name=e}on(...e){return new Er(e,this.name)}},Or=class{constructor(e,t,n,r){this.table=e,this.columns=t,this.name=r??Tr(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static[y]=`PgUniqueConstraint`;columns;name;nullsNotDistinct=!1;getName(){return this.name}};function kr(e,t,n){for(let r=t;r<e.length;r++){let i=e[r];if(i===`\\`)r++;else{if(i===`"`)return[e.slice(t,r).replace(/\\/g,``),r+1];if(!n&&(i===`,`||i===`}`))return[e.slice(t,r).replace(/\\/g,``),r]}}return[e.slice(t).replace(/\\/g,``),e.length]}function Ar(e,t=0){let n=[],r=t,i=!1;for(;r<e.length;){let a=e[r];if(a===`,`){(i||r===t)&&n.push(``),i=!0,r++;continue}if(i=!1,a===`\\`){r+=2;continue}if(a===`"`){let[t,i]=kr(e,r+1,!0);n.push(t),r=i;continue}if(a===`}`)return[n,r+1];if(a===`{`){let[t,i]=Ar(e,r+1);n.push(t),r=i;continue}let[o,s]=kr(e,r,!1);n.push(o),r=s}return[n,r]}function jr(e){let[t]=Ar(e,1);return t}function Mr(e){return`{${e.map(e=>Array.isArray(e)?Mr(e):typeof e==`string`?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:`${e}`).join(`,`)}}`}var S=class extends yr{foreignKeyConfigs=[];static[y]=`PgColumnBuilder`;array(e){return new Fr(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:`always`,mode:`stored`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>Cr((n,r)=>{let i=new xr(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)},n,r))}buildExtraConfigColumn(e){return new Nr(e,this.config)}},C=class extends x{constructor(e,t){t.uniqueName||=Tr(e,[t.name]),super(e,t),this.table=e}static[y]=`PgColumn`},Nr=class extends C{static[y]=`ExtraConfigColumn`;getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??`asc`,nulls:this.config.nulls??`last`,opClass:this.config.opClass};defaultConfig={order:`asc`,nulls:`last`,opClass:void 0};asc(){return this.indexConfig.order=`asc`,this}desc(){return this.indexConfig.order=`desc`,this}nullsFirst(){return this.indexConfig.nulls=`first`,this}nullsLast(){return this.indexConfig.nulls=`last`,this}op(e){return this.indexConfig.opClass=e,this}},Pr=class{static[y]=`IndexedColumn`;constructor(e,t,n,r){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=r}name;keyAsName;type;indexConfig},Fr=class extends S{static[y]=`PgArrayBuilder`;constructor(e,t,n){super(e,`array`,`PgArray`),this.config.baseBuilder=t,this.config.size=n}build(e){let t=this.config.baseBuilder.build(e);return new Ir(e,this.config,t)}},Ir=class e extends C{constructor(e,t,n,r){super(e,t),this.baseColumn=n,this.range=r,this.size=t.size}size;static[y]=`PgArray`;getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==`number`?this.size:``}]`}mapFromDriverValue(e){return typeof e==`string`&&(e=jr(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(t,n=!1){let r=t.map(t=>t===null?null:b(this.baseColumn,e)?this.baseColumn.mapToDriverValue(t,!0):this.baseColumn.mapToDriverValue(t));return n?r:Mr(r)}},Lr=class extends S{static[y]=`PgEnumObjectColumnBuilder`;constructor(e,t){super(e,`string`,`PgEnumObjectColumn`),this.config.enum=t}build(e){return new Rr(e,this.config)}},Rr=class extends C{static[y]=`PgEnumObjectColumn`;enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},zr=Symbol.for(`drizzle:isPgEnum`);function Br(e){return!!e&&typeof e==`function`&&zr in e&&e[zr]===!0}var Vr=class extends S{static[y]=`PgEnumColumnBuilder`;constructor(e,t){super(e,`string`,`PgEnumColumn`),this.config.enum=t}build(e){return new Hr(e,this.config)}},Hr=class extends C{static[y]=`PgEnumColumn`;enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};function Ur(e,t,n){let r=Object.assign(e=>new Vr(e??``,r),{enumName:e,enumValues:t,schema:n,[zr]:!0});return r}function Wr(e,t,n){let r=Object.assign(e=>new Lr(e??``,r),{enumName:e,enumValues:Object.values(t),schema:n,[zr]:!0});return r}var w=class{static[y]=`Subquery`;constructor(e,t,n,r=!1,i=[]){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r,usedTables:i}}},Gr=class extends w{static[y]=`WithSubquery`},T={startActiveSpan(e,t){return t()}},E=Symbol.for(`drizzle:ViewBaseConfig`),Kr=Symbol.for(`drizzle:Schema`),qr=Symbol.for(`drizzle:Columns`),Jr=Symbol.for(`drizzle:ExtraConfigColumns`),Yr=Symbol.for(`drizzle:OriginalName`),Xr=Symbol.for(`drizzle:BaseName`),Zr=Symbol.for(`drizzle:IsAlias`),Qr=Symbol.for(`drizzle:ExtraConfigBuilder`),$r=Symbol.for(`drizzle:IsDrizzleTable`),D=class{static[y]=`Table`;static Symbol={Name:br,Schema:Kr,OriginalName:Yr,Columns:qr,ExtraConfigColumns:Jr,BaseName:Xr,IsAlias:Zr,ExtraConfigBuilder:Qr};[br];[Yr];[Kr];[qr];[Jr];[Xr];[Zr]=!1;[$r]=!0;[Qr]=void 0;constructor(e,t,n){this[br]=this[Yr]=e,this[Kr]=t,this[Xr]=n}};function ei(e){return e[br]}function ti(e){return`${e[Kr]??`public`}.${e[br]}`}function ni(e){return e!=null&&typeof e.getSQL==`function`}function ri(e){let t={sql:``,params:[]};for(let n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||=[],t.typings.push(...n.typings));return t}var O=class{static[y]=`StringChunk`;value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new k([this])}},k=class e{constructor(e){this.queryChunks=e;for(let t of e)if(b(t,D)){let e=t[D.Symbol.Schema];this.usedTables.push(e===void 0?t[D.Symbol.Name]:e+`.`+t[D.Symbol.Name])}}static[y]=`SQL`;decoder=oi;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return T.startActiveSpan(`drizzle.buildSQL`,t=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(t,n){let r=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:i,escapeName:a,escapeParam:o,prepareTyping:s,inlineParams:c,paramStartIndex:l}=r;return ri(t.map(t=>{if(b(t,O))return{sql:t.value.join(``),params:[]};if(b(t,ii))return{sql:a(t.value),params:[]};if(t===void 0)return{sql:``,params:[]};if(Array.isArray(t)){let e=[new O(`(`)];for(let[n,r]of t.entries())e.push(r),n<t.length-1&&e.push(new O(`, `));return e.push(new O(`)`)),this.buildQueryFromSourceParams(e,r)}if(b(t,e))return this.buildQueryFromSourceParams(t.queryChunks,{...r,inlineParams:c||t.shouldInlineParams});if(b(t,D)){let e=t[D.Symbol.Schema],n=t[D.Symbol.Name];return{sql:e===void 0||t[Zr]?a(n):a(e)+`.`+a(n),params:[]}}if(b(t,x)){let e=i.getColumnCasing(t);if(n.invokeSource===`indexes`)return{sql:a(e),params:[]};let r=t.table[D.Symbol.Schema];return{sql:t.table[Zr]||r===void 0?a(t.table[D.Symbol.Name])+`.`+a(e):a(r)+`.`+a(t.table[D.Symbol.Name])+`.`+a(e),params:[]}}if(b(t,fi)){let e=t[E].schema,n=t[E].name;return{sql:e===void 0||t[E].isAlias?a(n):a(e)+`.`+a(n),params:[]}}if(b(t,ci)){if(b(t.value,li))return{sql:o(l.value++,t),params:[t],typings:[`none`]};let n=t.value===null?null:t.encoder.mapToDriverValue(t.value);if(b(n,e))return this.buildQueryFromSourceParams([n],r);if(c)return{sql:this.mapInlineParam(n,r),params:[]};let i=[`none`];return s&&(i=[s(t.encoder)]),{sql:o(l.value++,n),params:[n],typings:i}}return b(t,li)?{sql:o(l.value++,t),params:[t],typings:[`none`]}:b(t,e.Aliased)&&t.fieldAlias!==void 0?{sql:a(t.fieldAlias),params:[]}:b(t,w)?t._.isWith?{sql:a(t._.alias),params:[]}:this.buildQueryFromSourceParams([new O(`(`),t._.sql,new O(`) `),new ii(t._.alias)],r):Br(t)?t.schema?{sql:a(t.schema)+`.`+a(t.enumName),params:[]}:{sql:a(t.enumName),params:[]}:ni(t)?t.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([t.getSQL()],r):this.buildQueryFromSourceParams([new O(`(`),t.getSQL(),new O(`)`)],r):c?{sql:this.mapInlineParam(t,r),params:[]}:{sql:o(l.value++,t),params:[t],typings:[`none`]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},ii=class{constructor(e){this.value=e}static[y]=`Name`;brand;getSQL(){return new k([this])}};function ai(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var oi={mapFromDriverValue:e=>e},si={mapToDriverValue:e=>e};({...oi,...si});var ci=class{constructor(e,t=si){this.value=e,this.encoder=t}static[y]=`Param`;brand;getSQL(){return new k([this])}};function A(e,...t){let n=[];(t.length>0||e.length>0&&e[0]!==``)&&n.push(new O(e[0]));for(let[r,i]of t.entries())n.push(i,new O(e[r+1]));return new k(n)}(e=>{function t(){return new k([])}e.empty=t;function n(e){return new k(e)}e.fromList=n;function r(e){return new k([new O(e)])}e.raw=r;function i(e,t){let n=[];for(let[r,i]of e.entries())r>0&&t!==void 0&&n.push(t),n.push(i);return new k(n)}e.join=i;function a(e){return new ii(e)}e.identifier=a;function o(e){return new li(e)}e.placeholder=o;function s(e,t){return new ci(e,t)}e.param=s})(A||={}),(e=>{class t{constructor(e,t){this.sql=e,this.fieldAlias=t}static[y]=`SQL.Aliased`;isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(k||={});var li=class{constructor(e){this.name=e}static[y]=`Placeholder`;getSQL(){return new k([this])}};function ui(e,t){return e.map(e=>{if(b(e,li)){if(!(e.name in t))throw Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(b(e,ci)&&b(e.value,li)){if(!(e.value.name in t))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(t[e.value.name])}return e})}var di=Symbol.for(`drizzle:IsDrizzleView`),fi=class{static[y]=`View`;[E];[di]=!0;constructor({name:e,schema:t,selectedFields:n,query:r}){this[E]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new k([this])}};x.prototype.getSQL=function(){return new k([this])},D.prototype.getSQL=function(){return new k([this])},w.prototype.getSQL=function(){return new k([this])};var pi=class{constructor(e){this.table=e}static[y]=`ColumnAliasProxyHandler`;get(e,t){return t===`table`?this.table:e[t]}},mi=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[y]=`TableAliasProxyHandler`;get(e,t){if(t===D.Symbol.IsAlias)return!0;if(t===D.Symbol.Name||this.replaceOriginalName&&t===D.Symbol.OriginalName)return this.alias;if(t===E)return{...e[E],name:this.alias,isAlias:!0};if(t===D.Symbol.Columns){let t=e[D.Symbol.Columns];if(!t)return t;let n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new pi(new Proxy(e,this)))}),n}let n=e[t];return b(n,x)?new Proxy(n,new pi(new Proxy(e,this))):n}};function hi(e,t){return new Proxy(e,new mi(t,!1))}function gi(e,t){return new Proxy(e,new pi(new Proxy(e.table,new mi(t,!1))))}function _i(e,t){return new k.Aliased(vi(e.sql,t),e.fieldAlias)}function vi(e,t){return A.join(e.queryChunks.map(e=>b(e,x)?gi(e,t):b(e,k)?vi(e,t):b(e,k.Aliased)?_i(e,t):e))}var j=class e{static[y]=`SelectionProxyHandler`;config;constructor(e){this.config={...e}}get(t,n){if(n===`_`)return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(n===E)return{...t[E],selectedFields:new Proxy(t[E].selectedFields,this)};if(typeof n==`symbol`)return t[n];let r=(b(t,w)?t._.selectedFields:b(t,fi)?t[E].selectedFields:t)[n];if(b(r,k.Aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!r.isSelectionField)return r.sql;let e=r.clone();return e.isSelectionField=!0,e}if(b(r,k)){if(this.config.sqlBehavior===`sql`)return r;throw Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return b(r,x)?this.config.alias?new Proxy(r,new pi(new Proxy(r.table,new mi(this.config.alias,this.config.replaceOriginalName??!1)))):r:typeof r!=`object`||!r?r:new Proxy(r,new e(this.config))}};function yi(e,t,n){let r={},i=e.reduce((e,{path:i,field:a},o)=>{let s;s=b(a,x)?a:b(a,k)?a.decoder:b(a,w)?a._.sql.decoder:a.sql.decoder;let c=e;for(let[e,l]of i.entries())if(e<i.length-1)l in c||(c[l]={}),c=c[l];else{let e=t[o],u=c[l]=e===null?null:s.mapFromDriverValue(e);if(n&&b(a,x)&&i.length===2){let e=i[0];e in r?typeof r[e]==`string`&&r[e]!==ei(a.table)&&(r[e]=!1):r[e]=u===null&&ei(a.table)}}return e},{});if(n&&Object.keys(r).length>0)for(let[e,t]of Object.entries(r))typeof t==`string`&&!n[t]&&(i[e]=null);return i}function bi(e,t){return Object.entries(e).reduce((e,[n,r])=>{if(typeof n!=`string`)return e;let i=t?[...t,n]:[n];return b(r,x)||b(r,k)||b(r,k.Aliased)||b(r,w)?e.push({path:i,field:r}):b(r,D)?e.push(...bi(r[D.Symbol.Columns],i)):e.push(...bi(r,i)),e},[])}function xi(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function Si(e,t){let n=Object.entries(t).filter(([,e])=>e!==void 0).map(([t,n])=>b(n,k)||b(n,x)?[t,n]:[t,new ci(n,e[D.Symbol.Columns][t])]);if(n.length===0)throw Error(`No values to set`);return Object.fromEntries(n)}function Ci(e,t){for(let n of t)for(let t of Object.getOwnPropertyNames(n.prototype))t!==`constructor`&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function wi(e){return e[D.Symbol.Columns]}function Ti(e){return b(e,w)?e._.alias:b(e,fi)?e[E].name:b(e,k)?void 0:e[D.Symbol.IsAlias]?e[D.Symbol.Name]:e[D.Symbol.BaseName]}function M(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}function Ei(e){if(typeof e!=`object`||!e||e.constructor.name!==`Object`)return!1;if(`logger`in e){let t=typeof e.logger;return t===`boolean`||t===`object`&&typeof e.logger.logQuery==`function`||t===`undefined`}if(`schema`in e){let t=typeof e.schema;return t===`object`||t===`undefined`}if(`casing`in e){let t=typeof e.casing;return t===`string`||t===`undefined`}if(`mode`in e)return e.mode==="default"&&e.mode===`planetscale`&&e.mode===void 0;if(`connection`in e){let t=typeof e.connection;return t===`string`||t===`object`||t===`undefined`}if(`client`in e){let t=typeof e.client;return t===`object`||t===`function`||t===`undefined`}return Object.keys(e).length===0}typeof TextDecoder>`u`||new TextDecoder;var Di=class extends S{static[y]=`PgIntColumnBaseBuilder`;generatedAlwaysAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`always`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`always`};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`byDefault`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`byDefault`};return this.config.hasDefault=!0,this.config.notNull=!0,this}},Oi=class extends Di{static[y]=`PgBigInt53Builder`;constructor(e){super(e,`number`,`PgBigInt53`)}build(e){return new ki(e,this.config)}},ki=class extends C{static[y]=`PgBigInt53`;getSQLType(){return`bigint`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},Ai=class extends Di{static[y]=`PgBigInt64Builder`;constructor(e){super(e,`bigint`,`PgBigInt64`)}build(e){return new ji(e,this.config)}},ji=class extends C{static[y]=`PgBigInt64`;getSQLType(){return`bigint`}mapFromDriverValue(e){return BigInt(e)}};function Mi(e,t){let{name:n,config:r}=M(e,t);return r.mode===`number`?new Oi(n):new Ai(n)}var Ni=class extends S{static[y]=`PgBigSerial53Builder`;constructor(e){super(e,`number`,`PgBigSerial53`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Pi(e,this.config)}},Pi=class extends C{static[y]=`PgBigSerial53`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},Fi=class extends S{static[y]=`PgBigSerial64Builder`;constructor(e){super(e,`bigint`,`PgBigSerial64`),this.config.hasDefault=!0}build(e){return new Ii(e,this.config)}},Ii=class extends C{static[y]=`PgBigSerial64`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return BigInt(e)}};function Li(e,t){let{name:n,config:r}=M(e,t);return r.mode===`number`?new Ni(n):new Fi(n)}var Ri=class extends S{static[y]=`PgBooleanBuilder`;constructor(e){super(e,`boolean`,`PgBoolean`)}build(e){return new zi(e,this.config)}},zi=class extends C{static[y]=`PgBoolean`;getSQLType(){return`boolean`}};function Bi(e){return new Ri(e??``)}var Vi=class extends S{static[y]=`PgCharBuilder`;constructor(e,t){super(e,`string`,`PgChar`),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Hi(e,this.config)}},Hi=class extends C{static[y]=`PgChar`;length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?`char`:`char(${this.length})`}};function Ui(e,t={}){let{name:n,config:r}=M(e,t);return new Vi(n,r)}var Wi=class extends S{static[y]=`PgCidrBuilder`;constructor(e){super(e,`string`,`PgCidr`)}build(e){return new Gi(e,this.config)}},Gi=class extends C{static[y]=`PgCidr`;getSQLType(){return`cidr`}};function Ki(e){return new Wi(e??``)}var qi=class extends S{static[y]=`PgCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`PgCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new Ji(e,this.config)}},Ji=class extends C{static[y]=`PgCustomColumn`;sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==`function`?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==`function`?this.mapTo(e):e}};function Yi(e){return(t,n)=>{let{name:r,config:i}=M(t,n);return new qi(r,i,e)}}var Xi=class extends S{static[y]=`PgDateColumnBaseBuilder`;defaultNow(){return this.default(A`now()`)}},Zi=class extends Xi{static[y]=`PgDateBuilder`;constructor(e){super(e,`date`,`PgDate`)}build(e){return new Qi(e,this.config)}},Qi=class extends C{static[y]=`PgDate`;getSQLType(){return`date`}mapFromDriverValue(e){return typeof e==`string`?new Date(e):e}mapToDriverValue(e){return e.toISOString()}},$i=class extends Xi{static[y]=`PgDateStringBuilder`;constructor(e){super(e,`string`,`PgDateString`)}build(e){return new ea(e,this.config)}},ea=class extends C{static[y]=`PgDateString`;getSQLType(){return`date`}mapFromDriverValue(e){return typeof e==`string`?e:e.toISOString().slice(0,-14)}};function ta(e,t){let{name:n,config:r}=M(e,t);return r?.mode===`date`?new Zi(n):new $i(n)}var na=class extends S{static[y]=`PgDoublePrecisionBuilder`;constructor(e){super(e,`number`,`PgDoublePrecision`)}build(e){return new ra(e,this.config)}},ra=class extends C{static[y]=`PgDoublePrecision`;getSQLType(){return`double precision`}mapFromDriverValue(e){return typeof e==`string`?Number.parseFloat(e):e}};function ia(e){return new na(e??``)}var aa=class extends S{static[y]=`PgInetBuilder`;constructor(e){super(e,`string`,`PgInet`)}build(e){return new oa(e,this.config)}},oa=class extends C{static[y]=`PgInet`;getSQLType(){return`inet`}};function sa(e){return new aa(e??``)}var ca=class extends Di{static[y]=`PgIntegerBuilder`;constructor(e){super(e,`number`,`PgInteger`)}build(e){return new la(e,this.config)}},la=class extends C{static[y]=`PgInteger`;getSQLType(){return`integer`}mapFromDriverValue(e){return typeof e==`string`?Number.parseInt(e):e}};function ua(e){return new ca(e??``)}var da=class extends S{static[y]=`PgIntervalBuilder`;constructor(e,t){super(e,`string`,`PgInterval`),this.config.intervalConfig=t}build(e){return new fa(e,this.config)}},fa=class extends C{static[y]=`PgInterval`;fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){return`interval${this.fields?` ${this.fields}`:``}${this.precision?`(${this.precision})`:``}`}};function pa(e,t={}){let{name:n,config:r}=M(e,t);return new da(n,r)}var ma=class extends S{static[y]=`PgJsonBuilder`;constructor(e){super(e,`json`,`PgJson`)}build(e){return new ha(e,this.config)}},ha=class extends C{static[y]=`PgJson`;constructor(e,t){super(e,t)}getSQLType(){return`json`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function ga(e){return new ma(e??``)}var _a=class extends S{static[y]=`PgJsonbBuilder`;constructor(e){super(e,`json`,`PgJsonb`)}build(e){return new va(e,this.config)}},va=class extends C{static[y]=`PgJsonb`;constructor(e,t){super(e,t)}getSQLType(){return`jsonb`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function ya(e){return new _a(e??``)}var ba=class extends S{static[y]=`PgLineBuilder`;constructor(e){super(e,`array`,`PgLine`)}build(e){return new xa(e,this.config)}},xa=class extends C{static[y]=`PgLine`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(r)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},Sa=class extends S{static[y]=`PgLineABCBuilder`;constructor(e){super(e,`json`,`PgLineABC`)}build(e){return new Ca(e,this.config)}},Ca=class extends C{static[y]=`PgLineABC`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(r)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}};function wa(e,t){let{name:n,config:r}=M(e,t);return!r?.mode||r.mode===`tuple`?new ba(n):new Sa(n)}var Ta=class extends S{static[y]=`PgMacaddrBuilder`;constructor(e){super(e,`string`,`PgMacaddr`)}build(e){return new Ea(e,this.config)}},Ea=class extends C{static[y]=`PgMacaddr`;getSQLType(){return`macaddr`}};function Da(e){return new Ta(e??``)}var Oa=class extends S{static[y]=`PgMacaddr8Builder`;constructor(e){super(e,`string`,`PgMacaddr8`)}build(e){return new ka(e,this.config)}},ka=class extends C{static[y]=`PgMacaddr8`;getSQLType(){return`macaddr8`}};function Aa(e){return new Oa(e??``)}var ja=class extends S{static[y]=`PgNumericBuilder`;constructor(e,t,n){super(e,`string`,`PgNumeric`),this.config.precision=t,this.config.scale=n}build(e){return new Ma(e,this.config)}},Ma=class extends C{static[y]=`PgNumeric`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`string`?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},Na=class extends S{static[y]=`PgNumericNumberBuilder`;constructor(e,t,n){super(e,`number`,`PgNumericNumber`),this.config.precision=t,this.config.scale=n}build(e){return new Pa(e,this.config)}},Pa=class extends C{static[y]=`PgNumericNumber`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},Fa=class extends S{static[y]=`PgNumericBigIntBuilder`;constructor(e,t,n){super(e,`bigint`,`PgNumericBigInt`),this.config.precision=t,this.config.scale=n}build(e){return new Ia(e,this.config)}},Ia=class extends C{static[y]=`PgNumericBigInt`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}};function La(e,t){let{name:n,config:r}=M(e,t),i=r?.mode;return i===`number`?new Na(n,r?.precision,r?.scale):i===`bigint`?new Fa(n,r?.precision,r?.scale):new ja(n,r?.precision,r?.scale)}var Ra=class extends S{static[y]=`PgPointTupleBuilder`;constructor(e){super(e,`array`,`PgPointTuple`)}build(e){return new za(e,this.config)}},za=class extends C{static[y]=`PgPointTuple`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},Ba=class extends S{static[y]=`PgPointObjectBuilder`;constructor(e){super(e,`json`,`PgPointObject`)}build(e){return new Va(e,this.config)}},Va=class extends C{static[y]=`PgPointObject`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}};function Ha(e,t){let{name:n,config:r}=M(e,t);return!r?.mode||r.mode===`tuple`?new Ra(n):new Ba(n)}function Ua(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}function Wa(e,t){let n=new DataView(new ArrayBuffer(8));for(let r=0;r<8;r++)n.setUint8(r,e[t+r]);return n.getFloat64(0,!0)}function Ga(e){let t=Ua(e),n=0,r=t[n];n+=1;let i=new DataView(t.buffer),a=i.getUint32(n,r===1);if(n+=4,a&536870912&&(i.getUint32(n,r===1),n+=4),(a&65535)==1){let e=Wa(t,n);n+=8;let r=Wa(t,n);return n+=8,[e,r]}throw Error(`Unsupported geometry type`)}var Ka=class extends S{static[y]=`PgGeometryBuilder`;constructor(e){super(e,`array`,`PgGeometry`)}build(e){return new qa(e,this.config)}},qa=class extends C{static[y]=`PgGeometry`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){return Ga(e)}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},Ja=class extends S{static[y]=`PgGeometryObjectBuilder`;constructor(e){super(e,`json`,`PgGeometryObject`)}build(e){return new Ya(e,this.config)}},Ya=class extends C{static[y]=`PgGeometryObject`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){let t=Ga(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}};function Xa(e,t){let{name:n,config:r}=M(e,t);return!r?.mode||r.mode===`tuple`?new Ka(n):new Ja(n)}var Za=class extends S{static[y]=`PgRealBuilder`;constructor(e,t){super(e,`number`,`PgReal`),this.config.length=t}build(e){return new Qa(e,this.config)}},Qa=class extends C{static[y]=`PgReal`;constructor(e,t){super(e,t)}getSQLType(){return`real`}mapFromDriverValue=e=>typeof e==`string`?Number.parseFloat(e):e};function $a(e){return new Za(e??``)}var eo=class extends S{static[y]=`PgSerialBuilder`;constructor(e){super(e,`number`,`PgSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new to(e,this.config)}},to=class extends C{static[y]=`PgSerial`;getSQLType(){return`serial`}};function no(e){return new eo(e??``)}var ro=class extends Di{static[y]=`PgSmallIntBuilder`;constructor(e){super(e,`number`,`PgSmallInt`)}build(e){return new io(e,this.config)}},io=class extends C{static[y]=`PgSmallInt`;getSQLType(){return`smallint`}mapFromDriverValue=e=>typeof e==`string`?Number(e):e};function ao(e){return new ro(e??``)}var oo=class extends S{static[y]=`PgSmallSerialBuilder`;constructor(e){super(e,`number`,`PgSmallSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new so(e,this.config)}},so=class extends C{static[y]=`PgSmallSerial`;getSQLType(){return`smallserial`}};function co(e){return new oo(e??``)}var lo=class extends S{static[y]=`PgTextBuilder`;constructor(e,t){super(e,`string`,`PgText`),this.config.enumValues=t.enum}build(e){return new uo(e,this.config)}},uo=class extends C{static[y]=`PgText`;enumValues=this.config.enumValues;getSQLType(){return`text`}};function N(e,t={}){let{name:n,config:r}=M(e,t);return new lo(n,r)}var fo=class extends Xi{constructor(e,t,n){super(e,`string`,`PgTime`),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static[y]=`PgTimeBuilder`;build(e){return new po(e,this.config)}},po=class extends C{static[y]=`PgTime`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function mo(e,t={}){let{name:n,config:r}=M(e,t);return new fo(n,r.withTimezone??!1,r.precision)}var ho=class extends Xi{static[y]=`PgTimestampBuilder`;constructor(e,t,n){super(e,`date`,`PgTimestamp`),this.config.withTimezone=t,this.config.precision=n}build(e){return new go(e,this.config)}},go=class extends C{static[y]=`PgTimestamp`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:` (${this.precision})`}${this.withTimezone?` with time zone`:``}`}mapFromDriverValue(e){return typeof e==`string`?new Date(this.withTimezone?e:e+`+0000`):e}mapToDriverValue=e=>e.toISOString()},_o=class extends Xi{static[y]=`PgTimestampStringBuilder`;constructor(e,t,n){super(e,`string`,`PgTimestampString`),this.config.withTimezone=t,this.config.precision=n}build(e){return new vo(e,this.config)}},vo=class extends C{static[y]=`PgTimestampString`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}mapFromDriverValue(e){if(typeof e==`string`)return e;let t=e.toISOString().slice(0,-1).replace(`T`,` `);if(this.withTimezone){let n=e.getTimezoneOffset();return`${t}${n<=0?`+`:`-`}${Math.floor(Math.abs(n)/60).toString().padStart(2,`0`)}`}return t}};function P(e,t={}){let{name:n,config:r}=M(e,t);return r?.mode===`string`?new _o(n,r.withTimezone??!1,r.precision):new ho(n,r?.withTimezone??!1,r?.precision)}var yo=class extends S{static[y]=`PgUUIDBuilder`;constructor(e){super(e,`string`,`PgUUID`)}defaultRandom(){return this.default(A`gen_random_uuid()`)}build(e){return new bo(e,this.config)}},bo=class extends C{static[y]=`PgUUID`;getSQLType(){return`uuid`}};function xo(e){return new yo(e??``)}var So=class extends S{static[y]=`PgVarcharBuilder`;constructor(e,t){super(e,`string`,`PgVarchar`),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Co(e,this.config)}},Co=class extends C{static[y]=`PgVarchar`;length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?`varchar`:`varchar(${this.length})`}};function wo(e,t={}){let{name:n,config:r}=M(e,t);return new So(n,r)}var To=class extends S{static[y]=`PgBinaryVectorBuilder`;constructor(e,t){super(e,`string`,`PgBinaryVector`),this.config.dimensions=t.dimensions}build(e){return new Eo(e,this.config)}},Eo=class extends C{static[y]=`PgBinaryVector`;dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}};function Do(e,t){let{name:n,config:r}=M(e,t);return new To(n,r)}var Oo=class extends S{static[y]=`PgHalfVectorBuilder`;constructor(e,t){super(e,`array`,`PgHalfVector`),this.config.dimensions=t.dimensions}build(e){return new ko(e,this.config)}},ko=class extends C{static[y]=`PgHalfVector`;dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function Ao(e,t){let{name:n,config:r}=M(e,t);return new Oo(n,r)}var jo=class extends S{static[y]=`PgSparseVectorBuilder`;constructor(e,t){super(e,`string`,`PgSparseVector`),this.config.dimensions=t.dimensions}build(e){return new Mo(e,this.config)}},Mo=class extends C{static[y]=`PgSparseVector`;dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function No(e,t){let{name:n,config:r}=M(e,t);return new jo(n,r)}var Po=class extends S{static[y]=`PgVectorBuilder`;constructor(e,t){super(e,`array`,`PgVector`),this.config.dimensions=t.dimensions}build(e){return new Fo(e,this.config)}},Fo=class extends C{static[y]=`PgVector`;dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function Io(e,t){let{name:n,config:r}=M(e,t);return new Po(n,r)}function Lo(){return{bigint:Mi,bigserial:Li,boolean:Bi,char:Ui,cidr:Ki,customType:Yi,date:ta,doublePrecision:ia,inet:sa,integer:ua,interval:pa,json:ga,jsonb:ya,line:wa,macaddr:Da,macaddr8:Aa,numeric:La,point:Ha,geometry:Xa,real:$a,serial:no,smallint:ao,smallserial:co,text:N,time:mo,timestamp:P,uuid:xo,varchar:wo,bit:Do,halfvec:Ao,sparsevec:No,vector:Io}}var Ro=Symbol.for(`drizzle:PgInlineForeignKeys`),zo=Symbol.for(`drizzle:EnableRLS`),Bo=class extends D{static[y]=`PgTable`;static Symbol=Object.assign({},D.Symbol,{InlineForeignKeys:Ro,EnableRLS:zo});[Ro]=[];[zo]=!1;[D.Symbol.ExtraConfigBuilder]=void 0;[D.Symbol.ExtraConfigColumns]={}};function Vo(e,t,n,r,i=e){let a=new Bo(e,r,i),o=typeof t==`function`?t(Lo()):t,s=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;n.setName(e);let r=n.build(a);return a[Ro].push(...n.buildForeignKeys(r,a)),[e,r]})),c=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;return n.setName(e),[e,n.buildExtraConfigColumn(a)]})),l=Object.assign(a,s);return l[D.Symbol.Columns]=s,l[D.Symbol.ExtraConfigColumns]=c,n&&(l[Bo.Symbol.ExtraConfigBuilder]=n),Object.assign(l,{enableRLS:()=>(l[Bo.Symbol.EnableRLS]=!0,l)})}var Ho=(e,t,n)=>Vo(e,t,n,void 0),Uo=class{constructor(e,t){this.name=e,this.value=t}static[y]=`PgCheckBuilder`;brand;build(e){return new Wo(e,this)}},Wo=class{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[y]=`PgCheck`;name;value};function Go(e,t){return new Uo(e,t)}var Ko=class{constructor(e,t){this.unique=e,this.name=t}static[y]=`PgIndexBuilderOn`;on(...e){return new qo(e.map(e=>{if(b(e,k))return e;e=e;let t=new Pr(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...e){return new qo(e.map(e=>{if(b(e,k))return e;e=e;let t=new Pr(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,t}),this.unique,!0,this.name)}using(e,...t){return new qo(t.map(e=>{if(b(e,k))return e;e=e;let t=new Pr(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!0,this.name,e)}},qo=class{static[y]=`PgIndexBuilder`;config;constructor(e,t,n,r,i=`btree`){this.config={name:r,columns:e,unique:t,only:n,method:i}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new Jo(this.config,e)}},Jo=class{static[y]=`PgIndex`;config;constructor(e,t){this.config={...e,table:t}}};function F(e){return new Ko(!1,e)}function Yo(e){return new Ko(!0,e)}function Xo(...e){return e[0].columns?new Zo(e[0].columns,e[0].name):new Zo(e)}var Zo=class{static[y]=`PgPrimaryKeyBuilder`;columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Qo(e,this.columns,this.name)}},Qo=class{constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[y]=`PgPrimaryKey`;columns;name;getName(){return this.name??`${this.table[Bo.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}},$o=Symbol.for(`drizzle:PgViewConfig`);function es(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join(`_`)}function ts(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function ns(e){return e}var rs=class{static[y]=`CasingCache`;cache={};cachedTables={};convert;constructor(e){this.convert=e===`snake_case`?es:e===`camelCase`?ts:ns}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=`${e.table[D.Symbol.Schema]??`public`}.${e.table[D.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let t=`${e[D.Symbol.Schema]??`public`}.${e[D.Symbol.OriginalName]}`;if(!this.cachedTables[t]){for(let n of Object.values(e[D.Symbol.Columns])){let e=`${t}.${n.name}`;this.cache[e]=this.convert(n.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}},is=class extends Error{static[y]=`DrizzleError`;constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}},as=class e extends Error{constructor(t,n,r){super(`Failed query: ${t}
14
- params: ${n}`),this.query=t,this.params=n,this.cause=r,Error.captureStackTrace(this,e),r&&(this.cause=r)}},os=class extends is{static[y]=`TransactionRollbackError`;constructor(){super({message:`Rollback`})}};function ss(e,t){return ai(t)&&!ni(e)&&!b(e,ci)&&!b(e,li)&&!b(e,x)&&!b(e,D)&&!b(e,fi)?new ci(e,t):e}var cs=(e,t)=>A`${e} = ${ss(t,e)}`,ls=(e,t)=>A`${e} <> ${ss(t,e)}`;function us(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new k(t):new k([new O(`(`),A.join(t,new O(` and `)),new O(`)`)])}function ds(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new k(t):new k([new O(`(`),A.join(t,new O(` or `)),new O(`)`)])}function fs(e){return A`not ${e}`}var ps=(e,t)=>A`${e} > ${ss(t,e)}`,ms=(e,t)=>A`${e} >= ${ss(t,e)}`,hs=(e,t)=>A`${e} < ${ss(t,e)}`,gs=(e,t)=>A`${e} <= ${ss(t,e)}`;function _s(e,t){return Array.isArray(t)?t.length===0?A`false`:A`${e} in ${t.map(t=>ss(t,e))}`:A`${e} in ${ss(t,e)}`}function vs(e,t){return Array.isArray(t)?t.length===0?A`true`:A`${e} not in ${t.map(t=>ss(t,e))}`:A`${e} not in ${ss(t,e)}`}function ys(e){return A`${e} is null`}function bs(e){return A`${e} is not null`}function xs(e){return A`exists ${e}`}function Ss(e){return A`not exists ${e}`}function Cs(e,t,n){return A`${e} between ${ss(t,e)} and ${ss(n,e)}`}function ws(e,t,n){return A`${e} not between ${ss(t,e)} and ${ss(n,e)}`}function Ts(e,t){return A`${e} like ${t}`}function Es(e,t){return A`${e} not like ${t}`}function Ds(e,t){return A`${e} ilike ${t}`}function Os(e,t){return A`${e} not ilike ${t}`}function ks(e){return A`${e} asc`}function As(e){return A`${e} desc`}var js=class{constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[D.Symbol.Name]}static[y]=`Relation`;referencedTableName;fieldName},Ms=class{constructor(e,t){this.table=e,this.config=t}static[y]=`Relations`},Ns=class e extends js{constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[y]=`One`;withFieldName(t){let n=new e(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=t,n}},Ps=class e extends js{constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[y]=`Many`;withFieldName(t){let n=new e(this.sourceTable,this.referencedTable,this.config);return n.fieldName=t,n}};function Fs(){return{and:us,between:Cs,eq:cs,exists:xs,gt:ps,gte:ms,ilike:Ds,inArray:_s,isNull:ys,isNotNull:bs,like:Ts,lt:hs,lte:gs,ne:ls,not:fs,notBetween:ws,notExists:Ss,notLike:Es,notIlike:Os,notInArray:vs,or:ds,sql:A}}function Is(){return{sql:A,asc:ks,desc:As}}function Ls(e,t){Object.keys(e).length===1&&`default`in e&&!b(e.default,D)&&(e=e.default);let n={},r={},i={};for(let[a,o]of Object.entries(e))if(b(o,D)){let e=ti(o),t=r[e];n[e]=a,i[a]={tsName:a,dbName:o[D.Symbol.Name],schema:o[D.Symbol.Schema],columns:o[D.Symbol.Columns],relations:t?.relations??{},primaryKey:t?.primaryKey??[]};for(let e of Object.values(o[D.Symbol.Columns]))e.primary&&i[a].primaryKey.push(e);let s=o[D.Symbol.ExtraConfigBuilder]?.(o[D.Symbol.ExtraConfigColumns]);if(s)for(let e of Object.values(s))b(e,Zo)&&i[a].primaryKey.push(...e.columns)}else if(b(o,Ms)){let e=ti(o.table),a=n[e],s=o.config(t(o.table)),c;for(let[t,n]of Object.entries(s))if(a){let e=i[a];e.relations[t]=n}else e in r||(r[e]={relations:{},primaryKey:c}),r[e].relations[t]=n}return{tables:i,tableNamesMap:n}}function Rs(e,t){return new Ms(e,e=>Object.fromEntries(Object.entries(t(e)).map(([e,t])=>[e,t.withFieldName(e)])))}function zs(e){return function(t,n){return new Ns(e,t,n,n?.fields.reduce((e,t)=>e&&t.notNull,!0)??!1)}}function Bs(e){return function(t,n){return new Ps(e,t,n)}}function Vs(e,t,n){if(b(n,Ns)&&n.config)return{fields:n.config.fields,references:n.config.references};let r=t[ti(n.referencedTable)];if(!r)throw Error(`Table "${n.referencedTable[D.Symbol.Name]}" not found in schema`);let i=e[r];if(!i)throw Error(`Table "${r}" not found in schema`);let a=n.sourceTable,o=t[ti(a)];if(!o)throw Error(`Table "${a[D.Symbol.Name]}" not found in schema`);let s=[];for(let e of Object.values(i.relations))(n.relationName&&n!==e&&e.relationName===n.relationName||!n.relationName&&e.referencedTable===n.sourceTable)&&s.push(e);if(s.length>1)throw n.relationName?Error(`There are multiple relations with name "${n.relationName}" in table "${r}"`):Error(`There are multiple relations between "${r}" and "${n.sourceTable[D.Symbol.Name]}". Please specify relation name`);if(s[0]&&b(s[0],Ns)&&s[0].config)return{fields:s[0].config.references,references:s[0].config.fields};throw Error(`There is not enough information to infer relation "${o}.${n.fieldName}"`)}function Hs(e){return{one:zs(e),many:Bs(e)}}function Us(e,t,n,r,i=e=>e){let a={};for(let[o,s]of r.entries())if(s.isJson){let r=t.relations[s.tsKey],c=n[o],l=typeof c==`string`?JSON.parse(c):c;a[s.tsKey]=b(r,Ns)?l&&Us(e,e[s.relationTableTsKey],l,s.selection,i):l.map(t=>Us(e,e[s.relationTableTsKey],t,s.selection,i))}else{let e=i(n[o]),t=s.field,r;r=b(t,x)?t:b(t,k)?t.decoder:t.sql.decoder,a[s.tsKey]=e===null?null:r.mapFromDriverValue(e)}return a}var Ws=class extends fi{static[y]=`PgViewBase`},Gs=class{static[y]=`PgDialect`;casing;constructor(e){this.casing=new rs(e?.casing)}async migrate(e,t,n){let r=typeof n==`string`?`__drizzle_migrations`:n.migrationsTable??`__drizzle_migrations`,i=typeof n==`string`?`drizzle`:n.migrationsSchema??`drizzle`,a=A`
15
- CREATE TABLE IF NOT EXISTS ${A.identifier(i)}.${A.identifier(r)} (
16
- id SERIAL PRIMARY KEY,
17
- hash text NOT NULL,
18
- created_at bigint
19
- )
20
- `;await t.execute(A`CREATE SCHEMA IF NOT EXISTS ${A.identifier(i)}`),await t.execute(a);let o=(await t.all(A`select id, hash, created_at from ${A.identifier(i)}.${A.identifier(r)} order by created_at desc limit 1`))[0];await t.transaction(async t=>{for await(let n of e)if(!o||Number(o.created_at)<n.folderMillis){for(let e of n.sql)await t.execute(A.raw(e));await t.execute(A`insert into ${A.identifier(i)}.${A.identifier(r)} ("hash", "created_at") values(${n.hash}, ${n.folderMillis})`)}})}escapeName(e){return`"${e.replace(/"/g,`""`)}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[A`with `];for(let[n,r]of e.entries())t.push(A`${A.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(A`, `);return t.push(A` `),A.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r}){let i=this.buildWithCTE(r),a=n?A` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,o=t?A` where ${t}`:void 0;return A`${i}delete from ${e}${o}${a}`}buildUpdateSet(e,t){let n=e[D.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return A.join(r.flatMap((e,r)=>{let a=n[e],o=a.onUpdateFn?.(),s=t[e]??(b(o,k)?o:A.param(o,a)),c=A`${A.identifier(this.casing.getColumnCasing(a))} = ${s}`;return r<i-1?[c,A.raw(`, `)]:[c]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,from:a,joins:o}){let s=this.buildWithCTE(i),c=e[Bo.Symbol.Name],l=e[Bo.Symbol.Schema],u=e[Bo.Symbol.OriginalName],d=c===u?void 0:c,f=A`${l?A`${A.identifier(l)}.`:void 0}${A.identifier(u)}${d&&A` ${A.identifier(d)}`}`,p=this.buildUpdateSet(e,t),m=a&&A.join([A.raw(` from `),this.buildFromTable(a)]),h=this.buildJoins(o),g=r?A` returning ${this.buildSelection(r,{isSingleTable:!a})}`:void 0,_=n?A` where ${n}`:void 0;return A`${s}update ${f} set ${p}${m}${h}${_}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let n=e.length,r=e.flatMap(({field:e},r)=>{let i=[];if(b(e,k.Aliased)&&e.isSelectionField)i.push(A.identifier(e.fieldAlias));else if(b(e,k.Aliased)||b(e,k)){let n=b(e,k.Aliased)?e.sql:e;t?i.push(new k(n.queryChunks.map(e=>b(e,C)?A.identifier(this.casing.getColumnCasing(e)):e))):i.push(n),b(e,k.Aliased)&&i.push(A` as ${A.identifier(e.fieldAlias)}`)}else if(b(e,x))t?i.push(A.identifier(this.casing.getColumnCasing(e))):i.push(e);else if(b(e,w)){let t=Object.entries(e._.selectedFields);if(t.length===1){let n=t[0][1],r=b(n,k)?n.decoder:b(n,x)?{mapFromDriverValue:e=>n.mapFromDriverValue(e)}:n.sql.decoder;r&&(e._.sql.decoder=r)}i.push(e)}return r<n-1&&i.push(A`, `),i});return A.join(r)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[n,r]of e.entries()){n===0&&t.push(A` `);let i=r.table,a=r.lateral?A` lateral`:void 0,o=r.on?A` on ${r.on}`:void 0;if(b(i,Bo)){let e=i[Bo.Symbol.Name],n=i[Bo.Symbol.Schema],s=i[Bo.Symbol.OriginalName],c=e===s?void 0:r.alias;t.push(A`${A.raw(r.joinType)} join${a} ${n?A`${A.identifier(n)}.`:void 0}${A.identifier(s)}${c&&A` ${A.identifier(c)}`}${o}`)}else if(b(i,fi)){let e=i[E].name,n=i[E].schema,s=i[E].originalName,c=e===s?void 0:r.alias;t.push(A`${A.raw(r.joinType)} join${a} ${n?A`${A.identifier(n)}.`:void 0}${A.identifier(s)}${c&&A` ${A.identifier(c)}`}${o}`)}else t.push(A`${A.raw(r.joinType)} join${a} ${i}${o}`);n<e.length-1&&t.push(A` `)}return A.join(t)}buildFromTable(e){if(b(e,D)&&e[D.Symbol.IsAlias]){let t=A`${A.identifier(e[D.Symbol.OriginalName])}`;return e[D.Symbol.Schema]&&(t=A`${A.identifier(e[D.Symbol.Schema])}.${t}`),A`${t} ${A.identifier(e[D.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,lockingClause:d,distinct:f,setOperators:p}){let m=n??bi(t);for(let e of m)if(b(e.field,x)&&ei(e.field.table)!==(b(a,w)?a._.alias:b(a,Ws)?a[E].name:b(a,k)?void 0:ei(a))&&!(e=>o?.some(({alias:t})=>t===(e[D.Symbol.IsAlias]?ei(e):e[D.Symbol.BaseName])))(e.field.table)){let t=ei(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let h=!o||o.length===0,g=this.buildWithCTE(e),_;f&&(_=f===!0?A` distinct`:A` distinct on (${A.join(f.on,A`, `)})`);let ee=this.buildSelection(m,{isSingleTable:h}),te=this.buildFromTable(a),ne=this.buildJoins(o),re=r?A` where ${r}`:void 0,ie=i?A` having ${i}`:void 0,ae;s&&s.length>0&&(ae=A` order by ${A.join(s,A`, `)}`);let oe;c&&c.length>0&&(oe=A` group by ${A.join(c,A`, `)}`);let se=typeof l==`object`||typeof l==`number`&&l>=0?A` limit ${l}`:void 0,ce=u?A` offset ${u}`:void 0,le=A.empty();if(d){let e=A` for ${A.raw(d.strength)}`;d.config.of&&e.append(A` of ${A.join(Array.isArray(d.config.of)?d.config.of:[d.config.of],A`, `)}`),d.config.noWait?e.append(A` nowait`):d.config.skipLocked&&e.append(A` skip locked`),le.append(e)}let ue=A`${g}select${_} ${ee} from ${te}${ne}${re}${oe}${ie}${ae}${se}${ce}${le}`;return p.length>0?this.buildSetOperations(ue,p):ue}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=A`(${e.getSQL()}) `,c=A`(${r.getSQL()})`,l;if(a&&a.length>0){let e=[];for(let t of a)if(b(t,C))e.push(A.identifier(t.name));else if(b(t,k)){for(let e=0;e<t.queryChunks.length;e++){let n=t.queryChunks[e];b(n,C)&&(t.queryChunks[e]=A.identifier(n.name))}e.push(A`${t}`)}else e.push(A`${t}`);l=A` order by ${A.join(e,A`, `)} `}let u=typeof i==`object`||typeof i==`number`&&i>=0?A` limit ${i}`:void 0,d=A.raw(`${t} ${n?`all `:``}`),f=o?A` offset ${o}`:void 0;return A`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a,overridingSystemValue_:o}){let s=[],c=e[D.Symbol.Columns],l=Object.entries(c).filter(([e,t])=>!t.shouldDisableInsert()),u=l.map(([,e])=>A.identifier(this.casing.getColumnCasing(e)));if(a){let e=t;b(e,k)?s.push(e):s.push(e.getSQL())}else{let e=t;s.push(A.raw(`values `));for(let[t,n]of e.entries()){let r=[];for(let[e,t]of l){let i=n[e];if(i===void 0||b(i,ci)&&i.value===void 0){if(t.defaultFn!==void 0){let e=t.defaultFn(),n=b(e,k)?e:A.param(e,t);r.push(n)}else if(!t.default&&t.onUpdateFn!==void 0){let e=t.onUpdateFn(),n=b(e,k)?e:A.param(e,t);r.push(n)}else r.push(A`default`)}else r.push(i)}s.push(r),t<e.length-1&&s.push(A`, `)}}let d=this.buildWithCTE(i),f=A.join(s),p=r?A` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,m=n?A` on conflict ${n}`:void 0,h=o===!0?A`overriding system value `:void 0;return A`${d}insert into ${e} ${u} ${h}${f}${m}${p}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:n}){let r=t?A` concurrently`:void 0,i=n?A` with no data`:void 0;return A`refresh materialized view${r} ${e}${i}`}prepareTyping(e){return b(e,va)||b(e,ha)?`json`:b(e,Ma)?`decimal`:b(e,po)?`time`:b(e,go)||b(e,vo)?`timestamp`:b(e,Qi)||b(e,ea)?`date`:b(e,bo)?`uuid`:`none`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:n,table:r,tableConfig:i,queryConfig:a,tableAlias:o,nestedQueryRelation:s,joinOn:c}){let l=[],u,d,f=[],p,m=[];if(a===!0)l=Object.entries(i.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:gi(t,o),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let r=Object.fromEntries(Object.entries(i.columns).map(([e,t])=>[e,gi(t,o)]));if(a.where){let e=typeof a.where==`function`?a.where(r,Fs()):a.where;p=e&&vi(e,o)}let s=[],c=[];if(a.columns){let e=!1;for(let[t,n]of Object.entries(a.columns))n!==void 0&&t in i.columns&&(!e&&n===!0&&(e=!0),c.push(t));c.length>0&&(c=e?c.filter(e=>a.columns?.[e]===!0):Object.keys(i.columns).filter(e=>!c.includes(e)))}else c=Object.keys(i.columns);for(let e of c){let t=i.columns[e];s.push({tsKey:e,value:t})}let h=[];a.with&&(h=Object.entries(a.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:i.relations[e]})));let g;if(a.extras){g=typeof a.extras==`function`?a.extras(r,{sql:A}):a.extras;for(let[e,t]of Object.entries(g))s.push({tsKey:e,value:_i(t,o)})}for(let{tsKey:e,value:t}of s)l.push({dbKey:b(t,k.Aliased)?t.fieldAlias:i.columns[e].name,tsKey:e,field:b(t,x)?gi(t,o):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let _=typeof a.orderBy==`function`?a.orderBy(r,Is()):a.orderBy??[];Array.isArray(_)||(_=[_]),f=_.map(e=>b(e,x)?gi(e,o):vi(e,o)),u=a.limit,d=a.offset;for(let{tsKey:r,queryConfig:i,relation:a}of h){let s=Vs(t,n,a),c=n[ti(a.referencedTable)],u=`${o}_${r}`,d=us(...s.fields.map((e,t)=>cs(gi(s.references[t],u),gi(e,o)))),f=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:n,table:e[c],tableConfig:t[c],queryConfig:b(a,Ns)?i===!0?{limit:1}:{...i,limit:1}:i,tableAlias:u,joinOn:d,nestedQueryRelation:a}),p=A`${A.identifier(u)}.${A.identifier(`data`)}`.as(r);m.push({on:A`true`,table:new w(f.sql,{},u),alias:u,joinType:`left`,lateral:!0}),l.push({dbKey:r,tsKey:r,field:p,relationTableTsKey:c,isJson:!0,selection:f.selection})}}if(l.length===0)throw new is({message:`No fields selected for table "${i.tsName}" ("${o}")`});let h;if(p=us(c,p),s){let e=A`json_build_array(${A.join(l.map(({field:e,tsKey:t,isJson:n})=>n?A`${A.identifier(`${o}_${t}`)}.${A.identifier(`data`)}`:b(e,k.Aliased)?e.sql:e),A`, `)})`;b(s,Ps)&&(e=A`coalesce(json_agg(${e}${f.length>0?A` order by ${A.join(f,A`, `)}`:void 0}), '[]'::json)`);let t=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:i.tsName,selection:l}];u!==void 0||d!==void 0||f.length>0?(h=this.buildSelectQuery({table:hi(r,o),fields:{},fieldsFlat:[{path:[],field:A.raw(`*`)}],where:p,limit:u,offset:d,orderBy:f,setOperators:[]}),p=void 0,u=void 0,d=void 0,f=[]):h=hi(r,o),h=this.buildSelectQuery({table:b(h,Bo)?h:new w(h,{},o),fields:{},fieldsFlat:t.map(({field:e})=>({path:[],field:b(e,x)?gi(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]})}else h=this.buildSelectQuery({table:hi(r,o),fields:{},fieldsFlat:l.map(({field:e})=>({path:[],field:b(e,x)?gi(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]});return{tableTsKey:i.tsName,sql:h,selection:l}}},Ks=class{static[y]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},qs=class{static[y]=`PgSelectBuilder`;fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,n=e,r;return r=this.fields?this.fields:b(n,w)?Object.fromEntries(Object.keys(n._.selectedFields).map(e=>[e,n[e]])):b(n,Ws)?n[E].selectedFields:b(n,k)?{}:wi(n),new Ys({table:n,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},Js=class extends Ks{static[y]=`PgSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=Ti(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of gc(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(n,r)=>{let i=this.tableName,a=Ti(n);for(let e of gc(n))this.usedTables.add(e);if(typeof a==`string`&&this.config.joins?.some(e=>e.alias===a))throw Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==`string`&&(this.config.fields={[i]:this.config.fields}),typeof a==`string`&&!b(n,k))){let e=b(n,w)?n._.selectedFields:b(n,fi)?n[E].selectedFields:n[D.Symbol.Columns];this.config.fields[a]=e}if(typeof r==`function`&&(r=r(new Proxy(this.config.fields,new j({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:r,table:n,joinType:e,alias:a,lateral:t}),typeof a==`string`)switch(e){case`left`:this.joinsNotNullableMap[a]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[a]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[a]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[a]=!1}return this}}leftJoin=this.createJoin(`left`,!1);leftJoinLateral=this.createJoin(`left`,!0);rightJoin=this.createJoin(`right`,!1);innerJoin=this.createJoin(`inner`,!1);innerJoinLateral=this.createJoin(`inner`,!0);fullJoin=this.createJoin(`full`,!1);crossJoin=this.createJoin(`cross`,!1);crossJoinLateral=this.createJoin(`cross`,!0);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(Zs()):n;if(!xi(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);intersectAll=this.createSetOperator(`intersect`,!0);except=this.createSetOperator(`except`,!1);exceptAll=this.createSetOperator(`except`,!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new j({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new j({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new j({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new j({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...gc(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...gc(e.table));return new Proxy(new w(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new j({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new j({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},Ys=class extends Js{static[y]=`PgSelect`;_prepare(e){let{session:t,config:n,dialect:r,joinsNotNullableMap:i,authToken:a,cacheConfig:o,usedTables:s}=this;if(!t)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let{fields:c}=n;return T.startActiveSpan(`drizzle.prepareQuery`,()=>{let n=bi(c),l=t.prepareQuery(r.sqlToQuery(this.getSQL()),n,e,!0,void 0,{type:`select`,tables:[...s]},o);return l.joinsNotNullableMap=i,l.setToken(a)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>T.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))};Ci(Ys,[vr]);function Xs(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!xi(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var Zs=()=>({union:Qs,unionAll:$s,intersect:ec,intersectAll:tc,except:nc,exceptAll:rc}),Qs=Xs(`union`,!1),$s=Xs(`union`,!0),ec=Xs(`intersect`,!1),tc=Xs(`intersect`,!0),nc=Xs(`except`,!1),rc=Xs(`except`,!0),ic=class{static[y]=`PgQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=b(e,Gs)?e:void 0,this.dialectConfig=b(e,Gs)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new Gr(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new j({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new qs({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(e){return new qs({fields:e??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function i(e,n){return new qs({fields:n??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:e}})}return{select:n,selectDistinct:r,selectDistinctOn:i}}select(e){return new qs({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new qs({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new qs({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||=new Gs(this.dialectConfig),this.dialect}},ac=class{constructor(e,t){this.name=e,this.schema=t}static[y]=`PgDefaultViewBuilderCore`;config={};with(e){return this.config.with=e,this}},oc=class extends ac{static[y]=`PgViewBuilder`;as(e){typeof e==`function`&&(e=e(new ic));let t=new j({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new dc({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},sc=class extends ac{static[y]=`PgManualViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=wi(Ho(e,t))}existing(){return new Proxy(new dc({pgConfig:void 0,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new j({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new dc({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new j({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},cc=class{constructor(e,t){this.name=e,this.schema=t}static[y]=`PgMaterializedViewBuilderCore`;config={};using(e){return this.config.using=e,this}with(e){return this.config.with=e,this}tablespace(e){return this.config.tablespace=e,this}withNoData(){return this.config.withNoData=!0,this}},lc=class extends cc{static[y]=`PgMaterializedViewBuilder`;as(e){typeof e==`function`&&(e=e(new ic));let t=new j({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new pc({pgConfig:{with:this.config.with,using:this.config.using,tablespace:this.config.tablespace,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},uc=class extends cc{static[y]=`PgManualMaterializedViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=wi(Ho(e,t))}existing(){return new Proxy(new pc({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new j({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new pc({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new j({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},dc=class extends Ws{static[y]=`PgView`;[$o];constructor({pgConfig:e,config:t}){super(t),e&&(this[$o]={with:e.with})}},fc=Symbol.for(`drizzle:PgMaterializedViewConfig`),pc=class extends Ws{static[y]=`PgMaterializedView`;[fc];constructor({pgConfig:e,config:t}){super(t),this[fc]={with:e?.with,using:e?.using,tablespace:e?.tablespace,withNoData:e?.withNoData}}};function mc(e,t,n){return t?new sc(e,t,n):new oc(e,n)}function hc(e,t,n){return t?new uc(e,t,n):new lc(e,n)}function gc(e){return b(e,Bo)?[e[Kr]?`${e[Kr]}.${e[D.Symbol.BaseName]}`:e[D.Symbol.BaseName]]:b(e,w)?e._.usedTables??[]:b(e,k)?e.usedTables??[]:[]}var _c=class extends vr{constructor(e,t,n,r){super(),this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[y]=`PgDelete`;config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[D.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=bi(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return T.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`delete`,tables:gc(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>T.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j({alias:ei(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},vc=class{constructor(e,t,n,r,i){this.table=e,this.session=t,this.dialect=n,this.withList=r,this.overridingSystemValue_=i}static[y]=`PgInsertBuilder`;authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let t=e.map(e=>{let t={},n=this.table[D.Symbol.Columns];for(let r of Object.keys(e)){let i=e[r];t[r]=b(i,k)?i:new ci(i,n[r])}return t});return new yc(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e==`function`?e(new ic):e;if(!b(t,k)&&!xi(this.table[qr],t._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new yc(this.table,t,this.session,this.dialect,this.withList,!0)}},yc=class extends vr{constructor(e,t,n,r,i,a,o){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a,overridingSystemValue_:o}}static[y]=`PgInsert`;config;cacheConfig;returning(e=this.config.table[D.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=bi(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=A`do nothing`;else{let t=``;t=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?A` where ${e.where}`:void 0;this.config.onConflict=A`(${A.raw(t)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);let t=e.where?A` where ${e.where}`:void 0,n=e.targetWhere?A` where ${e.targetWhere}`:void 0,r=e.setWhere?A` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,Si(this.config.table,e.set)),a=``;return a=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=A`(${A.raw(a)})${n} do update set ${i}${t}${r}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return T.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:gc(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>T.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j({alias:ei(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},bc=class extends vr{constructor(e,t,n){super(),this.session=t,this.dialect=n,this.config={view:e}}static[y]=`PgRefreshMaterializedView`;config;concurrently(){if(this.config.withNoData!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return T.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>T.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))},xc=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[y]=`PgUpdateBuilder`;authToken;setToken(e){return this.authToken=e,this}set(e){return new Sc(this.table,Si(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},Sc=class extends vr{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]},this.tableName=Ti(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}static[y]=`PgUpdate`;config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,n=Ti(t);return typeof n==`string`&&(this.joinsNotNullableMap[n]=!0),this.config.from=t,this}getTableLikeFields(e){return b(e,Bo)?e[D.Symbol.Columns]:b(e,w)?e._.selectedFields:e[E].selectedFields}createJoin(e){return(t,n)=>{let r=Ti(t);if(typeof r==`string`&&this.config.joins.some(e=>e.alias===r))throw Error(`Alias "${r}" is already used in this query`);if(typeof n==`function`){let e=this.config.from&&!b(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[D.Symbol.Columns],new j({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new j({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}if(this.config.joins.push({on:n,table:t,joinType:e,alias:r}),typeof r==`string`)switch(e){case`left`:this.joinsNotNullableMap[r]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[r]=!0;break;case`inner`:this.joinsNotNullableMap[r]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[r]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[D.Symbol.Columns]),this.config.from)){let t=Ti(this.config.from);if(typeof t==`string`&&this.config.from&&!b(this.config.from,k)){let n=this.getTableLikeFields(this.config.from);e[t]=n}for(let t of this.config.joins){let n=Ti(t.table);if(typeof n==`string`&&!b(t.table,k)){let r=this.getTableLikeFields(t.table);e[n]=r}}}return this.config.returningFields=e,this.config.returning=bi(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:gc(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j({alias:ei(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Cc=class e extends k{constructor(t){super(e.buildEmbeddedCount(t.source,t.filters).queryChunks),this.params=t,this.mapWith(Number),this.session=t.session,this.sql=e.buildCount(t.source,t.filters)}sql;token;static[y]=`PgCountBuilder`;[Symbol.toStringTag]=`PgCountBuilder`;session;static buildEmbeddedCount(e,t){return A`(select count(*) from ${e}${A.raw(` where `).if(t)}${t})`}static buildCount(e,t){return A`select count(*) as count from ${e}${A.raw(` where `).if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},wc=class{constructor(e,t,n,r,i,a,o){this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o}static[y]=`PgRelationalQueryBuilder`;findMany(e){return new Tc(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return new Tc(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},Tc=class extends vr{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[y]=`PgRelationalQuery`;_prepare(e){return T.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(e,n)=>{let r=e.map(e=>Us(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return T.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},Ec=class extends vr{constructor(e,t,n,r){super(),this.execute=e,this.sql=t,this.query=n,this.mapBatchResult=r}static[y]=`PgRaw`;getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},Dc=class{constructor(e,t,n){if(this.dialect=e,this.session=t,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[r,i]of Object.entries(this._.schema))this.query[r]=new wc(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[r],i,e,t);this.$cache={invalidate:async e=>{}}}static[y]=`PgDatabase`;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new ic(n.dialect))),new Proxy(new Gr(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new j({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new Cc({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function n(n){return new qs({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new qs({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n,r){return new qs({fields:r??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:n}})}function a(n){return new xc(n,t.session,t.dialect,e)}function o(n){return new vc(n,t.session,t.dialect,e)}function s(n){return new _c(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,selectDistinctOn:i,update:a,insert:o,delete:s}}select(e){return new qs({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new qs({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new qs({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new xc(e,this.session,this.dialect)}insert(e){return new vc(e,this.session,this.dialect)}delete(e){return new _c(e,this.session,this.dialect)}refreshMaterializedView(e){return new bc(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e==`string`?A.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(t),r=this.session.prepareQuery(n,void 0,void 0,!1);return new Ec(()=>r.execute(void 0,this.authToken),t,n,e=>r.mapResult(e,!0))}transaction(e,t){return this.session.transaction(e,t)}},Oc=class{static[y]=`Cache`},kc=class extends Oc{strategy(){return`all`}static[y]=`NoopCache`;async get(e){}async put(e,t,n,r){}async onMutate(e){}};async function Ac(e,t){let n=`${e}-${JSON.stringify(t)}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest(`SHA-256`,r);return[...new Uint8Array(i)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}var jc=class{constructor(e,t,n){this.seqName=e,this.seqOptions=t,this.schema=n}static[y]=`PgSequence`};function Mc(e,t,n){return new jc(e,t,n)}var Nc=class{constructor(e){this.schemaName=e}static[y]=`PgSchema`;table=(e,t,n)=>Vo(e,t,n,this.schemaName);view=(e,t)=>mc(e,t,this.schemaName);materializedView=(e,t)=>hc(e,t,this.schemaName);enum(e,t){return Array.isArray(t)?Ur(e,[...t],this.schemaName):Wr(e,t,this.schemaName)}sequence=(e,t)=>Mc(e,t,this.schemaName);getSQL(){return new k([A.identifier(this.schemaName)])}shouldOmitSQLParens(){return!0}};function Pc(e){if(e===`public`)throw Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`);return new Nc(e)}var Fc=class{constructor(e,t,n,r){this.query=e,this.cache=t,this.queryMetadata=n,this.cacheConfig=r,t&&t.strategy()===`all`&&r===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[y]=`PgPreparedQuery`;joinsNotNullableMap;async queryWithCache(e,t,n){if(this.cache===void 0||b(this.cache,kc)||this.queryMetadata===void 0||this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(n){throw new as(e,t,n)}if((this.queryMetadata.type===`insert`||this.queryMetadata.type===`update`||this.queryMetadata.type===`delete`)&&this.queryMetadata.tables.length>0)try{let[e]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return e}catch(n){throw new as(e,t,n)}if(!this.cacheConfig)try{return await n()}catch(n){throw new as(e,t,n)}if(this.queryMetadata.type===`select`){let r=await this.cache.get(this.cacheConfig.tag??await Ac(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let r;try{r=await n()}catch(n){throw new as(e,t,n)}return await this.cache.put(this.cacheConfig.tag??await Ac(e,t),r,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),r}return r}try{return await n()}catch(n){throw new as(e,t,n)}}},Ic=class{constructor(e){this.dialect=e}static[y]=`PgSession`;execute(e,t){return T.startActiveSpan(`drizzle.operation`,()=>T.startActiveSpan(`drizzle.prepareQuery`,()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let n=await this.execute(e,t);return Number(n[0].count)}},Lc=class extends Dc{constructor(e,t,n,r=0){super(e,t,n),this.schema=n,this.nestedIndex=r}static[y]=`PgTransaction`;rollback(){throw new os}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable==`boolean`&&t.push(e.deferrable?`deferrable`:`not deferrable`),A.raw(t.join(` `))}setTransaction(e){return this.session.execute(A`set transaction ${this.getTransactionConfigSQL(e)}`)}},{Pool:Rc,types:zc}=mr,Bc=class extends Fc{constructor(e,t,n,r,i,a,o,s,c,l,u){super({sql:t,params:n},i,a,o),this.client=e,this.queryString=t,this.params=n,this.logger=r,this.fields=s,this._isResponseInArrayMode=l,this.customResultMapper=u,this.rawQueryConfig={name:c,text:t,types:{getTypeParser:(e,t)=>e===zc.builtins.TIMESTAMPTZ||e===zc.builtins.TIMESTAMP||e===zc.builtins.DATE||e===zc.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:zc.getTypeParser(e,t)}},this.queryConfig={name:c,text:t,rowMode:`array`,types:{getTypeParser:(e,t)=>e===zc.builtins.TIMESTAMPTZ||e===zc.builtins.TIMESTAMP||e===zc.builtins.DATE||e===zc.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:zc.getTypeParser(e,t)}}}static[y]=`NodePgPreparedQuery`;rawQueryConfig;queryConfig;async execute(e={}){return T.startActiveSpan(`drizzle.execute`,async()=>{let t=ui(this.params,e);this.logger.logQuery(this.rawQueryConfig.text,t);let{fields:n,rawQueryConfig:r,client:i,queryConfig:a,joinsNotNullableMap:o,customResultMapper:s}=this;if(!n&&!s)return T.startActiveSpan(`drizzle.driver.execute`,async e=>(e?.setAttributes({"drizzle.query.name":r.name,"drizzle.query.text":r.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(r.text,t,async()=>await i.query(r,t))));let c=await T.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":a.name,"drizzle.query.text":a.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(a.text,t,async()=>await i.query(a,t))));return T.startActiveSpan(`drizzle.mapResponse`,()=>s?s(c.rows):c.rows.map(e=>yi(n,e,o)))})}all(e={}){return T.startActiveSpan(`drizzle.execute`,()=>{let t=ui(this.params,e);return this.logger.logQuery(this.rawQueryConfig.text,t),T.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":this.rawQueryConfig.name,"drizzle.query.text":this.rawQueryConfig.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(this.rawQueryConfig.text,t,async()=>this.client.query(this.rawQueryConfig,t)).then(e=>e.rows)))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},Vc=class e extends Ic{constructor(e,t,n,r={}){super(t),this.client=e,this.schema=n,this.options=r,this.logger=r.logger??new _r,this.cache=r.cache??new kc}static[y]=`NodePgSession`;logger;cache;prepareQuery(e,t,n,r,i,a,o){return new Bc(this.client,e.sql,e.params,this.logger,this.cache,a,o,t,n,r,i)}async transaction(t,n){let r=this.client instanceof Rc||Object.getPrototypeOf(this.client).constructor.name.includes(`Pool`),i=r?new e(await this.client.connect(),this.dialect,this.schema,this.options):this,a=new Hc(this.dialect,i,this.schema);await a.execute(A`begin${n?A` ${a.getTransactionConfigSQL(n)}`:void 0}`);try{let e=await t(a);return await a.execute(A`commit`),e}catch(e){throw await a.execute(A`rollback`),e}finally{r&&i.client.release()}}async count(e){let t=await this.execute(e);return Number(t.rows[0].count)}},Hc=class e extends Lc{static[y]=`NodePgTransaction`;async transaction(t){let n=`sp${this.nestedIndex+1}`,r=new e(this.dialect,this.session,this.schema,this.nestedIndex+1);await r.execute(A.raw(`savepoint ${n}`));try{let e=await t(r);return await r.execute(A.raw(`release savepoint ${n}`)),e}catch(e){throw await r.execute(A.raw(`rollback to savepoint ${n}`)),e}}},Uc=class{constructor(e,t,n={}){this.client=e,this.dialect=t,this.options=n}static[y]=`NodePgDriver`;createSession(e){return new Vc(this.client,this.dialect,e,{logger:this.options.logger,cache:this.options.cache})}},Wc=class extends Dc{static[y]=`NodePgDatabase`};function Gc(e,t={}){let n=new Gs({casing:t.casing}),r;t.logger===!0?r=new gr:t.logger!==!1&&(r=t.logger);let i;if(t.schema){let e=Ls(t.schema,Hs);i={fullSchema:t.schema,schema:e.tables,tableNamesMap:e.tableNamesMap}}let a=new Wc(n,new Uc(e,n,{logger:r,cache:t.cache}).createSession(i),i);return a.$client=e,a.$cache=t.cache,a.$cache&&(a.$cache.invalidate=t.cache?.onMutate),a}function Kc(...e){if(typeof e[0]==`string`)return Gc(new mr.Pool({connectionString:e[0]}),e[1]);if(Ei(e[0])){let{connection:t,client:n,...r}=e[0];return Gc(n||(typeof t==`string`?new mr.Pool({connectionString:t}):new mr.Pool(t)),r)}return Gc(e[0],e[1])}(e=>{function t(e){return Gc({},e)}e.mock=t})(Kc||={});var qc={crossOriginEmbedderPolicy:[`Cross-Origin-Embedder-Policy`,`require-corp`],crossOriginResourcePolicy:[`Cross-Origin-Resource-Policy`,`same-origin`],crossOriginOpenerPolicy:[`Cross-Origin-Opener-Policy`,`same-origin`],originAgentCluster:[`Origin-Agent-Cluster`,`?1`],referrerPolicy:[`Referrer-Policy`,`no-referrer`],strictTransportSecurity:[`Strict-Transport-Security`,`max-age=15552000; includeSubDomains`],xContentTypeOptions:[`X-Content-Type-Options`,`nosniff`],xDnsPrefetchControl:[`X-DNS-Prefetch-Control`,`off`],xDownloadOptions:[`X-Download-Options`,`noopen`],xFrameOptions:[`X-Frame-Options`,`SAMEORIGIN`],xPermittedCrossDomainPolicies:[`X-Permitted-Cross-Domain-Policies`,`none`],xXssProtection:[`X-XSS-Protection`,`0`]},Jc={crossOriginEmbedderPolicy:!1,crossOriginResourcePolicy:!0,crossOriginOpenerPolicy:!0,originAgentCluster:!0,referrerPolicy:!0,strictTransportSecurity:!0,xContentTypeOptions:!0,xDnsPrefetchControl:!0,xDownloadOptions:!0,xFrameOptions:!0,xPermittedCrossDomainPolicies:!0,xXssProtection:!0,removePoweredBy:!0,permissionsPolicy:{}},Yc=e=>{let t={...Jc,...e},n=Xc(t),r=[];if(t.contentSecurityPolicy){let[e,i]=Zc(t.contentSecurityPolicy,`Content-Security-Policy`);e&&r.push(e),n.push([`Content-Security-Policy`,i])}if(t.contentSecurityPolicyReportOnly){let[e,i]=Zc(t.contentSecurityPolicyReportOnly,`Content-Security-Policy-Report-Only`);e&&r.push(e),n.push([`Content-Security-Policy-Report-Only`,i])}return t.permissionsPolicy&&Object.keys(t.permissionsPolicy).length>0&&n.push([`Permissions-Policy`,Qc(t.permissionsPolicy)]),t.reportingEndpoints&&n.push([`Reporting-Endpoints`,el(t.reportingEndpoints)]),t.reportTo&&n.push([`Report-To`,tl(t.reportTo)]),async function(e,i){let a=r.length===0?n:r.reduce((t,n)=>n(e,t),n);await i(),nl(e,a),t?.removePoweredBy&&e.res.headers.delete(`X-Powered-By`)}};function Xc(e){return Object.entries(qc).filter(([t])=>e[t]).map(([t,n])=>{let r=e[t];return typeof r==`string`?[n[0],r]:n})}function Zc(e,t){let n=[],r=[];for(let[t,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];e.forEach((e,i)=>{if(typeof e==`function`){let a=i*2+2+r.length;n.push((n,r)=>{r[a]=e(n,t)})}}),r.push(t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(e,t)=>t?`-`+e.toLowerCase():e.toLowerCase()),...e.flatMap(e=>[` `,e]),`; `)}return r.pop(),n.length===0?[void 0,r.join(``)]:[(e,r)=>r.map(r=>{if(r[0]===t){let t=r[1].slice();return n.forEach(n=>{n(e,t)}),[r[0],t.join(``)]}return r}),r]}function Qc(e){return Object.entries(e).map(([e,t])=>{let n=$c(e);return typeof t==`boolean`?`${n}=${t?`*`:`()`}`:Array.isArray(t)?t.length===0?`${n}=()`:t.length===1&&t[0]===`*`?`${n}=*`:t.length===1&&t[0]===`none`?`${n}=()`:`${n}=(${t.map(e=>[`self`,`src`].includes(e)?e:`"${e}"`).join(` `)})`:``}).filter(Boolean).join(`, `)}function $c(e){return e.replace(/([a-z\d])([A-Z])/g,`$1-$2`).toLowerCase()}function el(e=[]){return e.map(e=>`${e.name}="${e.url}"`).join(`, `)}function tl(e=[]){return e.map(e=>JSON.stringify(e)).join(`, `)}function nl(e,t){t.forEach(([t,n])=>{e.res.headers.set(t,n)})}var rl=/^[a-z_][a-z0-9_]{0,62}$/,il=(()=>{let e=globalThis.process?.env?.DATABASE_SCHEMA;if(e&&e!==`public`){if(!rl.test(e))throw Error(`Invalid DATABASE_SCHEMA: ${JSON.stringify(e)}. Set it to a lowercase Postgres schema name, such as pr_141, or leave it unset.`);return e}})(),I=il?Pc(il).table:Ho,al=I(`account`,{accessToken:N(`access_token`),accessTokenExpiresAt:P(`access_token_expires_at`),accountId:N(`account_id`).notNull(),createdAt:P(`created_at`).defaultNow().notNull(),id:N(`id`).primaryKey(),idToken:N(`id_token`),password:N(`password`),providerId:N(`provider_id`).notNull(),refreshToken:N(`refresh_token`),refreshTokenExpiresAt:P(`refresh_token_expires_at`),scope:N(`scope`),updatedAt:P(`updated_at`).$onUpdate(()=>new Date).notNull(),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[F(`account_userId_idx`).on(e.userId)]),ol=Rs(al,({one:e})=>({user:e(R,{fields:[al.userId],references:[R.id]})})),sl=I(`device_code`,{acr:N(`acr`),amr:N(`amr`).array(),authTime:P(`auth_time`),clientId:N(`client_id`),deviceCode:N(`device_code`).notNull(),expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey(),lastPolledAt:P(`last_polled_at`),oauthClientId:N(`oauth_client_id`),pollingInterval:ua(`polling_interval`),referenceId:N(`reference_id`),resources:N(`resources`).array(),scope:N(`scope`),status:N(`status`).notNull(),userCode:N(`user_code`).notNull(),userId:N(`user_id`)},e=>[Yo(`deviceCode_deviceCode_uidx`).on(e.deviceCode),F(`deviceCode_expiresAt_idx`).on(e.expiresAt),Yo(`deviceCode_userCode_uidx`).on(e.userCode)]),cl=I(`jwks`,{alg:N(`alg`),createdAt:P(`created_at`).notNull(),crv:N(`crv`),expiresAt:P(`expires_at`),id:N(`id`).primaryKey(),privateKey:N(`private_key`).notNull(),publicKey:N(`public_key`).notNull()}),ll=I(`oauth_access_token`,{authorizationCodeId:N(`authorization_code_id`),clientId:N(`client_id`).notNull().references(()=>L.clientId,{onDelete:`cascade`}),confirmation:ya(`confirmation`),createdAt:P(`created_at`).notNull(),expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey(),referenceId:N(`reference_id`),refreshId:N(`refresh_id`).references(()=>_l.id,{onDelete:`cascade`}),requestedUserInfoClaims:N(`requested_user_info_claims`).array(),resources:N(`resources`).array(),revoked:P(`revoked`),scopes:N(`scopes`).array().notNull(),sessionId:N(`session_id`).references(()=>xl.id,{onDelete:`set null`}),token:N(`token`).notNull().unique(),userId:N(`user_id`).references(()=>R.id,{onDelete:`cascade`})},e=>[F(`oauthAccessToken_authorizationCodeId_idx`).on(e.authorizationCodeId),F(`oauthAccessToken_clientId_idx`).on(e.clientId),F(`oauthAccessToken_expiresAt_idx`).on(e.expiresAt),F(`oauthAccessToken_refreshId_idx`).on(e.refreshId),F(`oauthAccessToken_sessionId_idx`).on(e.sessionId),F(`oauthAccessToken_userId_idx`).on(e.userId)]),ul=Rs(ll,({one:e})=>({oauthClient:e(L,{fields:[ll.clientId],references:[L.clientId]}),oauthRefreshToken:e(_l,{fields:[ll.refreshId],references:[_l.id]}),session:e(xl,{fields:[ll.sessionId],references:[xl.id]}),user:e(R,{fields:[ll.userId],references:[R.id]})})),L=I(`oauth_client`,{applicationType:N(`application_type`),backchannelLogoutSessionRequired:Bi(`backchannel_logout_session_required`),backchannelLogoutUri:N(`backchannel_logout_uri`),clientCredentialsScopes:N(`client_credentials_scopes`).array().default([]),clientDiscoveryId:N(`client_discovery_id`),clientId:N(`client_id`).notNull().unique(),clientSecret:N(`client_secret`),contacts:N(`contacts`).array(),createdAt:P(`created_at`),disabled:Bi(`disabled`).default(!1),dpopBoundAccessTokens:Bi(`dpop_bound_access_tokens`).default(!1),enableEndSession:Bi(`enable_end_session`),frontchannelLogoutSessionRequired:Bi(`frontchannel_logout_session_required`),frontchannelLogoutUri:N(`frontchannel_logout_uri`),grantTypes:N(`grant_types`).array(),icon:N(`icon`),id:N(`id`).primaryKey(),jwks:N(`jwks`),jwksUri:N(`jwks_uri`),metadata:ya(`metadata`),name:N(`name`),policy:N(`policy`),postLogoutRedirectUris:N(`post_logout_redirect_uris`).array(),redirectUris:N(`redirect_uris`).array().notNull(),referenceId:N(`reference_id`),refreshTokenLifetime:ua(`refresh_token_lifetime`).default(2592e3),requirePKCE:Bi(`require_pkce`),responseTypes:N(`response_types`).array(),scopes:N(`scopes`).array(),sectorIdentifier:N(`sector_identifier`),skipConsent:Bi(`skip_consent`),softwareId:N(`software_id`),softwareStatement:N(`software_statement`),softwareVersion:N(`software_version`),subjectType:N(`subject_type`),tokenEndpointAuthMethod:N(`token_endpoint_auth_method`),tos:N(`tos`),updatedAt:P(`updated_at`),uri:N(`uri`),userId:N(`user_id`).references(()=>R.id,{onDelete:`cascade`})},e=>[F(`oauthClient_userId_idx`).on(e.userId)]),dl=I(`oauth_client_assertion`,{expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey()},e=>[F(`oauthClientAssertion_expiresAt_idx`).on(e.expiresAt)]),fl=Rs(L,({many:e,one:t})=>({oauthAccessTokens:e(ll),oauthClientResources:e(pl),oauthConsents:e(hl),oauthRefreshTokens:e(_l),user:t(R,{fields:[L.userId],references:[R.id]})})),pl=I(`oauth_client_resource`,{clientId:N(`client_id`).notNull().references(()=>L.clientId,{onDelete:`cascade`}),createdAt:P(`created_at`),id:N(`id`).primaryKey(),metadata:ya(`metadata`),resourceId:N(`resource_id`).notNull().references(()=>yl.identifier,{onDelete:`cascade`})},e=>[F(`oauthClientResource_clientId_idx`).on(e.clientId),Yo(`oauthClientResource_clientId_resourceId_uidx`).on(e.clientId,e.resourceId),F(`oauthClientResource_resourceId_idx`).on(e.resourceId)]),ml=Rs(pl,({one:e})=>({oauthClient:e(L,{fields:[pl.clientId],references:[L.clientId]}),oauthResource:e(yl,{fields:[pl.resourceId],references:[yl.identifier]})})),hl=I(`oauth_consent`,{clientId:N(`client_id`).notNull().references(()=>L.clientId,{onDelete:`cascade`}),createdAt:P(`created_at`).notNull(),id:N(`id`).primaryKey(),referenceId:N(`reference_id`),requestedUserInfoClaims:N(`requested_user_info_claims`).array(),resources:N(`resources`).array(),scopes:N(`scopes`).array().notNull(),updatedAt:P(`updated_at`).notNull(),userId:N(`user_id`).references(()=>R.id,{onDelete:`cascade`})},e=>[F(`oauthConsent_clientId_idx`).on(e.clientId),F(`oauthConsent_userId_idx`).on(e.userId)]),gl=Rs(hl,({one:e})=>({oauthClient:e(L,{fields:[hl.clientId],references:[L.clientId]}),user:e(R,{fields:[hl.userId],references:[R.id]})})),_l=I(`oauth_refresh_token`,{acr:N(`acr`),amr:N(`amr`).array(),authorizationCodeId:N(`authorization_code_id`),authTime:P(`auth_time`),clientId:N(`client_id`).notNull().references(()=>L.clientId,{onDelete:`cascade`}),confirmation:ya(`confirmation`),createdAt:P(`created_at`).notNull(),expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey(),referenceId:N(`reference_id`),requestedUserInfoClaims:N(`requested_user_info_claims`).array(),resources:N(`resources`).array(),revoked:P(`revoked`),rotatedAt:P(`rotated_at`),rotationReplayExpiresAt:P(`rotation_replay_expires_at`),rotationReplayResponse:N(`rotation_replay_response`),scopes:N(`scopes`).array().notNull(),sessionId:N(`session_id`).references(()=>xl.id,{onDelete:`set null`}),token:N(`token`).notNull().unique(),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[F(`oauthRefreshToken_authorizationCodeId_idx`).on(e.authorizationCodeId),F(`oauthRefreshToken_clientId_idx`).on(e.clientId),F(`oauthRefreshToken_expiresAt_idx`).on(e.expiresAt),F(`oauthRefreshToken_sessionId_idx`).on(e.sessionId),F(`oauthRefreshToken_userId_idx`).on(e.userId)]),vl=Rs(_l,({many:e,one:t})=>({oauthAccessTokens:e(ll),oauthClient:t(L,{fields:[_l.clientId],references:[L.clientId]}),session:t(xl,{fields:[_l.sessionId],references:[xl.id]}),user:t(R,{fields:[_l.userId],references:[R.id]})})),yl=I(`oauth_resource`,{accessTokenTtl:ua(`access_token_ttl`),allowedScopes:N(`allowed_scopes`).array(),createdAt:P(`created_at`),customClaims:ya(`custom_claims`),disabled:Bi(`disabled`).default(!1),dpopBoundAccessTokensRequired:Bi(`dpop_bound_access_tokens_required`).default(!1),id:N(`id`).primaryKey(),identifier:N(`identifier`).notNull().unique(),metadata:ya(`metadata`),name:N(`name`).notNull(),policyVersion:ua(`policy_version`).default(1),refreshTokenTtl:ua(`refresh_token_ttl`),signingAlgorithm:N(`signing_algorithm`),signingKeyId:N(`signing_key_id`),updatedAt:P(`updated_at`)}),bl=Rs(yl,({many:e})=>({oauthClientResources:e(pl)})),xl=I(`session`,{createdAt:P(`created_at`).defaultNow().notNull(),expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey(),ipAddress:N(`ip_address`),token:N(`token`).notNull().unique(),updatedAt:P(`updated_at`).$onUpdate(()=>new Date).notNull(),userAgent:N(`user_agent`),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[F(`session_expiresAt_idx`).on(e.expiresAt),F(`session_userId_idx`).on(e.userId)]),Sl=Rs(xl,({many:e,one:t})=>({oauthAccessTokens:e(ll),oauthRefreshTokens:e(_l),user:t(R,{fields:[xl.userId],references:[R.id]})})),R=I(`user`,{createdAt:P(`created_at`).defaultNow().notNull(),email:N(`email`).notNull().unique(),emailVerified:Bi(`email_verified`).default(!1).notNull(),id:N(`id`).primaryKey(),image:N(`image`),name:N(`name`).notNull(),updatedAt:P(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull()}),Cl=Rs(R,({many:e})=>({accounts:e(al),oauthAccessTokens:e(ll),oauthClients:e(L),oauthConsents:e(hl),oauthRefreshTokens:e(_l),sessions:e(xl)})),z=I(`verification`,{createdAt:P(`created_at`).defaultNow().notNull(),expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey(),identifier:N(`identifier`).notNull(),updatedAt:P(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull(),value:N(`value`).notNull()},e=>[F(`verification_expiresAt_idx`).on(e.expiresAt),F(`verification_identifier_idx`).on(e.identifier)]),wl=r({account:()=>al,accountConfigs:()=>Tl,accountRelations:()=>ol,appRealms:()=>El,deviceCode:()=>sl,deviceRequests:()=>Dl,firstAccounts:()=>Ol,jwks:()=>cl,keys:()=>kl,oauthAccessToken:()=>ll,oauthAccessTokenRelations:()=>ul,oauthClient:()=>L,oauthClientAssertion:()=>dl,oauthClientRelations:()=>fl,oauthClientResource:()=>pl,oauthClientResourceRelations:()=>ml,oauthConsent:()=>hl,oauthConsentRelations:()=>gl,oauthRefreshToken:()=>_l,oauthRefreshTokenRelations:()=>vl,oauthResource:()=>yl,oauthResourceRelations:()=>bl,pendingKeys:()=>Al,realmPasskeys:()=>jl,realmPrivy:()=>Ml,realmSecp256k1:()=>Nl,realms:()=>Pl,secp256k1Owners:()=>Fl,session:()=>xl,sessionRelations:()=>Sl,user:()=>R,userRelations:()=>Cl,verification:()=>z}),Tl=I(`account_configs`,{address:N(`address`).notNull(),chainId:ua(`chain_id`).notNull(),createdAt:P(`created_at`).defaultNow().notNull(),key:N(`key`).notNull(),owners:ya(`owners`).notNull(),salt:N(`salt`).notNull(),threshold:ua(`threshold`).notNull(),updatedAt:P(`updated_at`).defaultNow().notNull(),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`}),version:N(`version`).notNull()},e=>[Xo({columns:[e.chainId,e.address]}),F(`account_configs_user_id_idx`).on(e.userId)]),El=I(`app_realms`,{clientId:N(`client_id`).notNull().references(()=>L.clientId,{onDelete:`cascade`}),position:ua(`position`).notNull(),realmId:N(`realm_id`).notNull().references(()=>Pl.id)},e=>[Go(`app_realms_position_check`,A`${e.position} >= 0`),Xo({columns:[e.clientId,e.position]}),wr(`app_realms_client_id_realm_id_unique`).on(e.clientId,e.realmId)]),Dl=I(`device_requests`,{account:N(`account`),challenge:N(`challenge`),createdAt:P(`created_at`).defaultNow().notNull(),device:N(`device`),expiresAt:P(`expires_at`).notNull(),id:N(`id`).primaryKey(),ip:N(`ip`),key:ya(`key`),keyAuthorization:ya(`key_authorization`),location:N(`location`)},e=>[F(`device_requests_expires_at_idx`).on(e.expiresAt)]),Ol=I(`first_accounts`,{createdAt:P(`created_at`).defaultNow().notNull(),realmId:N(`realm_id`).notNull().references(()=>Pl.id,{onDelete:`cascade`}),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[Xo({columns:[e.userId,e.realmId]})]),kl=I(`keys`,{address:N(`address`).unique(),createdAt:P(`created_at`).defaultNow().notNull(),id:N(`id`).primaryKey(),publicKey:N(`public_key`).notNull(),rpId:N(`rp_id`).notNull(),source:N(`source`).notNull(),type:N(`type`).notNull(),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[Go(`keys_source_check`,A`${e.source} in ('registered', 'tempo-id', 'tempo-wallet', 'wallet')`),Go(`keys_type_check`,A`${e.type} = 'passkey'`),F(`keys_user_id_idx`).on(e.userId)]),Al=I(`pending_keys`,{account:N(`account`).notNull(),clientId:N(`client_id`).notNull().references(()=>L.clientId,{onDelete:`cascade`}),codeChallenge:N(`code_challenge`).notNull(),createdAt:P(`created_at`).defaultNow().notNull(),expiresAt:P(`expires_at`).notNull(),keyAuthorization:ya(`key_authorization`).notNull(),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[F(`pending_keys_expires_at_idx`).on(e.expiresAt),Xo({columns:[e.clientId,e.codeChallenge]})]),jl=I(`realm_passkeys`,{createdAt:P(`created_at`).defaultNow().notNull(),realmId:N(`realm_id`).primaryKey().references(()=>Pl.id,{onDelete:`cascade`}),rpId:N(`rp_id`).notNull().unique()}),Ml=I(`realm_privy`,{appId:N(`app_id`).notNull().unique(),appSecret:N(`app_secret`).notNull(),createdAt:P(`created_at`).defaultNow().notNull(),realmId:N(`realm_id`).primaryKey().references(()=>Pl.id,{onDelete:`cascade`})}),Nl=I(`realm_secp256k1`,{createdAt:P(`created_at`).defaultNow().notNull(),realmId:N(`realm_id`).primaryKey().references(()=>Pl.id,{onDelete:`cascade`})}),Pl=I(`realms`,{createdAt:P(`created_at`).defaultNow().notNull(),id:N(`id`).primaryKey(),name:N(`name`).notNull()},e=>[Go(`realms_id_check`,A`${e.id} ~ '^[a-z0-9]+(-[a-z0-9]+)*$'`)]),Fl=I(`secp256k1_owners`,{address:N(`address`).notNull().unique(),createdAt:P(`created_at`).defaultNow().notNull(),privateKey:N(`private_key`).notNull(),realmId:N(`realm_id`).notNull().references(()=>Pl.id,{onDelete:`cascade`}),userId:N(`user_id`).notNull().references(()=>R.id,{onDelete:`cascade`})},e=>[Xo({columns:[e.userId,e.realmId]})]),Il=`Payload Too Large`,Ll=e=>{let t=e.onError||(()=>{throw new tt(413,{res:new Response(Il,{status:413})})}),n=e.maxSize;return async function(e,r){if(!e.req.raw.body)return r();let i=e.req.raw.headers.has(`transfer-encoding`);if(e.req.raw.headers.has(`content-length`)&&!i)return parseInt(e.req.raw.headers.get(`content-length`)||`0`,10)>n?t(e):r();let a=0,o=[],s=e.req.raw.body.getReader();for(;;){let{done:r,value:i}=await s.read();if(r)break;if(a+=i.length,a>n)return t(e);o.push(i)}let c={body:new ReadableStream({start(e){for(let t of o)e.enqueue(t);e.close()}}),duplex:`half`};return e.req.raw=new Request(e.req.raw,c),r()}};function Rl(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function zl(e,t=`|`){return e.map(e=>uu(e)).join(t)}function Bl(e,t){return typeof t==`bigint`?t.toString():t}var Vl=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function Hl(e){return new Vl(e)}function Ul(e){return e==null}function Wl(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Gl(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function Kl(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ql(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Jl(e){return ql(e._zod.def)??e._zod.def.shape}function Yl(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Kl(this,t,e),e},enumerable:!0,configurable:!0})}function Xl(e,t,n){t in e?Kl(e,t,n):e[t]=n}function Zl(e,t,n,r){let i=Jl(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Yl(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Xl(e,a,r?r(n.value,a):n.value))}}function Ql(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Yl(e,n,()=>t[n]):Xl(e,n,r.value))}}function $l(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function eu(e){return JSON.stringify(e)}function tu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var nu=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function ru(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var iu=Hl(()=>{if(ed.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function au(e){if(ru(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ru(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ou(e){return au(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var su=new Set([`string`,`number`,`symbol`]);function cu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function lu(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function B(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function uu(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function du(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var fu={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},pu={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function mu(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return Zl(i,e,hu(e,t)),lu(e,$l(n,{shape:i,checks:[]}))}function hu(e,t){let n=Jl(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function gu(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(hu(e,t)),a={};return Zl(a,e,Reflect.ownKeys(Jl(e)).filter(e=>!i.has(e))),lu(e,$l(n,{shape:a,checks:[]}))}function _u(e,t){if(!au(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Jl(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return lu(e,$l(e._zod.def,{shape:vu(e,t)}))}function vu(e,t){let n={};return Zl(n,e,Reflect.ownKeys(Jl(e))),Ql(n,t),n}function yu(e,t){if(!au(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return lu(e,$l(e._zod.def,{shape:vu(e,t)}))}function bu(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Zl(n,e,Reflect.ownKeys(Jl(e))),Zl(n,t,Reflect.ownKeys(Jl(t))),lu(e,$l(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function xu(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(hu(t,n)):void 0,o={};return Zl(o,t,Reflect.ownKeys(Jl(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),lu(t,$l(t._zod.def,{shape:o,checks:[]}))}function Su(e,t,n){let r=n?new Set(hu(t,n)):void 0,i={};return Zl(i,t,Reflect.ownKeys(Jl(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),lu(t,$l(t._zod.def,{shape:i}))}function Cu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function wu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Tu(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Eu(e){return typeof e==`string`?e:e?.message}function Du(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function Ou(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ku(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:Eu(e.inst?._zod.def?.error?.(e))??Eu(a?.(e))??Eu(t?.error?.(e))??Eu(n.customError?.(e))??Eu(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}var Au=/[\uD800-\uDBFF]/;function ju(e){let t=e.length;if(!Au.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function Mu(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Nu(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function Pu(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function Fu(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):zu(e,n,r.value)}}function Iu(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Lu(e,t,n){return Iu(e,t,n,!1)}function Ru(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Iu(this,n,r(this))},set(e){Iu(this,n,e)}})}return t}function zu(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Iu(this,t,n.bind(this))},set(e){Iu(this,t,e)}})}function Bu(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var Vu,Hu=!1,Uu={configurable:!0,get(){Hu=!0}};function V(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Vu!==e._zod?Vu=void 0:(Vu=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Uu);let e=Hu;Hu=!1;try{let r=n(this);return Hu?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Hu||=e,r}catch(n){throw delete this[t],Hu||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Wu(e,t,n,r){let i=Bu(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Gu=`~constantCatch`;function Ku(e){let t=()=>e;return t[Gu]=!0,t}var qu,Ju=Object.freeze({status:`aborted`}),Yu={value:void 0,enumerable:!1},Xu=`captureStackTrace`in Error?Error:null;function Zu(e){let t=Xu;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Xu=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function H(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Yu.value=new a(r);try{Object.defineProperty(n,"_zod",Yu)}finally{Yu.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),Fu(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Zu(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Qu=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$u=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(qu=globalThis).__zod_globalConfig??(qu.__zod_globalConfig={});var ed=globalThis.__zod_globalConfig;function td(e){return e&&Object.assign(ed,e),ed}function nd(){let e=this._zod;return e.message??=JSON.stringify(e.def,Bl,2),e.message}function rd(e){this._zod.message=e}var id={get:nd,set:rd,enumerable:!0,configurable:!0},ad={value:void 0,enumerable:!1},od=new WeakSet([Object.prototype,Error.prototype]),sd=H(`$ZodError`,(e,t)=>{e.name=`$ZodError`,ad.value=t,Object.defineProperty(e,"issues",ad),ad.value=void 0,Object.defineProperty(e,"message",id);let n=Object.getPrototypeOf(e);od.has(n)||(od.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function cd(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function ld(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?cd(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function ud(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function dd(e,t){return{callee:t?.callee??e,Err:t?.Err}}var fd=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qu;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ku(e,o,td())));throw nu(n,a?.callee??t),n}return s.value};return t},pd=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ku(e,o,td())));throw nu(n,a?.callee??t),n}return s.value};return t},md=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Qu;return a.issues.length?hd(e,a.issues,i):{success:!0,data:a.value}};function hd(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>ku(e,n,td()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var gd=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?hd(e,a.issues,i):{success:!0,data:a.value}},_d=Symbol.for(`zod.compile.invalid`),vd=Symbol.for(`zod.compile.fallback`),yd=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==_d)return!0;if(r.definite===!0&&n===void 0)return!1}return bd(e,t,n)});function bd(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[vd]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Qu;return a.issues.length===0}var xd=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},Sd=e=>{let t=fd(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,dd(n,a))};return n},Cd=e=>{let t=fd(e),n=(e,r,i,a)=>t(e,r,i,dd(n,a));return n},wd=e=>{let t=pd(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,dd(n,a))};return n},Td=e=>{let t=pd(e),n=async(e,r,i,a)=>await t(e,r,i,dd(n,a));return n},Ed=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return md(e)(t,n,i)},Dd=e=>(t,n,r)=>md(e)(t,n,r),Od=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return gd(e)(t,n,i)},kd=e=>async(t,n,r)=>gd(e)(t,n,r),Ad=/^[cC][0-9a-z]{6,}$/,jd=/^[0-9a-z]+$/,Md=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Nd=/^[0-9a-vA-V]{20}$/,Pd=/^[A-Za-z0-9]{27}$/,Fd=/^[a-zA-Z0-9_-]{21}$/;function Id(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Ld=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Rd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,zd=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Bd=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Vd=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function Hd(){return new RegExp(Vd,`u`)}var Ud=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Gd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Kd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Jd=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Yd=/^https?$/,Xd=/^\+[1-9]\d{6,14}$/,Zd=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function Qd(e){return RegExp(`^${e}$`)}var $d=Qd(Zd);function ef(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function tf(e){return RegExp(`^${ef(e)}$`)}function nf(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${ef({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${ef({precision:e.precision})}`:n;return RegExp(`^${Zd}T(?:${r})$`)}var rf=/^[\s\S]{0,}$/,af=/^-?\d+$/,of=/^-?\d+(?:\.\d+)?$/,sf=/^(?:true|false)$/i,cf=/^[^A-Z]*$/,lf=/^[^a-z]*$/,uf=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),df=e=>{let t=e.value;return!Ul(t)&&t.length!==void 0},ff={number:`number`,bigint:`bigint`,object:`date`},pf=H(`$ZodCheckLessThan`,(e,t)=>{uf.init(e,t);let n=ff[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:ff[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mf=H(`$ZodCheckGreaterThan`,(e,t)=>{uf.init(e,t);let n=ff[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:ff[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),hf=H(`$ZodCheckMultipleOf`,(e,t)=>{uf.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Gl(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),gf=H(`$ZodCheckNumberFormat`,(e,t)=>{uf.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=fu[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),_f=H(`$ZodCheckMaxLength`,(e,t)=>{var n;uf.init(e,t),(n=e._zod.def).when??(n.when=df),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?ju(r):i)<=t.maximum)return;let a=Mu(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),vf=H(`$ZodCheckMinLength`,(e,t)=>{var n;uf.init(e,t),(n=e._zod.def).when??(n.when=df),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?ju(r):i)>=t.minimum)return;let a=Mu(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),yf=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;uf.init(e,t),(n=e._zod.def).when??(n.when=df),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?ju(r):i;if(a===t.length)return;let o=Mu(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),bf=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;uf.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),xf=H(`$ZodCheckRegex`,(e,t)=>{bf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Sf=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=cf,bf.init(e,t)}),Cf=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=lf,bf.init(e,t)}),wf=H(`$ZodCheckIncludes`,(e,t)=>{uf.init(e,t);let n=cu(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Tf=H(`$ZodCheckStartsWith`,(e,t)=>{uf.init(e,t);let n=RegExp(`^${cu(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ef=H(`$ZodCheckEndsWith`,(e,t)=>{uf.init(e,t);let n=RegExp(`.*${cu(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Df=H(`$ZodCheckOverwrite`,(e,t)=>{uf.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Of=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
21
- `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
22
- `)}\n};`)(...Object.values(this.closed))}},kf={major:4,minor:6,patch:7},U=H(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=kf;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=Cu(t),a;for(let o of n){if(o._zod.def.when){if(wu(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Qu;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(Ou(t.issues,n,e),i||=Cu(t,n))});else{if(t.issues.length===n)continue;Ou(t.issues,n,e),i||=Cu(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(Cu(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Qu;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Qu;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return Lu(this,`~standard`,Mf(this))},set"~standard"(e){Iu(this,`~standard`,e)}}),Af=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ku(e,t,td()))}:{value:e.value};async function jf(e,t){let n={async:!0};return Af(await e._zod.run({value:t,issues:[]},n),n)}function Mf(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Af(r,n)}catch{}return jf(e,t)},vendor:`zod`,version:1}}var Nf=H(`$ZodString`,(e,t)=>{U.init(e,t),e._zod.pattern=t.pattern??rf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),W=H(`$ZodStringFormat`,(e,t)=>{bf.init(e,t),Nf.init(e,t)}),Pf=H(`$ZodGUID`,(e,t)=>{t.pattern??=Rd,W.init(e,t)}),Ff=H(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=zd(e)}else t.pattern??=zd();W.init(e,t)}),If=H(`$ZodEmail`,(e,t)=>{t.pattern??=Bd,W.init(e,t)});function Lf(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Rf(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Lf(e)||2:zf(e,t)}function zf(e,t){if(!t.normalize&&t.protocol?.source===Yd.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}var Bf=/[\t\n\r]/g;function Vf(e){return e.replace(Bf,``)}function Hf(e,t){return t.lastIndex=0,t.test(e.hostname)}function Uf(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var Wf=H(`$ZodURL`,(e,t)=>{W.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Rf(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=Vf(r);return}t.hostname&&!Hf(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Uf(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Vf(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Gf=H(`$ZodEmoji`,(e,t)=>{t.pattern??=Hd(),W.init(e,t)}),Kf=H(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Fd:Id(t.length),W.init(e,t)}),qf=H(`$ZodCUID`,(e,t)=>{t.pattern??=Ad,W.init(e,t)}),Jf=H(`$ZodCUID2`,(e,t)=>{t.pattern??=jd,W.init(e,t)}),Yf=H(`$ZodULID`,(e,t)=>{t.pattern??=Md,W.init(e,t)}),Xf=H(`$ZodXID`,(e,t)=>{t.pattern??=Nd,W.init(e,t)}),Zf=H(`$ZodKSUID`,(e,t)=>{t.pattern??=Pd,W.init(e,t)}),Qf=H(`$ZodISODateTime`,(e,t)=>{t.pattern??=nf(t),W.init(e,t)}),$f=H(`$ZodISODate`,(e,t)=>{t.pattern??=$d,W.init(e,t)}),ep=H(`$ZodISOTime`,(e,t)=>{t.pattern??=tf(t),W.init(e,t)}),tp=H(`$ZodISODuration`,(e,t)=>{t.pattern??=Ld,W.init(e,t)}),np=H(`$ZodIPv4`,(e,t)=>{t.pattern??=Ud,W.init(e,t)}),rp=/^[0-9a-fA-F:.]+$/;function ip(e){return rp.test(e)?Lf(`http://[${e}]`):!1}var ap=H(`$ZodIPv6`,(e,t)=>{t.pattern??=Wd,W.init(e,t),e._zod.check=n=>{ip(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),op=H(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Gd,W.init(e,t)});function sp(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:ip(n)}var cp=H(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Kd,W.init(e,t),e._zod.check=n=>{sp(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function lp(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var up=/^[0-9a-zA-Z+/]*={0,2}$/,dp=H(`$ZodBase64`,(e,t)=>{t.pattern??=up,W.init(e,t),e._zod.check=n=>{lp(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),fp=/^[A-Za-z0-9_-]*$/;function pp(e){if(!fp.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return lp(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var mp=H(`$ZodBase64URL`,(e,t)=>{t.pattern??=fp,W.init(e,t),e._zod.check=n=>{pp(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),hp=H(`$ZodE164`,(e,t)=>{t.pattern??=Xd,W.init(e,t)});function gp(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var _p=H(`$ZodJWT`,(e,t)=>{W.init(e,t),e._zod.check=n=>{gp(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),vp=H(`$ZodNumber`,(e,t)=>{U.init(e,t),e._zod.pattern=of,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),yp=H(`$ZodNumberFormat`,(e,t)=>{gf.init(e,t),vp.init(e,t)}),bp=H(`$ZodBoolean`,(e,t)=>{U.init(e,t),e._zod.pattern=sf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),xp=H(`$ZodUnknown`,(e,t)=>{U.init(e,t),e._zod.parse=e=>e}),Sp=H(`$ZodNever`,(e,t)=>{U.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Cp(e,t){let n=Du(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of Du(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,Ou(n.issues,t,e),n}}return i(n,a)}}var wp=e=>Array.isArray(e)?e.length:-1;function Tp(e,t,n){e.issues.length&&t.issues.push(...Tu(n,e.issues)),t.value[n]=e.value}var Ep=H(`$ZodArray`,(e,t)=>{U.init(e,t);let n=ed.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>Tp(t,r,e)));else if(Tp(c,r,e),s&&c.issues.length!==0&&Cu(c))break}return o.length?Promise.all(o).then(()=>r):r},Cp(e,wp)});function Dp(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...Tu(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}var Op=[];function kp(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Op,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=du(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Ap(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(Cu(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Dp(e,n,i,t,d,f))):Dp(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var jp=H(`$ZodObject`,(e,t)=>{U.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=Hl(()=>kp(t));V(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Kl(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=ru,o=t.catchall,s,c=ed.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(Cu(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>Dp(n,t,e,r,a,o))):Dp(s,t,e,r,a,o)}return o?Ap(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),Mp=H(`$ZodObjectJIT`,(e,t)=>{jp.init(e,t);let n=e._zod.parse,r=Hl(()=>kp(t)),i=ed.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Of([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
23
- let ${e}_ab = false;
24
- for (let i = 0; i < ${e}.issues.length; i++) {
25
- const iss = ${e}.issues[i];
26
- iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
27
- payload.issues.push(iss);
28
- if (iss.continue !== true) ${e}_ab = true;
29
- }
30
- if (${e}_ab && ctx && ctx.abortEarly) {
31
- payload.value = newResult;
32
- return payload;
33
- }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:eu(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
34
- const ${n}_present = ${i};
35
- if (!${n}.issues.length || ${n}_present) {
36
- if (${n}.issues.length) {${c(n,r)}
37
- }
38
-
39
- if (${e}) {
40
- newResult[${r}] = ${n}.value;
41
- }
42
- }
43
-
44
- `)}else f?(o.write(`
45
- if (${n}.issues.length) {${c(n,r)}
46
- }
47
- `),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
48
- if (${n}.value !== undefined || ${i}) {
49
- newResult[${r}] = ${n}.value;
50
- }
51
- `)):o.write(`
52
- const ${n}_present = ${i};
53
- if (${n}.issues.length) {${c(n,r)}
54
- }
55
- if (!${n}_present && !${n}.issues.length) {
56
- payload.issues.push({
57
- code: "invalid_type",
58
- expected: "nonoptional",
59
- input: undefined,
60
- path: [${r}]
61
- });
62
- if (ctx && ctx.abortEarly) {
63
- payload.value = newResult;
64
- return payload;
65
- }
66
- }
67
-
68
- if (${n}_present) {
69
- newResult[${r}] = ${n}.value;
70
- }
71
-
72
- `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=ru,c=!ed.jitless,l=c&&iu.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Ap([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Np(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Cu(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ku(e,r,td())))}),t)}var Pp=H(`$ZodUnion`,(e,t)=>{U.init(e,t),V(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),V(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),V(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),V(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Wl(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Np(t,r,e,i)):Np(o,r,e,i)}}),Fp=H(`$ZodIntersection`,(e,t)=>{U.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Lp(e,t,n)):Lp(e,i,a)}});function Ip(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(au(e)&&au(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Ip(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Ip(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Lp(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=Ip(t.value,n.value);if(!c.valid){if(Cu(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Rp=H(`$ZodRecord`,(e,t)=>{U.init(e,t);let n=ed.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!au(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>ku(e,i,td())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Tu(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Tu(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&of.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>ku(e,i,td())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Tu(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Tu(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),zp=H(`$ZodEnum`,(e,t)=>{U.init(e,t);let n=Rl(t.entries),r=new Set(n);e._zod.values=r,V(e,`pattern`,e=>{let t=Rl(e.def.entries).filter(e=>su.has(typeof e));return RegExp(t.length?`^(${t.map(e=>cu(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Bp=H(`$ZodLiteral`,(e,t)=>{U.init(e,t);let n=new Set(t.values);e._zod.values=n,V(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?cu(e):e?cu(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Vp=H(`$ZodTransform`,(e,t)=>{U.init(e,t),e._zod.optin=`optional`,ed.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $u(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Qu;return n.value=i,n}});function Hp(e,t){return e.value=t.issues.length?void 0:t.value,e}var Up=H(`$ZodOptional`,(e,t)=>{U.init(e,t),V(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,V(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),V(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Wl(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Hp(e,t)):Hp(e,r)}return t.innerType._zod.run(e,n)}}),Wp=H(`$ZodExactOptional`,(e,t)=>{Up.init(e,t),V(e,`values`,e=>e.def.innerType._zod.values),V(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Gp=H(`$ZodNullable`,(e,t)=>{U.init(e,t),V(e,`optin`,e=>e.def.innerType._zod.optin),V(e,`optout`,e=>e.def.innerType._zod.optout),V(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Wl(t.source)}|null)$`):void 0}),V(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Kp=H(`$ZodDefault`,(e,t)=>{U.init(e,t),e._zod.optin=`defaulted`,V(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>qp(e,t)):qp(r,t)}});function qp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Jp=H(`$ZodPrefault`,(e,t)=>{U.init(e,t),e._zod.optin=`defaulted`,V(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Yp=H(`$ZodNonOptional`,(e,t)=>{U.init(e,t),V(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Xp(t,e)):Xp(i,e)}});function Xp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Zp(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ku(e,r,td()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Qp=H(`$ZodCatch`,(e,t)=>{U.init(e,t),V(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),V(e,`optout`,e=>e.def.innerType._zod.optout),V(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Zp(e,r,t,n)):Zp(e,r,t,n)}}),$p=H(`$ZodPipe`,(e,t)=>{U.init(e,t),V(e,`values`,e=>e.def.in._zod.values),V(e,`optin`,e=>e.def.in._zod.optin),V(e,`optout`,e=>e.def.out._zod.optout),V(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>em(e,t.in,n)):em(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>em(e,t.out,n)):em(r,t.out,n)}});function em(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var tm=H(`$ZodReadonly`,(e,t)=>{U.init(e,t),V(e,`propValues`,e=>e.def.innerType._zod.propValues),V(e,`values`,e=>e.def.innerType._zod.values),V(e,`optin`,e=>e.def.innerType?._zod?.optin),V(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(nm):nm(r)}});function nm(e){return e.memo||(e.value=Object.freeze(e.value)),e}var rm=H(`$ZodCustom`,(e,t)=>{uf.init(e,t),U.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>im(t,n,r,e));im(i,n,r,e)}});function im(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Pu(e))}}var am=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},om=`~memo`,sm=[];function cm(e){return typeof e==`object`&&!!e}function lm(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var um=new WeakMap,dm=0,fm=1,pm=2;function mm(e,t,n){let r=um.get(e);if(r!==void 0)return r?pm:dm;if(t.has(e))return pm;t.add(e);let i=dm,a=e=>{if(i!==pm&&e?._zod){let r=mm(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=dm;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?fm:o.value?._zod?mm(o.value,t,n):dm;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=ql(c);s(e?o(e,!0):fm),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?mm(r,t,!1):fm);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),hm(e,i)}function hm(e,t){return t!==fm&&um.set(e,t===pm),t}function gm(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var _m,vm=[],ym={alloc(e,t,n){let r=_m;if(!r)return n;_m=void 0;let i={value:n,issues:null};return r.set(t.value,i),vm.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&xm(n,e.value))throw new am;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=mm(e,new Set,!1);if(i===dm)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===pm||r?n=!0:r=!0}let l=s.value;if(!cm(l))return t(s,c);let u=c[om];u||(u={buckets:new WeakMap,backEdges:void 0},c[om]=u);let d;i===c?d=a:(d=gm(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...lm(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;_m=d;let p=vm.length,m=t(s,c);_m=void 0;let h=vm.length>p?vm.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?lm(e.issues):sm),e)):(h&&(h.issues=m.issues.length?lm(m.issues):sm),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function bm(){return ym}function xm(e,t){let n=e[om]?.backEdges;return n!==void 0&&cm(t)&&n.has(t)}var Sm=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(Nu(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${uu(e.values[0])}`:`Invalid option: expected one of ${zl(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${zl(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Cm(){return{localeError:Sm()}}var wm,Tm=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Em(){return new Tm}(wm=globalThis).__zod_globalRegistry??(wm.__zod_globalRegistry=Em());var Dm=globalThis.__zod_globalRegistry;function Om(e){return e.checks&&=[...e.checks],e}function km(e,t){return new e(Om({type:`string`,...B(t)}))}function Am(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...B(t)})}function jm(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...B(t)})}function Mm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...B(t)})}function Nm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...B(t)})}function Pm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...B(t)})}function Fm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...B(t)})}function Im(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...B(t)})}function Lm(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...B(t)})}function Rm(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...B(t)})}function zm(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...B(t)})}function Bm(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...B(t)})}function Vm(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...B(t)})}function Hm(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...B(t)})}function Um(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...B(t)})}function Wm(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...B(t)})}function Gm(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...B(t)})}function Km(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...B(t)})}function qm(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...B(t)})}function Jm(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...B(t)})}function Ym(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...B(t)})}function Xm(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...B(t)})}function Zm(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...B(t)})}function Qm(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...B(t)})}function $m(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...B(t)})}function eh(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...B(t)})}function th(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...B(t)})}function nh(e,t){return new e(Om({type:`number`,checks:[],...B(t)}))}function rh(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...B(t)})}function ih(e,t){return new e({type:`boolean`,...B(t)})}function ah(e){return new e({type:`unknown`})}function oh(e,t){return new e({type:`never`,...B(t)})}function sh(e,t){return new pf({check:`less_than`,...B(t),value:e,inclusive:!1})}function ch(e,t){return new pf({check:`less_than`,...B(t),value:e,inclusive:!0})}function lh(e,t){return new mf({check:`greater_than`,...B(t),value:e,inclusive:!1})}function uh(e,t){return new mf({check:`greater_than`,...B(t),value:e,inclusive:!0})}function dh(e,t){return new hf({check:`multiple_of`,...B(t),value:e})}function fh(e,t){return new _f({check:`max_length`,...B(t),maximum:e})}function ph(e,t){return new vf({check:`min_length`,...B(t),minimum:e})}function mh(e,t){return new yf({check:`length_equals`,...B(t),length:e})}function hh(e,t){return new xf({check:`string_format`,format:`regex`,...B(t),pattern:e})}function gh(e){return new Sf({check:`string_format`,format:`lowercase`,...B(e)})}function _h(e){return new Cf({check:`string_format`,format:`uppercase`,...B(e)})}function vh(e,t){return new wf({check:`string_format`,format:`includes`,...B(t),includes:e})}function yh(e,t){return new Tf({check:`string_format`,format:`starts_with`,...B(t),prefix:e})}function bh(e,t){return new Ef({check:`string_format`,format:`ends_with`,...B(t),suffix:e})}function xh(e){return new Df({check:`overwrite`,tx:e})}function Sh(e){return xh(t=>t.normalize(e))}function Ch(){return xh(e=>e.trim())}function wh(){return xh(e=>e.toLowerCase())}function Th(){return xh(e=>e.toUpperCase())}function Eh(){return xh(e=>tu(e))}function Dh(e,t,n){return new e({type:`array`,element:t,...B(n)})}function Oh(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...B(n)})}function kh(e,t){let n=Ah(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Pu(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Pu(r))}},e(t.value,t)),t);return n}function Ah(e,t){let n=new uf({check:`custom`,...B(t)});return n._zod.check=e,n}function jh(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Kl(e,t,n[t]);return e}function Mh(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Dm,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function G(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function K(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,K(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&jh(o.schema,c),t.io===`input`&&Hh(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Nh(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Ph(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${Nh(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+Nh(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
73
-
74
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Fh(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;Fh(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var Ih=new Set([`type`,`properties`,`required`,`additionalProperties`]),Lh=[`oneOf`,`anyOf`];function Rh(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function zh(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Ih.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Rh(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Kl(n,r,e.length===1?e[0]:zh(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Rh(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Bh(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ih)if(t in e)return;let n=t.filter(e=>Lh.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=zh(t);else{let e=n[0],i=Lh.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>zh([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,jh(e,r))}function Vh(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):jh(i,s),jh(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())Fh(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Bh(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}jh(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Kl(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Wh(t,`input`,e.processors),output:Wh(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Hh(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Hh(r.element,n);if(r.type===`set`)return Hh(r.valueType,n);if(r.type===`lazy`)return Hh(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return Hh(r.innerType,n);if(r.type===`intersection`)return Hh(r.left,n)||Hh(r.right,n);if(r.type===`record`||r.type===`map`)return Hh(r.keyType,n)||Hh(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Hh(r.in,n)||Hh(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Hh(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Hh(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Hh(e,n))return!0;return!!(r.rest&&Hh(r.rest,n))}return!1}var Uh=(e,t={})=>n=>{let r=Mh({...n,processors:t});return K(e,r),Ph(r,e),Vh(r,e)},Wh=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Mh({...i??{},target:a,io:t,processors:n});return K(e,o),Ph(o,e),Vh(o,e)},Gh=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Kh=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},qh=(e,t)=>{Gh(e,`minimum`,t),Kh(e,`maximum`,t)},Jh=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Yh=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Xh=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Zh=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Qh=(e,t)=>Gh(e,`minimum`,t.minimum),$h=(e,t)=>Kh(e,`maximum`,t.maximum),eg=e=>(t,n)=>{Zh(t,n.format);let[r,i]=e[n.format];Gh(t,`minimum`,r),Kh(t,`maximum`,i)},tg={greater_than:(e,t)=>Gh(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Kh(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Jh(e,t.value),number_format:eg(fu),bigint_format:eg(pu),min_length:Qh,max_length:$h,length_equals:(e,t)=>qh(e,t.length),min_size:Qh,max_size:$h,size_equals:(e,t)=>qh(e,t.size),string_format:(e,t)=>{Zh(e,t.format),t.pattern&&Yh(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Xh(e,t.mime)};function ng(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)tg[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Gh(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Gh(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Kh(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Kh(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Jh(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Xh(t,i.mime);for(let e of i.patterns??[])Yh(t,e);return t}var rg={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ig=new Map([[up,qd],[fp,Jd]]),ag=e=>ig.get(e)??e,og=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=ng(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=rg[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ag);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},sg=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ng(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):G(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},cg=(e,t,n,r)=>{n.type=`boolean`},lg=(e,t,n,r)=>{G(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},ug=(e,t,n,r)=>{G(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},dg=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},fg=(e,t,n,r)=>{G(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},pg=(e,t,n,r)=>{G(e,t,n,r,`Void cannot be represented in JSON Schema`)},mg=(e,t,n,r)=>{n.not={}},hg=(e,t,n,r)=>{},gg=(e,t,n,r)=>{},_g=(e,t,n,r)=>{G(e,t,n,r,`Date cannot be represented in JSON Schema`)},vg=(e,t,n,r)=>{let i=e._zod.def,a=Rl(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},yg=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(G(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(G(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},bg=(e,t,n,r)=>{G(e,t,n,r,`NaN cannot be represented in JSON Schema`)},xg=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Sg=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=ng(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},Cg=(e,t,n,r)=>{n.type=`boolean`},wg=(e,t,n,r)=>{G(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Tg=(e,t,n,r)=>{G(e,t,n,r,`Function types cannot be represented in JSON Schema`)},Eg=(e,t,n,r)=>{G(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Dg=(e,t,n,r)=>{G(e,t,n,r,`Map cannot be represented in JSON Schema`)},Og=(e,t,n,r)=>{G(e,t,n,r,`Set cannot be represented in JSON Schema`)},kg=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=ng(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=K(a.element,t,{...r,path:[...r.path,`items`]})};function Ag(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Ag(t.out):t.type===`catch`?Ag(t.innerType):e._zod.optin}var jg=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&G(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Kl(i.properties,e,K(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Ag(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=K(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Mg=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>K(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ng=(e,t,n,r)=>{let i=e._zod.def,a=K(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=K(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Pg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>K(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?K(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Ag(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=ng(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Fg(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Fg(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Fg(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?of:af).source)),p}var Ig=new WeakMap;function Lg(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of Ig.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Fg(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Rg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=ng(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=K(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Kl(i.patternProperties,ag(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=K(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Ig.get(t);n||(n=[],Ig.set(t,n),t.deferred.push(()=>Lg(t))),n.push(e)}i.additionalProperties=K(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Ag(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},zg=(e,t,n,r)=>{let i=e._zod.def,a=K(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Bg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Vg=Symbol();function Hg(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(G(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Vg):JSON.parse(o)}var Ug=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Hg(i.defaultValue,e,t,n,r);o!==Vg&&(n.default=o)},Wg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Hg(i.defaultValue,e,t,n,r);o!==Vg&&(n._prefault=o)},Gg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{G(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Kg=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;K(o,t,r);let s=t.seen.get(e);s.ref=o},qg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Jg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Yg=(e,t,n,r)=>{let i=e._zod.def;K(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xg={string:og,number:sg,boolean:cg,bigint:lg,symbol:ug,null:dg,undefined:fg,void:pg,never:mg,any:hg,unknown:gg,date:_g,enum:vg,literal:yg,nan:bg,template_literal:xg,file:Sg,success:Cg,custom:wg,function:Tg,transform:Eg,map:Dg,set:Og,array:kg,object:jg,union:Mg,intersection:Ng,tuple:Pg,record:Rg,nullable:zg,nonoptional:Bg,default:Ug,prefault:Wg,catch:Gg,pipe:Kg,readonly:qg,promise:Jg,optional:Yg,lazy:(e,t,n,r)=>{let i=e._zod.innerType;K(i,t,r);let a=t.seen.get(e);a.ref=i}};function Zg(e,t){if(`_idmap`in e){let n=e,r=Mh({...t,processors:Xg}),i={};for(let e of n._idmap.entries()){let[t,n]=e;K(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Ph(r,n),Kl(a,t,Vh(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Mh({...t,processors:Xg});return K(e,n),Ph(n,e),Vh(n,e)}var Qg=r({$ZodArray:()=>Ep,$ZodAsyncError:()=>Qu,$ZodBase64:()=>dp,$ZodBase64URL:()=>mp,$ZodBoolean:()=>bp,$ZodCIDRv4:()=>op,$ZodCIDRv6:()=>cp,$ZodCUID:()=>qf,$ZodCUID2:()=>Jf,$ZodCatch:()=>Qp,$ZodCheck:()=>uf,$ZodCheckEndsWith:()=>Ef,$ZodCheckGreaterThan:()=>mf,$ZodCheckIncludes:()=>wf,$ZodCheckLengthEquals:()=>yf,$ZodCheckLessThan:()=>pf,$ZodCheckLowerCase:()=>Sf,$ZodCheckMaxLength:()=>_f,$ZodCheckMinLength:()=>vf,$ZodCheckMultipleOf:()=>hf,$ZodCheckNumberFormat:()=>gf,$ZodCheckOverwrite:()=>Df,$ZodCheckRegex:()=>xf,$ZodCheckStartsWith:()=>Tf,$ZodCheckStringFormat:()=>bf,$ZodCheckUpperCase:()=>Cf,$ZodCustom:()=>rm,$ZodCyclicError:()=>am,$ZodDefault:()=>Kp,$ZodE164:()=>hp,$ZodEmail:()=>If,$ZodEmoji:()=>Gf,$ZodEncodeError:()=>$u,$ZodEnum:()=>zp,$ZodError:()=>sd,$ZodExactOptional:()=>Wp,$ZodGUID:()=>Pf,$ZodIPv4:()=>np,$ZodIPv6:()=>ap,$ZodISODate:()=>$f,$ZodISODateTime:()=>Qf,$ZodISODuration:()=>tp,$ZodISOTime:()=>ep,$ZodIntersection:()=>Fp,$ZodJWT:()=>_p,$ZodKSUID:()=>Zf,$ZodLiteral:()=>Bp,$ZodNanoID:()=>Kf,$ZodNever:()=>Sp,$ZodNonOptional:()=>Yp,$ZodNullable:()=>Gp,$ZodNumber:()=>vp,$ZodNumberFormat:()=>yp,$ZodObject:()=>jp,$ZodObjectJIT:()=>Mp,$ZodOptional:()=>Up,$ZodPipe:()=>$p,$ZodPrefault:()=>Jp,$ZodReadonly:()=>tm,$ZodRecord:()=>Rp,$ZodRegistry:()=>Tm,$ZodString:()=>Nf,$ZodStringFormat:()=>W,$ZodTransform:()=>Vp,$ZodType:()=>U,$ZodULID:()=>Yf,$ZodURL:()=>Wf,$ZodUUID:()=>Ff,$ZodUnion:()=>Pp,$ZodUnknown:()=>xp,$ZodXID:()=>Xf,$constructor:()=>H,Doc:()=>Of,NEVER:()=>Ju,URL_BAD_FORMAT:()=>1,URL_UNPARSEABLE:()=>2,_array:()=>Dh,_base64:()=>Jm,_base64url:()=>Ym,_boolean:()=>ih,_check:()=>Ah,_cidrv4:()=>Km,_cidrv6:()=>qm,_cuid:()=>zm,_cuid2:()=>Bm,_decode:()=>Cd,_decodeAsync:()=>Td,_e164:()=>Xm,_email:()=>Am,_emoji:()=>Lm,_encode:()=>Sd,_encodeAsync:()=>wd,_endsWith:()=>bh,_gt:()=>lh,_gte:()=>uh,_guid:()=>jm,_includes:()=>vh,_int:()=>rh,_ipv4:()=>Wm,_ipv6:()=>Gm,_isoDate:()=>$m,_isoDateTime:()=>Qm,_isoDuration:()=>th,_isoTime:()=>eh,_jwt:()=>Zm,_ksuid:()=>Um,_length:()=>mh,_lowercase:()=>gh,_lt:()=>sh,_lte:()=>ch,_max:()=>ch,_maxLength:()=>fh,_min:()=>uh,_minLength:()=>ph,_multipleOf:()=>dh,_nanoid:()=>Rm,_never:()=>oh,_normalize:()=>Sh,_number:()=>nh,_overwrite:()=>xh,_parse:()=>fd,_parseAsync:()=>pd,_refine:()=>Oh,_regex:()=>hh,_safeDecode:()=>Dd,_safeDecodeAsync:()=>kd,_safeEncode:()=>Ed,_safeEncodeAsync:()=>Od,_safeParse:()=>md,_safeParseAsync:()=>gd,_slugify:()=>Eh,_startsWith:()=>yh,_string:()=>km,_superRefine:()=>kh,_toLowerCase:()=>wh,_toUpperCase:()=>Th,_trim:()=>Ch,_ulid:()=>Vm,_unknown:()=>ah,_uppercase:()=>_h,_url:()=>Im,_uuid:()=>Mm,_uuidv4:()=>Nm,_uuidv6:()=>Pm,_uuidv7:()=>Fm,_xid:()=>Hm,base64Charset:()=>up,base64urlCharset:()=>fp,canParseURL:()=>Lf,config:()=>td,createStandardJSONSchemaMethod:()=>Wh,createToJSONSchemaMethod:()=>Uh,extractDefs:()=>Ph,finalize:()=>Vh,flattenError:()=>ld,formatError:()=>ud,globalConfig:()=>ed,globalRegistry:()=>Dm,handleUnrepresentable:()=>G,initializeContext:()=>Mh,isBackEdge:()=>xm,isValidBase64:()=>lp,isValidBase64URL:()=>pp,isValidCIDRv6:()=>sp,isValidIPv6:()=>ip,isValidJWT:()=>gp,memoizer:()=>bm,mergeValues:()=>Ip,parseURLObject:()=>zf,process:()=>K,processSchema:()=>K,registry:()=>Em,standardProps:()=>Mf,stripTabAndNewline:()=>Vf,toJSONSchema:()=>Zg,urlHostnameOk:()=>Hf,urlProtocolOk:()=>Uf,validate:()=>yd,validateAsync:()=>xd,validateURL:()=>Rf,version:()=>kf}),$g=new WeakSet([Object.prototype,Error.prototype]);function e_(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var t_=H(`ZodError`,(e,t)=>{sd.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);$g.has(n)||($g.add(n),e_(n,`format`,e=>t=>ud(e,t)),e_(n,`flatten`,e=>t=>ld(e,t)),e_(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Bl,2)}),e_(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Bl,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),n_=fd(t_),r_=pd(t_),i_=md(t_),a_=gd(t_),o_=Sd(t_),s_=Cd(t_),c_=wd(t_),l_=Td(t_),u_=Ed(t_),d_=Dd(t_),f_=Od(t_),p_=kd(t_);function m_(){ed.localeError||td(Cm())}function h_(){ed.memoizer||td({memoizer:bm()})}var q=H(`ZodType`,(e,t)=>(m_(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone($l(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return lu(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Fv(e,t))},superRefine(e,t){return this.check(Iv(e,t))},overwrite(e){return this.check(xh(e))},optional(){return _v(this)},exactOptional(){return yv(this)},nullable(){return xv(this)},nullish(){return _v(xv(this))},nonoptional(e){return Dv(this,e)},array(){return nv(this)},or(e){return av([this,e])},and(e){return sv(this,e)},transform(e){return jv(this,hv(e))},default(e){return Cv(this,e)},prefault(e){return Tv(this,e)},catch(e){return kv(this,e)},pipe(e){return jv(this,e)},readonly(){return Nv(this)},describe(e){let t=this.clone();return Dm.add(t,{description:e}),t},meta(...e){if(e.length===0)return Dm.get(this);let t=this.clone();return Dm.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Lu(this,`~standard`,{...Mf(this),jsonSchema:{input:Wh(this,`input`),output:Wh(this,`output`)}})},set"~standard"(e){Iu(this,`~standard`,e)},parse:function e(t,n){return n_(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await r_(this,t,n,{callee:e})},safeParse(e,t){return i_(this,e,t)},async safeParseAsync(e,t){return a_(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Iu(this,`spa`,e)},validate(e,t){return yd(this,e,t)},validateAsync(e,t){return xd(this,e,t)},encode:function e(t,n){return o_(this,t,n,{callee:e})},decode:function e(t,n){return s_(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await c_(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await l_(this,t,n,{callee:e})},safeEncode(e,t){return u_(this,e,t)},safeDecode(e,t){return d_(this,e,t)},async safeEncodeAsync(e,t){return f_(this,e,t)},async safeDecodeAsync(e,t){return p_(this,e,t)},toJSONSchema(e){return Uh(this,{})(e)},get description(){return Dm.get(this)?.description},get _def(){return this._zod.def}}),g_=H(`_ZodString`,(e,t)=>{Nf.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>og(e,t,n,r)},Ru({format:e=>ng(e).format??null,minLength:e=>ng(e).minimum??null,maxLength:e=>ng(e).maximum??null},{regex(...e){return this.check(hh(...e))},includes(...e){return this.check(vh(...e))},startsWith(...e){return this.check(yh(...e))},endsWith(...e){return this.check(bh(...e))},min(...e){return this.check(ph(...e))},max(...e){return this.check(fh(...e))},length(...e){return this.check(mh(...e))},nonempty(...e){return this.check(ph(1,...e))},lowercase(e){return this.check(gh(e))},uppercase(e){return this.check(_h(e))},trim(){return this.check(Ch())},normalize(...e){return this.check(Sh(...e))},toLowerCase(){return this.check(wh())},toUpperCase(){return this.check(Th())},slugify(){return this.check(Eh())}})),__=H(`ZodString`,(e,t)=>{Nf.init(e,t),g_.init(e,t)},{email(e){return this.check(Am(S_,e))},url(e){return this.check(Im(E_,e))},jwt(e){return this.check(Zm(W_,e))},emoji(e){return this.check(Lm(O_,e))},guid(e){return this.check(jm(w_,e))},uuid(e){return this.check(Mm(T_,e))},uuidv4(e){return this.check(Nm(T_,e))},uuidv6(e){return this.check(Pm(T_,e))},uuidv7(e){return this.check(Fm(T_,e))},nanoid(e){return this.check(Rm(k_,e))},cuid(e){return this.check(zm(A_,e))},cuid2(e){return this.check(Bm(j_,e))},ulid(e){return this.check(Vm(M_,e))},base64(e){return this.check(Jm(V_,e))},base64url(e){return this.check(Ym(H_,e))},xid(e){return this.check(Hm(N_,e))},ksuid(e){return this.check(Um(P_,e))},ipv4(e){return this.check(Wm(F_,e))},ipv6(e){return this.check(Gm(L_,e))},cidrv4(e){return this.check(Km(z_,e))},cidrv6(e){return this.check(qm(B_,e))},e164(e){return this.check(Xm(U_,e))},datetime(e){return this.check(Qm(v_,e))},date(e){return this.check($m(y_,e))},time(e){return this.check(eh(b_,e))},duration(e){return this.check(th(x_,e))}});function J(e){return km(__,e)}var Y=H(`ZodStringFormat`,(e,t)=>{W.init(e,t),g_.init(e,t)}),v_=H(`ZodISODateTime`,(e,t)=>{Qf.init(e,t),Y.init(e,t)}),y_=H(`ZodISODate`,(e,t)=>{$f.init(e,t),Y.init(e,t)}),b_=H(`ZodISOTime`,(e,t)=>{ep.init(e,t),Y.init(e,t)}),x_=H(`ZodISODuration`,(e,t)=>{tp.init(e,t),Y.init(e,t)}),S_=H(`ZodEmail`,(e,t)=>{If.init(e,t),Y.init(e,t)});function C_(e){return Am(S_,e)}var w_=H(`ZodGUID`,(e,t)=>{Pf.init(e,t),Y.init(e,t)}),T_=H(`ZodUUID`,(e,t)=>{Ff.init(e,t),Y.init(e,t)}),E_=H(`ZodURL`,(e,t)=>{Wf.init(e,t),Y.init(e,t)});function D_(e){return Im(E_,e)}var O_=H(`ZodEmoji`,(e,t)=>{Gf.init(e,t),Y.init(e,t)}),k_=H(`ZodNanoID`,(e,t)=>{Kf.init(e,t),Y.init(e,t)}),A_=H(`ZodCUID`,(e,t)=>{qf.init(e,t),Y.init(e,t)}),j_=H(`ZodCUID2`,(e,t)=>{Jf.init(e,t),Y.init(e,t)}),M_=H(`ZodULID`,(e,t)=>{Yf.init(e,t),Y.init(e,t)}),N_=H(`ZodXID`,(e,t)=>{Xf.init(e,t),Y.init(e,t)}),P_=H(`ZodKSUID`,(e,t)=>{Zf.init(e,t),Y.init(e,t)}),F_=H(`ZodIPv4`,(e,t)=>{np.init(e,t),Y.init(e,t)});function I_(e){return Wm(F_,e)}var L_=H(`ZodIPv6`,(e,t)=>{ap.init(e,t),Y.init(e,t)});function R_(e){return Gm(L_,e)}var z_=H(`ZodCIDRv4`,(e,t)=>{op.init(e,t),Y.init(e,t)}),B_=H(`ZodCIDRv6`,(e,t)=>{cp.init(e,t),Y.init(e,t)}),V_=H(`ZodBase64`,(e,t)=>{dp.init(e,t),Y.init(e,t)}),H_=H(`ZodBase64URL`,(e,t)=>{mp.init(e,t),Y.init(e,t)}),U_=H(`ZodE164`,(e,t)=>{hp.init(e,t),Y.init(e,t)}),W_=H(`ZodJWT`,(e,t)=>{_p.init(e,t),Y.init(e,t)}),G_=H(`ZodNumber`,(e,t)=>{vp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sg(e,t,n,r),e.isFinite=!0},Ru({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=ng(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=ng(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=ng(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>ng(e).format??null},{gt(e,t){return this.check(lh(e,t))},gte(e,t){return this.check(uh(e,t))},min(e,t){return this.check(uh(e,t))},lt(e,t){return this.check(sh(e,t))},lte(e,t){return this.check(ch(e,t))},max(e,t){return this.check(ch(e,t))},int(e){return this.check(J_(e))},safe(e){return this.check(J_(e))},positive(e){return this.check(lh(0,e))},nonnegative(e){return this.check(uh(0,e))},negative(e){return this.check(sh(0,e))},nonpositive(e){return this.check(ch(0,e))},multipleOf(e,t){return this.check(dh(e,t))},step(e,t){return this.check(dh(e,t))},finite(){return this}}));function K_(e){return nh(G_,e)}var q_=H(`ZodNumberFormat`,(e,t)=>{yp.init(e,t),G_.init(e,t)});function J_(e){return rh(q_,e)}var Y_=H(`ZodBoolean`,(e,t)=>{bp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cg(e,t,n,r)});function X_(e){return ih(Y_,e)}var Z_=H(`ZodUnknown`,(e,t)=>{xp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Q_(){return ah(Z_)}var $_=H(`ZodNever`,(e,t)=>{Sp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mg(e,t,n,r)});function ev(e){return oh($_,e)}var tv=H(`ZodArray`,(e,t)=>{h_(),Ep.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>kg(e,t,n,r),e.element=t.element},{min(e,t){return this.check(ph(e,t))},nonempty(e){return this.check(ph(1,e))},max(e,t){return this.check(fh(e,t))},length(e,t){return this.check(mh(e,t))},unwrap(){return this.element}});function nv(e,t){return Dh(tv,e,t)}var rv=H(`ZodObject`,(e,t)=>{h_(),Mp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jg(e,t,n,r),Wu(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return dv(Object.keys(this._zod.def.shape))},catchall(e){return this.clone($l(this._zod.def,{catchall:e}))},passthrough(){return this.clone($l(this._zod.def,{catchall:Q_()}))},loose(){return this.clone($l(this._zod.def,{catchall:Q_()}))},strict(){return this.clone($l(this._zod.def,{catchall:ev()}))},strip(){return this.clone($l(this._zod.def,{catchall:void 0}))},extend(e){return _u(this,e)},safeExtend(e){return yu(this,e)},merge(e){return bu(this,e)},pick(e){return mu(this,e)},omit(e){return gu(this,e)},partial(...e){return xu(gv,this,e[0])},exactPartial(...e){return xu(vv,this,e[0],`exactPartial`)},required(...e){return Su(Ev,this,e[0])}});function X(e,t){return new rv({type:`object`,shape:e??{},...B(t)})}var iv=H(`ZodUnion`,(e,t)=>{Pp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mg(e,t,n,r),e.options=t.options});function av(e,t){return new iv({type:`union`,options:e,...B(t)})}var ov=H(`ZodIntersection`,(e,t)=>{Fp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ng(e,t,n,r)});function sv(e,t){return new ov({type:`intersection`,left:e,right:t})}var cv=H(`ZodRecord`,(e,t)=>{h_(),Rp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rg(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function lv(e,t,n){return!t||!t._zod?new cv({type:`record`,keyType:J(),valueType:e,...B(t)}):new cv({type:`record`,keyType:e,valueType:t,...B(n)})}var uv=H(`ZodEnum`,(e,t)=>{zp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vg(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new uv({...t,checks:[],...B(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new uv({...t,checks:[],...B(r),entries:i})}});function dv(e,t){return new uv({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...B(t)})}var fv=H(`ZodLiteral`,(e,t)=>{Bp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yg(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function pv(e,t){return new fv({type:`literal`,values:Array.isArray(e)?e:[e],...B(t)})}var mv=H(`ZodTransform`,(e,t)=>{h_(),Vp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eg(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $u(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Pu(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Pu(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function hv(e){return new mv({type:`transform`,transform:e})}var gv=H(`ZodOptional`,(e,t)=>{Up.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function _v(e){return new gv({type:`optional`,innerType:e})}var vv=H(`ZodExactOptional`,(e,t)=>{Wp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yv(e){return new vv({type:`optional`,innerType:e})}var bv=H(`ZodNullable`,(e,t)=>{Gp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function xv(e){return new bv({type:`nullable`,innerType:e})}var Sv=H(`ZodDefault`,(e,t)=>{Kp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Cv(e,t){return new Sv({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ou(t)}})}var wv=H(`ZodPrefault`,(e,t)=>{Jp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Tv(e,t){return new wv({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ou(t)}})}var Ev=H(`ZodNonOptional`,(e,t)=>{Yp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Dv(e,t){return new Ev({type:`nonoptional`,innerType:e,...B(t)})}var Ov=H(`ZodCatch`,(e,t)=>{Qp.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function kv(e,t){return new Ov({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Ku(t)})}var Av=H(`ZodPipe`,(e,t)=>{$p.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kg(e,t,n,r),e.in=t.in,e.out=t.out});function jv(e,t){return new Av({type:`pipe`,in:e,out:t})}var Mv=H(`ZodReadonly`,(e,t)=>{tm.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Nv(e){return new Mv({type:`readonly`,innerType:e})}var Pv=H(`ZodCustom`,(e,t)=>{rm.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wg(e,t,n,r)});function Fv(e,t={}){return Oh(Pv,e,t)}function Iv(e,t){return kh(e,t)}function Lv(e){return Qm(v_,e)}var Rv=`https://github.com/tempoxyz/id/blob/main/docs/errors.md`,zv={already_decided:{description:`The user code was already approved or denied.`,error:`invalid_request`,status:409},app_exists:{description:`Another OAuth app already has the client ID.`,error:`invalid_request`,status:409},authorization_expired:{description:`The app's authorization request that sign-in or the approval page continues is forged or expired.`,error:`invalid_request`,status:400},backend_sign_in_not_permitted:{description:`The app may not sign users in from its backend: it is not an enabled first-party app with a client secret and backend sign-in.`,error:`unauthorized_client`,status:403},body_too_large:{description:`The request body exceeds 64 KiB.`,error:`invalid_request`,status:413},challenge_not_permitted:{description:"A request carries a challenge, and its app lacks the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},config_conflict:{description:`The chain's configuration of the account differs from the one that Tempo ID stores.`,error:`invalid_request`,status:409},configurable_accounts_disabled:{description:`The deployment has no configurable accounts, or the request names another chain.`,error:`invalid_request`,status:400},cross_site_request:{description:`A form or body-less write came from another site.`,error:`access_denied`,status:403},duplicate_limit:{description:`Two limits name the same token.`,error:`invalid_authorization_details`,status:400},duplicate_scope:{description:`Two scopes name the same call on one target, or one allows any function on a target that another names a function on.`,error:`invalid_authorization_details`,status:400},empty_limits:{description:"`limits` is an empty list.",error:`invalid_authorization_details`,status:400},empty_scopes:{description:"`scopes` is an empty list.",error:`invalid_authorization_details`,status:400},expiry_exceeds_maximum:{description:`A headless key lasts longer than a year.`,error:`invalid_authorization_details`,status:403},expiry_passed:{description:`The key expiry has passed.`,error:`invalid_authorization_details`,status:400},foreign_account:{description:`The request names a Tempo Account that is not the user's in the app's realms.`,error:`access_denied`,status:403},invalid_app:{description:`A value of an OAuth app, such as its name or a redirect URI, is not valid, or does not fit the app's type.`,error:`invalid_request`,status:400},invalid_chain:{description:`The key chain ID is 0.`,error:`invalid_authorization_details`,status:400},invalid_client:{description:`The client authentication failed: the app is unknown or disabled, or the client secret is missing or wrong.`,error:`invalid_client`,status:401},invalid_code:{description:`The emailed code is wrong or expired.`,error:`invalid_grant`,status:401},invalid_expiry:{description:`The key expiry is 0, which never expires.`,error:`invalid_authorization_details`,status:400},invalid_field:{description:`A field is missing or malformed.`,error:`invalid_request`,status:400},invalid_id_token_hint:{description:`The ID token hint is not an ID token that Tempo ID signed for the app.`,error:`invalid_request`,status:400},invalid_origin:{description:`A headless request came from an origin its redirect URI does not allow.`,error:`unauthorized_client`,status:403},invalid_period:{description:"A limit's `period` is not a whole number of seconds.",error:`invalid_authorization_details`,status:400},invalid_public_key:{description:`The key public key is not a valid point.`,error:`invalid_authorization_details`,status:400},invalid_recipients:{description:"A scope's `recipients` names the zero address or a duplicate, or is on a call other than `transfer`, `transferWithMemo`, or `approve` on a TIP-20 token.",error:`invalid_authorization_details`,status:400},limit_exceeds_maximum:{description:`A headless key limit exceeds the token’s ceiling.`,error:`invalid_authorization_details`,status:403},logout_not_permitted:{description:`The app that the ID token hint names may not end the session at the end-session endpoint.`,error:`unauthorized_client`,status:403},malformed_body:{description:`The request body is not valid JSON.`,error:`invalid_request`,status:400},missing_key:{description:`The key authorization names no key.`,error:`invalid_authorization_details`,status:400},missing_permissions:{description:"A third-party app's key request leaves out `expiry`, `limits`, or `scopes`.",error:`invalid_authorization_details`,status:400},missing_recipients:{description:"An `approve` scope names no spenders.",error:`invalid_authorization_details`,status:400},passkey_link_expired:{description:`The email step's link to a wallet.tempo passkey expired, or the browser holds no link for it.`,error:`invalid_request`,status:400},passkey_not_permitted:{description:`A passkey sign-in names an app, or reaches a realm, that holds no passkeys for Tempo ID.`,error:`unauthorized_client`,status:403},passkey_register_not_permitted:{description:"A passkey registration comes from an app's page, and no app at the page's origin holds the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},not_configurable:{description:`The account is not configurable on the chain, so no owner can join it, or no passkey owns it, so it cannot upgrade.`,error:`invalid_request`,status:400},owner_exists:{description:`The account already holds the owner that the request adds, or is already configurable.`,error:`invalid_request`,status:409},passkey_limit:{description:`The user holds the most passkeys that Tempo ID registers for one user.`,error:`access_denied`,status:403},post_logout_redirect_not_permitted:{description:`The post-logout redirect URI is not one of the post-logout redirect URIs the app registered.`,error:`invalid_request`,status:400},public_app:{description:`The OAuth app redeems codes with PKCE alone, so it has no client secret to rotate.`,error:`invalid_request`,status:400},rate_limited:{description:`Tempo ID, or a service it depends on, is rate limiting the request.`,error:`temporarily_unavailable`,status:429},reauthentication_required:{description:`The request needs a session that signed in within the last 10 minutes.`,error:`login_required`,status:401},rejected:{description:`The issuer refused the authorization request.`,error:`invalid_request`,status:400},scope_without_limit:{description:`A scope calls a listed token that no limit names.`,error:`invalid_authorization_details`,status:400},session_changed:{description:`The signed-in session differs from the one that the approval page showed.`,error:`invalid_request`,status:409},session_required:{description:`The request needs a signed-in session.`,error:`login_required`,status:401},sign_up_not_permitted:{description:`The verified address has no account, and its domain is not one where the deployment creates accounts.`,error:`access_denied`,status:403},unexpected:{description:`An unexpected failure.`,error:`server_error`,status:500},unknown_app:{description:`No registered OAuth app has the client ID.`,error:`invalid_request`,status:404},unknown_code:{description:`The user code is wrong or expired.`,error:`invalid_request`,status:404},unknown_endpoint:{description:`No API endpoint matches this method and path.`,error:`invalid_request`,status:404},unsupported_call:{description:`A selector does not parse, a scope allows any function on a TIP-20 token, or a headless scope names an unrecognized call.`,error:`invalid_authorization_details`,status:400},unsupported_token:{description:`A limit names a token that is not supported on the chain.`,error:`invalid_authorization_details`,status:400},upgrade_required:{description:`A key authorization names a wallet.tempo passkey's account on a chain whose accounts are configurable, before its upgrade.`,error:`interaction_required`,status:403},upstream_unavailable:{description:`A service Tempo ID depends on failed or did not respond.`,error:`temporarily_unavailable`,status:503},webauthn_rejected:{description:`A passkey ceremony failed: its challenge is unknown, spent, or expired, or its response does not verify.`,error:`access_denied`,status:401},webauthn_required:{description:`A request without a page names a Tempo Account whose passkey signs only on a Tempo ID page.`,error:`interaction_required`,status:403}},Bv=class extends tt{name=`ErrorResponse.ResponseError`;response;constructor(e){let t=zv[e.reason].status;super(t,{res:Response.json(e,{status:t})}),this.response=e}};function Vv(e){return class extends Bv{static reason=e;constructor(t){super(Yv({...t,reason:e}))}}}var Hv=class extends Vv(`cross_site_request`){name=`ErrorResponse.CrossSiteRequestError`;constructor(){super({error_description:`Cross-site request refused. Send JSON from an allowed origin.`})}},Uv=class extends Vv(`malformed_body`){name=`ErrorResponse.MalformedBodyError`;constructor(){super({error_description:"Malformed request body. Send a JSON object with `Content-Type: application/json`."})}},Wv=class extends Vv(`rate_limited`){name=`ErrorResponse.RateLimitedError`;retryAfter;constructor(e={}){let{retryAfter:t}=e;super({error_description:`Rate limited by an upstream service. Try again ${t?`in ${Qv({seconds:t})}`:`later`}.`,...t?{meta:{retryAfter:t}}:{}}),this.retryAfter=t}},Gv=class extends Vv(`unexpected`){name=`ErrorResponse.UnexpectedError`;constructor(){super({error_description:`Unexpected error. Try again.`})}},Kv=class extends Vv(`unknown_endpoint`){name=`ErrorResponse.UnknownEndpointError`;constructor(){super({error_description:`Unknown endpoint. Check the method and path against the API reference at /openapi.json.`})}},qv=class extends Vv(`upstream_unavailable`){name=`ErrorResponse.UpstreamUnavailableError`;constructor(){super({error_description:`An upstream service is unavailable. Retry later.`})}},Jv;(function(e){let t=e.base=X({error:J().meta({description:"The OAuth error code (RFC 6749, OIDC Core, RFC 8628, RFC 9396), which `reason` determines."}),error_description:J().meta({description:`What went wrong and how to fix it, for people. Its wording may change.`}),error_uri:D_().meta({description:"The errors page, at the refusal’s `reason`."}),field:J().optional().meta({description:`Extension: the request field at fault, as a dotted path.`}),meta:lv(J(),av([K_(),J()])).readonly().optional().meta({description:`Extension: the values the refusal compared. Base units are decimal strings.`}),reason:J().meta({description:`Extension: a stable name for the refusal, to branch on.`}),request_id:J().optional().meta({description:"Extension: the request ID, which `X-Request-Id` also carries. The Worker adds it to every error response."})}),n={already_decided:{error_description:`Code already approved or denied.`,field:`code`},app_exists:{error_description:`App client_01JZ8Q6W3N1R5B4V7C2X9K0M3T already exists. Update it, or choose another client ID.`,field:`clientId`},authorization_expired:{error_description:`Expired authorization request: the request from the app is no longer valid. Return to the app, and start again.`,field:`oauth_query`},backend_sign_in_not_permitted:{error_description:"Backend sign-in not permitted: the app does not hold backend sign-in. Grant it with `tempo-id admin apps update --backend-sign-in`.",field:`client_id`},body_too_large:{error_description:`Invalid request body: exceeds the 65536-byte maximum. Send a body of 65536 bytes or fewer.`},challenge_not_permitted:{error_description:"Challenge not permitted: the app lacks the `tempo-id:sign` scope. Remove `challenge`, or grant the app the scope.",field:`challenge`},config_conflict:{error_description:`Configuration conflict: the chain's configuration of 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c differs from the stored one. Reload the account, and try again.`,field:`account`},configurable_accounts_disabled:{error_description:"Configurable accounts are not available on the chain `testnet`. Select the chain `t14`.",field:`chain`},cross_site_request:{error_description:`Cross-site request refused. Send JSON from an allowed origin.`},duplicate_limit:{error_description:`Duplicate limit for 0x20c0000000000000000000000000000000000001. Limit each token once.`,field:`key_authorization.limits.1.token`},duplicate_scope:{error_description:`Duplicate scope for 0xa9059cbb on OUSD. Name each call on a target once.`,field:`key_authorization.scopes.1.selector`},empty_limits:{error_description:"Empty `limits`. Name at least one token, or omit `limits`.",field:`key_authorization.limits`},empty_scopes:{error_description:"Empty `scopes`. Name at least one call, or omit `scopes`.",field:`key_authorization.scopes`},expiry_exceeds_maximum:{error_description:"Invalid `expiry`: Sat, 01 Jan 2028 00:00:00 GMT exceeds the one-year maximum. Use an earlier expiry, or authorize through a redirect or device grant.",field:`key_authorization.expiry`},expiry_passed:{error_description:"Invalid `expiry`: Wed, 01 Jan 2025 00:00:00 GMT has passed. Use a future Unix time.",field:`key_authorization.expiry`},foreign_account:{error_description:`Access denied to Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c. Name one of the user's accounts in the app's realms.`,field:`account`},invalid_app:{error_description:`Invalid redirect URI: http://app.example/callback uses http. Use an https URI.`},invalid_chain:{error_description:"Invalid `chainId`: 0. Use a Tempo chain ID, such as 4217.",field:`key_authorization.chainId`},invalid_client:{error_description:`Client authentication failed. Send the client ID and secret of an enabled app.`,field:`client_secret`},invalid_code:{error_description:`Invalid or expired code. Request a new one.`,field:`code`},invalid_expiry:{error_description:"Invalid `expiry`: 0 never expires. Use a future Unix time.",field:`key_authorization.expiry`},invalid_field:{error_description:"Invalid request. `email`: Invalid email address.",field:`email`},invalid_id_token_hint:{error_description:`Invalid id_token_hint: it is not an ID token that this issuer signed for the app. Send the ID token that the app received at sign-in.`,field:`id_token_hint`},invalid_origin:{error_description:"Invalid `Origin`: https://other.example.com. Requests for this redirect URI must come from https://app.example.com.",field:`Origin`},invalid_period:{error_description:"Invalid `period` on the OUSD limit: 1.5. Use a whole number of seconds, or 0 for a one-time limit.",field:`key_authorization.limits.0.period`},invalid_public_key:{error_description:"Invalid `publicKey`. Provide an uncompressed public key, or `address`.",field:`key_authorization.publicKey`},invalid_recipients:{error_description:`Invalid recipient 0x0000000000000000000000000000000000000000 for 0x095ea7b3 on OUSD. Name each recipient once, and never the zero address.`,field:`key_authorization.scopes.0.recipients.0`},limit_exceeds_maximum:{error_description:`Invalid OUSD limit: 5000 exceeds the 1000 maximum. Lower the limit, or authorize through a redirect or device grant.`,field:`key_authorization.limits.0.limit`},logout_not_permitted:{error_description:`Logout not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T may not end the session. Register the app for logout, then retry.`},malformed_body:{error_description:"Malformed request body. Send a JSON object with `Content-Type: application/json`."},missing_key:{error_description:"Missing `address` or `publicKey`. Provide the access key.",field:`key_authorization.address`},missing_permissions:{error_description:"Missing `limits` and `scopes`. Name the expiry, limits, and scopes of the key, since a third-party app receives no defaults.",field:`key_authorization.limits`},missing_recipients:{error_description:"Missing `recipients` for `approve` on OUSD. Name the allowed spenders.",field:`key_authorization.scopes.0.recipients`},passkey_link_expired:{error_description:`Expired passkey sign-in: the link from the passkey step is no longer valid. Enter the code again to sign in with email only, or sign in with the passkey again.`,field:`link`},passkey_not_permitted:{error_description:`Passkey not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T holds no passkeys. Sign in with an emailed code.`},passkey_register_not_permitted:{error_description:"Passkey registration not permitted: no app at https://app.example.com holds the `tempo-id:sign` scope. Register the passkey on Tempo ID, or grant the app the scope."},not_configurable:{error_description:`Not configurable: 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c is not a configurable account yet. Upgrade it with its passkey, then add the owner.`,field:`account`},owner_exists:{error_description:`Owner exists: a cloud wallet already owns 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c. Use the account as it is.`,field:`wallet`},passkey_limit:{error_description:`Passkey limit reached: the user holds 10 registered passkeys, the most that Tempo ID registers. Sign in with one of them.`},post_logout_redirect_not_permitted:{error_description:`Invalid post_logout_redirect_uri: https://app.example/elsewhere is not registered for the app. Use one of its post-logout redirect URIs, or leave it out.`,field:`post_logout_redirect_uri`},public_app:{error_description:`App client_01JZ8Q6W3N1R5B4V7C2X9K0M3T has no client secret. Rotate the secret of an app with a backend.`,field:`clientId`},rate_limited:{error_description:`Too many requests. Try again in 30 seconds.`},reauthentication_required:{error_description:`Sign in again: adding a passkey needs a sign-in within the last 10 minutes.`},rejected:{error_description:"Authorization request rejected. Check `client_id`, `redirect_uri`, and `scope` against the app's registration."},scope_without_limit:{error_description:`Scope on 0x20c0000000000000000000000000000000000002 has no limit. Add a limit for it, or remove the scope.`,field:`key_authorization.scopes.0.address`},session_changed:{error_description:`Changed session: the signed-in account differs from the one that this page showed. Reload the page, and check the account before the decision.`,field:`session_id`},session_required:{error_description:`Sign in first.`},sign_up_not_permitted:{error_description:`Sign-up not permitted: new accounts need an address at example.com. Sign in with an existing account, or with an address at example.com.`,field:`email`},unexpected:{error_description:`Unexpected error. Try again.`},unknown_app:{error_description:`Unknown app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T. Name a registered OAuth app.`,field:`clientId`},unknown_code:{error_description:`Invalid or expired code. Check the code in the terminal.`,field:`code`},unknown_endpoint:{error_description:`Unknown endpoint. Check the method and path against the API reference at /openapi.json.`},unsupported_call:{error_description:"Unsupported call on OUSD: any function, which includes `approve` without spenders. Name each function in `selector`, such as `transfer`.",field:`key_authorization.scopes.0.selector`},unsupported_token:{error_description:`Unsupported token on chain 4217: 0x20c00000000000000000000000000000000000ff. Use a supported token, such as OUSD.`,field:`key_authorization.limits.0.token`},upgrade_required:{error_description:`Upgrade required: Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c is not a configurable account on this chain yet. Upgrade it on the account page, then authorize again.`,field:`key_authorization.account`},upstream_unavailable:{error_description:`An upstream service is unavailable. Retry later.`},webauthn_rejected:{error_description:`Passkey rejected. Request new options, then try again with the same passkey or another one.`},webauthn_required:{error_description:`Passkey required: Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c signs key authorizations only with its passkey, on a Tempo ID page. Authorize through a redirect, popup, or device grant, or name another account.`,field:`key_authorization.account`}},r=new Map(Object.entries(zv).map(([e,r])=>{let i=n[e],a=t.extend({error:pv(r.error).meta(t.shape.error.meta()),error_description:t.shape.error_description.meta({...t.shape.error_description.meta(),examples:[i.error_description]}),error_uri:t.shape.error_uri.meta({...t.shape.error_uri.meta(),examples:[`${Rv}#${e}`]}),reason:pv(e).meta(t.shape.reason.meta()),request_id:t.shape.request_id.meta({...t.shape.request_id.meta(),examples:[`8f1c2a3b4d5e6f70-SJC`]})});return[e,(i.field?a.extend({field:t.shape.field.meta({...t.shape.field.meta(),examples:[i.field]})}):a.omit({field:!0})).meta({description:`\`${r.error}\` (${r.status}): ${r.description}`,id:`ErrorResponse.${e}`})]}));function i(e){return r.get(e)}e.of=i})(Jv||={});function Yv(e){let{error_description:t,field:n,meta:r,reason:i}=e;return{error:zv[i].error,error_description:t,error_uri:`${Rv}#${i}`,...n?{field:n}:{},...r?{meta:r}:{},reason:i}}function Xv(e){if(e instanceof tt)return;let t=`status`in e?e.status:void 0;if(t===429)return new Wv({retryAfter:(()=>{if(e instanceof Response){let t=Number(e.headers.get(`retry-after`));return Number.isInteger(t)&&t>0?t:void 0}return`retryAfter`in e&&typeof e.retryAfter==`number`?e.retryAfter:void 0})()});let n=`status`in e&&t===void 0;if(typeof t==`number`&&(t===408||t>=500)||n||e instanceof Error&&e.name===`TimeoutError`)return new qv}(function(e){e.errors=[Wv,qv]})(Xv||={});function Zv(e,t){if(e instanceof Bv)return Z(t,e);if(e instanceof tt&&e.status===400)return Z(t,new Uv);if(e instanceof tt&&e.status===403)return Z(t,new Hv);let n=Xv(e);return n?(nn(t,{error:e,message:`An upstream service refused a request.`}),Z(t,n)):($t(t,{error:e,message:`The API failed a request.`}),Z(t,new Gv))}function Z(e,t){let{response:n}=t;return t instanceof Wv&&t.retryAfter&&e.header(`retry-after`,String(t.retryAfter)),e.json(n,zv[n.reason].status)}function Qv(e){let{seconds:t}=e,[n,r]=t<60?[t,`second`]:t<3600?[Math.ceil(t/60),`minute`]:[Math.ceil(t/3600),`hour`];return new Intl.NumberFormat(`en`,{style:`unit`,unit:r,unitDisplay:`long`}).format(n)}var $v=class extends Vv(`body_too_large`){name=`BodyLimit.BodyTooLargeError`;constructor(){super({error_description:`Invalid request body: exceeds the ${ey}-byte maximum. Send a body of ${ey} bytes or fewer.`,meta:{maximum:ey}})}},ey=65536,ty=Ll({maxSize:ey,onError:e=>Z(e,new $v)}),ny=e=>e.__COMPOSED_HANDLER?ny(e[Ct]):e,ry=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;return n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t),h(r,e)[e]}return r?h(r):{}},iy=(e,t,n)=>{let r;return r=n?.prefix===`secure`?d(`__Secure-`+e,t,{path:`/`,...n,secure:!0}):n?.prefix===`host`?d(`__Host-`+e,t,{...n,path:`/`,secure:!0,domain:void 0}):d(e,t,{path:`/`,...n}),r},ay=(e,t,n,r)=>{let i=iy(t,n,r);e.header(`Set-Cookie`,i,{append:!0})},oy=(e,t,n)=>{let r=ry(e,t,n?.prefix);return ay(e,t,``,{...n,maxAge:0}),r},sy=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i,cy=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/i,ly=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i,uy=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!sy.test(a))break;try{i=await n.req.json()}catch{throw new tt(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(cy.test(a)||ly.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{e=await rt(await n.req.arrayBuffer(),a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new tt(400,{message:t})}let t=Object.create(null);e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):Object.hasOwn(t,n)?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ry(n)}let o=await t(i,n);return o instanceof Response?o:(n.req.addValidatedData(e,o),await r())},dy={header:[`cookie`]};function fy(e,t,n){if(!(n in dy))return e;let r=dy[n]||[];return t===`arktype`?py(e,r):t===`valibot`?my(e,r):e}function py(e,t){return e.map(e=>{if(e&&typeof e==`object`&&`data`in e&&typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)){let n={...e.data};for(let e of t)delete n[e];let r=Object.create(Object.getPrototypeOf(e));return Object.assign(r,e,{data:n}),r}return e})}function my(e,t){return e.map(e=>{if(e&&typeof e==`object`&&`path`in e&&Array.isArray(e.path)){for(let n of e.path)if(typeof n==`object`&&`input`in n&&typeof n.input==`object`&&n.input!==null&&!Array.isArray(n.input))for(let e of t)delete n.input[e]}return e})}var hy=(e,t,n)=>uy(e,async(r,i)=>{let a=await t[`~standard`].validate(r);if(n){let t=await n(a.issues?{data:r,error:a.issues,success:!1,target:e}:{data:r,success:!0,target:e},i);if(t){if(t instanceof Response)return t;if(typeof t==`object`&&`response`in t)return t.response}}if(a.issues){let n=fy(a.issues,t[`~standard`].vendor,e);return i.json({data:r,error:n,success:!1},400)}return a.value}),gy=Symbol(`openapi`),_y=`__HonoOpenAPIValidator__`,vy=[`GET`,`PUT`,`POST`,`DELETE`,`OPTIONS`,`HEAD`,`PATCH`,`TRACE`],yy=e=>{let t=e;if(t.startsWith(`:`)){let e=t.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);e?t=`{${e[1]}}`:(t=t.slice(1,t.length),t.endsWith(`?`)&&(t=t.slice(0,-1)),t=`{${t}}`)}return t},by=e=>e.split(`/`).map(yy).join(`/`),xy=e=>e.split(/[\W_]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``),Sy=e=>{let t=e.method.toLowerCase();if(e.path===`/`)return`${t}Index`;for(let n of e.path.split(`/`)){let e=yy(n);e.charCodeAt(0)===123?t+=`By${xy(e.slice(1,-1))}`:t+=xy(e)}return t},Cy=e=>`$ref`in e?e.$ref:`${e.in} ${e.name}`;function wy(...e){let t=e.flatMap(e=>e??[]).reduce((e,t)=>(e.set(Cy(t),t),e),new Map);return Array.from(t.values())}var Ty=new Map;function Ey(e,t){let n=[];for(let[r,i]of t){if(!i)continue;let t=r.endsWith(`/*`)?r.slice(0,-2):r;(e===t||e.startsWith(`${t}/`))&&n.push(i)}return n}function Dy(e,t){return!e||!t||`$ref`in e||`$ref`in t?t:{...e,...t,content:{...e.content,...t.content}}}function Oy(e,...t){return t.reduce((t,n)=>{if(!n||!t)return t;for(let[r,i]of Object.entries(n))if(i!=null){if(r in t&&(typeof i==`object`||typeof i==`function`&&r===`operationId`)){if(Array.isArray(i)){let e=[...t[r]??[],...i];t[r]=r===`tags`?Array.from(new Set(e)):r===`parameters`?wy(e):e}else typeof i==`function`?t[r]=i(e):r===`parameters`?t[r]=wy(t[r],i):r===`requestBody`?t.requestBody=Dy(t.requestBody,i):t[r]={...t[r],...i}}else t[r]=i}return t},{operationId:Sy(e)})}function ky({route:e,specs:t,paths:n},r=Ty){let i=by(e.path),a=e.method.toLowerCase();if(a===`all`){if(!t)return;if(r.has(i)){let n=r.get(i)??{};r.set(i,Oy(e,n,t))}else r.set(i,t)}else{let o=Ey(i,r);i in n||(n[i]={}),n[i]&&(n[i][a]=Oy(e,...o,n[i]?.[a],t))}}function Ay(e,t){let{exclude:n,excludeStaticFile:r}=t.options,i={},a=Array.isArray(n)?n:[n];for(let[n,o]of Object.entries(e)){if(o==null||a.some(e=>typeof e==`string`?n===e:e.test(n))||n.includes(`*`)&&!n.includes(`{`))continue;if(r){let e=n.includes(`{`),t=(n.split(`/`).pop()||``).includes(`.`);if(!e&&t)continue}for(let e of Object.keys(o)){let r=o[e];if(r==null)continue;let i=r[_y]===!0;if(delete r[_y],n.includes(`{`)){r.parameters=r.parameters?[...r.parameters]:[];let e=n.split(`/`).filter(e=>e.startsWith(`{`)&&!r.parameters.find(t=>t.in===`path`&&t.name===e.slice(1,e.length-1)));for(let n of e){let e=n.slice(1,n.length-1);r.parameters.findIndex(n=>{if(`$ref`in n){let r=n.$ref.split(`/`).pop();if(r){let n=t.components.parameters?.[r];if(n&&!(`$ref`in n))return n.in===`path`&&n.name===e}return!1}return n.in===`path`&&n.name===e})===-1&&r.parameters.push({schema:{type:`string`},in:`path`,name:e,required:!0})}}if(r.responses||={200:{}},i&&t.options.defaultValidationErrorResponse!==!1&&!r.responses[400]){let e=t.options.defaultValidationErrorResponse;typeof e==`object`?r.responses[400]=structuredClone(e):t.validationErrorResponse&&(r.responses[400]=structuredClone(t.validationErrorResponse))}}let e={};for(let t of Object.keys(o))o[t]!=null&&(e[t]=o[t]);Object.keys(e).length>0&&(i[n]=e)}return i}var jy={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:[`OPTIONS`],excludeTags:[],defaultValidationErrorResponse:!0},My={description:`Validation Error`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,enum:[!1]},error:{type:`array`,items:{}},data:{}},required:[`success`,`error`,`data`]}}}};async function Ny(e,t=jy,n){let r={components:{},options:{...jy,...t},validationErrorResponse:My},i=r.options.documentation??{},a={...i,components:i.components&&{...i.components}},o=await Py(e,r);for(let e in o)for(let t in o[e])Fy({valueOrFunc:o[e][t]?.hide,method:t,path:e,c:n})&&(o[e][t]=void 0);let s=a.components?.responses?await By(a.components.responses):void 0;s&&a.components&&(a.components.responses=s.responses);let c=Hy(a.components,s?.components,r.components);return{openapi:`3.1.0`,...a,tags:a.tags?.filter(e=>!r.options.excludeTags?.includes(e?.name)),info:{title:`Hono Documentation`,description:`Development documentation`,version:`0.0.0`,...a.info},paths:{...Ay(o,r),...a.paths},components:c}}async function Py(e,t){let n={},r=new Map;for(let i of e.routes){let e=ny(i.handler)[gy];if(!e){t.options.includeEmptyPaths&&ky({route:i,paths:n},r);continue}let a=i.method;if(a!==`ALL`&&(t.options.excludeMethods?.includes(a)||!vy.includes(a)))continue;let{schema:o,components:s={}}=await Iy(e,t.options.defaultOptions?.[a]&&{...t.options.defaultOptions[a]},t.components.parameters);t.components=Hy(t.components,s),ky({route:i,specs:o,paths:n},r)}return n}function Fy(e){let{valueOrFunc:t,c:n,method:r,path:i}=e;if(t!=null){if(typeof t==`boolean`)return t;if(typeof t==`function`)return t({c:n,method:r,path:i})}return!1}async function Iy(e,t,n){if(`spec`in e){let n={...t,...e.spec,responses:{...t?.responses,...e.spec.responses}},r={};if(n.responses){let e=await By(n.responses);n.responses=e.responses,r=e.components}if(n.requestBody&&`content`in n.requestBody){let e=await zy(n.requestBody.content);n.requestBody={...n.requestBody,content:e.content},r=Hy(r,e.components)}return{schema:n,components:r}}let r=await e.toOpenAPISchema();Vy(r);let i={...t,[_y]:!0};if(e.target===`form`||e.target===`json`){let t=e.options?.media??(e.target===`json`?`application/json`:`multipart/form-data`);!i.requestBody||!(`content`in i.requestBody)||!i.requestBody.content?i.requestBody={required:!0,content:{[t]:{schema:r.schema}}}:i.requestBody.content[t]={schema:r.schema}}else{let t=[];if(`$ref`in r.schema){let i=r.schema.$ref.split(`/`).pop();if(i&&r.components?.schemas?.[i]){let a=r.components.schemas[i],o=Ly(e.target,a,r.components.schemas),s=o.length===1?o[0]:void 0,c=n?.[i];s&&(!c||`in`in c&&c.in===s.in&&c.name===s.name)?(r.components.parameters??={},r.components.parameters[i]=s,t.push({$ref:`#/components/parameters/${i}`}),delete r.components.schemas[i]):t=o}}else t=Ly(e.target,r.schema,r.components?.schemas);i.parameters=t}return{schema:i,components:r.components}}function Ly(e,t,n){let r=[];for(let[i,a]of Ry(t,n)){let t={in:e===`param`?`path`:e,name:i,schema:a.schema};a.required&&(t.required=!0),t.schema&&`description`in t.schema&&t.schema.description&&(t.description=t.schema.description,t.schema={...t.schema,description:void 0}),r.push(t)}return r}function Ry(e,t){let n=new Map,r=new Set,i=e=>{for(let[t,r]of Object.entries(e.properties??{})){let i=n.get(t);n.set(t,{schema:i?{allOf:[i.schema,r]}:r,required:!!e.required?.includes(t)||i?.required})}for(let n of e.allOf??[])if(`$ref`in n){if(!n.$ref.startsWith(`#/components/schemas/`))continue;let e=n.$ref.slice(21).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`),a=t?.[e];a&&!r.has(e)&&(r.add(e),i(a),r.delete(e))}else i(n)};return i(e),n}async function zy(e){let t={},n={};for(let[r,i]of Object.entries(e))if(i){if(i.schema&&`toOpenAPISchema`in i.schema){let e=await i.schema.toOpenAPISchema();Vy(e),n[r]={...i,schema:e.schema},e.components&&(t=Hy(t,e.components))}else n[r]=i}return{content:n,components:t}}async function By(e){let t={},n={};for(let[r,i]of Object.entries(e)){if(!i||!(`content`in i)||!i.content){n[r]=i;continue}let e=await zy(i.content);n[r]={...i,content:e.content},t=Hy(t,e.components)}return{responses:n,components:t}}function Vy(e){let t=e.schema.$defs;t&&typeof t==`object`&&(e.components??={},e.components.schemas={...t,...e.components.schemas},delete e.schema.$defs)}function Hy(...e){return e.reduce((e,t,n)=>(t==null||n===0||((e.schemas&&Object.keys(e.schemas).length>0||t.schemas&&Object.keys(t.schemas).length>0)&&(e.schemas={...e.schemas,...t.schemas}),(e.parameters&&Object.keys(e.parameters).length>0||t.parameters&&Object.keys(t.parameters).length>0)&&(e.parameters={...e.parameters,...t.parameters})),e),e[0]??{})}var Uy=e=>e.base,Wy=e=>{e.zodSchema._zod.def.type===`date`&&(e.jsonSchema.type=`string`,e.jsonSchema.format=`date-time`)};function Gy(e,t){let n=e[`~standard`].vendor;return{vendor:n,validate:e[`~standard`].validate,toJSONSchema:n=>_(e,{...t,...n}),toOpenAPISchema:r=>ee(e,{...t,...r,...n===`arktype`?Ky(t,r):void 0,...n===`zod`?qy(e,t,r):void 0})}}function Ky(e,t){let n=e?.options,r=t?.options;if(!(e?.fallback||n?.fallback||t?.fallback||r?.fallback))return{options:{fallback:Uy,...n,...r}}}function qy(e,t,n){if(!(`_zod`in e))return;let r=t?.options,i=n?.options;if(!(t?.override||r?.override||n?.override||i?.override))return{options:{unrepresentable:`any`,override:Wy,...r,...i}}}function Jy(e,t,n,r){let i=hy(e,t,n);return Object.defineProperty(i,"name",{value:`validator`,configurable:!0}),Object.assign(i,{[gy]:{target:e,...Gy(t,r),options:r}})}function Yy(e){let t=async(e,t)=>{await t()};return Object.defineProperty(t,"name",{value:`describeRoute`,configurable:!0}),Object.assign(t,{[gy]:{spec:e}})}function Xy(e){switch(e){case`a-z`:return`abcdefghijklmnopqrstuvwxyz`;case`A-Z`:return`ABCDEFGHIJKLMNOPQRSTUVWXYZ`;case`0-9`:return`0123456789`;case`-_`:return`-_`;default:throw Error(`Unsupported alphabet: ${e}`)}}function Zy(...e){let t=e.map(Xy).join(``);if(t.length===0)throw Error(`No valid characters provided for random string generation.`);let n=t.length;return(e,...r)=>{if(e<=0)throw Error(`Length must be a positive integer.`);let i=t,a=n;r.length>0&&(i=r.map(Xy).join(``),a=i.length);let o=Math.floor(256/a)*a,s=new Uint8Array(e*2),c=s.length,l=``,u=c,d;for(;l.length<e;)u>=c&&(crypto.getRandomValues(s),u=0),d=s[u++],d<o&&(l+=i[d%a]);return l}}var Qy=Zy(`a-z`,`0-9`,`A-Z`,`-_`),$y=[`javascript:`,`data:`,`vbscript:`],eb=I_(),tb=R_();function nb(e){return rb(e)||ib(e)}function rb(e){return yd(eb,e)}function ib(e){return yd(tb,e)}function ab(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(rb(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&rb(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=ob(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function ob(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function sb(e,t){let n=ob(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function cb(e,t={}){if(rb(e)||!ib(e))return e.toLowerCase();let n=ab(e);return n?n.toLowerCase():sb(e,t.ipv6Subnet??64)}var lb=new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function ub(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function db(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function fb(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function pb(e){return e.replace(/\.+$/,``)}function mb(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function Q(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function hb(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function gb(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=Q(e);return hb(t,Q(`127.0.0.0`),8)?`loopback`:hb(t,Q(`10.0.0.0`),8)||hb(t,Q(`172.16.0.0`),12)||hb(t,Q(`192.168.0.0`),16)?`private`:hb(t,Q(`169.254.0.0`),16)?`linkLocal`:hb(t,Q(`100.64.0.0`),10)?`sharedAddressSpace`:hb(t,Q(`192.0.2.0`),24)||hb(t,Q(`198.51.100.0`),24)||hb(t,Q(`203.0.113.0`),24)?`documentation`:hb(t,Q(`198.18.0.0`),15)?`benchmarking`:hb(t,Q(`224.0.0.0`),4)?`multicast`:hb(t,Q(`0.0.0.0`),8)||hb(t,Q(`192.0.0.0`),24)||hb(t,Q(`192.88.99.0`),24)||hb(t,Q(`240.0.0.0`),4)?`reserved`:`public`}function _b(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function vb(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=_b(e,1);return t&&gb(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=_b(e,6);return t&&gb(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=_b(e,6,{xor:!0});return t&&gb(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function yb(e){let t=pb(fb(ub(db(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!nb(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:lb.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(mb(t))return{kind:gb(t),literal:`ipv4`,canonical:t};let n=cb(t,{ipv6Subnet:128});return mb(n)?{kind:gb(n),literal:`ipv4`,canonical:n}:{kind:vb(n),literal:`ipv6`,canonical:n}}function bb(e){let t=yb(e).kind;return t===`loopback`||t===`localhost`}var xb=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,Sb=new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function Cb(e){let t=e.protocol.slice(0,-1),n=e.href.slice(e.protocol.length);return e.protocol!==`http:`&&e.protocol!==`https:`&&e.host.length===0&&n.startsWith(`/`)&&!n.startsWith(`//`)&&xb.test(t)}function wb(e){return Sb.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function Tb(e){return Cb(e)||wb(e)}D_().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),Ju}$y.includes(n.protocol)?t.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`}):(e.includes(`#`)&&t.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),n.protocol===`http:`&&!bb(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))});var Eb=new TextEncoder,Db=new TextDecoder,Ob=Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[t,e.charCodeAt(0)])),kb={...Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63};function Ab(e,t={}){let{pad:n=!0,url:r=!1}=t,i=new Uint8Array(Math.ceil(e.length/3)*4);for(let t=0,n=0;n<e.length;t+=4,n+=3){let r=(e[n]<<16)+(e[n+1]<<8)+(e[n+2]|0);i[t]=Ob[r>>18],i[t+1]=Ob[r>>12&63],i[t+2]=Ob[r>>6&63],i[t+3]=Ob[r&63]}let a=e.length%3,o=Math.floor(e.length/3)*4+(a&&a+1),s=Db.decode(new Uint8Array(i.buffer,0,o));return n&&a===1&&(s+=`==`),n&&a===2&&(s+=`=`),r&&(s=s.replaceAll(`+`,`-`).replaceAll(`/`,`_`)),s}function jb(e){let t=e.replace(/=+$/,``),n=t.length,r=new Uint8Array(n+3);Eb.encodeInto(t+`===`,r);for(let e=0,n=0;e<t.length;e+=4,n+=3){let t=(kb[r[e]]<<18)+(kb[r[e+1]]<<12)+(kb[r[e+2]]<<6)+kb[r[e+3]];r[n]=t>>16,r[n+1]=t>>8&255,r[n+2]=t&255}let i=(n>>2)*3+(n%4&&n%4-1);return new Uint8Array(r.buffer,0,i)}var Mb=class extends Error{name=`Apps.ExistsError`;constructor(e){super(`App ${e.clientId} already exists. Update it, or choose another client ID.`)}},Nb=class extends Error{name=`Apps.InvalidError`},Pb=class extends Error{name=`Apps.NotFoundError`;constructor(e){super(`Unknown app ${e.clientId}. Name a registered OAuth app.`)}},Fb=class extends Error{name=`Apps.PublicError`;constructor(e){super(`App ${e.clientId} has no client secret. Rotate the secret of an app with a backend.`)}},Ib=`urn:ietf:params:oauth:grant-type:device_code`,Lb=`urn:tempo:params:oauth:grant-type:email-code`,Rb=2147483647,zb=`tempo-id:sign`,Bb=[`openid`,`profile`,`email`,`offline_access`];async function Vb(e,t){let n=t.type??`web`,r=Zb(t.name),i=Qb(t.postLogoutRedirectUris??[],{type:n}),a=t.backendSignIn??!1,o=t.device??!1;if(o&&(t.secret||t.clientSecret!==void 0))throw new Nb(`Invalid app: a device app has no client secret, since a CLI cannot keep one. Leave out the secret.`);if(a&&(o||!(t.secret||t.clientSecret)))throw new Nb(`Invalid app: backend sign-in needs a client secret, which a device app cannot hold. Add the secret, or leave out backend sign-in.`);let s=o&&(t.redirectUris??[]).length===0?[]:$b(t.redirectUris??[],{type:n}),c=ex(t.refreshTokenLifetime??2592e3),l=t.clientId===void 0?Qy(32,`a-z`,`A-Z`):Yb(t.clientId),u=t.clientSecret===void 0?t.secret?nx():void 0:Xb(t.clientSecret),d=new Date,[f]=await e.insert(L).values({applicationType:n,clientId:l,clientSecret:u?await Hb(u):null,createdAt:d,enableEndSession:!0,grantTypes:o?[Ib,`refresh_token`]:[`authorization_code`,...a?[Lb]:[],`refresh_token`],id:crypto.randomUUID(),name:r,postLogoutRedirectUris:[...i],redirectUris:[...s],refreshTokenLifetime:c,responseTypes:[`code`],scopes:tx({sign:t.sign??!1}),skipConsent:!0,tokenEndpointAuthMethod:u?`client_secret_post`:`none`,updatedAt:d}).onConflictDoNothing({target:L.clientId}).returning();if(!f)throw new Mb({clientId:l});return{app:rx(f),...u?{clientSecret:u}:{}}}async function Hb(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Ab(new Uint8Array(t),{pad:!1,url:!0})}function Ub(e,t){let n=jb(e),r=jb(t);if(n.length!==r.length)return!1;let i=0;for(let e=0;e<n.length;e++)i|=n[e]^r[e];return i===0}async function Wb(e){return(await e.select().from(L).where(ys(L.clientDiscoveryId)).orderBy(ks(L.createdAt),ks(L.clientId))).map(rx)}async function Gb(e,t){let[n]=await e.delete(L).where(us(cs(L.clientId,t.clientId),ys(L.clientDiscoveryId))).returning();if(!n)throw new Pb({clientId:t.clientId});return rx(n)}async function Kb(e,t){let n=t.clientSecret===void 0?nx():Xb(t.clientSecret),r=await Jb(e,t);if(!r.clientSecret)throw new Fb(t);if(Ub(r.clientSecret,await Hb(n)))throw new Nb(`Invalid client secret: it matches the current secret. Use a new secret.`);let[i]=await e.update(L).set({clientSecret:await Hb(n),updatedAt:new Date}).where(us(cs(L.clientId,t.clientId),cs(L.clientSecret,r.clientSecret))).returning();if(!i)throw await Jb(e,t),new Nb(`Invalid rotation: another rotation replaced the client secret first. Rotate it again.`);return{app:rx(i),clientSecret:n}}async function qb(e,t){let n=await Jb(e,t);if(n.clientDiscoveryId)throw new Pb({clientId:t.clientId});let r=rx(n),i=t.name===void 0?void 0:Zb(t.name),a=t.postLogoutRedirectUris===void 0?void 0:Qb(t.postLogoutRedirectUris,{type:r.type}),o=t.redirectUris===void 0?void 0:$b(t.redirectUris,{type:r.type}),s=t.refreshTokenLifetime===void 0?void 0:ex(t.refreshTokenLifetime);if(t.backendSignIn&&!r.secret)throw new Nb(`Invalid app: ${t.clientId} has no client secret, which backend sign-in needs. Register an app with a client secret.`);let c=t.backendSignIn===void 0?void 0:[...(n.grantTypes??[]).filter(e=>e!==Lb),...t.backendSignIn?[Lb]:[]],[l]=await e.update(L).set({...c===void 0?{}:{grantTypes:c},...i===void 0?{}:{name:i},...a===void 0?{}:{postLogoutRedirectUris:[...a]},...a?.length?{enableEndSession:!0}:{},...o===void 0?{}:{redirectUris:[...o]},...s===void 0?{}:{refreshTokenLifetime:s},...t.sign===void 0?{}:{scopes:tx({scopes:n.scopes??void 0,sign:t.sign})},updatedAt:new Date}).where(cs(L.clientId,t.clientId)).returning();if(!l)throw new Pb(t);return rx(l)}async function Jb(e,t){let[n]=await e.select().from(L).where(cs(L.clientId,t.clientId));if(!n)throw new Pb({clientId:t.clientId});return n}function Yb(e){if(!/^[A-Za-z0-9_-]{8,64}$/.test(e))throw new Nb(`Invalid client ID: ${e}. Use 8 to 64 letters, digits, -, or _.`);return e}function Xb(e){if(e.length<32)throw new Nb(`Invalid client secret: fewer than 32 characters. Use a longer secret.`);return e}function Zb(e){let t=e.trim();if(!t)throw new Nb(`Invalid app: the name is empty. Set a name.`);return t}function Qb(e,t){return e.length===0?[]:$b(e,t)}function $b(e,t){if(e.length===0)throw new Nb(`Invalid app: no redirect URI. Set at least one redirect URI.`);for(let n of e){let e=URL.parse(n),r=(()=>{if(!e)return`is not an absolute URI`;if(e.hash||n.includes(`#`))return`has a fragment`;if(e.username||e.password)return`holds credentials`;if(e.protocol===`https:`)return bb(e.hostname)?`has a loopback host`:void 0;if(e.protocol===`http:`)return`uses http`;if(t.type===`web`)return`is not https`;if(!Tb(e))return`is not a valid custom scheme`})();if(r)throw new Nb(`Invalid redirect URI: ${n} ${r}. Use an https URI${t.type===`native`?`, or a custom scheme such as com.example.app:/callback`:``}.`)}return[...new Set(e)]}function ex(e){if(e===`never`)return null;if(Number.isSafeInteger(e)&&e>0&&e<=Rb)return e;throw new Nb(`Invalid refresh token lifetime: ${e}. Pass a positive integer of seconds up to ${Rb}, or never.`)}function tx(e){return[...(e.scopes??Bb).filter(e=>e!==zb),...e.sign?[zb]:[]]}function nx(){return Qy(32,`a-z`,`A-Z`)}function rx(e){return{backendSignIn:(e.grantTypes??[]).includes(Lb),clientId:e.clientId,createdAt:e.createdAt,device:(e.grantTypes??[]).includes(Ib),firstParty:!e.clientDiscoveryId&&e.skipConsent===!0,logo:e.icon?.startsWith(`data:image/`)?e.icon:null,name:e.name,postLogoutRedirectUris:e.postLogoutRedirectUris??[],redirectUris:e.redirectUris,refreshTokenLifetime:e.refreshTokenLifetime??`never`,secret:!!e.clientSecret,sign:(e.scopes??[]).includes(zb),type:e.applicationType===`native`?`native`:`web`}}var ix=class extends Vv(`invalid_field`){name=`Validation.InvalidFieldError`;constructor(e){let{issues:t}=e;super({error_description:`Invalid request. ${t.map(e=>`${ax(e)?`\`${ax(e)}\``:`Body`}: ${e.message}.`).join(` `)}`,field:t[0]&&ax(t[0])?ax(t[0]):void 0})}};function ax(e){return(e.path??[]).map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}var ox=class extends Vv(`invalid_code`){name=`Auth.InvalidCodeError`;constructor(){super({error_description:`Invalid or expired code. Request a new one.`,field:`code`})}},sx={options:{override:e=>{let{jsonSchema:t}=e;delete t.readOnly;let n=t.anyOf?.filter(e=>Object.keys(e).length>0);n&&n.length!==t.anyOf.length&&(n.length===1?(delete t.anyOf,Object.assign(t,n[0])):t.anyOf=n)},unrepresentable:`any`}},cx={integrity:`sha384-U11tb2XnKvmwt8RlTvnwUnYgrN+ur4Xyh9htLhjajWNR/Oyl5AX5DEz00qRmlrmK`,src:`https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.72.1/dist/browser/standalone.js`},lx={description:"Tempo ID signs users in to Tempo apps, authorizes apps for them, and signs key authorizations on their Tempo Accounts. Every refusal is an OAuth error response (RFC 6749 §5.2) whose `reason` determines its `error` and status.",title:`Tempo ID`,version:`0.0.0`},ux=[{description:`Sign-in with an emailed code or a passkey, in two requests each. The first returns a code or WebAuthn options, and the second verifies it and sets the session cookie.`,name:`Authenticate`},{description:"Authorizes an app for the signed-in user. The redirect flow starts at `GET /oauth2/authorize` and ends at `POST /oauth2/token`, and a first-party page can use `POST /v1/authorize` without a redirect.",name:`Authorization`},{description:"Authorizes a device without a browser (RFC 8628). The device requests codes, the user approves the user code on the device page, and the device polls `POST /oauth2/token`.",name:`Device grant`},{description:`The signed-in user's Tempo Accounts and passkeys. A passkey registers in three requests: the options, the new credential, and the new passkey's signature.`,name:`Account`},{description:`The issuer's standard OAuth 2.0 and OpenID Connect endpoints.`,name:`OAuth`},{description:`The Worker's status.`,name:`Health`},{description:`This document and its API reference.`,name:`Reference`}];function dx(e,t={}){let n=_x.get(e);if(n)return n;let r=vx(e,t);return _x.set(e,r),r.catch(()=>_x.delete(e)),r}var fx=`<!doctype html>
75
- <html lang="en">
76
- <head>
77
- <meta charset="utf-8" />
78
- <meta name="viewport" content="width=device-width, initial-scale=1" />
79
- <title>Tempo ID API</title>
80
- </head>
81
- <body>
82
- <script id="api-reference" type="application/json" data-url="openapi.json"><\/script>
83
- <script src="${cx.src}" integrity="${cx.integrity}" crossorigin="anonymous"><\/script>
84
- </body>
85
- </html>
86
- `,px=[`default-src 'self'`,`script-src ${cx.src}`,`style-src 'self' 'unsafe-inline' https://fonts.scalar.com`,`font-src https://fonts.scalar.com`,`img-src 'self' data:`,`connect-src 'self'`,`object-src 'none'`,`base-uri 'none'`,`form-action 'none'`,`frame-ancestors 'none'`].join(`; `);function mx(e){let t=new Map;for(let n of new Set([...e,Gv].map(e=>e.reason)).values()){let e=zv[n].status;t.set(e,[...t.get(e)??[],n])}return Object.fromEntries([...t].map(([e,t])=>[e,{content:{"application/json":{schema:{anyOf:t.map(e=>({$ref:`#/components/schemas/ErrorResponse.${e}`}))}}},description:t.map(e=>`\`${e}\``).join(`, `)}]))}function hx(e){let{errors:t=[],success:n}=e;return{[n.status??200]:{content:{"application/json":{schema:Gy(n.schema,sx)}},description:n.description},...mx(t)}}function gx(e,t){return Jy(e,t,(e,t)=>{if(!e.success)return Z(t,new ix({issues:e.error}))},sx)}(function(e){e.errors=[Uv,ix]})(gx||={});var _x=new WeakMap;async function vx(e,t){let n=await Promise.all(Object.keys(zv).map(async e=>(await Gy(Jv.of(e),sx).toOpenAPISchema()).components?.schemas));return Ny(e,{defaultValidationErrorResponse:!1,excludeStaticFile:!1,documentation:{components:{schemas:Object.assign({},...n),securitySchemes:t.securitySchemes??{accessToken:{bearerFormat:`JWT`,description:"An access token from `/oauth2/token`, as `Authorization: Bearer <token>`.",scheme:`bearer`,type:`http`},clientBasic:{description:"An OAuth app's client ID and secret, as HTTP Basic `Authorization` (RFC 6749 §2.3.1).",scheme:`basic`,type:`http`},sessionCookie:{description:`The Tempo ID session, which sign-in sets as an HTTP-only cookie on Tempo ID's origin.`,in:`cookie`,name:`tempo-id-session`,type:`apiKey`}}},info:t.info?{...t.info,version:lx.version}:lx,openapi:`3.1.0`,...t.security?{security:t.security.map(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,[...t]])))}:{},tags:t.tags?[...t.tags]:ux}})}var yx=({limitLength:e=255,headerName:t=`X-Request-Id`,generator:n=()=>crypto.randomUUID()}={})=>async function(r,i){let a=t?r.req.header(t):void 0;(!a||a.length>e||/[^\w\-=]/.test(a))&&(a=n(r)),r.set(`requestId`,a),t&&r.header(t,a),await i()},bx=`X-Request-Id`;function xx(){let e=yx({generator:Tx,headerName:``});return qt(async(t,n)=>{await e(t,n);let r=t.var.requestId,i=t.res,a=wx(i)?await v(t,Dx(i),`response.json`):void 0;a&&t.set(`refusal`,Sx(t,{body:a,id:r})),t.header(bx,r)})}function Sx(e,t){let n=e.res;return e.res=new Response(JSON.stringify({...t.body,request_id:t.id}),{headers:n.headers,status:n.status,statusText:n.statusText}),e.header(`content-length`,void 0),{error:Cx(t.body.error),reason:Cx(t.body.reason)}}function Cx(e){return typeof e==`string`&&/^[a-z_]{1,64}$/.test(e)?e:void 0}function wx(e){return e.status>=400&&!!e.headers.get(`content-type`)?.startsWith(`application/json`)}function Tx(e){let t=e.req.header(`cf-ray`);return t&&/^[\da-f]{16}(?:-[A-Z]{3})?$/.test(t)?t:crypto.randomUUID()}function Ex(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Dx(e){let t=await e.clone().json().catch(()=>void 0);return Ex(t)&&typeof t.error==`string`?t:void 0}var Ox=class extends Vv(`app_exists`){name=`AdminApps.ExistsError`},kx=class extends Vv(`invalid_app`){name=`AdminApps.InvalidError`},Ax=class extends Vv(`unknown_app`){name=`AdminApps.NotFoundError`},jx=class extends Vv(`public_app`){name=`AdminApps.PublicError`};function Mx(e,t={}){let{clientId:n}=t,r=n===void 0?void 0:`clientId`;if(e instanceof Mb)return new Ox({error_description:e.message,field:r});if(e instanceof Nb)return new kx({error_description:e.message});if(e instanceof Pb)return new Ax({error_description:e.message,field:r});if(e instanceof Fb)return new jx({error_description:e.message,field:r})}(function(e){e.errors=[Ox,kx,Ax,jx]})(Mx||={});var Nx;(function(e){let t;(function(e){e.response=X({apps:nv(e.app=X({backendSignIn:X_().meta({description:`Whether the app's backend signs users in with an emailed code through the email code grant, with its client secret.`,examples:[!1]}),clientId:J().meta({description:"The client ID, which the app sends as `client_id`.",examples:[`DkqRtYbWvXzPmNcLaJhGfEsUoIyTrQwe`]}),createdAt:Lv().nullable().meta({description:"When the app was registered, or `null` for an app without a record of it.",examples:[`2026-10-26T12:00:00.000Z`]}),device:X_().meta({description:`Whether the app signs in through the device grant, as a CLI does.`,examples:[!1]}),firstParty:X_().meta({description:`Whether the app skips consent for requests without a key.`,examples:[!0]}),logo:J().nullable().meta({description:"The logo as a `data:` URL, or `null`. Only a third-party app with an origin client ID has one.",examples:[null]}),name:J().nullable().meta({description:`The display name on the approval page.`,examples:[`Tempo Wallet`]}),postLogoutRedirectUris:nv(J()).meta({description:"The URIs that `GET /oauth2/end-session` may return to.",examples:[[`https://wallet.example.com`]]}),redirectUris:nv(J()).meta({description:`The URIs that the app returns to.`,examples:[[`https://wallet.example.com/callback`]]}),refreshTokenLifetime:av([K_().int().positive(),pv(`never`)]).meta({description:"The seconds that each refresh token stays valid after its issue, or `never`. A refresh rotates the token.",examples:[2592e3,`never`]}),secret:X_().meta({description:`Whether the app holds a client secret for its backend.`,examples:[!1]}),sign:X_().meta({description:"Whether the app holds the `tempo-id:sign` scope.",examples:[!1]}),type:dv([`native`,`web`]).meta({description:"`web` for a browser app or a backend, and `native` for a mobile app.",examples:[`web`]})}).meta({description:`An OAuth app.`,id:`AdminApp`})).meta({description:`Every registered app, oldest first, without third-party apps.`})})})(t||=e.list||={});let n;(function(e){e.json=X({backendSignIn:X_().optional().meta({description:"Whether the app's backend signs users in with an emailed code through the email code grant. Needs a client secret. Defaults to `false`.",examples:[!1]}),clientId:J().optional().meta({description:`Another deployment's client ID to keep. Defaults to 32 random letters.`,examples:[`tempo-wallet`]}),clientSecret:J().optional().meta({description:"Another deployment's client secret to keep. Implies `secret`. Defaults to none.",examples:[`a3F9kQ2mX7pL4vR8tY1wZ6bN0cJ5hD2gS9eU4iO7`]}),device:X_().optional().meta({description:"Whether the app signs in through the device grant, as a CLI does. A device app needs no redirect URI. Defaults to `false`.",examples:[!1]}),name:J().meta({description:`The display name on the approval page.`,examples:[`Tempo Wallet`]}),postLogoutRedirectUris:nv(J()).optional().meta({description:"The URIs that `GET /oauth2/end-session` may return to. Defaults to none.",examples:[[`https://wallet.example.com`]]}),redirectUris:nv(J()).optional().meta({description:`The URIs that the app returns to, in every environment. Every app but a device app needs one.`,examples:[[`https://wallet.example.com/callback`]]}),refreshTokenLifetime:av([K_().int().positive(),pv(`never`)]).optional().meta({description:"The seconds that each refresh token stays valid after its issue, up to 2147483647, or `never`. Defaults to 30 days.",examples:[2592e3,`never`]}),secret:X_().optional().meta({description:"Whether to issue a client secret, for an app with a backend. Defaults to `false`.",examples:[!1]}),sign:X_().optional().meta({description:"Whether the app holds the `tempo-id:sign` scope, which permits it to bind its own challenges. Defaults to `false`.",examples:[!1]}),type:dv([`native`,`web`]).optional().meta({description:"The application type. Defaults to `web`.",examples:[`web`]})}),e.response=X({app:t.app,clientSecret:J().optional().meta({description:`The client secret. Only this response holds it. Absent for an app without a secret.`,examples:[`a3F9kQ2mX7pL4vR8tY1wZ6bN0cJ5hD2gS9eU4iO7`]})})})(n||=e.create||={});let r;(function(e){e.param=X({clientId:J().min(1).meta({description:`The app's client ID.`,examples:[`DkqRtYbWvXzPmNcLaJhGfEsUoIyTrQwe`]})}),e.json=X({backendSignIn:X_().optional().meta({description:"Grants the email code grant with `true`, or removes it with `false`. `true` needs a client secret. Absent, it stays.",examples:[!0]}),name:J().optional().meta({description:`The display name. Absent, it stays.`,examples:[`Tempo Wallet`]}),postLogoutRedirectUris:nv(J()).optional().meta({description:`Replaces the post-logout redirect URIs. An empty list clears them. Absent, they stay.`,examples:[[`https://wallet.example.com`]]}),redirectUris:nv(J()).optional().meta({description:`Replaces the redirect URIs. Absent, they stay.`,examples:[[`https://wallet.example.com/callback`]]}),refreshTokenLifetime:av([K_().int().positive(),pv(`never`)]).optional().meta({description:"The seconds that each refresh token stays valid after its issue, up to 2147483647, or `never`. Applies to each token issued or rotated after the change. Absent, it stays.",examples:[2592e3,`never`]}),sign:X_().optional().meta({description:"Grants the `tempo-id:sign` scope with `true`, or removes it with `false`. Absent, it stays.",examples:[!0]})}),e.response=X({app:t.app})})(r||=e.update||={});let i;(function(e){e.param=r.param,e.response=X({app:t.app.meta({description:`The app as it was before its removal.`})})})(i||=e.remove||={});let a;(function(e){e.param=r.param,e.response=X({app:t.app,clientSecret:J().meta({description:`The new client secret. Only this response holds it. The earlier secret stops working at once.`,examples:[`a3F9kQ2mX7pL4vR8tY1wZ6bN0cJ5hD2gS9eU4iO7`]})})})(a||=e.rotateSecret||={})})(Nx||={});var Px=new Kt().get(`/apps`,Yy({description:`Lists every registered OAuth app, oldest first, without third-party apps or client secrets.`,responses:hx({success:{description:`The registered apps.`,schema:Nx.list.response}}),tags:[`Apps`]}),async e=>{let t=await v(e,Wb(e.var.db),`Apps.list`);return e.json({apps:t.map(Ix)},200)}).post(`/apps`,Yy({description:`Registers a first-party OAuth app, which skips consent for requests without a key. The response holds its client secret, which no later response returns.`,responses:hx({errors:[...gx.errors,Ox,kx],success:{description:`The registered app, with its client secret.`,schema:Nx.create.response,status:201}}),tags:[`Apps`]}),gx(`json`,Nx.create.json),async e=>{let t=e.req.valid(`json`),n=await v(e,Vb(e.var.db,t).catch(Fx({clientId:t.clientId})),`Apps.create`);return en(e,{fields:{actor:e.var.actor.sub,clientId:n.app.clientId},message:`An admin registered an OAuth app.`}),e.json({app:Ix(n.app),...n.clientSecret?{clientSecret:n.clientSecret}:{}},201)}).patch(`/apps/:clientId`,Yy({description:"Changes an OAuth app's name, redirect URIs, post-logout redirect URIs, or `tempo-id:sign` scope. A value left out stays.",responses:hx({errors:[...gx.errors,kx,Ax],success:{description:`The updated app.`,schema:Nx.update.response}}),tags:[`Apps`]}),gx(`param`,Nx.update.param),gx(`json`,Nx.update.json),async e=>{let{clientId:t}=e.req.valid(`param`),n=await v(e,qb(e.var.db,{clientId:t,...e.req.valid(`json`)}).catch(Fx({clientId:t})),`Apps.update`);return en(e,{fields:{actor:e.var.actor.sub,clientId:t},message:`An admin updated an OAuth app.`}),e.json({app:Ix(n)},200)}).delete(`/apps/:clientId`,Yy({description:`Removes an OAuth app, with its consents, tokens, and realm assignments. Its users stay.`,responses:hx({errors:[...gx.errors,Ax],success:{description:`The removed app.`,schema:Nx.remove.response}}),tags:[`Apps`]}),gx(`param`,Nx.remove.param),async e=>{let{clientId:t}=e.req.valid(`param`),n=await v(e,Gb(e.var.db,{clientId:t}).catch(Fx({clientId:t})),`Apps.remove`);return en(e,{fields:{actor:e.var.actor.sub,clientId:t},message:`An admin removed an OAuth app.`}),e.json({app:Ix(n)},200)}).post(`/apps/:clientId/secret`,Yy({description:`Replaces an OAuth app's client secret with a new one, which only this response returns. The earlier secret stops working at once.`,responses:hx({errors:[...gx.errors,kx,Ax,jx],success:{description:`The app, with its new client secret.`,schema:Nx.rotateSecret.response}}),tags:[`Apps`]}),gx(`param`,Nx.rotateSecret.param),async e=>{let{clientId:t}=e.req.valid(`param`),n=await v(e,Kb(e.var.db,{clientId:t}).catch(Fx({clientId:t})),`Apps.rotateSecret`);return en(e,{fields:{actor:e.var.actor.sub,clientId:t},message:`An admin rotated an OAuth app's client secret.`}),e.json({app:Ix(n.app),clientSecret:n.clientSecret},200)});function Fx(e){return t=>{throw Mx(t,e)??t}}function Ix(e){return{...e,createdAt:e.createdAt?.toISOString()??null,postLogoutRedirectUris:[...e.postLogoutRedirectUris],redirectUris:[...e.redirectUris]}}function Lx(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}var Rx=i((e=>{var t=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;e.validate=function(e){if(!e||e.length>254||!t.test(e))return!1;var n=e.split(`@`);return!(n[0].length>64||n[1].split(`.`).some(function(e){return e.length>63}))}}))(),zx=5242880,Bx=Math.floor(zx*3/4),Vx=16384,Hx=`\r
87
- `,Ux=/^[\x20-\x7e]*$/,Wx=/^[!-9;-~]+$/;function Gx(e,t){for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r===13||r===10||r===0)throw new $(`MIME_ERROR`,`${e}: must not contain CR, LF, or NUL.`)}}function Kx(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==9||n===127)return t}return-1}function qx(e,t){let n=Kx(t);if(n!==-1)throw new $(`MIME_ERROR`,`${e} contains a control character (U+${t.charCodeAt(n).toString(16).toUpperCase().padStart(4,`0`)}).`)}var Jx=`()<>@,;:\\"/[]?=`;function Yx(e){return e>32&&e<127&&!Jx.includes(String.fromCharCode(e))}function Xx(e,t){let n=()=>new $(`MIME_ERROR`,`${e} is not a valid media type (RFC 2045 §5.1: type/subtype, then ; attribute=value parameters).`),r=t.length,i=0,a=()=>{let e=i;for(;i<r&&Yx(t.charCodeAt(i));)i++;return i-e},o=()=>{for(;i<r&&(t[i]===` `||t[i]===` `);)i++};if(a()===0||t[i]!==`/`||(i++,a()===0))throw n();let s=new Set;for(;i<r;){if(o(),t[i]!==`;`)throw n();i++,o();let c=i;if(a()===0||t[i]!==`=`)throw n();let l=t.slice(c,i).toLowerCase();if(i++,t[i]===`"`)for(i++;;){if(i>=r)throw n();let e=t[i++];if(e===`"`)break;if(e===`\\`){if(i>=r)throw n();i++}}else if(a()===0)throw n();if(l===`name`)throw new $(`MIME_ERROR`,`${e} must not carry a name= parameter; the builder adds name="<filename>" itself.`);if(s.has(l))throw new $(`MIME_ERROR`,`${e} gives the same parameter twice; attribute names are case-insensitive and each may appear once (RFC 6838 §4.3).`);s.add(l)}}var Zx="!#$%&'*+-/=?^_`{|}~";function Qx(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||Zx.includes(String.fromCharCode(e))}function $x(e,t){let n=()=>new $(`MIME_ERROR`,`${e} is not a valid Content-ID (RFC 5322 §3.6.4 msg-id: an identifier of atext, "." and "@", optionally in one pair of angle brackets).`),r=0,i=t.length;if(t[0]===`<`){if(i<2||t[i-1]!==`>`)throw n();r=1,i--}let a=()=>{let e=0;for(;r<i;r++){let n=t.charCodeAt(r);if(Qx(n))e++;else if(n===46&&e>0)e=0;else break}return e>0};if(!a()||r<i&&(t[r]!==`@`||(r++,!a()))||r!==i)throw n()}var eS={txt:`text/plain`,html:`text/html`,htm:`text/html`,css:`text/css`,csv:`text/csv`,pdf:`application/pdf`,json:`application/json`,xml:`application/xml`,zip:`application/zip`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,ico:`image/x-icon`,ics:`text/calendar`,eml:`message/rfc822`};function tS(e){return eS[e.split(`.`).pop()?.toLowerCase()??``]??`application/octet-stream`}var $=class extends Error{code;constructor(e,t){super(t),this.name=`MimeError`,this.code=e}};function nS(e){return e===`from`?`INVALID_FROM`:e===`to`?`INVALID_TO`:`MIME_ERROR`}function rS(e,t,n){if(t.length>320)throw new $(nS(e),`${e}: address is ${t.length} characters, over the 320-character limit.`);if(!(0,Rx.validate)(t))throw new $(nS(e),`${e}: address is not a valid email address (ASCII local part and dotted domain, RFC 5322 dot-atom; at most 64 characters before the '@' and 254 in total).`);if(n!==void 0){if(Gx(`${e} display name`,n),Ux.test(n)&&hS.test(n)&&n.length+CS>yS)throw new $(nS(e),`${e}: display name is ${n.length} characters and must be quoted, which cannot be folded, so its line would exceed the ${yS}-octet limit in RFC 5322 §2.1.1. Shorten it.`);if(n.includes(`@`))throw new $(nS(e),`${e}: display name '${n}' must not contain '@' (likely a malformed address).`)}}function iS(e){let t=e.indexOf(`\\`);if(t===-1)return e;let n=0;for(let r=t;r<e.length;r++)e.charCodeAt(r)===92&&(n++,r++);let r=new Uint16Array(e.length-n),i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n===92&&(n=e.charCodeAt(++t)),r[i++]=n}return AS(r)}function aS(e,t){if(typeof e==`string`){Gx(`${t} address`,e);let n=e.match(/^\s*"((?:[^"\\]|\\.)*)"\s*<\s*([^>\s]+)\s*>\s*$/),r=n??e.match(/^\s*(?:([^"<\s](?:[^"<]*[^"<\s])?)\s*)?<\s*([^>\s]+)\s*>\s*$/);if(r){let e=(n?iS(r[1]??``):r[1])?.trim(),i=r[2];return rS(t,i,e),e?{email:i,name:e}:{email:i}}let i=e.trim();return rS(t,i),{email:i}}return rS(t,e.email??``,e.name),e.name?{email:e.email,name:e.name}:{email:e.email}}function oS(e,t){return(Array.isArray(e)?e:[e]).map(e=>aS(e,t))}function sS(e){return e?Array.isArray(e)?e.length:1:0}function cS(e){return new $(`MIME_ERROR`,`email: attachment size ${e} bytes exceeds Cloudflare limit of ${Bx} bytes.`)}function lS(e){return e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:typeof Blob<`u`&&e instanceof Blob?e.size:typeof e==`string`?e.length:0}async function uS(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(typeof e==`string`)return new TextEncoder().encode(e);throw new $(`MIME_ERROR`,`attachment content must be string, Uint8Array, ArrayBuffer, or Blob.`)}async function dS(e){if(!e.filename)throw new $(`MIME_ERROR`,`attachment: missing filename.`);if(Gx(`attachment filename`,e.filename),e.filename.length+bS>yS)throw new $(`MIME_ERROR`,`attachment filename is ${e.filename.length} characters; a quoted \`filename=\` parameter cannot be folded, so its line would exceed the ${yS}-octet limit in RFC 5322 §2.1.1. Shorten the filename.`);if(qx(`attachment filename`,e.filename),e.contentType!==void 0){if(Gx(`attachment contentType`,e.contentType),e.contentType.length+xS>yS)throw new $(`MIME_ERROR`,`attachment contentType is ${e.contentType.length} characters; at most ${yS-xS} fit on the Content-Type line under the ${yS}-octet limit in RFC 5322 §2.1.1. Shorten it.`);qx(`attachment contentType`,e.contentType),Xx(`attachment contentType`,e.contentType)}if(e.contentId!==void 0){Gx(`attachment contentId`,e.contentId);let t=e.contentId.startsWith(`<`)?0:2;if(e.contentId.length+t+SS>yS)throw new $(`MIME_ERROR`,`attachment contentId is ${e.contentId.length} characters; at most ${yS-SS-t} fit on the Content-ID line under the ${yS}-octet limit in RFC 5322 §2.1.1. Shorten it.`);qx(`attachment contentId`,e.contentId),$x(`attachment contentId`,e.contentId)}if(e.disposition!==void 0&&e.disposition!==`attachment`&&e.disposition!==`inline`)throw new $(`MIME_ERROR`,`attachment disposition must be 'attachment' or 'inline'.`);let t=await uS(e.content);return{filename:e.filename,contentType:e.contentType??tS(e.filename),bytes:t,contentId:e.contentId,disposition:e.disposition??(e.contentId?`inline`:`attachment`)}}async function fS(e){if(!e.text&&!e.html)throw new $(`MIME_ERROR`,`email: at least one of 'text' or 'html' is required.`);if(e.subject!==void 0&&Gx(`subject`,e.subject),e.headers){let t=0,n=0,r=new TextEncoder;for(let[i,a]of Object.entries(e.headers)){if(!Wx.test(i))throw new $(`MIME_ERROR`,`headers: '${i}' is not a valid RFC 5322 header name.`);if(i.length+wS>yS)throw new $(`MIME_ERROR`,`headers: a header name is ${i.length} characters; a field name cannot be folded, so its line would exceed the ${yS}-octet limit in RFC 5322 §2.1.1. Shorten the name.`);if(t+i.length+a.length+4>Vx||(t+=i.length+r.encode(a).byteLength+4,t>Vx)||(Gx(`header '${i}'`,a),!BS.has(i.toLowerCase())&&(n+i.length+KS+VS(a)>Vx||(n+=vS(i,mS(a)).length+2,n>Vx))))throw new $(`MIME_ERROR`,`email: custom headers exceed the 16 KiB limit.`)}}let t=sS(e.to)+sS(e.cc)+sS(e.bcc);if(t>50)throw new $(`INVALID_TO`,`email: too many recipients (max 50, got ${t}) across 'to', 'cc' and 'bcc'.`);let n=aS(e.from,`from`),r=oS(e.to,`to`);if(r.length===0)throw new $(`INVALID_TO`,`email: 'to' must include at least one recipient.`);let i=e.cc?oS(e.cc,`cc`):[],a=e.bcc?oS(e.bcc,`bcc`):[],o=e.replyTo?aS(e.replyTo,`replyTo`):void 0,s=e.attachments??[];if(!Array.isArray(s))throw new $(`MIME_ERROR`,`email: attachments must be an array.`);if(s.length>GS)throw new $(`MIME_ERROR`,`email: too many attachments (max ${GS}, got ${s.length}).`);let c=[],l=0;for(let e of s){let t=lS(e.content);if(l+t>Bx)throw cS(l+t);let n=await dS(e);if(l+=n.bytes.byteLength,l>Bx)throw cS(l);c.push(n)}return e.threading?.inReplyTo&&Gx(`threading.inReplyTo`,e.threading.inReplyTo),e.threading?.references&&Gx(`threading.references`,e.threading.references),{from:n,to:r,cc:i,bcc:a,replyTo:o,subject:e.subject??``,text:e.text,html:e.html,headers:e.headers?{...e.headers}:{},attachments:c,threading:e.threading}}var pS=45;function mS(e){if(Ux.test(e))return e;let t=new TextEncoder,n=new Uint8Array(49),r=0,i=[],a=()=>{r>0&&(i.push(`=?UTF-8?B?${Lx(n.subarray(0,r))}?=`),r=0)};for(let i of e){let e=t.encode(i);r>0&&r+e.length>pS&&a(),n.set(e,r),r+=e.length}return a(),i.join(` `)}var hS=/[()<>[\]:;@\\,."]/;function gS(e){return e.name?Ux.test(e.name)?hS.test(e.name)?`"${ES(e.name)}" <${e.email}>`:`${e.name} <${e.email}>`:`${mS(e.name)} <${e.email}>`:e.email}function _S(e){return e.map(gS).join(`, `)}function vS(e,t){let n=`${e}: ${t}`;if(n.length<=78)return n;let r=[],i=[`${e}:`],a=e.length+1,o=0,s=(e,t)=>{o++;let n=t?`${e},`:e;n.length>0&&a+1+n.length>76?(r.push(i.join(` `)),i=[``,n],a=1+n.length):(i.push(n),a+=1+n.length)},c=-1,l=-1,u=-1,d=e=>{c<0||(l>=0&&s(t.slice(l,u),!1),l=c,u=e,c=-1)},f=e=>{l>=0?(s(t.slice(l,u),!e),l=-1):s(``,!e)},p=!1,m=!1;for(let e=0;e<t.length;e++){let n=t[e];m?(m=!1,c<0&&(c=e)):n===`\\`&&p?(m=!0,c<0&&(c=e)):n===`"`?(p=!p,c<0&&(c=e)):!p&&n===`,`&&t[e+1]===` `?(d(e),f(!1),e++):!p&&(n===` `||n===` `)?d(e):c<0&&(c=e)}return d(t.length),f(!0),o<=1?n:(r.push(i.join(` `)),r.join(Hx))}var yS=998,bS=12,xS=2,SS=12,CS=3,wS=1;function TS(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===13&&e.charCodeAt(r+1)===10){if(n>yS)return{index:t,octets:n};t++,n=0,r++}else if(i<128)n+=1;else if(i<2048)n+=2;else if(i>=55296&&i<=56319&&r+1<e.length){let t=e.charCodeAt(r+1);t>=56320&&t<=57343?(n+=4,r++):n+=3}else n+=3}return n>yS?{index:t,octets:n}:void 0}function ES(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function DS(e){let t=new Uint8Array(8);crypto.getRandomValues(t);let n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return`${e}_${Date.now().toString(36)}${n}`}function OS(e){let t=Lx(e),n=[];for(let e=0;e<t.length;e+=76)n.push(t.slice(e,e+76));return n.join(Hx)}function kS(e){let t=new TextEncoder().encode(e),n=new Uint8Array(Math.ceil(t.length*3*(76/73))+8),r=0,i=0,a=`0123456789ABCDEF`,o=e=>{n[r++]=e},s=(e,t,n)=>{let r=n===void 0?t===void 0?1:2:3;i+r>75&&(o(61),o(13),o(10),i=0),o(e),t!==void 0&&o(t),n!==void 0&&o(n),i+=r},c=e=>s(61,a.charCodeAt(e>>4),a.charCodeAt(e&15));for(let e=0;e<t.length;e++){let n=t[e];if(n===10)o(13),o(10),i=0;else if(n===13){if(t[e+1]===10)continue;o(13),o(10),i=0}else n===32||n===9?e===t.length-1||t[e+1]===10||t[e+1]===13?c(n):s(n):n===61||n<32||n>126?c(n):s(n)}return AS(n.subarray(0,r))}function AS(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return t}function jS(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===10)t=0;else{if(r===13){if(e.charCodeAt(n+1)===10)continue;return!0}if(r<32||r>126||(t++,t>990))return!0}}return!1}function MS(e){let t=0;for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&(n===0||e.charCodeAt(n-1)!==13)&&t++;if(t===0)return e;let n=new Uint8Array(e.length+t),r=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i===10&&(t===0||e.charCodeAt(t-1)!==13)&&(n[r++]=13),n[r++]=i}return AS(n)}function NS(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=6;else if(r>=55296&&r<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);if(r>=56320&&r<=57343){t+=12,n++;continue}t+=9}else t+=9}return t}function PS(e){return Math.ceil(e/3)*4}function FS(e){return e.headers.map(([e,t])=>vS(e,t)).join(Hx)+`\r
88
- \r
89
- `+e.body}function IS(e,t){let n=jS(t);return{headers:[[`Content-Type`,`${e}; charset=UTF-8`],[`Content-Transfer-Encoding`,n?`quoted-printable`:`7bit`]],body:n?kS(t):MS(t)}}function LS(e){let t=[[`Content-Type`,`${e.contentType}; name="${ES(e.filename)}"`],[`Content-Transfer-Encoding`,`base64`],[`Content-Disposition`,`${e.disposition}; filename="${ES(e.filename)}"`]];if(e.contentId){let n=e.contentId.startsWith(`<`)?e.contentId:`<${e.contentId}>`;t.push([`Content-ID`,n])}return{headers:t,body:OS(e.bytes)}}function RS(e){let t=new Uint8Array(16);return crypto.getRandomValues(t),`=_void_${e}_${Lx(t).replace(/[+/=]/g,``)}`}function zS(e,t){let n=RS(e);return{headers:[[`Content-Type`,`multipart/${e}; boundary="${n}"`]],body:t.map(e=>`--${n}${Hx}${FS(e)}`).join(Hx)+`${Hx}--${n}--${Hx}`}}var BS=new Set([`from`,`to`,`cc`,`bcc`,`subject`,`reply-to`,`date`,`message-id`,`in-reply-to`,`references`,`mime-version`,`content-type`,`content-transfer-encoding`,`content-disposition`]);function VS(e){let t=0,n=0,r=!1;for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a<128){if(t+=1,a===32||a===9)continue;(a<32||a===127)&&(r=!0),n+=1}else if(r=!0,a<2048)t+=2;else if(a>=55296&&a<=56319&&i+1<e.length){let n=e.charCodeAt(i+1);if(n>=56320&&n<=57343){t+=4,i++;continue}t+=3}else t+=3}return r?Math.floor(t*4/3)+12*Math.floor(t/pS):n}function HS(e){return e.email.length+(e.name?VS(e.name):0)}function US(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r!==32&&r!==9&&(t+=1)}return t}var WS=117,GS=Math.floor(zx/119),KS=4;function qS(e){let t=VS(e.subject);for(let[n,r]of Object.entries(e.headers))BS.has(n.toLowerCase())||(t+=n.length+KS+VS(r));t+=HS(e.from);for(let n of e.to)t+=HS(n);for(let n of e.cc)t+=HS(n);e.replyTo&&(t+=HS(e.replyTo)),e.threading?.inReplyTo&&(t+=US(e.threading.inReplyTo)),e.threading?.references&&(t+=US(e.threading.references));for(let n of e.attachments)t+=WS+2*n.filename.length,t+=US(n.contentType),n.contentId&&(t+=US(n.contentId));return t}function JS(e){let t=e.split(`@`)[1]??`localhost`,n=new Uint8Array(12);return crypto.getRandomValues(n),`<${Lx(n).replace(/[+/=]/g,``)}@${t}>`}function YS(e){let t=qS(e)+(e.text?NS(e.text):0)+(e.html?NS(e.html):0)+e.attachments.reduce((e,t)=>e+PS(t.bytes.byteLength),0);if(t>5242880)throw new $(`MIME_ERROR`,`email: message is at least ${t} bytes once encoded, which exceeds Cloudflare limit of ${zx} bytes.`);let n=JS(e.from.email),r=[[`Date`,new Date().toUTCString().replace(`GMT`,`+0000`)],[`From`,gS(e.from)],[`To`,_S(e.to)]];e.cc.length>0&&r.push([`Cc`,_S(e.cc)]),e.replyTo&&r.push([`Reply-To`,gS(e.replyTo)]),r.push([`Subject`,mS(e.subject)]),r.push([`Message-ID`,n]),e.threading?.inReplyTo&&r.push([`In-Reply-To`,e.threading.inReplyTo]),e.threading?.references&&r.push([`References`,e.threading.references]),r.push([`MIME-Version`,`1.0`]);for(let[t,n]of Object.entries(e.headers))BS.has(t.toLowerCase())||r.push([t,mS(n)]);let i=e.text?IS(`text/plain`,e.text):void 0,a=e.html?IS(`text/html`,e.html):void 0,o;if(o=i&&a?zS(`alternative`,[i,a]):i??a,e.attachments.length>0){let t=e.attachments.filter(e=>e.disposition===`inline`),n=e.attachments.filter(e=>e.disposition!==`inline`);t.length>0&&a?o=zS(`related`,[o,...t.map(LS)]):n.push(...t),n.length>0&&(o=zS(`mixed`,[o,...n.map(LS)]))}for(let[e,t]of o.headers)r.push([e,t]);let s=r.map(([e,t])=>vS(e,t)).join(Hx)+`\r
90
- \r
91
- `+o.body,c=new TextEncoder().encode(s),l=TS(s);if(l!==void 0)throw new $(`MIME_ERROR`,`email: header line ${l.index+1} is ${l.octets} octets, over the ${yS}-octet limit in RFC 5322 §2.1.1. A value with no whitespace cannot be folded — shorten it, or move it into the body.`);if(c.byteLength>5242880)throw new $(`MIME_ERROR`,`email: message size ${c.byteLength} bytes exceeds Cloudflare limit of ${zx} bytes.`);return{raw:c,messageId:n}}var XS=`/__void/inbox/_capture`,ZS=`__VOID_EMAIL_DEV_INBOX`,QS=`__VOID_EMAIL_DEV_INBOX_TOKEN`;function $S(e){return JSON.stringify({...e,raw:Lx(e.raw)})}var eC=`__voidEmailSinks__`,tC=globalThis;function nC(){let e=tC[eC];return e||(e={sinks:new Set},tC[eC]=e),e}function rC(e){for(let t of nC().sinks)try{t(e)}catch(e){console.warn(`[email-dev-inbox] sink error:`,e)}}function iC(){return nC().sinks.size>0}function aC(e,t,n){return{id:DS(`dev`),capturedAt:Date.now(),raw:t,messageId:n,from:e.from,to:e.to,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo,subject:e.subject,text:e.text,html:e.html,headers:{...e.headers},attachments:e.attachments.map(e=>({filename:e.filename,contentType:e.contentType,size:e.bytes.byteLength,contentId:e.contentId,disposition:e.disposition}))}}new TextEncoder,new TextDecoder(`utf-8`,{fatal:!0});var oC=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!1});async function sC(e,t,n){if(e<=0)throw n();let r;try{return await Promise.race([t(),new Promise((t,i)=>{r=setTimeout(()=>i(n()),e)})])}finally{r!==void 0&&clearTimeout(r)}}async function cC(e,t,n,{rejectEncoding:r=!1}={}){let i=e.headers.get(`content-length`);if(r&&e.headers.has(`content-encoding`)||i!==null&&(!/^\d+$/.test(i)||Number(i)>t))throw e.body?.cancel().catch(()=>{}),Error(`email response refused before reading`);let a=e.body?.getReader();if(!a)throw Error(`email response is empty`);let o=new Uint8Array(t),s=0;try{for(;;){let e=await n(()=>a.read());if(e.done)break;if(s+e.value.byteLength>t)throw Error(`email response too large`);o.set(e.value,s),s+=e.value.byteLength}}finally{a.cancel().catch(()=>{});try{a.releaseLock()}catch{}}if(i!==null&&s!==Number(i))throw Error(`email response length mismatch`);return JSON.parse(oC.decode(o.subarray(0,s)))}new TextEncoder;function lC(){try{return Pe()}catch{return}}function uC(e){let t=lC()?.[e];return typeof t==`string`&&t.length>0?t:void 0}var dC=/^[a-z0-9](?:[a-z0-9-]{0,54}[a-z0-9])?$/;function fC(){let e=uC(`__VOID_PROJECT_SLUG`);return e!==void 0&&dC.test(e)?e:void 0}function pC(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function mC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hC(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,cause:n}}var gC=`SEND_EMAIL`,_C=3e4,vC=6e4,yC=class extends Error{constructor(){super(`email binding outcome unknown after timeout`),this.name=`EmailBindingTimeoutError`}};function bC(e){let t=e?.[gC];if(typeof t==`object`&&t)return typeof t.send==`function`?t:void 0}function xC(e){let t=e instanceof Error?e.message:String(e);switch(typeof e?.code==`string`?e.code:``){case`E_RECIPIENT_NOT_ALLOWED`:return hC(`UNVERIFIED_DESTINATION`,t,e);case`E_SENDER_NOT_VERIFIED`:case`E_SENDER_DOMAIN_NOT_AVAILABLE`:return hC(`INVALID_FROM`,t,e);case`E_RATE_LIMIT_EXCEEDED`:case`E_DAILY_LIMIT_EXCEEDED`:return hC(`QUOTA_EXCEEDED`,t,e)}return SC.test(t)?hC(`UNVERIFIED_DESTINATION`,t,e):hC(`OUTCOME_UNKNOWN`,t,e)}var SC=/^[^\n]{0,200}destination address[^\n]{0,200}not (?:yet )?verified/i;async function CC(e,t,n,r,i){let a;try{({EmailMessage:a}=await import(`cloudflare:email`))}catch(e){return EC(`UPSTREAM_ERROR`,`email: SEND_EMAIL is bound but cloudflare:email could not be loaded: ${e instanceof Error?e.message:String(e)}`,e)}let o=[],s=Date.now()+vC,c=()=>Math.min(_C,s-Date.now());for(let s=0;s<n.length;s++){let l=n[s];if(c()<=0){for(let e of n.slice(s))o.push({recipient:e,ok:!1,state:`cancelled`,error:hC(`UPSTREAM_ERROR`,`email: batch deadline elapsed before provider submission`)});break}try{let n=await sC(c(),()=>e.send(new a(t,l,pC(r))),()=>new yC),s=typeof n?.messageId==`string`?n.messageId:``;o.push({recipient:l,ok:!0,messageId:s||i})}catch(e){let t=e instanceof yC?hC(`OUTCOME_UNKNOWN`,`email: binding submission timed out; inspect provider logs before retrying`,e):xC(e);o.push({recipient:l,ok:!1,...t.code===`OUTCOME_UNKNOWN`?{state:`outcome_unknown`}:{},error:t})}}return o.some(e=>!e.ok)?{ok:!1,deliveries:o}:{ok:!0,ids:o.map(e=>({recipient:e.recipient,messageId:e.messageId}))}}function wC(e){let t=new Set,n=[];for(let r of[...e.to,...e.cc,...e.bcc]){let e=r.email.toLowerCase();t.has(e)||(t.add(e),n.push(e))}return n}function TC(e){let t=e.from;if(!(t==null||typeof t==`string`&&t.trim()===``||typeof t==`object`&&t&&!(`email`in t)))return e;let n=uC(`__VOID_EMAIL_FROM`);if(n)return{...e,from:n};let r=fC(),i=uC(`__VOID_EMAIL_DOMAIN`);if(!r||!i){if(t===null){let t={...e};return delete t.from,t}return e}return{...e,from:`${r}+noreply@${i}`}}function EC(e,t,n){return{ok:!1,error:hC(e,t,n)}}function DC(e){return[`BINDING_MISSING`,`INVALID_FROM`,`INVALID_TO`,`UNVERIFIED_DESTINATION`,`MIME_ERROR`,`QUOTA_EXCEEDED`,`IDEMPOTENCY_CONFLICT`,`OUTCOME_UNKNOWN`,`UPSTREAM_ERROR`].find(t=>t===e)??`UPSTREAM_ERROR`}function OC(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{error:t,message:n}=e;return typeof t!=`string`||t===``?null:typeof n==`string`&&n!==``?n:t}function kC(e){if(!mC(e))return null;let t=e.operationId;if(e.ok===!0&&Array.isArray(e.ids))return{ok:!0,ids:e.ids,operationId:t};if(e.ok!==!1)return null;if(Array.isArray(e.deliveries))return{ok:!1,deliveries:e.deliveries,operationId:t};let n=e.error;return typeof n==`object`&&n?{ok:!1,error:{code:`code`in n?n.code:void 0,message:`message`in n?n.message:void 0},operationId:t}:null}function AC(e,t,n,r){if(e.length!==t.length)return{ok:!1,reason:`expected ${t.length} deliveries, got ${e.length}`};let i=new Set(t),a=new Set,o=[];for(let[t,s]of e.entries()){let e=typeof s==`object`&&s?s:null,c=e?.recipient;if(e===null||typeof c!=`string`)return{ok:!1,reason:`entry ${t} is not ${n}`};let l=r(e,c);if(l===void 0)return{ok:!1,reason:`entry ${t} is not ${n}`};if(!i.has(c))return{ok:!1,reason:`entry ${t} names a recipient that was not requested`};if(a.has(c))return{ok:!1,reason:`entry ${t} repeats a recipient`};a.add(c),o.push(l)}return{ok:!0,entries:o}}function jC(e,t,n){return AC(e,t,`{ recipient: string, messageId: string }`,(e,t)=>typeof e.messageId==`string`?{recipient:t,messageId:e.messageId||n,...e.state===`provider_accepted`?{state:`provider_accepted`}:{}}:void 0)}function MC(e,t,n){return AC(e,t,`{ recipient: string, ok: true, messageId: string } | { recipient: string, ok: false, error: { message: string } }`,(e,t)=>{if(e.ok===!0)return typeof e.messageId==`string`?{recipient:t,ok:!0,messageId:e.messageId||n,...e.state===`provider_accepted`?{state:`provider_accepted`}:{}}:void 0;if(e.ok===!1){let n=NC(e.state),r=e.error;return typeof r==`object`&&r&&typeof r.message==`string`?{recipient:t,ok:!1,error:hC(DC(r.code),r.message),...n?{state:n}:{}}:void 0}})}function NC(e){return[`rejected`,`reserved`,`attempt_started`,`provider_accepted`,`failed`,`outcome_unknown`,`cancelled`].find(t=>t===e)}var PC=65536;async function FC(e,t,n,r){let i;try{i=await cC(e,PC,r)}catch{return EC(`OUTCOME_UNKNOWN`,`email: could not establish the send outcome (status ${e.status}); check email logs or repeat the same idempotency key`)}let a=kC(i);if(a===null){let t=OC(i);return!e.ok&&t!==null?EC(`UPSTREAM_ERROR`,`email: proxy returned ${e.status}: ${t}`,i):EC(`OUTCOME_UNKNOWN`,`email: proxy returned malformed response (status ${e.status})`,i)}let o=e=>EC(`OUTCOME_UNKNOWN`,`email: proxy returned a malformed delivery list (${e}); do not retry with a new idempotency key`,i),s=typeof a.operationId==`string`&&a.operationId.length<=128?{operationId:a.operationId}:{};if(a.ok===!0){let e=jC(a.ids,t,n);return e.ok?{ok:!0,ids:e.entries,...s}:o(e.reason)}if(`deliveries`in a){let e=MC(a.deliveries,t,n);return e.ok?{ok:!1,deliveries:e.entries,...s}:o(e.reason)}let c=a.error;return{...EC(DC(c.code),typeof c.message==`string`?c.message:`email: upstream send failed`),...s}}function IC(e){let t=e?.[ZS];if(typeof t!=`string`||t.length===0)return;let n=e?.[t];if(typeof n!=`object`||!n||typeof n.fetch!=`function`)return;let r=e?.[QS];return{fetcher:n,token:typeof r==`string`&&r.length>0?r:void 0}}var LC=5e3,RC=200,zC=1e3;async function BC(e){let t;try{let n=e.body?.getReader();if(!n)return``;let r=await Promise.race([n.read().then(({value:e})=>e),new Promise(e=>{t=setTimeout(()=>e(void 0),zC)})]);return n.cancel().catch(()=>{}),r?new TextDecoder().decode(r).trim().split(`
92
- `)[0].slice(0,RC):``}catch{return``}finally{t!==void 0&&clearTimeout(t)}}async function VC(e,t){let n;try{let r=Promise.resolve(e.fetcher.fetch(`http://localhost${XS}`,{method:`POST`,headers:{"content-type":`application/json`,...e.token!==void 0&&{"x-void-dev-trigger":e.token}},body:$S(t)})).then(e=>({kind:`response`,res:e}),e=>({kind:`error`,cause:e})),i=await Promise.race([r,new Promise(e=>{n=setTimeout(()=>e({kind:`timeout`}),LC)})]);if(i.kind===`timeout`)return{ok:!1,reason:`no response within ${LC}ms`};if(i.kind===`error`){let e=i.cause;return{ok:!1,reason:e instanceof Error?e.message:String(e)}}let{res:a}=i;if(!a.ok){let e=await BC(a);return{ok:!1,reason:`dev server responded ${a.status}${e?`: ${e}`:``}`}}return a.headers.get(`x-void-email-inbox`)===`captured`?{ok:!0}:{ok:!1,reason:`response did not come from the dev inbox`}}catch(e){return{ok:!1,reason:e instanceof Error?e.message:String(e)}}finally{n!==void 0&&clearTimeout(n)}}function HC(e,t){return{ok:!0,ids:wC(e).map(e=>({recipient:e,messageId:t}))}}async function UC(e){if(e.idempotencyKey!==void 0&&(typeof e.idempotencyKey!=`string`||!/^[\x21-\x7e]{1,128}$/.test(e.idempotencyKey)))return EC(`MIME_ERROR`,`email: idempotencyKey must contain 1–128 printable non-space ASCII characters.`);let t=TC(e);if(t.from===void 0)return EC(`INVALID_FROM`,`email: 'from' is required. Set it explicitly or deploy via Void so the platform-injected __VOID_PROJECT_SLUG and __VOID_EMAIL_DOMAIN can default it to <slug>+noreply@<domain>.`);let n=t,r,i,a;try{r=await fS(n),{raw:i,messageId:a}=YS(r)}catch(e){return e instanceof $?EC(e.code,e.message,e):EC(`MIME_ERROR`,e instanceof Error?e.message:String(e),e)}let o=lC();if(!e.sendInDev&&iC()){let e=aC(r,i,a);return rC(e),HC(r,e.id)}let s=e.sendInDev?void 0:IC(o);if(s){let e=aC(r,i,a),t=await VC(s,e);if(t.ok)return HC(r,e.id);let n=`email: the void dev inbox at ${XS} is unreachable (${t.reason}), so nothing was captured and nothing was sent.`;return console.warn(`[void/email] ${n}`),EC(`UPSTREAM_ERROR`,n)}let c=wC(r),l=bC(o);if(l)return e.idempotencyKey===void 0?CC(l,r.from.email,c,i,a):EC(`MIME_ERROR`,`email: idempotencyKey requires a Void platform; the native Cloudflare binding cannot deduplicate sends.`);let u=o,d=u?.__VOID_PROXY,f=u?.__PROJECT_ID,p=u?.__VOID_PROXY_TOKEN;if(!d||!f||!p)return EC(`BINDING_MISSING`,"email: neither SEND_EMAIL nor __VOID_PROXY is available, so nothing was sent. Deploy via Void to bind the platform proxy, or set `email.from` in void.config.ts so `void deploy --platform cloudflare` provisions the SEND_EMAIL binding. Under `void dev` messages are captured by the local inbox at /__void/inbox instead — reaching this error there means that path was bypassed by the deprecated `sendInDev: true` (it never delivers) or unavailable (the worker has no assets binding to reach the dev server through).");let m={projectId:f,aiToken:p,from:r.from.email,recipients:c,mimeBase64:Lx(i),requestId:DS(`req`),...e.idempotencyKey===void 0?{}:{idempotencyKey:e.idempotencyKey}},h=JSON.stringify(m),g=new AbortController,_=Date.now()+vC,ee=e=>sC(_-Date.now(),e,()=>(g.abort(),Error(`email platform send timed out`))),te;try{te=await ee(()=>d.fetch(`https://email-proxy/email/send`,{method:`POST`,headers:{"content-type":`application/json`},body:h,signal:g.signal}))}catch(e){return EC(`OUTCOME_UNKNOWN`,`email: send outcome is unknown: ${e instanceof Error?e.message:String(e)}. Check email logs or repeat the same idempotency key; do not create a new send.`,e)}return FC(te,c,a,ee)}var WC={ACCOUNT_LIMIT:{limit:60,namespace:`1007`,period:60},APP_DISCOVERY_LIMIT:{limit:30,namespace:`1009`,period:60},AUTHORIZE_LIMIT:{limit:60,namespace:`1001`,period:60},DEVICE_LIMIT:{limit:10,namespace:`1002`,period:60},SIGN_IN_CODE_LIMIT:{limit:5,namespace:`1003`,period:60},SIGN_IN_IP_LIMIT:{limit:100,namespace:`1004`,period:60},TOKEN_APP_LIMIT:{limit:600,namespace:`1008`,period:60},TOKEN_LIMIT:{limit:300,namespace:`1006`,period:60}},GC=[`TOKEN_APP_LIMIT`],KC=class extends Vv(`rate_limited`){name=`RateLimit.LimitedError`;constructor(e){super({error_description:`Too many requests. Try again in ${Qv({seconds:e.retryAfter})}.`,meta:{retryAfter:e.retryAfter}})}},qC=`2a06:98c0:3600::103`;async function JC(e,t){let n=e.env,r=t.limits.flatMap(t=>t.key===void 0?[]:!n[t.binding]&&GC.includes(t.binding)?(nn(e,{fields:{binding:t.binding},message:`A rate limit has no binding, so the request is not counted.`}),[]):[{...t,key:t.key,policy:$C({binding:t.binding})}]);for(let t of r)XC(e,{policy:t.policy});for(let t of r)if(!await YC(e,{binding:t.binding,key:t.key}))return ew(e,{policy:t.policy,retryAfter:t.policy.window})}(function(e){e.errors=[KC]})(JC||={});function YC(e,t){let n=e.var.counted??new Map;e.var.counted||e.set(`counted`,n);let r=JSON.stringify([t.binding,t.key]),i=n.get(r)??v(e,e.env[t.binding].limit({key:t.key}),`ratelimit.limit`).then(e=>e.success);return n.set(r,i),i}function XC(e,t){let{policy:n}=t;e.header(`ratelimit-policy`,`"${n.name}";q=${n.quota};w=${n.window}`,{append:!0})}function ZC(e){return e}function QC(e){let t=e.req.header(`cf-connecting-ip`);if(t===qC)return`worker:${e.req.header(`cf-worker`)??``}`;if(!t?.includes(`:`)||t.includes(`.`))return t;let[n,r]=t.toLowerCase().split(`::`),i=n?n.split(`:`):[],a=r?r.split(`:`):[];return`${(r===void 0?i:[...i,...Array(Math.max(0,8-i.length-a.length)).fill(`0`),...a]).slice(0,4).map(e=>e.replace(/^0+(?=.)/,``)).join(`:`)}::/64`}function $C(e){let{binding:t}=e,n=WC[t];return ZC({name:t.replace(/_LIMIT$/,``).toLowerCase().replaceAll(`_`,`-`),quota:n.limit,window:n.period})}function ew(e,t){let{policy:n,retryAfter:r}=t;return e.header(`ratelimit`,`"${n.name}";r=0;t=${r}`),e.header(`retry-after`,String(r)),Z(e,new KC({retryAfter:r}))}var tw={address:{name:`address`,quota:5,window:3600},global:{name:`global`,quota:100,window:3600},ip:{name:`ip`,quota:30,window:3600}},nw=43200,rw=`tempo-id-admin-session`,iw=`admin-login:`,aw=`admin-login-limit:`;function ow(){let[e]=crypto.getRandomValues(new Uint32Array(1));return String(e%1e6).padStart(6,`0`)}function sw(e){return`${iw}${e.email.toLowerCase()}`}async function cw(e){if(e.key===void 0)return`${aw}${e.limit}`;let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.key.toLowerCase()));return`${aw}${e.limit}:${mw(new Uint8Array(t))}`}function lw(e){return e.email.toLowerCase().endsWith(`@${e.domain}`)}async function uw(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(`${e.email.toLowerCase()}:${e.code}`));return mw(new Uint8Array(t))}function dw(e){let t=new TextEncoder().encode(e.left),n=new TextEncoder().encode(e.right);return t.length===n.length&&crypto.subtle.timingSafeEqual(t,n)}async function fw(e){let t=hw(new TextEncoder().encode(JSON.stringify({email:e.email,exp:e.expires}))),n=await crypto.subtle.sign(`HMAC`,await pw({secret:e.secret}),new TextEncoder().encode(t));return`${t}.${hw(new Uint8Array(n))}`}async function pw(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(`tempo-id-admin-session:${e.secret}`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-256`,name:`HMAC`},!1,[`sign`,`verify`])}function mw(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}function hw(e){return btoa(String.fromCharCode(...e)).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``)}var gw;(function(e){let t;(function(e){e.json=X({email:C_().meta({description:`The address that receives the code.`,examples:[`ada@tempo.xyz`]})}),e.response=X({expiresAt:Lv().meta({description:`When the code expires, as an ISO 8601 string.`,examples:[`2026-10-27T05:00:00.000Z`]})})})(t||=e.code||={});let n;(function(e){e.json=X({code:J().regex(/^\d{6}$/).meta({description:`The 6-digit code from the email.`,examples:[`123456`]}),email:t.json.shape.email}),e.response=X({email:J().meta({description:`The signed-in address.`,examples:[`ada@tempo.xyz`]})})})(n||=e.verify||={})})(gw||={});var _w=new Kt().post(`/_dev/code`,Yy({description:`Emails a sign-in code to an address of the preview admin domain. Internal: only the admin app calls it.`,hide:!0,responses:hx({errors:[...gx.errors,Kv,KC],success:{description:`The code is sent.`,schema:gw.code.response}}),tags:[`Session`]}),gx(`json`,gw.code.json),async e=>{let t=e.env.ADMIN_LOGIN;if(!t)return Z(e,new Kv);let{email:n}=e.req.valid(`json`);if(!lw({domain:t.emailDomain,email:n}))return Z(e,new ix({issues:[{message:`Use an address at ${t.emailDomain}`,path:[`email`]}]}));let r=await vw(e,{limits:[{key:QC(e),limit:`ip`},{key:void 0,limit:`global`}]});if(r)return r;let i=sw({email:n}),a=ow(),o=await v(e,uw({code:a,email:n}),`Session.hash`),s=Date.now(),c=new Date(s+6e5),l=await v(e,e.var.db.transaction(async t=>{await t.execute(A`select pg_advisory_xact_lock(hashtextextended(${i}, 0))`);let[r]=await t.select({createdAt:z.createdAt}).from(z).where(cs(z.identifier,i)),a=r?(s-r.createdAt.getTime())/1e3:1/0;if(a<60)return Z(e,new KC({retryAfter:Math.ceil(60-a)}));let l=await vw(e,{db:t,limits:[{key:n,limit:`address`}]});if(l)return l;let u={attempts:0,hash:o};await t.delete(z).where(cs(z.identifier,i)),await t.insert(z).values({expiresAt:c,id:crypto.randomUUID(),identifier:i,value:JSON.stringify(u)})}),`db.verification.replace`);if(l)return l;if(!(await v(e,UC({from:t.from,subject:`${a} is your Tempo ID Admin sign-in code`,text:`Your Tempo ID Admin sign-in code is ${a}.\n\nIt expires in 10 minutes. If you did not request it, ignore this email.\n`,to:n}),`email.send`)).ok)throw Error(`The email service refused the code.`);return e.json({expiresAt:c.toISOString()},200)}).post(`/_dev/verify`,Yy({description:`Redeems a sign-in code, and sets the session cookie. Internal: only the admin app calls it.`,hide:!0,responses:hx({errors:[...gx.errors,ox,Kv,KC],success:{description:`The signed-in address.`,schema:gw.verify.response}}),tags:[`Session`]}),gx(`json`,gw.verify.json),async e=>{let t=e.env.ADMIN_LOGIN;if(!t)return Z(e,new Kv);let{code:n,email:r}=e.req.valid(`json`),i=await vw(e,{limits:[{key:QC(e),limit:`ip`},{key:void 0,limit:`global`}]});if(i)return i;let a=sw({email:r}),o=z.value,[s]=await v(e,e.var.db.update(z).set({value:A`jsonb_set(${o}::jsonb, '{attempts}', to_jsonb((${o}::jsonb->>'attempts')::int + 1))::text`}).where(us(cs(z.identifier,a),ps(z.expiresAt,new Date),hs(A`case when ${z.identifier} = ${a} then (${o}::jsonb->>'attempts')::int end`,5))).returning({id:z.id,value:o}),`db.verification.attempt`);if(!s)return Z(e,new ox);let c=JSON.parse(s.value);if(!dw({left:await v(e,uw({code:n,email:r}),`Session.hash`),right:c.hash}))return Z(e,new ox);let[l]=await v(e,e.var.db.delete(z).where(cs(z.id,s.id)).returning({id:z.id}),`db.verification.spend`);return l?(ay(e,rw,await v(e,fw({email:r,expires:Math.floor(Date.now()/1e3)+nw,secret:t.secret}),`Session.sign`),{httpOnly:!0,maxAge:nw,path:`/`,sameSite:`Lax`,secure:!0}),e.json({email:r},200)):Z(e,new ox)}).get(`/_dev/logout`,Yy({description:`Clears the session cookie, and redirects to the sign-in page. Internal: the dashboard links to it.`,hide:!0,responses:{302:{description:"Redirects to `/_dev/sign-in`."},...mx([Kv])},tags:[`Session`]}),e=>e.env.ADMIN_LOGIN?(oy(e,rw,{path:`/`,secure:!0}),e.redirect(`/_dev/sign-in`,302)):Z(e,new Kv));async function vw(e,t){let n=t.db??e.var.db;for(let r of t.limits){if(r.limit!==`global`&&r.key===void 0)continue;let t=tw[r.limit],i=await v(e,cw({key:r.key,limit:r.limit}),`Session.counter`),a=Date.now(),o=crypto.randomUUID();await v(e,n.insert(z).values({expiresAt:new Date(a+t.window*1e3),id:o,identifier:i,value:``}),`db.verification.count`);let[s]=await v(e,n.select({count:A`count(*)::int`}).from(z).where(us(cs(z.identifier,i),ps(z.expiresAt,new Date(a)))),`db.verification.count`);if(!((s?.count??0)<=t.quota))return await v(e,n.delete(z).where(cs(z.id,o)),`db.verification.uncount`),Z(e,new KC({retryAfter:t.window}))}}var yw;(function(e){let t;(function(e){e.response=X({actor:X({email:J().nullable().meta({description:"The actor's email address, which the page shows to the actor alone, or `null`.",examples:[`ada@tempo.xyz`]}),sub:J().meta({description:`The actor's stable, opaque ID.`,examples:[`00u1a2b3c4d5e6f7g8h9`]})}).meta({description:`The actor that the request acts as.`}),login:X_().meta({description:"Whether the actor signed in through the deployment's email-code sign-in, as on a preview, whose sign-out is `/_dev/logout`."})})})(t||=e.session||={})})(yw||={});var bw=new Kt().get(`/i/session`,Yy({description:`Returns the actor that the request acts as. Internal: only the admin app reads it.`,hide:!0,responses:hx({success:{description:`The actor.`,schema:yw.session.response}}),tags:[`Session`]}),e=>{let{email:t,sub:n}=e.var.actor;return e.json({actor:{email:t??null,sub:n},login:!!e.env.ADMIN_LOGIN},200)}),xw=new Kt().route(`/`,Px).route(`/`,_w).route(`/`,bw),Sw={description:"A Cloudflare Access token, such as from `cloudflared access token -app <admin URL>`. Access checks it, and forwards its assertion to the deployment.",in:`header`,name:`cf-access-token`},Cw={info:{description:"Tempo ID's Admin API, on a host of its own behind the deployment's authorization. It registers and operates OAuth apps. Every refusal of a route is an OAuth error response (RFC 6749 §5.2) whose `reason` determines its `error` and status. The deployment's authorization responds in a format of its own.",title:`Tempo ID Admin`},security:[{deployment:[]}],tags:[{description:`Registers, lists, changes, and removes OAuth apps, and rotates their client secrets.`,name:`Apps`},{description:`This OpenAPI document and its reference page.`,name:`Reference`}]},ww=qt(async(e,t)=>{if(e.env.ADMIN_LOGIN&&e.req.path.startsWith(`/_dev/`))return t();let n=await v(e,e.env.ADMIN_AUTHORIZE(e.req.raw),`Admin.authorize`);if(n instanceof Response)return new Response(n.body,n);if(!jw(n))throw Error("The deployment's `authorize` returned no actor.");e.set(`actor`,n),await t()}),Tw=qt(async(e,t)=>{await t(),e.res.headers.set(`cache-control`,`private, no-store`)}),Ew=qt(async(e,t)=>{let n=e.req.header(`origin`),r=e.req.header(`sec-fetch-site`);if(![`GET`,`HEAD`,`OPTIONS`].includes(e.req.method)&&(n!==void 0&&n!==new URL(e.req.url).origin||r===`cross-site`||r===`same-site`))return Z(e,new Hv);await t()}),Dw=qt(async(e,t)=>{if(typeof e.env.ADMIN_DATABASE_URL!=`string`||!e.env.ADMIN_DATABASE_URL)throw Error("The `db` option holds no connection string.");let n=new mr.Client({connectionString:e.env.ADMIN_DATABASE_URL});await v(e,n.connect(),`db.connect`),e.set(`db`,Kc({client:n,schema:wl}));try{await t()}finally{e.executionCtx.waitUntil(n.end().catch(t=>{nn(e,{error:t,message:`The Admin API failed to close a database connection.`})}))}}),Ow=new Kt().use(un).use(xx()).use(Tw).use(Yc({referrerPolicy:`no-referrer`})).use(Ew).use(ty).use(ww).use(`/apps`,Dw).use(`/apps/*`,Dw).use(`/_dev/*`,Dw).route(`/`,xw).get(`/openapi.json`,Yy({description:`Returns this OpenAPI document.`,responses:{200:{content:{"application/json":{schema:{type:`object`}}},description:`The OpenAPI 3.1 document.`},...mx([])},tags:[`Reference`]}),async e=>e.json(await v(e,dx(Ow,{...Cw,securitySchemes:{deployment:{...e.env.ADMIN_SECURITY_SCHEME??Sw,type:`apiKey`}}}),`OpenApi.document`),200)).get(`/docs`,Yy({description:`Renders this OpenAPI document as an API reference.`,responses:{200:{content:{"text/html":{schema:{type:`string`}}},description:`The API reference page.`},...mx([])},tags:[`Reference`]}),e=>(e.header(`content-security-policy`,px),e.html(fx))).notFound(async e=>{let t=[`GET`,`HEAD`].includes(e.req.method)&&!kw(e.req.path)?e.env.ADMIN_PAGES:void 0;return t?v(e,t(e),`page.render`):Z(e,new Kv)}).onError(Zv);function kw(e){return e!==`/_dev/sign-in`&&Aw.has(e.split(`/`)[1]??``)}var Aw=new Set(Ow.routes.flatMap(e=>{let t=e.path.split(`/`)[1]??``;return t&&t!==`*`&&!t.startsWith(`:`)?[t]:[]}));function jw(e){return typeof e==`object`&&!!e&&`sub`in e&&typeof e.sub==`string`&&e.sub.length>0}var Mw,Nw={fetch:(e,t,n)=>{let r=Pw(t);return Ow.fetch(e,{...r,ADMIN_PAGES:e=>Fw(e,{ctx:n,env:r})},n)}};function Pw(e){return e.ADMIN_AUTHORIZE,e}async function Fw(e,t){let{ctx:n,env:r}=t,i=new URL(e.req.url).origin,a=async(t,a)=>{let o=new Request(t,a),s=new URL(o.url);if(s.origin!==i||!(s.pathname===`/apps`||[`/apps/`,`/i/`].some(e=>s.pathname.startsWith(e))))throw Error(`A page called a path outside the Admin API.`);for(let[t,n]of e.req.raw.headers)o.headers.has(t)||o.headers.set(t,n);return v(e,Promise.resolve(Ow.fetch(o,r,n)),`api`,`${o.method} ${s.pathname}`)};Mw??=import(`./server-tS2GlQUk.js`).then(e=>e.createStartHandler(e.defaultStreamHandler));let o=await(await v(e,Mw,`pages.load`))(e.req.raw,{context:{fetch:a,fetchOptional:a,origin:i}});return e.header(`cache-control`,`private, no-store`),e.newResponse(o.body,o)}function Iw(){let e=null;return async(t,n)=>{if(e)return e;let r=globalThis.__VITE_MANIFEST__;if(typeof r==`object`&&r)return e=r,e;let i=n?.ASSETS;if(!i||typeof i.fetch!=`function`)return null;let a=await i.fetch(new Request(new URL(`/.vite/manifest.json`,t.url).toString()));return a.ok?(e=await a.json(),e):null}}var Lw=new WeakSet;function Rw(e){if(e instanceof Response)return e;let t;return t=e==null?new Response(null,{status:204}):typeof e==`string`?new Response(e,{headers:{"Content-Type":`text/html; charset=utf-8`}}):Response.json(e),Lw.add(t),t}function zw(e){return Array.from(e,e=>({message:e.message,path:e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`)}))}async function Bw(e,t){let n=await e[`~standard`].validate(t);return n.issues?{ok:!1,issues:n.issues}:{ok:!0,value:n.value}}async function Vw(e,t){let n={},r=[];if(e.params){let i=t.req.param(),a=await Bw(e.params,i);a.ok?n.params=a.value:r.push({slot:`params`,issues:zw(a.issues)})}if(e.query){let i=new URL(t.req.url),a={};for(let[e,t]of i.searchParams)a[e]=t;let o=await Bw(e.query,a);o.ok?n.query=o.value:r.push({slot:`query`,issues:zw(o.issues)})}if(e.body){let i;try{i=await t.req.json()}catch{return{ok:!1,response:Response.json({error:`Invalid JSON body`},{status:400})}}let a=await Bw(e.body,i);a.ok?n.body=a.value:r.push({slot:`body`,issues:zw(a.issues)})}return r.length>0?{ok:!1,response:Response.json({error:`Validation failed`,issues:r},{status:400})}:{ok:!0,input:n}}function Hw(...e){if(e.length===1)return e[0];let t=e.slice(0,-1),n=e[e.length-1];return(async e=>{let r=0,i=async()=>{if(r<t.length){let n=t[r++],a=await n(e,i);a instanceof Response&&(e.res=a)}else e.res=Rw(await n(e))};return await i(),e.res})}(function(e){function t(e){return t=>(async n=>{let r=await Vw(e,n);return r.ok?Rw(await t(n,r.input)):r.response})}e.withValidator=t})(Hw||={}),new TextEncoder,new TextDecoder(`utf-8`,{fatal:!0});var Uw={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function Ww(e,t,n=`assets`,r=!1){if(![`GET`,`HEAD`].includes(e.method)||![200,206,304].includes(t.status))return t;let i=new URL(e.url).pathname,a=i.slice(i.lastIndexOf(`/`)+1),o=a.slice(a.lastIndexOf(`.`)).toLowerCase(),s=new Headers(t.headers);!s.has(`Content-Type`)&&Uw[o]&&s.set(`Content-Type`,Uw[o]);let c=s.get(`Cache-Control`),l=(c??``).toLowerCase().split(`,`).map(e=>e.trim()).sort().join(`,`)===`max-age=0,must-revalidate,public`,u=r&&i.startsWith(`/`+n.replace(/^\/+|\/+$/g,``)+`/`)&&o!==`.html`&&!(s.get(`Content-Type`)??``).toLowerCase().includes(`text/html`);return!s.has(`Set-Cookie`)&&u&&(!c||l)?s.set(`Cache-Control`,`public, max-age=31536000, immutable`):c||s.set(`Cache-Control`,`no-store`),new Response(t.body,{status:t.status,statusText:t.statusText,headers:s})}function Gw(e,t=Iw()){let n;return async(r,i,a)=>{let o=new URL(r.url).pathname;return![`GET`,`HEAD`].includes(r.method)||![200,206,304].includes(a.status)||!o.startsWith(`/`+(e??`assets`).replace(/^\/+|\/+$/g,``)+`/`)?Ww(r,a,e):(n||=t(r,i).then(e=>new Set(Object.values(e??{}).flatMap(e=>Array.isArray(e?.immutableFiles)?e.immutableFiles:[])),()=>new Set),Ww(r,a,e,(await n).has(o.slice(1))))}}function Kw(e={}){let t=Gw(e.assetsDir);return async(n,r,i)=>{if(i.status!==404||!r.ASSETS||n.method!==`GET`&&n.method!==`HEAD`)return i;let a=await r.ASSETS.fetch(new Request(n.url,{method:n.method,headers:n.headers}));if(a.status!==404)return t(n,r,a);let o=n.headers.get(`accept`)??``;if(e.serveSpaFallback&&o.includes(`text/html`)){let e=new URL(`/index.html`,n.url),t=await r.ASSETS.fetch(new Request(e,{method:n.method}));if(t.status===200){let e=new Response(t.body,{status:200,headers:t.headers});return e.headers.set(`Cache-Control`,`no-store`),e.headers.set(`Content-Type`,`text/html; charset=utf-8`),e}}else if(!e.serveSpaFallback&&e.notFound===`404-page`&&o.includes(`text/html`)&&(a.headers.get(`content-type`)??``).includes(`text/html`)){let e=new Response(a.body,a);return e.headers.set(`Cache-Control`,`no-store`),e}return i}}var qw={...Nw,async fetch(e,t,n){return Jw(e,t,await Nw.fetch(e,t,n))}},Jw=Kw({assetsDir:`assets`,serveSpaFallback:!1,notFound:`none`}),Yw=qw??{};export{Qg as n,Yw as t};
93
- //# sourceMappingURL=worker-entry-DcGlpZzO.js.map