wiki-viewer 2.6.1 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +1 -0
  3. package/.next/standalone/.next/build-manifest.json +3 -3
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/required-server-files.json +3 -3
  6. package/.next/standalone/.next/routes-manifest.json +8 -0
  7. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  16. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  18. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  20. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  23. package/.next/standalone/.next/server/app/api/agent/activity/route.js +7 -7
  24. package/.next/standalone/.next/server/app/api/agent/activity/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/agent/admin/agents/[agentId]/revoke/route.js +5 -5
  26. package/.next/standalone/.next/server/app/api/agent/admin/agents/[agentId]/revoke/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/agent/admin/agents/route.js +5 -5
  28. package/.next/standalone/.next/server/app/api/agent/admin/agents/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/approve/route.js +3 -3
  30. package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/approve/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/deny/route.js +5 -5
  32. package/.next/standalone/.next/server/app/api/agent/admin/registrations/[regId]/deny/route.js.nft.json +1 -1
  33. package/.next/standalone/.next/server/app/api/agent/admin/registrations/route.js +5 -5
  34. package/.next/standalone/.next/server/app/api/agent/admin/registrations/route.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/api/agent/events/[...path]/route.js +6 -6
  36. package/.next/standalone/.next/server/app/api/agent/events/[...path]/route.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/api/agent/files/[...path]/route.js +8 -8
  38. package/.next/standalone/.next/server/app/api/agent/files/[...path]/route.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/api/agent/fs/file/[...path]/route.js +6 -6
  40. package/.next/standalone/.next/server/app/api/agent/fs/file/[...path]/route.js.nft.json +1 -1
  41. package/.next/standalone/.next/server/app/api/agent/fs/ls/[[...path]]/route.js +7 -7
  42. package/.next/standalone/.next/server/app/api/agent/fs/ls/[[...path]]/route.js.nft.json +1 -1
  43. package/.next/standalone/.next/server/app/api/agent/fs/move/route.js +7 -7
  44. package/.next/standalone/.next/server/app/api/agent/fs/move/route.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/api/agent/fs/search/route.js +7 -7
  46. package/.next/standalone/.next/server/app/api/agent/fs/search/route.js.nft.json +1 -1
  47. package/.next/standalone/.next/server/app/api/agent/internal/span/route.js +5 -5
  48. package/.next/standalone/.next/server/app/api/agent/internal/span/route.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/api/agent/settings/route.js +8 -8
  50. package/.next/standalone/.next/server/app/api/agent/settings/route.js.nft.json +1 -1
  51. package/.next/standalone/.next/server/app/api/agent/sidecar/[...path]/route.js +6 -6
  52. package/.next/standalone/.next/server/app/api/agent/sidecar/[...path]/route.js.nft.json +1 -1
  53. package/.next/standalone/.next/server/app/api/app-proxy/[...path]/route.js +1 -1
  54. package/.next/standalone/.next/server/app/api/app-proxy/[...path]/route.js.nft.json +1 -1
  55. package/.next/standalone/.next/server/app/api/assets/[...path]/route.js +6 -6
  56. package/.next/standalone/.next/server/app/api/assets/[...path]/route.js.nft.json +1 -1
  57. package/.next/standalone/.next/server/app/api/auth/[...all]/route.js +3 -3
  58. package/.next/standalone/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/api/pdf/save/route.js +5 -5
  60. package/.next/standalone/.next/server/app/api/pdf/save/route.js.nft.json +1 -1
  61. package/.next/standalone/.next/server/app/api/share/[token]/asset/route/app-paths-manifest.json +3 -0
  62. package/.next/standalone/.next/server/app/api/share/[token]/asset/route/build-manifest.json +9 -0
  63. package/.next/standalone/.next/server/app/api/share/[token]/asset/route/server-reference-manifest.json +4 -0
  64. package/.next/standalone/.next/server/app/api/share/[token]/asset/route.js +9 -0
  65. package/.next/standalone/.next/server/app/api/share/[token]/asset/route.js.map +5 -0
  66. package/.next/standalone/.next/server/app/api/share/[token]/asset/route.js.nft.json +1 -0
  67. package/.next/standalone/.next/server/app/api/share/[token]/asset/route_client-reference-manifest.js +3 -0
  68. package/.next/standalone/.next/server/app/api/share/[token]/route.js +5 -5
  69. package/.next/standalone/.next/server/app/api/share/[token]/route.js.nft.json +1 -1
  70. package/.next/standalone/.next/server/app/api/share/route.js +5 -5
  71. package/.next/standalone/.next/server/app/api/share/route.js.nft.json +1 -1
  72. package/.next/standalone/.next/server/app/api/system/admins/route.js +4 -4
  73. package/.next/standalone/.next/server/app/api/system/admins/route.js.nft.json +1 -1
  74. package/.next/standalone/.next/server/app/api/system/auth-config/route.js +6 -6
  75. package/.next/standalone/.next/server/app/api/system/auth-config/route.js.nft.json +1 -1
  76. package/.next/standalone/.next/server/app/api/system/auth-settings/route.js +4 -4
  77. package/.next/standalone/.next/server/app/api/system/auth-settings/route.js.nft.json +1 -1
  78. package/.next/standalone/.next/server/app/api/system/browse/route.js +4 -4
  79. package/.next/standalone/.next/server/app/api/system/browse/route.js.nft.json +1 -1
  80. package/.next/standalone/.next/server/app/api/system/clear-root/route.js +4 -4
  81. package/.next/standalone/.next/server/app/api/system/clear-root/route.js.nft.json +1 -1
  82. package/.next/standalone/.next/server/app/api/system/config/route.js +6 -6
  83. package/.next/standalone/.next/server/app/api/system/config/route.js.nft.json +1 -1
  84. package/.next/standalone/.next/server/app/api/system/pins/route.js +4 -4
  85. package/.next/standalone/.next/server/app/api/system/pins/route.js.nft.json +1 -1
  86. package/.next/standalone/.next/server/app/api/system/reveal/route.js +5 -5
  87. package/.next/standalone/.next/server/app/api/system/reveal/route.js.nft.json +1 -1
  88. package/.next/standalone/.next/server/app/api/system/root-status/route.js +4 -4
  89. package/.next/standalone/.next/server/app/api/system/root-status/route.js.nft.json +1 -1
  90. package/.next/standalone/.next/server/app/api/system/set-root/route.js +6 -6
  91. package/.next/standalone/.next/server/app/api/system/set-root/route.js.nft.json +1 -1
  92. package/.next/standalone/.next/server/app/api/system/users/route.js +5 -5
  93. package/.next/standalone/.next/server/app/api/system/users/route.js.nft.json +1 -1
  94. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/branch/route.js +4 -4
  95. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/branch/route.js.nft.json +1 -1
  96. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/open/route.js +6 -6
  97. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/open/route.js.nft.json +1 -1
  98. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/refresh/route.js +4 -4
  99. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/refresh/route.js.nft.json +1 -1
  100. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/route.js +6 -6
  101. package/.next/standalone/.next/server/app/api/system/workspaces/[id]/route.js.nft.json +1 -1
  102. package/.next/standalone/.next/server/app/api/system/workspaces/route.js +4 -4
  103. package/.next/standalone/.next/server/app/api/system/workspaces/route.js.nft.json +1 -1
  104. package/.next/standalone/.next/server/app/api/upload/[...path]/route.js +6 -6
  105. package/.next/standalone/.next/server/app/api/upload/[...path]/route.js.nft.json +1 -1
  106. package/.next/standalone/.next/server/app/api/wiki/app/route.js +8 -8
  107. package/.next/standalone/.next/server/app/api/wiki/app/route.js.nft.json +1 -1
  108. package/.next/standalone/.next/server/app/api/wiki/backlinks/route.js +8 -8
  109. package/.next/standalone/.next/server/app/api/wiki/backlinks/route.js.nft.json +1 -1
  110. package/.next/standalone/.next/server/app/api/wiki/content/route.js +6 -6
  111. package/.next/standalone/.next/server/app/api/wiki/content/route.js.nft.json +1 -1
  112. package/.next/standalone/.next/server/app/api/wiki/download/route.js +8 -8
  113. package/.next/standalone/.next/server/app/api/wiki/download/route.js.nft.json +1 -1
  114. package/.next/standalone/.next/server/app/api/wiki/file/route.js +6 -6
  115. package/.next/standalone/.next/server/app/api/wiki/file/route.js.nft.json +1 -1
  116. package/.next/standalone/.next/server/app/api/wiki/folder/route.js +7 -7
  117. package/.next/standalone/.next/server/app/api/wiki/folder/route.js.nft.json +1 -1
  118. package/.next/standalone/.next/server/app/api/wiki/git-branches/route.js +6 -6
  119. package/.next/standalone/.next/server/app/api/wiki/git-branches/route.js.nft.json +1 -1
  120. package/.next/standalone/.next/server/app/api/wiki/git-checkout/route.js +4 -4
  121. package/.next/standalone/.next/server/app/api/wiki/git-checkout/route.js.nft.json +1 -1
  122. package/.next/standalone/.next/server/app/api/wiki/git-diff/route.js +6 -6
  123. package/.next/standalone/.next/server/app/api/wiki/git-diff/route.js.nft.json +1 -1
  124. package/.next/standalone/.next/server/app/api/wiki/git-file-info/route.js +6 -6
  125. package/.next/standalone/.next/server/app/api/wiki/git-file-info/route.js.nft.json +1 -1
  126. package/.next/standalone/.next/server/app/api/wiki/git-history/route.js +6 -6
  127. package/.next/standalone/.next/server/app/api/wiki/git-history/route.js.nft.json +1 -1
  128. package/.next/standalone/.next/server/app/api/wiki/git-pull/route.js +6 -6
  129. package/.next/standalone/.next/server/app/api/wiki/git-pull/route.js.nft.json +1 -1
  130. package/.next/standalone/.next/server/app/api/wiki/move/route.js +5 -5
  131. package/.next/standalone/.next/server/app/api/wiki/move/route.js.nft.json +1 -1
  132. package/.next/standalone/.next/server/app/api/wiki/new-file/route.js +5 -5
  133. package/.next/standalone/.next/server/app/api/wiki/new-file/route.js.nft.json +1 -1
  134. package/.next/standalone/.next/server/app/api/wiki/outlinks/route.js +8 -8
  135. package/.next/standalone/.next/server/app/api/wiki/outlinks/route.js.nft.json +1 -1
  136. package/.next/standalone/.next/server/app/api/wiki/page/route.js +5 -5
  137. package/.next/standalone/.next/server/app/api/wiki/page/route.js.nft.json +1 -1
  138. package/.next/standalone/.next/server/app/api/wiki/presence/route.js +6 -6
  139. package/.next/standalone/.next/server/app/api/wiki/presence/route.js.nft.json +1 -1
  140. package/.next/standalone/.next/server/app/api/wiki/route.js +6 -6
  141. package/.next/standalone/.next/server/app/api/wiki/route.js.nft.json +1 -1
  142. package/.next/standalone/.next/server/app/api/wiki/search/route.js +8 -8
  143. package/.next/standalone/.next/server/app/api/wiki/search/route.js.nft.json +1 -1
  144. package/.next/standalone/.next/server/app/api/wiki/slugs/route.js +6 -6
  145. package/.next/standalone/.next/server/app/api/wiki/slugs/route.js.nft.json +1 -1
  146. package/.next/standalone/.next/server/app/api/wiki/upload/route.js +5 -5
  147. package/.next/standalone/.next/server/app/api/wiki/upload/route.js.nft.json +1 -1
  148. package/.next/standalone/.next/server/app/api/wiki/watch/route.js +5 -5
  149. package/.next/standalone/.next/server/app/api/wiki/watch/route.js.nft.json +1 -1
  150. package/.next/standalone/.next/server/app/index.html +1 -1
  151. package/.next/standalone/.next/server/app/index.rsc +3 -3
  152. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  153. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  154. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  155. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
  156. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  157. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  158. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  159. package/.next/standalone/.next/server/app/s/[token]/page.js.nft.json +1 -1
  160. package/.next/standalone/.next/server/app/s/[token]/page_client-reference-manifest.js +1 -1
  161. package/.next/standalone/.next/server/app/signin/page_client-reference-manifest.js +1 -1
  162. package/.next/standalone/.next/server/app-paths-manifest.json +1 -0
  163. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0zv_j05._.js → [root-of-the-server]__0-mos44._.js} +2 -2
  164. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0nmx3k2._.js → [root-of-the-server]__00xq4wx._.js} +2 -2
  165. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0ovhccp._.js → [root-of-the-server]__038~~rd._.js} +2 -2
  166. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0~rntxj._.js → [root-of-the-server]__04jklyx._.js} +2 -2
  167. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0nzlmkb._.js → [root-of-the-server]__04z5.s-._.js} +2 -2
  168. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0a6j6r4._.js → [root-of-the-server]__04~bqmd._.js} +2 -2
  169. package/.next/standalone/.next/server/chunks/[root-of-the-server]__05jd.5~._.js +3 -0
  170. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0ajw6de._.js → [root-of-the-server]__05~-fkm._.js} +2 -2
  171. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0esmskc._.js → [root-of-the-server]__06s802c._.js} +2 -2
  172. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0na11h0._.js → [root-of-the-server]__08-0m4o._.js} +4 -4
  173. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0s_8poz._.js → [root-of-the-server]__08mb7mf._.js} +2 -2
  174. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__000spch._.js → [root-of-the-server]__096dpr1._.js} +2 -2
  175. package/.next/standalone/.next/server/chunks/[root-of-the-server]__09i-r6q._.js +12 -0
  176. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0n9zdf0._.js → [root-of-the-server]__0a_c5s5._.js} +2 -2
  177. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0as-u6z._.js → [root-of-the-server]__0asy5fk._.js} +2 -2
  178. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0l-wu5u._.js → [root-of-the-server]__0bikav1._.js} +2 -2
  179. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0fshk._._.js → [root-of-the-server]__0cynf.m._.js} +2 -2
  180. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0yat~ul._.js → [root-of-the-server]__0dyghs~._.js} +2 -2
  181. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0w~__xz._.js → [root-of-the-server]__0ej__9l._.js} +2 -2
  182. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0wfv_by._.js → [root-of-the-server]__0f-y9ak._.js} +2 -2
  183. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0gurz9a._.js +26 -12
  184. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0oruwos._.js → [root-of-the-server]__0j456kt._.js} +2 -2
  185. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0zbkgnr._.js → [root-of-the-server]__0kgev~0._.js} +2 -2
  186. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0km~c.f._.js +3 -0
  187. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0.-oq-7._.js → [root-of-the-server]__0le9en3._.js} +2 -2
  188. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0lvz22t._.js +1 -1
  189. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0uibxf_._.js → [root-of-the-server]__0lwoa8u._.js} +2 -2
  190. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0-jzw2_._.js → [root-of-the-server]__0ocu5kq._.js} +2 -2
  191. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0fu72o7._.js → [root-of-the-server]__0omu2ls._.js} +2 -2
  192. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__09t4v4r._.js → [root-of-the-server]__0ou1yo3._.js} +2 -2
  193. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0u81k~2._.js → [root-of-the-server]__0qe_pj_._.js} +2 -2
  194. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0wlj-yw._.js → [root-of-the-server]__0snmvie._.js} +2 -2
  195. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__06booxp._.js → [root-of-the-server]__0sqf51n._.js} +2 -2
  196. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0vxex1w._.js → [root-of-the-server]__0syhzuy._.js} +2 -2
  197. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__024967n._.js → [root-of-the-server]__0xblgqt._.js} +2 -2
  198. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0s38pid._.js → [root-of-the-server]__0xzvkcg._.js} +2 -2
  199. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0z3wg9x._.js → [root-of-the-server]__0y6a-84._.js} +4 -4
  200. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0ywviax._.js +20 -0
  201. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__071_pmz._.js → [root-of-the-server]__0~1k.~a._.js} +2 -2
  202. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0bvtbax._.js → [root-of-the-server]__0~dajlm._.js} +2 -2
  203. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0sggstu._.js → [root-of-the-server]__0~oj7j3._.js} +2 -2
  204. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0e_9pc5._.js → [root-of-the-server]__0~yn~7e._.js} +2 -2
  205. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0c-ee48._.js → [root-of-the-server]__10l3owp._.js} +2 -2
  206. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0o0v6hf._.js → [root-of-the-server]__10ljgl.._.js} +2 -2
  207. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0_1f2cw._.js → [root-of-the-server]__10~3r6l._.js} +2 -2
  208. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__01qcera._.js → [root-of-the-server]__11akjkm._.js} +2 -2
  209. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0aoqat-._.js → [root-of-the-server]__11fcf05._.js} +2 -2
  210. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__02.uul~._.js → [root-of-the-server]__13f0ukk._.js} +2 -2
  211. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0_0bqpg._.js → [root-of-the-server]__13hpe9q._.js} +2 -2
  212. package/.next/standalone/.next/server/chunks/_next-internal_server_app_api_share_[token]_asset_route_actions_0mxwvof.js +3 -0
  213. package/.next/standalone/.next/server/chunks/_next-internal_server_app_api_system_workspaces_[id]_open_route_actions_1087xu7.js +1 -1
  214. package/.next/standalone/.next/server/chunks/src_lib_auth_server_ts_00f4e0h._.js +452 -0
  215. package/.next/standalone/.next/server/chunks/ssr/{0~w0_katex_dist_katex_mjs_0awdhzw._.js → 0~w0_katex_dist_katex_mjs_1115d6v._.js} +1 -1
  216. package/.next/standalone/.next/server/chunks/ssr/12y~_mermaid_dist_chunks_mermaid_core_chunk-5ZQYHXKU_mjs_0z1.978._.js +1 -1
  217. package/.next/standalone/.next/server/chunks/ssr/12y~_mermaid_dist_chunks_mermaid_core_chunk-KSCS5N6A_mjs_0v4oeem._.js +1 -1
  218. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0.j71x7._.js +3 -0
  219. package/.next/standalone/.next/server/chunks/ssr/{_0sxeqi8._.js → _03xt0rl._.js} +5 -5
  220. package/.next/standalone/.next/server/chunks/ssr/{_0kcfv3r._.js → _0i3r51-._.js} +5 -5
  221. package/.next/standalone/.next/server/chunks/ssr/_0v4uz-4._.js +3 -3
  222. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0_zq~v6._.js → node_modules__pnpm_0-gfnl9._.js} +1 -1
  223. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0cy5ftq._.js → node_modules__pnpm_0.41jpn._.js} +2 -2
  224. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0~5s0h-._.js → node_modules__pnpm_00mt6nh._.js} +1 -1
  225. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_01uc1hl._.js → node_modules__pnpm_06za8g0._.js} +1 -1
  226. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0t16czj._.js → node_modules__pnpm_0752tb8._.js} +1 -1
  227. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0jywdw0._.js → node_modules__pnpm_08.egvu._.js} +1 -1
  228. package/.next/standalone/.next/server/chunks/ssr/node_modules__pnpm_0a4su30._.js +1 -1
  229. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0w~3li6._.js → node_modules__pnpm_0a5jwqo._.js} +1 -1
  230. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0~xns8v._.js → node_modules__pnpm_0c-_96g._.js} +1 -1
  231. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0w3.bto._.js → node_modules__pnpm_0cxeac7._.js} +1 -1
  232. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_11-1cme._.js → node_modules__pnpm_0do9l33._.js} +1 -1
  233. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0h8t6~c._.js → node_modules__pnpm_0go8~j7._.js} +1 -1
  234. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_02vvjkq._.js → node_modules__pnpm_0h~ckqb._.js} +1 -1
  235. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0~l___j._.js → node_modules__pnpm_0knclqg._.js} +2 -2
  236. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_04hymjt._.js → node_modules__pnpm_0lne~4i._.js} +2 -2
  237. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0c5xt34._.js → node_modules__pnpm_0mrjai_._.js} +1 -1
  238. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0abi.df._.js → node_modules__pnpm_0mx7wsr._.js} +1 -1
  239. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0u3p3__._.js → node_modules__pnpm_0oi2w2s._.js} +1 -1
  240. package/.next/standalone/.next/server/chunks/ssr/node_modules__pnpm_0o~d81.._.js +1 -1
  241. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_131u09o._.js → node_modules__pnpm_0qiaujf._.js} +1 -1
  242. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_10y-1uw._.js → node_modules__pnpm_0r529m.._.js} +1 -1
  243. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0zt6ord._.js → node_modules__pnpm_0s8-kbr._.js} +2 -2
  244. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0j2ck16._.js → node_modules__pnpm_0uvds62._.js} +1 -1
  245. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0bwtedy._.js → node_modules__pnpm_0w7.zt6._.js} +1 -1
  246. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_13kfm1k._.js → node_modules__pnpm_0z5ch94._.js} +2 -2
  247. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0of-lo7._.js → node_modules__pnpm_0zya776._.js} +1 -1
  248. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_05py9u6._.js → node_modules__pnpm_10qgn1p._.js} +1 -1
  249. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0ve~5~d._.js → node_modules__pnpm_113-u.n._.js} +2 -2
  250. package/.next/standalone/.next/server/chunks/ssr/{node_modules__pnpm_0g7aqxf._.js → node_modules__pnpm_12v.ysz._.js} +2 -2
  251. package/.next/standalone/.next/server/chunks/ssr/src_app_s_[token]_page_tsx_0_fzrmd._.js +3 -0
  252. package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
  253. package/.next/standalone/.next/server/middleware-manifest.json +5 -5
  254. package/.next/standalone/.next/server/pages/404.html +1 -1
  255. package/.next/standalone/.next/server/pages/500.html +1 -1
  256. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  257. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  258. package/.next/standalone/.next/static/chunks/{0alhqgtsl8w~~.js → 0-6si2~0z2ds~.js} +3 -3
  259. package/.next/standalone/.next/static/chunks/0.a7ig7sonb84.js +17 -0
  260. package/.next/standalone/.next/static/chunks/{0on-0-cxvzy-7.js → 0gzs0suw~dy53.js} +3 -3
  261. package/.next/standalone/.next/static/chunks/0pw6gfeuvlhiu.css +5 -0
  262. package/.next/standalone/.next/static/chunks/11_s27j_.g~44.js +1 -0
  263. package/.next/standalone/node_modules/.pnpm/better-sqlite3@12.10.0/node_modules/better-sqlite3/build/Release/better_sqlite3.node +0 -0
  264. package/.next/standalone/package.json +1 -1
  265. package/.next/standalone/server.js +1 -1
  266. package/package.json +1 -1
  267. package/.next/standalone/.next/server/chunks/[root-of-the-server]__08n~vj1._.js +0 -12
  268. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0m6r9ip._.js +0 -3
  269. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0sfrx~.._.js +0 -3
  270. package/.next/standalone/.next/server/chunks/_0dr1r1g._.js +0 -452
  271. package/.next/standalone/.next/server/chunks/_101exke._.js +0 -452
  272. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0w2ebbx._.js +0 -3
  273. package/.next/standalone/.next/static/chunks/0.g_p6_b0v2sp.js +0 -1
  274. package/.next/standalone/.next/static/chunks/0ncw5hhg~98~p.css +0 -5
  275. package/.next/standalone/.next/static/chunks/11c7-ic7.2nku.js +0 -17
  276. /package/.next/standalone/.next/static/{9uKcomCuAmuvmqIvLKvxj → Ww8jT7MN_-EXqCtedCETt}/_buildManifest.js +0 -0
  277. /package/.next/standalone/.next/static/{9uKcomCuAmuvmqIvLKvxj → Ww8jT7MN_-EXqCtedCETt}/_clientMiddlewareManifest.js +0 -0
  278. /package/.next/standalone/.next/static/{9uKcomCuAmuvmqIvLKvxj → Ww8jT7MN_-EXqCtedCETt}/_ssgManifest.js +0 -0
@@ -0,0 +1,452 @@
1
+ module.exports=[254226,473845,860780,e=>{"use strict";let t,r,n,i,a,o,s,c,l,d,u,p,f;var h,m,y,g,w=e.i(563811),b=e.i(560912);async function A(t,r){let n;if(t.database)n="function"==typeof t.database?t.database(t):await r(t);else{let r=Object.keys((0,w.getAuthTables)(t)).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await e.A(168315);n=i(r)(t)}return n.transaction||(b.logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),n.transaction=async e=>e(n)),n}var E=e.i(451894);async function v(t){return A(t,async t=>{let{createKyselyAdapter:r}=await e.A(317691),{kysely:n,databaseType:i,transaction:a}=await r(t);if(!n)throw new E.BetterAuthError("Failed to initialize database adapter");let{kyselyAdapter:o}=await e.A(317691);return o(n,{type:i||"sqlite",debugLogs:!!t.database&&"debugLogs"in t.database&&t.database.debugLogs,transaction:a})(t)})}var k=e.i(177730);function _(e){return"-"===e||"^"===e||"$"===e||"+"===e||"."===e||"("===e||")"===e||"|"===e||"["===e||"]"===e||"{"===e||"}"===e||"*"===e||"?"===e||"\\"===e?`\\${e}`:e}function S(e,t){if("string"!=typeof t)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function x(e,t){if("string"!=typeof e&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if(("string"==typeof t||"boolean"==typeof t)&&(t={separator:t}),2==arguments.length&&!(void 0===t||"object"==typeof t&&null!==t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if("\\"===(t=t||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=function e(t,r=!0){if(Array.isArray(t))return`(?:${t.map(t=>`^${e(t,r)}$`).join("|")})`;let n="",i="",a=".";!0===r?(n="/",i="[/\\\\]",a="[^/\\\\]"):r&&((i=function(e){let t="";for(let r=0;r<e.length;r++)t+=_(e[r]);return t}(n=r)).length>1?(i=`(?:${i})`,a=`((?!${i}).)`):a=`[^${i}]`);let o=r?`${i}+?`:"",s=r?`${i}*?`:"",c=r?t.split(n):[t],l="";for(let e=0;e<c.length;e++){let t=c[e],n=c[e+1],i="";if(t||!(e>0)){if(r&&(i=e===c.length-1?s:"**"!==n?o:""),r&&"**"===t){i&&(l+=0===e?"":i,l+=`(?:${a}*?${i})*?`);continue}for(let e=0;e<t.length;e++){let r=t[e];"\\"===r?e<t.length-1&&(l+=_(t[e+1]),e++):"?"===r?l+=a:"*"===r?l+=`${a}*?`:l+=_(r)}l+=i}}return l}(e,t.separator),n=RegExp(`^${r}$`,t.flags),i=S.bind(null,n);return i.options=t,i.pattern=e,i.regexp=n,i}var T=e.i(426232);function R(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;return t===e.length?e:e.slice(0,t)}function I(e,t="/api/auth"){try{let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new E.BetterAuthError(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){if(t instanceof E.BetterAuthError)throw t;throw new E.BetterAuthError(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}if(function(e){try{return"/"!==(R(new URL(e).pathname)||"/")}catch{throw new E.BetterAuthError(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}(e))return e;let r=R(e);return t&&"/"!==t?(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`):r}function U(e,t){return!!e&&""!==e.trim()&&("proto"===t?"http"===e||"https"===e:"host"===t&&![/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))&&(/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e)))}function O(e,t,r,n,i){if(e)return I(e,t);if(!1!==n){let e=T.env.BETTER_AUTH_URL||T.env.NEXT_PUBLIC_BETTER_AUTH_URL||T.env.PUBLIC_BETTER_AUTH_URL||T.env.NUXT_PUBLIC_BETTER_AUTH_URL||T.env.NUXT_PUBLIC_AUTH_URL||("/"!==T.env.BASE_URL?T.env.BASE_URL:void 0);if(e)return I(e,t)}let a=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(a&&o&&i&&U(o,"proto")&&U(a,"host"))try{return I(`${o}://${a}`,t)}catch(e){}if(r){let e=P(r.url);if(!e)throw new E.BetterAuthError("Could not get origin from request. Please provide a valid base URL.");return I(e,t)}}function P(e){try{let t=new URL(e);return"null"===t.origin?null:t.origin}catch{return null}}function C(e){return"object"==typeof e&&null!==e&&"allowedHosts"in e&&Array.isArray(e.allowedHosts)}function D(e){return e instanceof Request||"object"==typeof e&&null!==e&&"[object Request]"===Object.prototype.toString.call(e)&&"string"==typeof e.url&&"object"==typeof e.headers&&null!==e.headers&&"function"==typeof e.headers.get}function L(e,t){let r=D(e)?e.headers:e;if(t){let e=r.get("x-forwarded-host");if(e&&U(e,"host"))return e}let n=r.get("host");if(n&&U(n,"host"))return n;if(D(e))try{return new URL(e.url).host}catch{}return null}let z=(e,t,r)=>{if(e.startsWith("/"))return!!r?.allowRelativePaths&&e.startsWith("/")&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(e);if(t.includes("*")||t.includes("?")){if(t.includes("://"))return x(t)(P(e)||e);let r=function(e){try{return new URL(e).host}catch{return null}}(e);return!!r&&x(t)(r)}let n=function(e){try{return new URL(e).protocol}catch{return null}}(e);return"http:"!==n&&"https:"!==n&&n?e.startsWith(t):t===P(e)};function $(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}var N=e.i(666680);function j(e,t){return new Promise((r,n)=>{(0,N.scrypt)(e.normalize("NFKC"),t,64,{N:16384,r:16,p:1,maxmem:0x4000000},(e,t)=>{e?n(e):r(t)})})}async function H(e){let t=(0,N.randomBytes)(16).toString("hex"),r=await j(e,t);return`${t}:${r.toString("hex")}`}async function B(e,t){let[r,n]=e.split(":");if(!r||!n)throw Error("Invalid password hash");return(await j(t,r)).toString("hex")===n}let V=async({hash:e,password:t})=>B(e,t);function M(e,t=""){if("number"!=typeof e){let r=t&&`"${t}" `;throw TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw RangeError(`${r}expected integer >= 0, got ${e}`)}}function K(e,t,r=""){let n=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT,i=e?.length,a=void 0!==t;if(!n||a&&i!==t){let o=(r&&`"${r}" `)+"expected Uint8Array"+(a?` of length ${t}`:"")+", got "+(n?`length=${i}`:`type=${typeof e}`);if(!n)throw TypeError(o);throw RangeError(o)}return e}function W(e){if("function"!=typeof e||"function"!=typeof e.create)throw TypeError("Hash must wrapped by utils.createHasher");if(M(e.outputLen),M(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function q(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function F(e,t){K(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function J(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Z(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function G(e,t){return e<<32-t|e>>>t}class Q{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(W(e),K(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let e=0;e<n.length;e++)n[e]^=54;this.iHash.update(n),this.oHash=e.create();for(let e=0;e<n.length;e++)n[e]^=106;this.oHash.update(n),J(n)}update(e){return q(this),this.iHash.update(e),this}digestInto(e){q(this),F(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return e.finished=n,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let Y=((o=(e,t,r)=>new Q(e,t).update(r).digest()).create=(e,t)=>new Q(e,t),o),X=Uint8Array.of(0),ee=Uint8Array.of();class et{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Z(this.buffer)}update(e){q(this),K(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(n-this.pos,i-a);if(o===n){let t=Z(e);for(;n<=i-a;a+=n)this.process(t,a);continue}r.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){q(this),F(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;t[a++]=128,J(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let e=a;e<n;e++)t[e]=0;r.setBigUint64(n-8,BigInt(8*this.length),i),this.process(r,0);let o=Z(e),s=this.outputLen;if(s%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=s/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){(e||=new this.constructor).set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}let er=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),en=Uint32Array.from([0xc1059ed8,0x367cd507,0x3070dd17,0xf70e5939,0xffc00b31,0x68581511,0x64f98fa7,0xbefa4fa4]),ei=Uint32Array.from([0xcbbb9d5d,0xc1059ed8,0x629a292a,0x367cd507,0x9159015a,0x3070dd17,0x152fecd8,0xf70e5939,0x67332667,0xffc00b31,0x8eb44a87,0x68581511,0xdb0c2e0d,0x64f98fa7,0x47b5481d,0xbefa4fa4]),ea=Uint32Array.from([0x6a09e667,0xf3bcc908,0xbb67ae85,0x84caa73b,0x3c6ef372,0xfe94f82b,0xa54ff53a,0x5f1d36f1,0x510e527f,0xade682d1,0x9b05688c,0x2b3e6c1f,0x1f83d9ab,0xfb41bd6b,0x5be0cd19,0x137e2179]),eo=BigInt(0x100000000-1),es=BigInt(32),ec=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),el=new Uint32Array(64);class ed extends et{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:a,G:o,H:s}=this;return[e,t,r,n,i,a,o,s]}set(e,t,r,n,i,a,o,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|a,this.G=0|o,this.H=0|s}process(e,t){for(let r=0;r<16;r++,t+=4)el[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=el[e-15],r=el[e-2],n=G(t,7)^G(t,18)^t>>>3,i=G(r,17)^G(r,19)^r>>>10;el[e]=i+el[e-7]+n+el[e-16]|0}let{A:r,B:n,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){var d,u,p,f;let t=l+(G(o,6)^G(o,11)^G(o,25))+((d=o)&s^~d&c)+ec[e]+el[e]|0,h=(G(r,2)^G(r,13)^G(r,22))+((u=r)&(p=n)^u&(f=i)^p&f)|0;l=c,c=s,s=o,o=a+t|0,a=i,i=n,n=r,r=t+h|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,i,a,o,s,c,l)}roundClean(){J(el)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),J(this.buffer)}}class eu extends ed{A=0|er[0];B=0|er[1];C=0|er[2];D=0|er[3];E=0|er[4];F=0|er[5];G=0|er[6];H=0|er[7];constructor(){super(32)}}let ep=function(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let a=0;a<r;a++){let{h:r,l:o}=function(e,t=!1){return t?{h:Number(e&eo),l:Number(e>>es&eo)}:{h:0|Number(e>>es&eo),l:0|Number(e&eo)}}(e[a],t);[n[a],i[a]]=[r,o]}return[n,i]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),ef=ep[0],eh=ep[1],em=new Uint32Array(80),ey=new Uint32Array(80),eg=function(e,t={}){let r=(t,r)=>e(r).update(t).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=t=>e(t),Object.assign(r,t),Object.freeze(r)}(()=>new eu,{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,1])}),ew=new TextEncoder,eb=new TextDecoder;function eA(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function eE(e,t,r){if(t<0||t>=0x100000000)throw RangeError(`value must be >= 0 and <= ${0x100000000-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,255&t],r)}function ev(e){let t=Math.floor(e/0x100000000),r=new Uint8Array(8);return eE(r,t,0),eE(r,e%0x100000000,4),r}function ek(e){let t=new Uint8Array(4);return eE(t,e),t}function e_(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function eS(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:eb.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=eb.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{var r=t;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);let e=atob(r),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function ex(e){let t=e;return("string"==typeof t&&(t=ew.encode(t)),Uint8Array.prototype.toBase64)?t.toBase64({alphabet:"base64url",omitPadding:!0}):(function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))})(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}e.s(["decode",0,eS,"encode",0,ex],797379);let eT=Symbol();function eR(e,t){if(e)throw TypeError(`${t} can only be called once`)}function eI(e,t,r){try{return eS(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}async function eU(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}let eO=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function eP(e,t){if(parseInt(e.hash.name.slice(4),10)!==t)throw eO(`SHA-${t}`,"algorithm.hash")}function eC(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function eD(e,t,r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if("AES-GCM"!==e.algorithm.name)throw eO("AES-GCM");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw eO(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if("AES-KW"!==e.algorithm.name)throw eO("AES-KW");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw eO(r,"algorithm.length");break}case"ECDH":switch(e.algorithm.name){case"ECDH":case"X25519":break;default:throw eO("ECDH or X25519")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if("PBKDF2"!==e.algorithm.name)throw eO("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if("RSA-OAEP"!==e.algorithm.name)throw eO("RSA-OAEP");eP(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError("CryptoKey does not support this operation")}eC(e,r)}function eL(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let ez=(e,...t)=>eL("Key must be ",e,...t),e$=(e,t,...r)=>eL(`Key for the ${e} algorithm must be `,t,...r);class eN extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class ej extends eN{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class eH extends eN{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class eB extends eN{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class eV extends eN{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class eM extends eN{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class eK extends eN{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class eW extends eN{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class eq extends eN{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class eF extends eN{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class eJ extends eN{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class eZ extends eN{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t)}}class eG extends eN{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class eQ extends eN{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}}class eY extends eN{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}function eX(e){if(!e0(e))throw Error("CryptoKey instance expected")}let e0=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},e1=e=>e?.[Symbol.toStringTag]==="KeyObject",e2=e=>e0(e)||e1(e);function e6(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new eV(`Unsupported JWE Algorithm: ${e}`)}}let e5=e=>crypto.getRandomValues(new Uint8Array(e6(e)>>3));function e8(e,t){let r=e.byteLength<<3;if(r!==t)throw new eK(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function e4(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new eV(`Unsupported JWE Algorithm: ${e}`)}}function e3(e,t){if(t.length<<3!==e4(e))throw new eK("Invalid Initialization Vector length")}async function e9(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(ez(t,"Uint8Array"));let n=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),macKey:await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]),keySize:n}}async function e7(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function te(e,t,r,n,i){let{encKey:a,macKey:o,keySize:s}=await e9(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),l=eA(i,n,c,ev(i.length<<3));return{ciphertext:c,tag:await e7(o,l,s),iv:n}}async function tt(e,t){if(!(e instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,e)),a=new Uint8Array(await crypto.subtle.sign(r,n,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return 0===o}async function tr(e,t,r,n,i,a){let o,s,{encKey:c,macKey:l,keySize:d}=await e9(e,t,"decrypt"),u=eA(a,n,r,ev(a.length<<3)),p=await e7(l,u,d);try{o=await tt(i,p)}catch{}if(!o)throw new eM;try{s=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!s)throw new eM;return s}async function tn(e,t,r,n,i){let a;r instanceof Uint8Array?a=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(eD(r,e,"encrypt"),a=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:n}}async function ti(e,t,r,n,i,a){let o;t instanceof Uint8Array?o=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(eD(t,e,"decrypt"),o=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},o,eA(r,i)))}catch{throw new eM}}let ta="Unsupported JWE Content Encryption Algorithm";async function to(e,t,r,n,i){if(!e0(r)&&!(r instanceof Uint8Array))throw TypeError(ez(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n)e3(e,n);else n=crypto.getRandomValues(new Uint8Array(e4(e)>>3));switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&e8(r,parseInt(e.slice(-3),10)),te(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&e8(r,parseInt(e.slice(1,4),10)),tn(e,t,r,n,i);default:throw new eV(ta)}}async function ts(e,t,r,n,i,a){if(!e0(t)&&!(t instanceof Uint8Array))throw TypeError(ez(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new eK("JWE Initialization Vector missing");if(!i)throw new eK("JWE Authentication Tag missing");switch(e3(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&e8(t,parseInt(e.slice(-3),10)),tr(e,t,r,n,i,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&e8(t,parseInt(e.slice(1,4),10)),ti(e,t,r,n,i,a);default:throw new eV(ta)}}function tc(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function tl(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):(eD(e,t,r),e)}async function td(e,t,r){let n=await tl(t,e,"wrapKey");tc(n,e);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function tu(e,t,r){let n=await tl(t,e,"unwrapKey");tc(n,e);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}function tp(e){return eA(ek(e.length),e)}async function tf(e,t,r){let n=t>>3,i=Math.ceil(n/32),a=new Uint8Array(32*i);for(let t=1;t<=i;t++){let n=new Uint8Array(4+e.length+r.length);n.set(ek(t),0),n.set(e,4),n.set(r,4+e.length);let i=await eU("sha256",n);a.set(i,(t-1)*32)}return a.slice(0,n)}async function th(e,t,r,n,i=new Uint8Array,a=new Uint8Array){var o;eD(e,"ECDH"),eD(t,"ECDH","deriveBits");let s=eA(tp(e_(r)),tp(i),tp(a),ek(n),new Uint8Array);return tf(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,"X25519"===(o=e).algorithm.name?256:Math.ceil(parseInt(o.algorithm.namedCurve.slice(-3),10)/8)<<3)),n,s)}function tm(e){switch(e.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return"X25519"===e.algorithm.name}}async function ty(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new eK("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||1!==Math.sign(r))throw new eK("PBES2 Count Input must be a positive integer");let i=eA(e_(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},s=await (n instanceof Uint8Array?crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveBits"]):(eD(n,t,"deriveBits"),n));return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function tg(e,t,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await ty(i,e,n,t);return{encryptedKey:await td(e.slice(-6),a,r),p2c:n,p2s:ex(i)}}async function tw(e,t,r,n,i){let a=await ty(i,e,n,t);return tu(e.slice(-6),a,r)}function tb(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function tA(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new eV(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function tE(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(ez(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}switch(e){case"HS256":case"HS384":case"HS512":if("HMAC"!==t.algorithm.name)throw eO("HMAC");eP(t.algorithm,parseInt(e.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==t.algorithm.name)throw eO("RSASSA-PKCS1-v1_5");eP(t.algorithm,parseInt(e.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==t.algorithm.name)throw eO("RSA-PSS");eP(t.algorithm,parseInt(e.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==t.algorithm.name)throw eO("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let n;if(n=t.algorithm,n.name!==e)throw eO(e);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==t.algorithm.name)throw eO("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(e);if(t.algorithm.namedCurve!==r)throw eO(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}return eC(t,r),t}async function tv(e,t,r){let n=await tE(e,t,"sign");return tb(e,n),new Uint8Array(await crypto.subtle.sign(tA(e,n.algorithm),n,r))}async function tk(e,t,r,n){let i=await tE(e,t,"verify");tb(e,i);let a=tA(e,i.algorithm);try{return await crypto.subtle.verify(a,i,r,n)}catch{return!1}}let t_=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new eV(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function tS(e,t,r){return eD(t,e,"encrypt"),tb(e,t),new Uint8Array(await crypto.subtle.encrypt(t_(e),t,r))}async function tx(e,t,r){return eD(t,e,"decrypt"),tb(e,t),new Uint8Array(await crypto.subtle.decrypt(t_(e),t,r))}function tT(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function tR(...e){let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0}let tI=e=>tT(e)&&"string"==typeof e.kty,tU='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function tO(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new eV(tU)}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new eV(tU)}break;case"EC":switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new eV(tU)}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new eV(tU)}break;default:throw new eV('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n={...e};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}let tP="given KeyObject instance cannot be used for this algorithm",tC=async(e,r,n,i=!1)=>{let a=(t||=new WeakMap).get(e);if(a?.[n])return a[n];let o=await tO({...r,alg:n});return i&&Object.freeze(e),a?a[n]=o:t.set(e,{[n]:o}),o};async function tD(e,r){if(e instanceof Uint8Array||e0(e))return e;if(e1(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,r)=>{let n,i=(t||=new WeakMap).get(e);if(i?.[r])return i[r];let a="public"===e.type,o=!!a;if("x25519"===e.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(tP)}n=e.toCryptoKey(e.asymmetricKeyType,o,a?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError(tP);n=e.toCryptoKey(e.asymmetricKeyType,o,[a?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==e.asymmetricKeyType.toUpperCase())throw TypeError(tP);n=e.toCryptoKey(e.asymmetricKeyType,o,[a?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let t;switch(r){case"RSA-OAEP":t="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":t="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":t="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":t="SHA-512";break;default:throw TypeError(tP)}if(r.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:t},o,a?["encrypt"]:["decrypt"]);n=e.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:t},o,[a?"verify":"sign"])}if("ec"===e.asymmetricKeyType){let t=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!t)throw TypeError(tP);let i={ES256:"P-256",ES384:"P-384",ES512:"P-521"};i[r]&&t===i[r]&&(n=e.toCryptoKey({name:"ECDSA",namedCurve:t},o,[a?"verify":"sign"])),r.startsWith("ECDH-ES")&&(n=e.toCryptoKey({name:"ECDH",namedCurve:t},o,a?[]:["deriveBits"]))}if(!n)throw TypeError(tP);return i?i[r]=n:t.set(e,{[r]:n}),n})(e,r)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return tC(e,n,r)}if(tI(e))return e.k?eS(e.k):tC(e,e,r,!0);throw Error("unreachable")}async function tL(e,t,r){let n;if(!tT(e))throw TypeError("JWK must be an object");switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return eS(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new eV('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return tO({...e,alg:t,ext:n});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return tO({...e,ext:n});case"EC":case"OKP":return tO({...e,alg:t,ext:n});default:throw new eV('Unsupported "kty" (Key Type) Parameter value')}}async function tz(e){if(e1(e))if("secret"!==e.type)return e.export({format:"jwk"});else e=e.export();if(e instanceof Uint8Array)return{kty:"oct",k:ex(e)};if(!e0(e))throw TypeError(ez(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...a}=await crypto.subtle.exportKey("jwk",e);return"AKP"===a.kty&&(a.alg=n),a}async function t$(e){return tz(e)}async function tN(e,t,r,n){let i=e.slice(0,7),a=await to(i,r,t,n,new Uint8Array);return{encryptedKey:a.ciphertext,iv:ex(a.iv),tag:ex(a.tag)}}async function tj(e,t,r,n,i){return ts(e.slice(0,7),t,r,n,i,new Uint8Array)}let tH='Invalid or unsupported "alg" (JWE Algorithm) header value';function tB(e){if(void 0===e)throw new eK("JWE Encrypted Key missing")}async function tV(e,t,r,n,i){switch(e){case"dir":if(void 0!==r)throw new eK("Encountered unexpected JWE Encrypted Key");return t;case"ECDH-ES":if(void 0!==r)throw new eK("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let i,a;if(!tT(n.epk))throw new eK('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(eX(t),!tm(t))throw new eV("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await tL(n.epk,e);if(eX(o),void 0!==n.apu){if("string"!=typeof n.apu)throw new eK('JOSE Header "apu" (Agreement PartyUInfo) invalid');i=eI(n.apu,"apu",eK)}if(void 0!==n.apv){if("string"!=typeof n.apv)throw new eK('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=eI(n.apv,"apv",eK)}let s=await th(o,t,"ECDH-ES"===e?n.enc:e,"ECDH-ES"===e?e6(n.enc):parseInt(e.slice(-5,-2),10),i,a);if("ECDH-ES"===e)return s;return tB(r),tu(e.slice(-6),s,r)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return tB(r),eX(t),tx(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let a;if(tB(r),"number"!=typeof n.p2c)throw new eK('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new eK('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof n.p2s)throw new eK('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return a=eI(n.p2s,"p2s",eK),tw(e,t,r,n.p2c,a)}case"A128KW":case"A192KW":case"A256KW":return tB(r),tu(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":if(tB(r),"string"!=typeof n.iv)throw new eK('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof n.tag)throw new eK('JOSE Header "tag" (Authentication Tag) missing or invalid');return tj(e,t,r,eI(n.iv,"iv",eK),eI(n.tag,"tag",eK));default:throw new eV(tH)}}async function tM(e,t,r,n,i={}){let a,o,s;switch(e){case"dir":s=r;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let c;if(eX(r),!tm(r))throw new eV("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:l,apv:d}=i;c=i.epk?await tD(i.epk,e):(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:u,y:p,crv:f,kty:h}=await t$(c),m=await th(r,c,"ECDH-ES"===e?t:e,"ECDH-ES"===e?e6(t):parseInt(e.slice(-5,-2),10),l,d);if(o={epk:{x:u,crv:f,kty:h}},"EC"===h&&(o.epk.y=p),l&&(o.apu=ex(l)),d&&(o.apv=ex(d)),"ECDH-ES"===e){s=m;break}s=n||e5(t);let y=e.slice(-6);a=await td(y,m,s);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s=n||e5(t),eX(r),a=await tS(e,r,s);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||e5(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await tg(e,r,s,c,l));break}case"A128KW":case"A192KW":case"A256KW":s=n||e5(t),a=await td(e,r,s);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||e5(t);let{iv:c}=i;({encryptedKey:a,...o}=await tN(e,r,s,c));break}default:throw new eV(tH)}return{cek:s,encryptedKey:a,parameters:o}}function tK(e,t,r,n,i){let a;if(void 0!==i.crit&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let o of(a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,n.crit)){if(!a.has(o))throw new eV(`Extension Header Parameter "${o}" is not recognized`);if(void 0===i[o])throw new e(`Extension Header Parameter "${o}" is missing`);if(a.get(o)&&void 0===n[o])throw new e(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}let tW=e=>e?.[Symbol.toStringTag],tq=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):n="wrapKey";break;case"decrypt"===r:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&t.key_ops?.includes?.(n)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0};function tF(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(tI(t)){if("oct"===t.kty&&"string"==typeof t.k&&tq(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!e2(t))throw TypeError(e$(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${tW(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,r);break;default:((e,t,r)=>{if(tI(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&tq(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&tq(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!e2(t))throw TypeError(e$(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${tW(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${tW(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${tW(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${tW(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${tW(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,r)}}function tJ(e){if(void 0===globalThis[e])throw new eV(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function tZ(e){tJ("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],i=t.readable.getReader();for(;;){let{value:e,done:t}=await i.read();if(t)break;n.push(e)}return eA(...n)}async function tG(e,t){tJ("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let i=[],a=0,o=r.readable.getReader();for(;;){let{value:e,done:r}=await o.read();if(r)break;if(i.push(e),a+=e.byteLength,t!==1/0&&a>t)throw new eK("Decompressed plaintext exceeded the configured limit")}return eA(...i)}class tQ{#e;#t;#r;#n;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return eR(this.#s,"setKeyManagementParameters"),this.#s=e,this}setProtectedHeader(e){return eR(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return eR(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return eR(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return eR(this.#a,"setContentEncryptionKey"),this.#a=e,this}setInitializationVector(e){return eR(this.#o,"setInitializationVector"),this.#o=e,this}async encrypt(e,t){let r,n,i,a,o,s;if(!this.#t&&!this.#n&&!this.#r)throw new eK("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!tR(this.#t,this.#n,this.#r))throw new eK("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let c={...this.#t,...this.#n,...this.#r};if(tK(eK,new Map,t?.crit,this.#t,c),void 0!==c.zip&&"DEF"!==c.zip)throw new eV('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==c.zip&&!this.#t?.zip)throw new eK('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:l,enc:d}=c;if("string"!=typeof l||!l)throw new eK('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof d||!d)throw new eK('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(this.#a&&("dir"===l||"ECDH-ES"===l))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${l}`);tF("dir"===l?d:l,e,"encrypt");{let i,a=await tD(e,l);({cek:n,encryptedKey:r,parameters:i}=await tM(l,d,a,this.#a,this.#s)),i&&(t&&eT in t?this.#n?this.#n={...this.#n,...i}:this.setUnprotectedHeader(i):this.#t?this.#t={...this.#t,...i}:this.setProtectedHeader(i))}if(this.#t?o=e_(a=ex(JSON.stringify(this.#t))):(a="",o=new Uint8Array),this.#i){let e=e_(s=ex(this.#i));i=eA(o,e_("."),e)}else i=o;let u=this.#e;"DEF"===c.zip&&(u=await tZ(u).catch(e=>{throw new eK("Failed to compress plaintext",{cause:e})}));let{ciphertext:p,tag:f,iv:h}=await to(d,u,n,this.#o,i),m={ciphertext:ex(p)};return h&&(m.iv=ex(h)),f&&(m.tag=ex(f)),r&&(m.encrypted_key=ex(r)),s&&(m.aad=s),this.#t&&(m.protected=a),this.#r&&(m.unprotected=this.#r),this.#n&&(m.header=this.#n),m}}class tY{#c;constructor(e){this.#c=new tQ(e)}setContentEncryptionKey(e){return this.#c.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#c.setInitializationVector(e),this}setProtectedHeader(e){return this.#c.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#c.setKeyManagementParameters(e),this}async encrypt(e,t){let r=await this.#c.encrypt(e,t);return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}}let tX=e=>Math.floor(e.getTime()/1e3),t0=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function t1(e){let t,r=t0.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let n=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*n);break;case"day":case"days":case"d":t=Math.round(86400*n);break;case"week":case"weeks":case"w":t=Math.round(604800*n);break;default:t=Math.round(0x1e187e0*n)}return"-"===r[1]||"ago"===r[4]?-t:t}function t2(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}let t6=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;function t5(e,t,r={}){var n,i;let a,o;try{a=JSON.parse(eb.decode(t))}catch{}if(!tT(a))throw new eq("JWT Claims Set must be a top-level JSON object");let{typ:s}=r;if(s&&("string"!=typeof e.typ||t6(e.typ)!==t6(s)))throw new ej('unexpected "typ" JWT header value',a,"typ","check_failed");let{requiredClaims:c=[],issuer:l,subject:d,audience:u,maxTokenAge:p}=r,f=[...c];for(let e of(void 0!==p&&f.push("iat"),void 0!==u&&f.push("aud"),void 0!==d&&f.push("sub"),void 0!==l&&f.push("iss"),new Set(f.reverse())))if(!(e in a))throw new ej(`missing required "${e}" claim`,a,e,"missing");if(l&&!(Array.isArray(l)?l:[l]).includes(a.iss))throw new ej('unexpected "iss" claim value',a,"iss","check_failed");if(d&&a.sub!==d)throw new ej('unexpected "sub" claim value',a,"sub","check_failed");if(u&&(n=a.aud,i="string"==typeof u?[u]:u,"string"==typeof n?!i.includes(n):!(Array.isArray(n)&&i.some(Set.prototype.has.bind(new Set(n))))))throw new ej('unexpected "aud" claim value',a,"aud","check_failed");switch(typeof r.clockTolerance){case"string":o=t1(r.clockTolerance);break;case"number":o=r.clockTolerance;break;case"undefined":o=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:h}=r,m=tX(h||new Date);if((void 0!==a.iat||p)&&"number"!=typeof a.iat)throw new ej('"iat" claim must be a number',a,"iat","invalid");if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw new ej('"nbf" claim must be a number',a,"nbf","invalid");if(a.nbf>m+o)throw new ej('"nbf" claim timestamp check failed',a,"nbf","check_failed")}if(void 0!==a.exp){if("number"!=typeof a.exp)throw new ej('"exp" claim must be a number',a,"exp","invalid");if(a.exp<=m-o)throw new eH('"exp" claim timestamp check failed',a,"exp","check_failed")}if(p){let e=m-a.iat;if(e-o>("number"==typeof p?p:t1(p)))throw new eH('"iat" claim timestamp check failed (too far in the past)',a,"iat","check_failed");if(e<0-o)throw new ej('"iat" claim timestamp check failed (it should be in the past)',a,"iat","check_failed")}return a}class t8{#l;constructor(e){if(!tT(e))throw TypeError("JWT Claims Set MUST be an object");this.#l=structuredClone(e)}data(){return ew.encode(JSON.stringify(this.#l))}get iss(){return this.#l.iss}set iss(e){this.#l.iss=e}get sub(){return this.#l.sub}set sub(e){this.#l.sub=e}get aud(){return this.#l.aud}set aud(e){this.#l.aud=e}set jti(e){this.#l.jti=e}set nbf(e){"number"==typeof e?this.#l.nbf=t2("setNotBefore",e):e instanceof Date?this.#l.nbf=t2("setNotBefore",tX(e)):this.#l.nbf=tX(new Date)+t1(e)}set exp(e){"number"==typeof e?this.#l.exp=t2("setExpirationTime",e):e instanceof Date?this.#l.exp=t2("setExpirationTime",tX(e)):this.#l.exp=tX(new Date)+t1(e)}set iat(e){void 0===e?this.#l.iat=tX(new Date):e instanceof Date?this.#l.iat=t2("setIssuedAt",tX(e)):"string"==typeof e?this.#l.iat=t2("setIssuedAt",tX(new Date)+t1(e)):this.#l.iat=t2("setIssuedAt",e)}}class t4{#a;#o;#s;#t;#d;#u;#p;#f;constructor(e={}){this.#f=new t8(e)}setIssuer(e){return this.#f.iss=e,this}setSubject(e){return this.#f.sub=e,this}setAudience(e){return this.#f.aud=e,this}setJti(e){return this.#f.jti=e,this}setNotBefore(e){return this.#f.nbf=e,this}setExpirationTime(e){return this.#f.exp=e,this}setIssuedAt(e){return this.#f.iat=e,this}setProtectedHeader(e){return eR(this.#t,"setProtectedHeader"),this.#t=e,this}setKeyManagementParameters(e){return eR(this.#s,"setKeyManagementParameters"),this.#s=e,this}setContentEncryptionKey(e){return eR(this.#a,"setContentEncryptionKey"),this.#a=e,this}setInitializationVector(e){return eR(this.#o,"setInitializationVector"),this.#o=e,this}replicateIssuerAsHeader(){return this.#d=!0,this}replicateSubjectAsHeader(){return this.#u=!0,this}replicateAudienceAsHeader(){return this.#p=!0,this}async encrypt(e,t){let r=new tY(this.#f.data());return this.#t&&(this.#d||this.#u||this.#p)&&(this.#t={...this.#t,iss:this.#d?this.#f.iss:void 0,sub:this.#u?this.#f.sub:void 0,aud:this.#p?this.#f.aud:void 0}),r.setProtectedHeader(this.#t),this.#o&&r.setInitializationVector(this.#o),this.#a&&r.setContentEncryptionKey(this.#a),this.#s&&r.setKeyManagementParameters(this.#s),r.encrypt(e,t)}}class t3{#l;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#l=e}setProtectedHeader(e){return eR(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return eR(this.#n,"setUnprotectedHeader"),this.#n=e,this}async sign(e,t){let r,n,i,a;if(!this.#t&&!this.#n)throw new eW("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!tR(this.#t,this.#n))throw new eW("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this.#t,...this.#n},s=tK(eW,new Map([["b64",!0]]),t?.crit,this.#t,o),c=!0;if(s.has("b64")&&"boolean"!=typeof(c=this.#t.b64))throw new eW('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:l}=o;if("string"!=typeof l||!l)throw new eW('JWS "alg" (Algorithm) Header Parameter missing or invalid');tF(l,e,"sign"),c?n=e_(r=ex(this.#l)):(n=this.#l,r=""),this.#t?a=e_(i=ex(JSON.stringify(this.#t))):(i="",a=new Uint8Array);let d=eA(a,e_("."),n),u=await tD(e,l),p={signature:ex(await tv(l,u,d)),payload:r};return this.#n&&(p.header=this.#n),this.#t&&(p.protected=i),p}}class t9{#c;constructor(e){this.#c=new t3(e)}setProtectedHeader(e){return this.#c.setProtectedHeader(e),this}async sign(e,t){let r=await this.#c.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}class t7{#t;#f;constructor(e={}){this.#f=new t8(e)}setIssuer(e){return this.#f.iss=e,this}setSubject(e){return this.#f.sub=e,this}setAudience(e){return this.#f.aud=e,this}setJti(e){return this.#f.jti=e,this}setNotBefore(e){return this.#f.nbf=e,this}setExpirationTime(e){return this.#f.exp=e,this}setIssuedAt(e){return this.#f.iat=e,this}setProtectedHeader(e){return this.#t=e,this}async sign(e,t){let r=new t9(this.#f.data());if(r.setProtectedHeader(this.#t),Array.isArray(this.#t?.crit)&&this.#t.crit.includes("b64")&&!1===this.#t.b64)throw new eq("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var re=e.i(797379),re=re;let rt=(e,t)=>{if("string"!=typeof e||!e)throw new eF(`${t} missing or invalid`)};async function rr(e,t){let r,n;if(tI(e))r=e;else if(e2(e))r=await t$(e);else throw TypeError(ez(e,"CryptoKey","KeyObject","JSON Web Key"));if("sha256"!==(t??="sha256")&&"sha384"!==t&&"sha512"!==t)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(r.kty){case"AKP":rt(r.alg,'"alg" (Algorithm) Parameter'),rt(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":rt(r.crv,'"crv" (Curve) Parameter'),rt(r.x,'"x" (X Coordinate) Parameter'),rt(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":rt(r.crv,'"crv" (Subtype of Key Pair) Parameter'),rt(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":rt(r.e,'"e" (Exponent) Parameter'),rt(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":rt(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new eV('"kty" (Key Type) Parameter missing or unsupported')}let i=e_(JSON.stringify(n));return ex(await eU(t,i))}function rn(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(eb.decode(eS(t)));if(!tT(e))throw Error();return e}catch{throw TypeError("Invalid Token or Protected Header formatting")}}function ri(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}async function ra(e,t,r){let n,i,a,o,s,c;if(!tT(e))throw new eK("Flattened JWE must be an object");if(void 0===e.protected&&void 0===e.header&&void 0===e.unprotected)throw new eK("JOSE Header missing");if(void 0!==e.iv&&"string"!=typeof e.iv)throw new eK("JWE Initialization Vector incorrect type");if("string"!=typeof e.ciphertext)throw new eK("JWE Ciphertext missing or incorrect type");if(void 0!==e.tag&&"string"!=typeof e.tag)throw new eK("JWE Authentication Tag incorrect type");if(void 0!==e.protected&&"string"!=typeof e.protected)throw new eK("JWE Protected Header incorrect type");if(void 0!==e.encrypted_key&&"string"!=typeof e.encrypted_key)throw new eK("JWE Encrypted Key incorrect type");if(void 0!==e.aad&&"string"!=typeof e.aad)throw new eK("JWE AAD incorrect type");if(void 0!==e.header&&!tT(e.header))throw new eK("JWE Shared Unprotected Header incorrect type");if(void 0!==e.unprotected&&!tT(e.unprotected))throw new eK("JWE Per-Recipient Unprotected Header incorrect type");if(e.protected)try{let t=eS(e.protected);n=JSON.parse(eb.decode(t))}catch{throw new eK("JWE Protected Header is invalid")}if(!tR(n,e.header,e.unprotected))throw new eK("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let l={...n,...e.header,...e.unprotected};if(tK(eK,new Map,r?.crit,n,l),void 0!==l.zip&&"DEF"!==l.zip)throw new eV('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==l.zip&&!n?.zip)throw new eK('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:d,enc:u}=l;if("string"!=typeof d||!d)throw new eK("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof u||!u)throw new eK("missing JWE Encryption Algorithm (enc) in JWE Header");let p=r&&ri("keyManagementAlgorithms",r.keyManagementAlgorithms),f=r&&ri("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(p&&!p.has(d)||!p&&d.startsWith("PBES2"))throw new eB('"alg" (Algorithm) Header Parameter value not allowed');if(f&&!f.has(u))throw new eB('"enc" (Encryption Algorithm) Header Parameter value not allowed');void 0!==e.encrypted_key&&(i=eI(e.encrypted_key,"encrypted_key",eK));let h=!1;"function"==typeof t&&(t=await t(n,e),h=!0),tF("dir"===d?u:d,t,"decrypt");let m=await tD(t,d);try{a=await tV(d,m,i,l,r)}catch(e){if(e instanceof TypeError||e instanceof eK||e instanceof eV)throw e;a=e5(u)}void 0!==e.iv&&(o=eI(e.iv,"iv",eK)),void 0!==e.tag&&(s=eI(e.tag,"tag",eK));let y=void 0!==e.protected?e_(e.protected):new Uint8Array;c=void 0!==e.aad?eA(y,e_("."),e_(e.aad)):y;let g=eI(e.ciphertext,"ciphertext",eK),w=await ts(u,a,g,o,s,c),b={plaintext:w};if("DEF"===l.zip){let e=r?.maxDecompressedLength??25e4;if(0===e)throw new eV('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");b.plaintext=await tG(w,e).catch(e=>{if(e instanceof eK)throw e;throw new eK("Failed to decompress plaintext",{cause:e})})}return(void 0!==e.protected&&(b.protectedHeader=n),void 0!==e.aad&&(b.additionalAuthenticatedData=eI(e.aad,"aad",eK)),void 0!==e.unprotected&&(b.sharedUnprotectedHeader=e.unprotected),void 0!==e.header&&(b.unprotectedHeader=e.header),h)?{...b,key:m}:b}async function ro(e,t,r){if(e instanceof Uint8Array&&(e=eb.decode(e)),"string"!=typeof e)throw new eK("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:a,3:o,4:s,length:c}=e.split(".");if(5!==c)throw new eK("Invalid Compact JWE");let l=await ra({ciphertext:o,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return"function"==typeof t?{...d,key:l.key}:d}async function rs(e,t,r){let n=await ro(e,t,r),i=t5(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(void 0!==a.iss&&a.iss!==i.iss)throw new ej('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(void 0!==a.sub&&a.sub!==i.sub)throw new ej('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(void 0!==a.aud&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new ej('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:a};return"function"==typeof t?{...o,key:n.key}:o}async function rc(e,t,r){if(!tT(e))throw new eW("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new eW('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new eW("JWS Protected Header incorrect type");if(void 0===e.payload)throw new eW("JWS Payload missing");if("string"!=typeof e.signature)throw new eW("JWS Signature missing or incorrect type");if(void 0!==e.header&&!tT(e.header))throw new eW("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let t=eS(e.protected);n=JSON.parse(eb.decode(t))}catch{throw new eW("JWS Protected Header is invalid")}if(!tR(n,e.header))throw new eW("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...e.header},a=tK(eW,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(a.has("b64")&&"boolean"!=typeof(o=n.b64))throw new eW('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=i;if("string"!=typeof s||!s)throw new eW('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&ri("algorithms",r.algorithms);if(c&&!c.has(s))throw new eB('"alg" (Algorithm) Header Parameter value not allowed');if(o){if("string"!=typeof e.payload)throw new eW("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new eW("JWS Payload must be a string or an Uint8Array instance");let l=!1;"function"==typeof t&&(t=await t(n,e),l=!0),tF(s,t,"verify");let d=eA(void 0!==e.protected?e_(e.protected):new Uint8Array,e_("."),"string"==typeof e.payload?o?e_(e.payload):ew.encode(e.payload):e.payload),u=eI(e.signature,"signature",eW),p=await tD(t,s);if(!await tk(s,p,u,d))throw new eY;let f={payload:o?eI(e.payload,"payload",eW):"string"==typeof e.payload?ew.encode(e.payload):e.payload};return(void 0!==e.protected&&(f.protectedHeader=n),void 0!==e.header&&(f.unprotectedHeader=e.header),l)?{...f,key:p}:f}async function rl(e,t,r){if(e instanceof Uint8Array&&(e=eb.decode(e)),"string"!=typeof e)throw new eW("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:a,length:o}=e.split(".");if(3!==o)throw new eW("Invalid Compact JWS");let s=await rc({payload:i,protected:n,signature:a},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}async function rd(e,t,r){let n=await rl(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new eq("JWTs MUST NOT use unencoded payload");let i={payload:t5(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}async function ru(e,t,r=3600){return await new t7(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function rp(e,t){try{return(await rd(e,new TextEncoder().encode(t))).payload}catch{return null}}let rf=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),rh="A256CBC-HS512";function rm(e,t){var r,n,i;return r=new TextEncoder().encode(e),n=new TextEncoder().encode(t),function(e,t,r,n=32){W(e),M(n,"length"),K(t,void 0,"prk");let i=e.outputLen;if(t.length<i)throw Error('"prk" must be at least HashLen octets');if(n>255*i)throw Error("Length must be <= 255*HashLen");let a=Math.ceil(n/i);void 0===r?r=ee:K(r,void 0,"info");let o=new Uint8Array(a*i),s=Y.create(e,t),c=s._cloneInto(),l=new Uint8Array(s.outputLen);for(let e=0;e<a;e++)X[0]=e+1,c.update(0===e?ee:l).update(r).update(X).digestInto(l),o.set(l,i*e),s._cloneInto(c);return s.destroy(),c.destroy(),J(l,X),o.slice(0,n)}(eg,(i=n,W(eg),void 0===i&&(i=new Uint8Array(eg.outputLen)),Y(eg,i,r)),rf,64)}function ry(e){if("string"==typeof e)return[{version:0,value:e}];let t=[];for(let[r,n]of e.keys)t.push({version:r,value:n});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function rg(e,t,r,n=3600){let i=rm(function(e){if("string"==typeof e)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}(t),r),a=await rr({kty:"oct",k:re.encode(i)},"sha256");return await new t4(e).setProtectedHeader({alg:"dir",enc:rh,kid:a}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+n).setJti(crypto.randomUUID()).encrypt(i)}let rw={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[rh,"A256GCM"]};async function rb(e,t,r){if(!e)return null;let n=!1;try{n=void 0!==rn(e).kid}catch{return null}try{let n=ry(t),{payload:i}=await rs(e,async e=>{let t=e.kid;if(void 0!==t){for(let e of n){let n=rm(e.value,r);if(t===await rr({kty:"oct",k:re.encode(n)},"sha256"))return n}throw Error("no matching decryption secret")}return n.length,rm(n[0].value,r)},rw);return i}catch{if(n)return null;let i=ry(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let n=i[t],{payload:a}=await rs(e,rm(n.value,r),rw);return a}catch{continue}return null}}var rA=e.i(163738);function rE(e,t){if(!e||!t)return e;let r=Object.entries(t).filter(([,{returned:e}])=>!1===e).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!r.includes(e)).reduce((e,[t,r])=>({...e,[t]:r}),{})}let rv=new WeakMap;function rk(e,t,r){let n=`${t}:${r}`;rv.has(e)||rv.set(e,new Map);let i=rv.get(e);if(i.has(n))return i.get(n);let a="output"===r?(0,w.getAuthTables)(e)[t]?.fields??{}:{},o="user"===t||"session"===t||"account"===t?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let r of e.plugins||[])r.schema&&r.schema[t]&&(s={...s,...r.schema[t].fields});return i.set(n,s),s}function r_(e,t){return rE(t,rk(e,"user","output"))}function rS(e,t){let r=rk(e,"user","output"),n={};for(let e in r){let i=r[e];!1!==i.returned&&(e in t&&void 0!==t[e]?n[e]=t[e]:void 0!==i.defaultValue?n[e]="function"==typeof i.defaultValue?i.defaultValue():i.defaultValue:i.required||(n[e]=null))}return"id"in t&&(n.id=t.id),n}function rx(e,t){return rE(t,rk(e,"session","output"))}function rT(e,t){let r=t.action||"create",n=t.fields,i=Object.create(null);for(let t in n){if(t in e){if(!1===n[t].input){if(void 0!==n[t].defaultValue&&"update"!==r){i[t]=n[t].defaultValue;continue}if(e[t])throw E.APIError.from("BAD_REQUEST",{...rA.BASE_ERROR_CODES.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(n[t].validator?.input&&void 0!==e[t]){let r=n[t].validator.input["~standard"].validate(e[t]);if(r instanceof Promise)throw E.APIError.from("INTERNAL_SERVER_ERROR",rA.BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in r&&r.issues)throw E.APIError.from("BAD_REQUEST",{...rA.BASE_ERROR_CODES.VALIDATION_ERROR,message:r.issues[0]?.message||"Validation Error"});i[t]=r.value;continue}if(n[t].transform?.input&&void 0!==e[t]){i[t]=n[t].transform?.input(e[t]);continue}i[t]=e[t];continue}if(void 0!==n[t].defaultValue&&"create"===r){if("function"==typeof n[t].defaultValue){i[t]=n[t].defaultValue();continue}i[t]=n[t].defaultValue;continue}if(n[t].required&&"create"===r)throw E.APIError.from("BAD_REQUEST",{...rA.BASE_ERROR_CODES.MISSING_FIELD,message:`${t} is required`})}return i}function rR(e,t={},r){return rT(t,{fields:rk(e,"user","input"),action:r})}let rI=(e,t="ms")=>new Date(Date.now()+("sec"===t?1e3*e:e)),rU=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function rO(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch{return e}}function rP(e){if(!e)return[];let t=[],r=0,n=0;for(;n<e.length;){if(","===e[n]){let i=n+1;for(;i<e.length&&" "===e[i];)i++;for(;i<e.length&&"="!==e[i]&&";"!==e[i]&&","!==e[i];)i++;if(i<e.length&&"="===e[i]){let i=e.slice(r,n).trim();for(i&&t.push(i),r=n+1;r<e.length&&" "===e[r];)r++;n=r;continue}}n++}let i=e.slice(r).trim();return i&&t.push(i),t}let rC=/^[\w!#$%&'*.^`|~+-]+$/,rD=/^[ !#-:<-[\]-~]*$/;function rL(e){return!(e.length<2)&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function rz(e){let t=0,r=e.length;for(;t<r;){let r=e.charCodeAt(t);if(32!==r&&9!==r)break;t++}for(;r>t;){let t=e.charCodeAt(r-1);if(32!==t&&9!==t)break;r--}return 0===t&&r===e.length?e:e.slice(t,r)}function r$(e){let t=new Map;if(e.length<2)return t;for(let r of e.split(";")){let e=r.indexOf("=");if(-1===e)continue;let n=rz(r.slice(0,e)),i=rL(rz(r.slice(e+1)));rC.test(n)&&rD.test(i)&&t.set(n,rO(i))}return t}var rN=e.i(858544);function rj(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:o,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class a extends i{}function o(e){var t;let i=r?.Parent?new a:this;for(let r of(n(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}Symbol("zod_brand");class rH extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class rB extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(y=globalThis).__zod_globalConfig??(y.__zod_globalConfig={});let rV=globalThis.__zod_globalConfig;function rM(e){return e&&Object.assign(rV,e),rV}function rK(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function rW(e,t){return"bigint"==typeof t?t.toString():t}function rq(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function rF(e){return null==e}function rJ(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function rZ(e,t){let r=e/t,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}let rG=Symbol("evaluating");function rQ(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==rG)return void 0===n&&(n=rG,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function rY(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function rX(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}function r0(e){return JSON.stringify(e)}function r1(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}let r2="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function r6(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let r5=rq(()=>{if(rV.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function r8(e){if(!1===r6(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==r6(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let r4=new Set(["string","number","symbol"]),r3=new Set(["string","number","bigint","boolean","symbol","undefined"]);function r9(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function r7(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ne(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function nt(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function nr(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let nn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ni={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function na(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function no(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ns(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function nc(e){return"string"==typeof e?e:e?.message}function nl(e,t,r){let n=e.message?e.message:nc(e.inst?._zod.def?.error?.(e))??nc(t?.error?.(e))??nc(r.customError?.(e))??nc(r.localeError?.(e))??"Invalid input",{inst:i,continue:a,input:o,...s}=e;return s.path??(s.path=[]),s.message=n,t?.reportInput&&(s.input=o),s}function nd(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function nu(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function np(...e){let[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function nf(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function nh(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}e.s(["BIGINT_FORMAT_RANGES",0,ni,"Class",0,class{constructor(...e){}},"NUMBER_FORMAT_RANGES",0,nn,"aborted",0,na,"allowsEval",0,r5,"assert",0,function(e){},"assertEqual",0,function(e){return e},"assertIs",0,function(e){},"assertNever",0,function(e){throw Error("Unexpected value in exhaustive check")},"assertNotEqual",0,function(e){return e},"assignProp",0,rY,"base64ToUint8Array",0,nf,"base64urlToUint8Array",0,function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return nf(t+r)},"cached",0,rq,"captureStackTrace",0,r2,"cleanEnum",0,function(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,rJ,"clone",0,r7,"cloneDef",0,function(e){return rX(e._zod.def)},"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,a)=>(t??(t=e()),Reflect.set(t,n,i,a)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})},"defineLazy",0,rQ,"esc",0,r0,"escapeRegex",0,r9,"explicitlyAborted",0,no,"extend",0,function(e,t){if(!r8(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=rX(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return rY(this,"shape",r),r}});return r7(e,n)},"finalizeIssue",0,nl,"floatSafeRemainder",0,rZ,"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>e?.[t],e):e},"getEnumValues",0,rK,"getLengthableOrigin",0,nu,"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,nd,"hexToUint8Array",0,function(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r},"isObject",0,r6,"isPlainObject",0,r8,"issue",0,np,"joinValues",0,function(e,t="|"){return e.map(e=>nt(e)).join(t)},"jsonStringifyReplacer",0,rW,"merge",0,function(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=rX(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return rY(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return r7(e,r)},"mergeDefs",0,rX,"normalizeParams",0,ne,"nullish",0,rF,"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"objectClone",0,function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))},"omit",0,function(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=rX(e._zod.def,{get shape(){let n={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return rY(this,"shape",n),n},checks:[]});return r7(e,i)},"optionalKeys",0,nr,"parsedType",0,function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":if(null===e)return"null";if(Array.isArray(e))return"array";if(e&&Object.getPrototypeOf(e)!==Object.prototype&&"constructor"in e&&e.constructor)return e.constructor.name}return t},"partial",0,function(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=rX(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(let t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return rY(this,"shape",i),i},checks:[]});return r7(t,i)},"pick",0,function(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=rX(e._zod.def,{get shape(){let e={};for(let n in t){if(!(n in r.shape))throw Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return rY(this,"shape",e),e},checks:[]});return r7(e,i)},"prefixIssues",0,ns,"primitiveTypes",0,r3,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let n=0;n<t.length;n++)r[t[n]]=e[n];return r})},"propertyKeyTypes",0,r4,"randomString",0,function(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r},"required",0,function(e,t,r){let n=rX(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let t in r){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(let t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return rY(this,"shape",i),i}});return r7(t,n)},"safeExtend",0,function(e,t){if(!r8(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=rX(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return rY(this,"shape",r),r}});return r7(e,r)},"shallowClone",0,function(e){return r8(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e},"slugify",0,r1,"stringifyPrimitive",0,nt,"uint8ArrayToBase64",0,nh,"uint8ArrayToBase64url",0,function(e){return nh(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"uint8ArrayToHex",0,function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},"unwrapMessage",0,nc],202721);let nm=/^[cC][0-9a-z]{6,}$/,ny=/^[0-9a-z]+$/,ng=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nw=/^[0-9a-vA-V]{20}$/,nb=/^[A-Za-z0-9]{27}$/,nA=/^[a-zA-Z0-9_-]{21}$/,nE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,nv=/^([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})$/,nk=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)$/,n_=nk(4),nS=nk(6),nx=nk(7),nT=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;function nI(){return RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}let nU=/^(?:(?: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])$/,nO=/^(([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}|:))$/,nP=e=>{let t=r9(e??":");return RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},nC=/^((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])$/,nD=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nL=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nz=/^[A-Za-z0-9_-]*$/,n$=/^https?$/,nN=/^\+[1-9]\d{6,14}$/,nj="(?:(?:\\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])))",nH=RegExp(`^${nj}$`);function nB(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function nV(e){return RegExp(`^${nB(e)}$`)}function nM(e){let t=nB({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return RegExp(`^${nj}T(?:${n})$`)}let nK=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${t}$`)},nW=/^-?\d+n?$/,nq=/^-?\d+$/,nF=/^-?\d+(?:\.\d+)?$/,nJ=/^(?:true|false)$/i,nZ=/^null$/i,nG=/^undefined$/i,nQ=/^[^A-Z]*$/,nY=/^[^a-z]*$/;function nX(e,t){return RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function n0(e){return RegExp(`^[A-Za-z0-9_-]{${e}}$`)}let n1=nX(22,"=="),n2=n0(22),n6=nX(27,"="),n5=n0(27),n8=nX(43,"="),n4=n0(43),n3=nX(64,""),n9=n0(64),n7=nX(86,"=="),ie=n0(86);e.s(["base64",0,nL,"base64url",0,nz,"bigint",0,nW,"boolean",0,nJ,"browserEmail",0,/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,"cidrv4",0,nC,"cidrv6",0,nD,"cuid",0,nm,"cuid2",0,ny,"date",0,nH,"datetime",0,nM,"domain",0,/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,"duration",0,nE,"e164",0,nN,"email",0,nT,"emoji",0,nI,"extendedDuration",0,/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,"guid",0,nv,"hex",0,/^[0-9a-fA-F]*$/,"hostname",0,/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,"html5Email",0,/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,"httpProtocol",0,n$,"idnEmail",0,nR,"integer",0,nq,"ipv4",0,nU,"ipv6",0,nO,"ksuid",0,nb,"lowercase",0,nQ,"mac",0,nP,"md5_base64",0,n1,"md5_base64url",0,n2,"md5_hex",0,/^[0-9a-fA-F]{32}$/,"nanoid",0,nA,"null",0,nZ,"number",0,nF,"rfc5322Email",0,/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"sha1_base64",0,n6,"sha1_base64url",0,n5,"sha1_hex",0,/^[0-9a-fA-F]{40}$/,"sha256_base64",0,n8,"sha256_base64url",0,n4,"sha256_hex",0,/^[0-9a-fA-F]{64}$/,"sha384_base64",0,n3,"sha384_base64url",0,n9,"sha384_hex",0,/^[0-9a-fA-F]{96}$/,"sha512_base64",0,n7,"sha512_base64url",0,ie,"sha512_hex",0,/^[0-9a-fA-F]{128}$/,"string",0,nK,"time",0,nV,"ulid",0,ng,"undefined",0,nG,"unicodeEmail",0,nR,"uppercase",0,nY,"uuid",0,nk,"uuid4",0,n_,"uuid6",0,nS,"uuid7",0,nx,"xid",0,nw],110107);let it=rj("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ir={number:"number",bigint:"bigint",object:"date"},ii=rj("$ZodCheckLessThan",(e,t)=>{it.init(e,t);let r=ir[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ia=rj("$ZodCheckGreaterThan",(e,t)=>{it.init(e,t);let r=ir[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),io=rj("$ZodCheckMultipleOf",(e,t)=>{it.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===rZ(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),is=rj("$ZodCheckNumberFormat",(e,t)=>{it.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,a]=nn[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=a,r&&(n.pattern=nq)}),e._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s))return void o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?o.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}))}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})}}),ic=rj("$ZodCheckBigIntFormat",(e,t)=>{it.init(e,t);let[r,n]=ni[t.format];e._zod.onattach.push(e=>{let i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=i=>{let a=i.value;a<r&&i.issues.push({origin:"bigint",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>n&&i.issues.push({origin:"bigint",input:a,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),il=rj("$ZodCheckMaxSize",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rF(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;n.size<=t.maximum||r.issues.push({origin:nd(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),id=rj("$ZodCheckMinSize",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rF(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;n.size>=t.minimum||r.issues.push({origin:nd(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),iu=rj("$ZodCheckSizeEquals",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rF(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{let n=r.value,i=n.size;if(i===t.size)return;let a=i>t.size;r.issues.push({origin:nd(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),ip=rj("$ZodCheckMaxLength",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rF(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;if(n.length<=t.maximum)return;let i=nu(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ih=rj("$ZodCheckMinLength",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rF(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;if(n.length>=t.minimum)return;let i=nu(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),im=rj("$ZodCheckLengthEquals",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!rF(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let n=r.value,i=n.length;if(i===t.length)return;let a=nu(n),o=i>t.length;r.issues.push({origin:a,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),iy=rj("$ZodCheckStringFormat",(e,t)=>{var r,n;it.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),ig=rj("$ZodCheckRegex",(e,t)=>{iy.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),iw=rj("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=nQ),iy.init(e,t)}),ib=rj("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=nY),iy.init(e,t)}),iA=rj("$ZodCheckIncludes",(e,t)=>{it.init(e,t);let r=r9(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),iE=rj("$ZodCheckStartsWith",(e,t)=>{it.init(e,t);let r=RegExp(`^${r9(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),iv=rj("$ZodCheckEndsWith",(e,t)=>{it.init(e,t);let r=RegExp(`.*${r9(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});(e,t)=>{it.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}};let ik=rj("$ZodCheckOverwrite",(e,t)=>{it.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class i_{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}let iS=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,rW,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ix=rj("$ZodError",iS),iT=rj("$ZodError",iS,{Parent:Error}),iR=e=>(t,r,n,i)=>{let a=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new rH;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>nl(e,a,rM())));throw r2(t,i?.callee),t}return o.value},iI=iR(iT),iU=e=>async(t,r,n,i)=>{let a=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>nl(e,a,rM())));throw r2(t,i?.callee),t}return o.value},iO=iU(iT),iP=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new rH;return a.issues.length?{success:!1,error:new(e??ix)(a.issues.map(e=>nl(e,i,rM())))}:{success:!0,data:a.value}},iC=iP(iT),iD=e=>async(t,r,n)=>{let i=n?{...n,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>nl(e,i,rM())))}:{success:!0,data:a.value}},iL=iD(iT),iz={major:4,minor:4,patch:3},i$=rj("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=iz;let n=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&n.unshift(e),n))for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,i=na(e);for(let a of t){if(a._zod.def.when){if(no(e)||!a._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&r?.async===!1)throw new rH;if(n||o instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(i||(i=na(e,t)))});else{if(e.issues.length===t)continue;i||(i=na(e,t))}}return n?n.then(()=>e):e},r=(r,i,a)=>{if(na(r))return r.aborted=!0,r;let o=t(i,n,a);if(o instanceof Promise){if(!1===a.async)throw new rH;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if("backward"===a.direction){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,a)):r(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(!1===a.async)throw new rH;return o.then(e=>t(e,n,a))}return t(o,n,a)}}rQ(e,"~standard",()=>({validate:t=>{try{let r=iC(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return iL(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),iN=rj("$ZodString",(e,t)=>{i$.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??nK(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ij=rj("$ZodStringFormat",(e,t)=>{iy.init(e,t),iN.init(e,t)}),iH=rj("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=nv),ij.init(e,t)}),iB=rj("$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(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nk(e))}else t.pattern??(t.pattern=nk());ij.init(e,t)}),iV=rj("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nT),ij.init(e,t)}),iM=rj("$ZodURL",(e,t)=>{ij.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===n$.source&&!/^https?:\/\//i.test(n))return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});let i=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),iK=rj("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=nI()),ij.init(e,t)}),iW=rj("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nA),ij.init(e,t)}),iq=rj("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=nm),ij.init(e,t)}),iF=rj("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ny),ij.init(e,t)}),iJ=rj("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ng),ij.init(e,t)}),iZ=rj("$ZodXID",(e,t)=>{t.pattern??(t.pattern=nw),ij.init(e,t)}),iG=rj("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=nb),ij.init(e,t)}),iQ=rj("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=nM(t)),ij.init(e,t)}),iY=rj("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=nH),ij.init(e,t)}),iX=rj("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=nV(t)),ij.init(e,t)}),i0=rj("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nE),ij.init(e,t)}),i1=rj("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=nU),ij.init(e,t),e._zod.bag.format="ipv4"}),i2=rj("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=nO),ij.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),i6=((e,t)=>{t.pattern??(t.pattern=nP(t.delimiter)),ij.init(e,t),e._zod.bag.format="mac"},rj("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=nC),ij.init(e,t)})),i5=rj("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=nD),ij.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(2!==n.length)throw Error();let[e,t]=n;if(!t)throw Error();let r=Number(t);if(`${r}`!==t||r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function i8(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let i4=rj("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=nL),ij.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{i8(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),i3=rj("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=nz),ij.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{!function(e){if(!nz.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return i8(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),i9=rj("$ZodE164",(e,t)=>{t.pattern??(t.pattern=nN),ij.init(e,t)}),i7=rj("$ZodJWT",(e,t)=>{ij.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ae=((e,t)=>{ij.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}},rj("$ZodNumber",(e,t)=>{i$.init(e,t),e._zod.pattern=e._zod.bag.pattern??nF,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let a="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),r}})),at=rj("$ZodNumberFormat",(e,t)=>{is.init(e,t),ae.init(e,t)}),ar=rj("$ZodBoolean",(e,t)=>{i$.init(e,t),e._zod.pattern=nJ,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),an=rj("$ZodBigInt",(e,t)=>{i$.init(e,t),e._zod.pattern=nW,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),ai=((e,t)=>{ic.init(e,t),an.init(e,t)},rj("$ZodAny",(e,t)=>{i$.init(e,t),e._zod.parse=e=>e})),aa=rj("$ZodUnknown",(e,t)=>{i$.init(e,t),e._zod.parse=e=>e}),ao=rj("$ZodNever",(e,t)=>{i$.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),as=((e,t)=>{i$.init(e,t),e._zod.parse=(t,r)=>{let n=t.value;return void 0===n||t.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),t}},rj("$ZodDate",(e,t)=>{i$.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}let i=r.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...a?{received:"Invalid Date"}:{},inst:e}),r}}));function ac(e,t,r){e.issues.length&&t.issues.push(...ns(r,e.issues)),t.value[r]=e.value}let al=rj("$ZodArray",(e,t)=>{i$.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},n);s instanceof Promise?a.push(s.then(t=>ac(t,r,e))):ac(s,r,e)}return a.length?Promise.all(a).then(()=>r):r}});function ad(e,t,r,n,i,a){let o=r in n;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...ns(r,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?o&&(t.value[r]=void 0):t.value[r]=e.value}function au(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=nr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ap(e,t,r,n,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,d="optional"===c.optin,u="optional"===c.optout;for(let i in t){if("__proto__"===i||s.has(i))continue;if("never"===l){o.push(i);continue}let a=c.run({value:t[i],issues:[]},n);a instanceof Promise?e.push(a.then(e=>ad(e,r,i,t,d,u))):ad(a,r,i,t,d,u)}return(o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:a}),e.length)?Promise.all(e).then(()=>r):r}let af=rj("$ZodObject",(e,t)=>{let r;i$.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=rq(()=>au(t));rQ(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let n=e[t]._zod;if(n.values)for(let e of(r[t]??(r[t]=new Set),n.values))r[t].add(e)}return r});let a=t.catchall;e._zod.parse=(t,n)=>{r??(r=i.value);let o=t.value;if(!r6(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};let s=[],c=r.shape;for(let e of r.keys){let r=c[e],i="optional"===r._zod.optin,a="optional"===r._zod.optout,l=r._zod.run({value:o[e],issues:[]},n);l instanceof Promise?s.push(l.then(r=>ad(r,t,e,o,i,a))):ad(l,t,e,o,i,a)}return a?ap(s,o,t,n,i.value,e):s.length?Promise.all(s).then(()=>t):t}}),ah=rj("$ZodObjectJIT",(e,t)=>{let r,n;af.init(e,t);let i=e._zod.parse,a=rq(()=>au(t)),o=!rV.jitless,s=o&&r5.value,c=t.catchall;e._zod.parse=(l,d)=>{n??(n=a.value);let u=l.value;return r6(u)?o&&s&&d?.async===!1&&!0!==d.jitless?(r||(r=(e=>{let t=new i_(["shape","payload","ctx"]),r=a.value,n=e=>{let t=r0(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),o=0;for(let e of r.keys)i[e]=`key_${o++}`;for(let a of(t.write("const newResult = {};"),r.keys)){let r=i[a],o=r0(a),s=e[a],c=s?._zod?.optin==="optional",l=s?._zod?.optout==="optional";t.write(`const ${r} = ${n(a)};`),c&&l?t.write(`
2
+ if (${r}.issues.length) {
3
+ if (${o} in input) {
4
+ payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
5
+ ...iss,
6
+ path: iss.path ? [${o}, ...iss.path] : [${o}]
7
+ })));
8
+ }
9
+ }
10
+
11
+ if (${r}.value === undefined) {
12
+ if (${o} in input) {
13
+ newResult[${o}] = undefined;
14
+ }
15
+ } else {
16
+ newResult[${o}] = ${r}.value;
17
+ }
18
+
19
+ `):c?t.write(`
20
+ if (${r}.issues.length) {
21
+ payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
22
+ ...iss,
23
+ path: iss.path ? [${o}, ...iss.path] : [${o}]
24
+ })));
25
+ }
26
+
27
+ if (${r}.value === undefined) {
28
+ if (${o} in input) {
29
+ newResult[${o}] = undefined;
30
+ }
31
+ } else {
32
+ newResult[${o}] = ${r}.value;
33
+ }
34
+
35
+ `):t.write(`
36
+ const ${r}_present = ${o} in input;
37
+ if (${r}.issues.length) {
38
+ payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
39
+ ...iss,
40
+ path: iss.path ? [${o}, ...iss.path] : [${o}]
41
+ })));
42
+ }
43
+ if (!${r}_present && !${r}.issues.length) {
44
+ payload.issues.push({
45
+ code: "invalid_type",
46
+ expected: "nonoptional",
47
+ input: undefined,
48
+ path: [${o}]
49
+ });
50
+ }
51
+
52
+ if (${r}_present) {
53
+ if (${r}.value === undefined) {
54
+ newResult[${o}] = undefined;
55
+ } else {
56
+ newResult[${o}] = ${r}.value;
57
+ }
58
+ }
59
+
60
+ `)}t.write("payload.value = newResult;"),t.write("return payload;");let s=t.compile();return(t,r)=>s(e,t,r)})(t.shape)),l=r(l,d),c)?ap([],u,l,d,n,e):l:i(l,d):(l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l)}});function am(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let i=e.filter(e=>!na(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>nl(e,n,rM())))}),t)}let ay=rj("$ZodUnion",(e,t)=>{i$.init(e,t),rQ(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),rQ(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),rQ(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),rQ(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>rJ(e.source)).join("|")})$`)}});let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(0===t.issues.length)return t;o.push(t)}}return a?Promise.all(o).then(t=>am(t,n,e,i)):am(o,n,e,i)}});function ag(e,t,r,n){let i=e.filter(e=>0===e.issues.length);return 1===i.length?t.value=i[0].value:0===i.length?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>nl(e,n,rM())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t}(e,t)=>{ay.init(e,t),t.inclusive=!1;let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},i);t instanceof Promise?(o.push(t),a=!0):o.push(t)}return a?Promise.all(o).then(t=>ag(t,n,e,i)):ag(o,n,e,i)}},(e,t)=>{t.inclusive=!1,ay.init(e,t);let r=e._zod.parse;rQ(e._zod,"propValues",()=>{let e={};for(let r of t.options){let n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(n))for(let n of(e[t]||(e[t]=new Set),r))e[t].add(n)}return e});let n=rq(()=>{let e=t.options,r=new Map;for(let n of e){let e=n._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,a)=>{let o=i.value;if(!r6(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;let s=n.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||"backward"===a.direction?r(i,a):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}};let aw=rj("$ZodIntersection",(e,t)=>{i$.init(e,t),e._zod.parse=(e,r)=>{let n=e.value,i=t.left._zod.run({value:n,issues:[]},r),a=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,r])=>ab(e,t,r)):ab(e,i,a)}});function ab(e,t,r){let n,i=new Map;for(let r of t.issues)if("unrecognized_keys"===r.code)for(let e of(n??(n=r),r.keys))i.has(e)||i.set(e,{}),i.get(e).l=!0;else e.issues.push(r);for(let t of r.issues)if("unrecognized_keys"===t.code)for(let e of t.keys)i.has(e)||i.set(e,{}),i.get(e).r=!0;else e.issues.push(t);let a=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&n&&e.issues.push({...n,keys:a}),na(e))return e;let o=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(r8(t)&&r8(r)){let n=Object.keys(r),i=Object.keys(t).filter(e=>-1!==n.indexOf(e)),a={...t,...r};for(let n of i){let i=e(t[n],r[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};a[n]=i.data}return{valid:!0,data:a}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let aA=rj("$ZodTuple",(e,t)=>{i$.init(e,t);let r=t.items;e._zod.parse=(n,i)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[],s=aE(r,"optin"),c=aE(r,"optout");if(!t.rest){if(a.length<s)return n.issues.push({code:"too_small",minimum:s,inclusive:!0,input:a,inst:e,origin:"array"}),n;a.length>r.length&&n.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:a,inst:e,origin:"array"})}let l=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=r.length-1;for(let s of a.slice(r.length)){e++;let r=t.rest._zod.run({value:s,issues:[]},i);r instanceof Promise?o.push(r.then(t=>av(t,n,e))):av(r,n,e)}}return o.length?Promise.all(o).then(()=>ak(l,n,r,a,c)):ak(l,n,r,a,c)}});function aE(e,t){for(let r=e.length-1;r>=0;r--)if("optional"!==e[r]._zod[t])return r+1;return 0}function av(e,t,r){e.issues.length&&t.issues.push(...ns(r,e.issues)),t.value[r]=e.value}function ak(e,t,r,n,i){for(let a=0;a<r.length;a++){let r=e[a],o=a<n.length;if(r.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...ns(a,r.issues))}t.value[a]=r.value}for(let e=t.value.length-1;e>=n.length;e--)if("optional"===r[e]._zod.optout&&void 0===t.value[e])t.value.length=e;else break;return t}let a_=rj("$ZodRecord",(e,t)=>{i$.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!r8(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let a=[],o=t.keyType._zod.values;if(o){let s;r.value={};let c=new Set;for(let s of o)if("string"==typeof s||"number"==typeof s||"symbol"==typeof s){c.add("number"==typeof s?s.toString():s);let o=t.keyType._zod.run({value:s,issues:[]},n);if(o instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>nl(e,n,rM())),input:s,path:[s],inst:e});continue}let l=o.value,d=t.valueType._zod.run({value:i[s],issues:[]},n);d instanceof Promise?a.push(d.then(e=>{e.issues.length&&r.issues.push(...ns(s,e.issues)),r.value[l]=e.value})):(d.issues.length&&r.issues.push(...ns(s,d.issues)),r.value[l]=d.value)}for(let e in i)c.has(e)||(s=s??[]).push(e);s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:s})}else for(let o of(r.value={},Reflect.ownKeys(i))){if("__proto__"===o||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},n);if(s instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof o&&nF.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},n);if(e instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===e.issues.length&&(s=e)}if(s.issues.length){"loose"===t.mode?r.value[o]=i[o]:r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>nl(e,n,rM())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&r.issues.push(...ns(o,e.issues)),r.value[s.value]=e.value})):(c.issues.length&&r.issues.push(...ns(o,c.issues)),r.value[s.value]=c.value)}return a.length?Promise.all(a).then(()=>r):r}});function aS(e,t,r,n,i,a,o){e.issues.length&&(r4.has(typeof n)?r.issues.push(...ns(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:a,issues:e.issues.map(e=>nl(e,o,rM()))})),t.issues.length&&(r4.has(typeof n)?r.issues.push(...ns(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:a,key:n,issues:t.issues.map(e=>nl(e,o,rM()))})),r.value.set(e.value,t.value)}function ax(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}(e,t)=>{i$.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;let a=[];for(let[o,s]of(r.value=new Map,i)){let c=t.keyType._zod.run({value:o,issues:[]},n),l=t.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||l instanceof Promise?a.push(Promise.all([c,l]).then(([t,a])=>{aS(t,a,r,o,i,e,n)})):aS(c,l,r,o,i,e,n)}return a.length?Promise.all(a).then(()=>r):r}},(e,t)=>{i$.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;let a=[];for(let e of(r.value=new Set,i)){let i=t.valueType._zod.run({value:e,issues:[]},n);i instanceof Promise?a.push(i.then(e=>ax(e,r))):ax(i,r)}return a.length?Promise.all(a).then(()=>r):r}};let aT=rj("$ZodEnum",(e,t)=>{i$.init(e,t);let r=rK(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=RegExp(`^(${r.filter(e=>r4.has(typeof e)).map(e=>"string"==typeof e?r9(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{let a=t.value;return n.has(a)||t.issues.push({code:"invalid_value",values:r,input:a,inst:e}),t}}),aR=((e,t)=>{if(i$.init(e,t),0===t.values.length)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?r9(e):e?r9(e.toString()):String(e)).join("|")})$`),e._zod.parse=(n,i)=>{let a=n.value;return r.has(a)||n.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),n}},rj("$ZodTransform",(e,t)=>{i$.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new rB(e.constructor.name);let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(r.value=e,r.fallback=!0,r));if(i instanceof Promise)throw new rH;return r.value=i,r.fallback=!0,r}}));function aI(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let aU=rj("$ZodOptional",(e,t)=>{i$.init(e,t),e._zod.optin="optional",e._zod.optout="optional",rQ(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),rQ(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${rJ(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let n=e.value,i=t.innerType._zod.run(e,r);return i instanceof Promise?i.then(e=>aI(e,n)):aI(i,n)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),aO=rj("$ZodExactOptional",(e,t)=>{aU.init(e,t),rQ(e._zod,"values",()=>t.innerType._zod.values),rQ(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),aP=rj("$ZodNullable",(e,t)=>{i$.init(e,t),rQ(e._zod,"optin",()=>t.innerType._zod.optin),rQ(e._zod,"optout",()=>t.innerType._zod.optout),rQ(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${rJ(e.source)}|null)$`):void 0}),rQ(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),aC=rj("$ZodDefault",(e,t)=>{i$.init(e,t),e._zod.optin="optional",rQ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>aD(e,t)):aD(n,t)}});function aD(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let aL=rj("$ZodPrefault",(e,t)=>{i$.init(e,t),e._zod.optin="optional",rQ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),az=rj("$ZodNonOptional",(e,t)=>{i$.init(e,t),rQ(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>a$(t,e)):a$(i,e)}});function a$(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}(e,t)=>{i$.init(e,t),e._zod.parse=(e,r)=>{if("backward"===r.direction)throw new rB("ZodSuccess");let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===n.issues.length,e)}};let aN=rj("$ZodCatch",(e,t)=>{i$.init(e,t),e._zod.optin="optional",rQ(e._zod,"optout",()=>t.innerType._zod.optout),rQ(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>nl(e,r,rM()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>nl(e,r,rM()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),aj=((e,t)=>{i$.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)},rj("$ZodPipe",(e,t)=>{i$.init(e,t),rQ(e._zod,"values",()=>t.in._zod.values),rQ(e._zod,"optin",()=>t.in._zod.optin),rQ(e._zod,"optout",()=>t.out._zod.optout),rQ(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>aH(e,t.in,r)):aH(n,t.in,r)}let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>aH(e,t.out,r)):aH(n,t.out,r)}}));function aH(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function aB(e,t,r){if(e.issues.length)return e.aborted=!0,e;if("forward"===(r.direction||"forward")){let n=t.transform(e.value,e);return n instanceof Promise?n.then(n=>aV(e,n,t.out,r)):aV(e,n,t.out,r)}{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(n=>aV(e,n,t.in,r)):aV(e,n,t.in,r)}}function aV(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}(e,t)=>{i$.init(e,t),rQ(e._zod,"values",()=>t.in._zod.values),rQ(e._zod,"optin",()=>t.in._zod.optin),rQ(e._zod,"optout",()=>t.out._zod.optout),rQ(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("forward"===(r.direction||"forward")){let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>aB(e,t,r)):aB(n,t,r)}{let n=t.out._zod.run(e,r);return n instanceof Promise?n.then(e=>aB(e,t,r)):aB(n,t,r)}}},(e,t)=>{aj.init(e,t)};let aM=rj("$ZodReadonly",(e,t)=>{i$.init(e,t),rQ(e._zod,"propValues",()=>t.innerType._zod.propValues),rQ(e._zod,"values",()=>t.innerType._zod.values),rQ(e._zod,"optin",()=>t.innerType?._zod?.optin),rQ(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(aK):aK(n)}});function aK(e){return e.value=Object.freeze(e.value),e}(e,t)=>{i$.init(e,t);let r=[];for(let e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let n=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(n,i))}else if(null===e||r3.has(typeof e))r.push(r9(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${r.join("")}$`),e._zod.parse=(r,n)=>("string"!=typeof r.value?r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source})),r)},(e,t)=>{i$.init(e,t),rQ(e._zod,"innerType",()=>(t._cachedInner||(t._cachedInner=t.getter()),t._cachedInner)),rQ(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),rQ(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),rQ(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),rQ(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)};let aW=rj("$ZodCustom",(e,t)=>{it.init(e,t),i$.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>aq(t,r,n,e));aq(i,r,n,e)}});function aq(e,t,r,n){if(!e){let e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(np(e))}}Symbol("ZodOutput"),Symbol("ZodInput");(g=globalThis).__zod_globalRegistry??(g.__zod_globalRegistry=new class e{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});let aF=globalThis.__zod_globalRegistry;function aJ(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ne(t)})}function aZ(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ne(t)})}function aG(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ne(t)})}function aQ(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ne(t)})}function aY(e,t){return new ii({check:"less_than",...ne(t),value:e,inclusive:!1})}function aX(e,t){return new ii({check:"less_than",...ne(t),value:e,inclusive:!0})}function a0(e,t){return new ia({check:"greater_than",...ne(t),value:e,inclusive:!1})}function a1(e,t){return new ia({check:"greater_than",...ne(t),value:e,inclusive:!0})}function a2(e,t){return new io({check:"multiple_of",...ne(t),value:e})}function a6(e,t){return new ip({check:"max_length",...ne(t),maximum:e})}function a5(e,t){return new ih({check:"min_length",...ne(t),minimum:e})}function a8(e,t){return new im({check:"length_equals",...ne(t),length:e})}function a4(e){return new ik({check:"overwrite",tx:e})}e.i(110107);var a3=e.i(202721),a3=a3;function a9(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??aF,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function a7(e,t,r={path:[],schemaPath:[]}){var n;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let n={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,n);else{let r=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,r,n)}let a=e._zod.parent;a&&(o.ref||(o.ref=a),a7(a,t,n),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),"input"===t.io&&function e(t,r){let n=r??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let i=t._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return e(i.element,n);if("set"===i.type)return e(i.valueType,n);if("lazy"===i.type)return e(i.getter(),n);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type)return e(i.innerType,n);if("intersection"===i.type)return e(i.left,n)||e(i.right,n);if("record"===i.type||"map"===i.type)return e(i.keyType,n)||e(i.valueType,n);if("pipe"===i.type)return!!t._zod.traits.has("$ZodCodec")||e(i.in,n)||e(i.out,n);if("object"===i.type){for(let t in i.shape)if(e(i.shape[t],n))return!0;return!1}if("union"===i.type){for(let t of i.options)if(e(t,n))return!0;return!1}if("tuple"===i.type){for(let t of i.items)if(e(t,n))return!0;if(i.rest&&e(i.rest,n))return!0}return!1}(e)&&(delete o.schema.examples,delete o.schema.default),"input"===t.io&&"_prefault"in o.schema&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function oe(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let t of e.seen.entries()){let r=e.metadataRegistry.get(t[0])?.id;if(r){let e=n.get(r);if(e&&e!==t[0])throw Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(r,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let n=t[1],{ref:i,defId:a}=(t=>{let n="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let r=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(r)return{ref:i(r)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i("__shared")}#/${n}/${a}`}}if(t[1]===r)return{ref:"#"};let i=`#/${n}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}})(t);n.def={...n.schema},a&&(n.defId=a);let o=n.schema;for(let e in o)delete o[e];o.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>
61
+
62
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let n=r[1];if(t===r[0]){i(r);continue}if(e.external){let n=e.external.registry.get(r[0])?.id;if(t!==r[0]&&n){i(r);continue}}if(e.metadataRegistry.get(r[0])?.id||n.cycle||n.count>1&&"ref"===e.reused){i(r);continue}}}function ot(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=t=>{let r=e.seen.get(t);if(null===r.ref)return;let i=r.def??r.schema,a={...i},o=r.ref;if(r.ref=null,o){n(o);let r=e.seen.get(o),s=r.schema;if(s.$ref&&("draft-07"===e.target||"draft-04"===e.target||"openapi-3.0"===e.target)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in a||delete i[e]);if(s.$ref&&r.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(i[e])===JSON.stringify(r.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){n(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())n(t[0]);let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(r)}Object.assign(i,r.def??r.schema);let a=e.metadataRegistry.get(t)?.id;void 0!==a&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?i.$defs=o:i.definitions=o);try{let r=JSON.parse(JSON.stringify(i));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:or(t,"input",e.processors),output:or(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}let or=(e,t,r={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=a9({...i??{},target:a,io:t,processors:r});return a7(e,o),oe(o,e),ot(o,e)},on={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},oi=(e,t,r,n)=>{let i=e._zod.def;a7(i.innerType,t,n),t.seen.get(e).ref=i.innerType},oa=rj("ZodISODateTime",(e,t)=>{iQ.init(e,t),oR.init(e,t)}),oo=rj("ZodISODate",(e,t)=>{iY.init(e,t),oR.init(e,t)}),os=rj("ZodISOTime",(e,t)=>{iX.init(e,t),oR.init(e,t)}),oc=rj("ZodISODuration",(e,t)=>{i0.init(e,t),oR.init(e,t)}),ol=rj("ZodError",(e,t)=>{ix.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>(function(e,t=e=>e.message){let r={_errors:[]},n=(e,i=[])=>{for(let a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map(e=>n({issues:e},[...i,...a.path]));else if("invalid_key"===a.code)n({issues:a.issues},[...i,...a.path]);else if("invalid_element"===a.code)n({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(0===e.length)r._errors.push(t(a));else{let n=r,i=0;for(;i<e.length;){let r=e[i];i===e.length-1?(n[r]=n[r]||{_errors:[]},n[r]._errors.push(t(a))):n[r]=n[r]||{_errors:[]},n=n[r],i++}}}};return n(e),r})(e,t)},flatten:{value:t=>(function(e,t=e=>e.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}})(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,rW,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,rW,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),od=iR(ol),ou=iU(ol),op=iP(ol),of=iD(ol),oh=(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iR(ol)(e,t,n)},om=(e,t,r)=>iR(ol)(e,t,r),oy=async(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iU(ol)(e,t,n)},og=async(e,t,r)=>iU(ol)(e,t,r),ow=(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iP(ol)(e,t,n)},ob=(e,t,r)=>iP(ol)(e,t,r),oA=async(e,t,r)=>{let n=r?{...r,direction:"backward"}:{direction:"backward"};return iD(ol)(e,t,n)},oE=async(e,t,r)=>iD(ol)(e,t,r),ov=new WeakMap;function ok(e,t,r){let n=Object.getPrototypeOf(e),i=ov.get(n);if(i||(i=new Set,ov.set(n,i)),!i.has(t))for(let e in i.add(t),r){let t=r[e];Object.defineProperty(n,e,{configurable:!0,enumerable:!1,get(){let r=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:r}),r},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}let o_=rj("ZodType",(e,t)=>(i$.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:or(e,"input"),output:or(e,"output")}}),e.toJSONSchema=((e,t={})=>r=>{let n=a9({...r,processors:t});return a7(e,n),oe(n,e),ot(n,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,r)=>od(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>op(e,t,r),e.parseAsync=async(t,r)=>ou(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>of(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>oh(e,t,r),e.decode=(t,r)=>om(e,t,r),e.encodeAsync=async(t,r)=>oy(e,t,r),e.decodeAsync=async(t,r)=>og(e,t,r),e.safeEncode=(t,r)=>ow(e,t,r),e.safeDecode=(t,r)=>ob(e,t,r),e.safeEncodeAsync=async(t,r)=>oA(e,t,r),e.safeDecodeAsync=async(t,r)=>oE(e,t,r),ok(e,"ZodType",{check(...e){let t=this.def;return this.clone(a3.mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return r7(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return new sA({type:"custom",check:"custom",fn:e,...ne(t)})}(e,t))},superRefine(e,t){return this.check(function(e,t){var r;let n,i;return r=t=>(t.addIssue=e=>{"string"==typeof e?t.issues.push(np(e,t.value,n._zod.def)):(e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=t.value),e.inst??(e.inst=n),e.continue??(e.continue=!n._zod.def.abort),t.issues.push(np(e)))},e(t.value,t)),(i=new it({check:"custom",...ne(t)}))._zod.check=r,n=i}(e,t))},overwrite(e){return this.check(a4(e))},optional(){return sl(this)},exactOptional(){var e;return e=this,new sd({type:"optional",innerType:e})},nullable(){return sp(this)},nullish(){return sl(sp(this))},nonoptional(e){var t,r;return t=this,r=e,new sm({type:"nonoptional",innerType:t,...a3.normalizeParams(r)})},array(){return o9(this)},or(e){return new st({type:"union",options:[this,e],...a3.normalizeParams(void 0)})},and(e){var t;return t=this,new sr({type:"intersection",left:t,right:e})},transform(e){return sw(this,new ss({type:"transform",transform:e}))},default(e){var t,r;return t=this,r=e,new sf({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():a3.shallowClone(r)}})},prefault(e){var t,r;return t=this,r=e,new sh({type:"prefault",innerType:t,get defaultValue(){return"function"==typeof r?r():a3.shallowClone(r)}})},catch(e){var t,r;return t=this,new sy({type:"catch",innerType:t,catchValue:"function"==typeof(r=e)?r:()=>r})},pipe(e){return sw(this,e)},readonly(){var e;return e=this,new sb({type:"readonly",innerType:e})},describe(e){let t=this.clone();return aF.add(t,{description:e}),t},meta(...e){if(0===e.length)return aF.get(this);let t=this.clone();return aF.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>aF.get(e)?.description,configurable:!0}),e)),oS=rj("_ZodString",(e,t)=>{iN.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{r.type="string";let{minimum:i,maximum:a,format:o,patterns:s,contentEncoding:c}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof a&&(r.maxLength=a),o&&(r.format=on[o]??o,""===r.format&&delete r.format,"time"===o&&delete r.format),c&&(r.contentEncoding=c),s&&s.size>0){let e=[...s];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,r,0);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,ok(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new ig({check:"string_format",format:"regex",...ne(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new iA({check:"string_format",format:"includes",...ne(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new iE({check:"string_format",format:"starts_with",...ne(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new iv({check:"string_format",format:"ends_with",...ne(t),suffix:e})}(...e))},min(...e){return this.check(a5(...e))},max(...e){return this.check(a6(...e))},length(...e){return this.check(a8(...e))},nonempty(...e){return this.check(a5(1,...e))},lowercase(e){return this.check(new iw({check:"string_format",format:"lowercase",...ne(e)}))},uppercase(e){return this.check(new ib({check:"string_format",format:"uppercase",...ne(e)}))},trim(){return this.check(a4(e=>e.trim()))},normalize(...e){return this.check(function(e){return a4(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(a4(e=>e.toLowerCase()))},toUpperCase(){return this.check(a4(e=>e.toUpperCase()))},slugify(){return this.check(a4(e=>r1(e)))}})}),ox=rj("ZodString",(e,t)=>{iN.init(e,t),oS.init(e,t),e.email=t=>e.check(aJ(oI,t)),e.url=t=>e.check(new oP({type:"string",format:"url",check:"string_format",abort:!1,...ne(t)})),e.jwt=t=>e.check(new oF({type:"string",format:"jwt",check:"string_format",abort:!1,...ne(t)})),e.emoji=t=>e.check(new oC({type:"string",format:"emoji",check:"string_format",abort:!1,...ne(t)})),e.guid=t=>e.check(aZ(oU,t)),e.uuid=t=>e.check(new oO({type:"string",format:"uuid",check:"string_format",abort:!1,...ne(t)})),e.uuidv4=t=>e.check(new oO({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ne(t)})),e.uuidv6=t=>e.check(new oO({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ne(t)})),e.uuidv7=t=>e.check(new oO({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ne(t)})),e.nanoid=t=>e.check(new oD({type:"string",format:"nanoid",check:"string_format",abort:!1,...ne(t)})),e.guid=t=>e.check(aZ(oU,t)),e.cuid=t=>e.check(new oL({type:"string",format:"cuid",check:"string_format",abort:!1,...ne(t)})),e.cuid2=t=>e.check(new oz({type:"string",format:"cuid2",check:"string_format",abort:!1,...ne(t)})),e.ulid=t=>e.check(new o$({type:"string",format:"ulid",check:"string_format",abort:!1,...ne(t)})),e.base64=t=>e.check(new oK({type:"string",format:"base64",check:"string_format",abort:!1,...ne(t)})),e.base64url=t=>e.check(new oW({type:"string",format:"base64url",check:"string_format",abort:!1,...ne(t)})),e.xid=t=>e.check(new oN({type:"string",format:"xid",check:"string_format",abort:!1,...ne(t)})),e.ksuid=t=>e.check(new oj({type:"string",format:"ksuid",check:"string_format",abort:!1,...ne(t)})),e.ipv4=t=>e.check(aG(oH,t)),e.ipv6=t=>e.check(aQ(oB,t)),e.cidrv4=t=>e.check(new oV({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ne(t)})),e.cidrv6=t=>e.check(new oM({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ne(t)})),e.e164=t=>e.check(new oq({type:"string",format:"e164",check:"string_format",abort:!1,...ne(t)})),e.datetime=t=>e.check(new oa({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ne(t)})),e.date=t=>e.check(new oo({type:"string",format:"date",check:"string_format",...ne(t)})),e.time=t=>e.check(new os({type:"string",format:"time",check:"string_format",precision:null,...ne(t)})),e.duration=t=>e.check(new oc({type:"string",format:"duration",check:"string_format",...ne(t)}))});function oT(e){return new ox({type:"string",...ne(e)})}let oR=rj("ZodStringFormat",(e,t)=>{ij.init(e,t),oS.init(e,t)}),oI=rj("ZodEmail",(e,t)=>{iV.init(e,t),oR.init(e,t)}),oU=rj("ZodGUID",(e,t)=>{iH.init(e,t),oR.init(e,t)}),oO=rj("ZodUUID",(e,t)=>{iB.init(e,t),oR.init(e,t)}),oP=rj("ZodURL",(e,t)=>{iM.init(e,t),oR.init(e,t)}),oC=rj("ZodEmoji",(e,t)=>{iK.init(e,t),oR.init(e,t)}),oD=rj("ZodNanoID",(e,t)=>{iW.init(e,t),oR.init(e,t)}),oL=rj("ZodCUID",(e,t)=>{iq.init(e,t),oR.init(e,t)}),oz=rj("ZodCUID2",(e,t)=>{iF.init(e,t),oR.init(e,t)}),o$=rj("ZodULID",(e,t)=>{iJ.init(e,t),oR.init(e,t)}),oN=rj("ZodXID",(e,t)=>{iZ.init(e,t),oR.init(e,t)}),oj=rj("ZodKSUID",(e,t)=>{iG.init(e,t),oR.init(e,t)}),oH=rj("ZodIPv4",(e,t)=>{i1.init(e,t),oR.init(e,t)}),oB=rj("ZodIPv6",(e,t)=>{i2.init(e,t),oR.init(e,t)}),oV=rj("ZodCIDRv4",(e,t)=>{i6.init(e,t),oR.init(e,t)}),oM=rj("ZodCIDRv6",(e,t)=>{i5.init(e,t),oR.init(e,t)}),oK=rj("ZodBase64",(e,t)=>{i4.init(e,t),oR.init(e,t)}),oW=rj("ZodBase64URL",(e,t)=>{i3.init(e,t),oR.init(e,t)}),oq=rj("ZodE164",(e,t)=>{i9.init(e,t),oR.init(e,t)}),oF=rj("ZodJWT",(e,t)=>{i7.init(e,t),oR.init(e,t)}),oJ=rj("ZodNumber",(e,t)=>{ae.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let{minimum:i,maximum:a,format:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;"string"==typeof o&&o.includes("int")?r.type="integer":r.type="number";let d="number"==typeof l&&l>=(i??-1/0),u="number"==typeof c&&c<=(a??1/0),p="draft-04"===t.target||"openapi-3.0"===t.target;d?p?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),u?p?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:"number"==typeof a&&(r.maximum=a),"number"==typeof s&&(r.multipleOf=s)})(e,t,r,0),ok(e,"ZodNumber",{gt(e,t){return this.check(a0(e,t))},gte(e,t){return this.check(a1(e,t))},min(e,t){return this.check(a1(e,t))},lt(e,t){return this.check(aY(e,t))},lte(e,t){return this.check(aX(e,t))},max(e,t){return this.check(aX(e,t))},int(e){return this.check(oQ(e))},safe(e){return this.check(oQ(e))},positive(e){return this.check(a0(0,e))},nonnegative(e){return this.check(a1(0,e))},negative(e){return this.check(aY(0,e))},nonpositive(e){return this.check(aX(0,e))},multipleOf(e,t){return this.check(a2(e,t))},step(e,t){return this.check(a2(e,t))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??-1/0,r.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(r.maximum??1/0,r.exclusiveMaximum??1/0)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function oZ(e){return new oJ({type:"number",checks:[],...ne(e)})}let oG=rj("ZodNumberFormat",(e,t)=>{at.init(e,t),oJ.init(e,t)});function oQ(e){return new oG({type:"number",check:"number_format",abort:!1,format:"safeint",...ne(e)})}let oY=rj("ZodBoolean",(e,t)=>{ar.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{t.type="boolean"}});function oX(e){return new oY({type:"boolean",...ne(e)})}let o0=rj("ZodBigInt",(e,t)=>{an.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")})(0,e,0,0),e.gte=(t,r)=>e.check(a1(t,r)),e.min=(t,r)=>e.check(a1(t,r)),e.gt=(t,r)=>e.check(a0(t,r)),e.gte=(t,r)=>e.check(a1(t,r)),e.min=(t,r)=>e.check(a1(t,r)),e.lt=(t,r)=>e.check(aY(t,r)),e.lte=(t,r)=>e.check(aX(t,r)),e.max=(t,r)=>e.check(aX(t,r)),e.positive=t=>e.check(a0(BigInt(0),t)),e.negative=t=>e.check(aY(BigInt(0),t)),e.nonpositive=t=>e.check(aX(BigInt(0),t)),e.nonnegative=t=>e.check(a1(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(a2(t,r));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),o1=rj("ZodAny",(e,t)=>{ai.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function o2(){return new o1({type:"any"})}let o6=rj("ZodUnknown",(e,t)=>{aa.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{}});function o5(){return new o6({type:"unknown"})}let o8=rj("ZodNever",(e,t)=>{ao.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>{t.not={}}}),o4=rj("ZodDate",(e,t)=>{as.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")})(0,e,0,0),e.min=(t,r)=>e.check(a1(t,r)),e.max=(t,r)=>e.check(aX(t,r));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null}),o3=rj("ZodArray",(e,t)=>{al.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(r.minItems=a),"number"==typeof o&&(r.maxItems=o),r.type="array",r.items=a7(i.element,t,{...n,path:[...n.path,"items"]})})(e,t,r,n),e.element=t.element,ok(e,"ZodArray",{min(e,t){return this.check(a5(e,t))},nonempty(e){return this.check(a5(1,e))},max(e,t){return this.check(a6(e,t))},length(e,t){return this.check(a8(e,t))},unwrap(){return this.element}})});function o9(e,t){return new o3({type:"array",element:e,...ne(t)})}let o7=rj("ZodObject",(e,t)=>{ah.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def;r.type="object",r.properties={};let a=i.shape;for(let e in a)r.properties[e]=a7(a[e],t,{...n,path:[...n.path,"properties",e]});let o=new Set([...new Set(Object.keys(a))].filter(e=>{let r=i.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));o.size>0&&(r.required=Array.from(o)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=a7(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)})(e,t,r,n),a3.defineLazy(e,"shape",()=>t.shape),ok(e,"ZodObject",{keyof(){return so(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:o5()})},loose(){return this.clone({...this._zod.def,catchall:o5()})},strict(){return this.clone({...this._zod.def,catchall:new o8({type:"never",...ne(void 0)})})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return a3.extend(this,e)},safeExtend(e){return a3.safeExtend(this,e)},merge(e){return a3.merge(this,e)},pick(e){return a3.pick(this,e)},omit(e){return a3.omit(this,e)},partial(...e){return a3.partial(sc,this,e[0])},required(...e){return a3.required(sm,this,e[0])}})});function se(e,t){return new o7({type:"object",shape:e??{},...a3.normalizeParams(t)})}let st=rj("ZodUnion",(e,t)=>{ay.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{var i,a,o,s;let c,l,d;return i=e,a=t,o=r,s=n,l=!1===(c=i._zod.def).inclusive,d=c.options.map((e,t)=>a7(e,a,{...s,path:[...s.path,l?"oneOf":"anyOf",t]})),void(l?o.oneOf=d:o.anyOf=d)},e.options=t.options}),sr=rj("ZodIntersection",(e,t)=>{aw.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o,s;return a=a7((i=e._zod.def).left,t,{...n,path:[...n.path,"allOf",0]}),o=a7(i.right,t,{...n,path:[...n.path,"allOf",1]}),void(r.allOf=[...(s=e=>"allOf"in e&&1===Object.keys(e).length)(a)?a.allOf:[a],...s(o)?o.allOf:[o]])}}),sn=rj("ZodRecord",(e,t)=>{a_.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i=e._zod.def;r.type="object";let a=i.keyType,o=a._zod.bag,s=o?.patterns;if("loose"===i.mode&&s&&s.size>0){let e=a7(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});for(let t of(r.patternProperties={},s))r.patternProperties[t.source]=e}else("draft-07"===t.target||"draft-2020-12"===t.target)&&(r.propertyNames=a7(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=a7(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let c=a._zod.values;if(c){let e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}})(e,t,r,n),e.keyType=t.keyType,e.valueType=t.valueType});function si(e,t,r){return new sn(t&&t._zod?{type:"record",keyType:e,valueType:t,...a3.normalizeParams(r)}:{type:"record",keyType:oT(),valueType:e,...a3.normalizeParams(t)})}let sa=rj("ZodEnum",(e,t)=>{aT.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;(i=rK(e._zod.def.entries)).every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{let i={};for(let n of e)if(r.has(n))i[n]=t.entries[n];else throw Error(`Key ${n} not found in enum`);return new sa({...t,checks:[],...a3.normalizeParams(n),entries:i})},e.exclude=(e,n)=>{let i={...t.entries};for(let t of e)if(r.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new sa({...t,checks:[],...a3.normalizeParams(n),entries:i})}});function so(e,t){return new sa({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...a3.normalizeParams(t)})}let ss=rj("ZodTransform",(e,t)=>{aR.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")})(0,e,0,0),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new rB(e.constructor.name);r.addIssue=n=>{"string"==typeof n?r.issues.push(a3.issue(n,r.value,t)):(n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),r.issues.push(a3.issue(n)))};let i=t.transform(r.value,r);return i instanceof Promise?i.then(e=>(r.value=e,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}}),sc=rj("ZodOptional",(e,t)=>{aU.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>oi(e,t,r,n),e.unwrap=()=>e._zod.def.innerType});function sl(e){return new sc({type:"optional",innerType:e})}let sd=rj("ZodExactOptional",(e,t)=>{aO.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>oi(e,t,r,n),e.unwrap=()=>e._zod.def.innerType}),su=rj("ZodNullable",(e,t)=>{aP.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o;return a=a7((i=e._zod.def).innerType,t,n),o=t.seen.get(e),void("openapi-3.0"===t.target?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}])},e.unwrap=()=>e._zod.def.innerType});function sp(e){return new su({type:"nullable",innerType:e})}let sf=rj("ZodDefault",(e,t)=>{aC.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a7((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),sh=rj("ZodPrefault",(e,t)=>{aL.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a7((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},e.unwrap=()=>e._zod.def.innerType}),sm=rj("ZodNonOptional",(e,t)=>{az.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a7((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType},e.unwrap=()=>e._zod.def.innerType}),sy=rj("ZodCatch",(e,t)=>{aN.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>((e,t,r,n)=>{let i,a=e._zod.def;a7(a.innerType,t,n),t.seen.get(e).ref=a.innerType;try{i=a.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i})(e,t,r,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),sg=rj("ZodPipe",(e,t)=>{aj.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i,a,o;return a=(i=e._zod.def).in._zod.traits.has("$ZodTransform"),void(a7(o="input"===t.io?a?i.out:i.in:i.out,t,n),t.seen.get(e).ref=o)},e.in=t.in,e.out=t.out});function sw(e,t){return new sg({type:"pipe",in:e,out:t})}let sb=rj("ZodReadonly",(e,t)=>{aM.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(t,r,n)=>{let i;a7((i=e._zod.def).innerType,t,n),t.seen.get(e).ref=i.innerType,r.readOnly=!0},e.unwrap=()=>e._zod.def.innerType}),sA=rj("ZodCustom",(e,t)=>{aW.init(e,t),o_.init(e,t),e._zod.processJSONSchema=(e,t,r)=>((e,t,r,n)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")})(0,e,0,0)});e.s(["bigint",0,function(e){return new o0({type:"bigint",coerce:!0,...ne(e)})},"boolean",0,function(e){return new oY({type:"boolean",coerce:!0,...ne(e)})},"date",0,function(e){return new o4({type:"date",coerce:!0,...ne(e)})},"number",0,function(e){return new oJ({type:"number",coerce:!0,checks:[],...ne(e)})},"string",0,function(e){return new ox({type:"string",coerce:!0,...ne(e)})}],803099);var sE=e.i(803099),sE=sE;function sv(e){let t=e.split("."),r=parseInt(t[t.length-1]||"0",10);return isNaN(r)?0:r}function sk(e,t){let r={};for(let n in e)r[n]={name:n,value:"",attributes:{...t,maxAge:0}};return r}let s_=e=>(t,r,n)=>{let i=function(e,t){let r={};for(let[n,i]of r$(t.headers?.get("cookie")||""))n.startsWith(e)&&(r[n]=i);return r}(t,n),a=n.context.logger;return{getValue:()=>Object.keys(i).sort((e,t)=>sv(e)-sv(t)).map(e=>i[e]).join(""),hasChunks:()=>Object.keys(i).length>0,chunk(n,o){let s=sk(i,r);for(let e in i)delete i[e];for(let c of function(e,t,r,n){let i=Math.ceil(t.value.length/3896);if(1===i)return r[t.name]=t.value,[t];let a=[];for(let e=0;e<i;e++){let n=`${t.name}.${e}`,i=3896*e,o=t.value.substring(i,i+3896);a.push({...t,name:n,value:o}),r[n]=o}return n.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds allowed 4096 bytes.`,emptyCookieSize:200,valueSize:t.value.length,chunkCount:i,chunks:a.map(e=>e.value.length+200)}),a}(e,{name:t,value:n,attributes:{...r,...o}},i,a))s[c.name]=c;return Object.values(s)},clean(){let e=sk(i,r);for(let e in i)delete i[e];return Object.values(e)},setCookies(e){for(let t of e)n.setCookie(t.name,t.value,t.attributes)}}},sS=s_("Session"),sx=s_("Account");function sT(e,t){let r=e.getCookie(t);if(r)return r;let n=[],i=e.headers?.get("cookie");if(!i)return null;for(let[e,r]of r$(i))if(e.startsWith(t+".")){let t=parseInt(e.split(".").at(-1)||"0",10);isNaN(t)||n.push({index:t,value:r})}return n.length>0?(n.sort((e,t)=>e.index-t.index),n.map(e=>e.value).join("")):null}async function sR(e,t){let r=e.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await rg(t,e.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>4096){let t=sx(r.name,n,e),a=t.chunk(i,n);t.setCookies(a)}else{let t=sx(r.name,n,e);if(t.hasChunks()){let e=t.clean();t.setCookies(e)}e.setCookie(r.name,i,n)}}async function sI(e){let t=sT(e,e.context.authCookies.accountData.name);if(t){let r=(0,rN.safeJSONParse)(await rb(t,e.context.secretConfig,"better-auth-account"));if(r)return r}return null}let sU=sl(se({disableCookieCache:sE.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:sE.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));function sO(e){return e?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function sP(e,t,r){let n="",i=0,a=0;for(let r of e)for(i=i<<8|r,a+=8;a>=6;)a-=6,n+=t[i>>a&63];if(a>0&&(n+=t[i<<6-a&63]),r){let e=(4-n.length%4)%4;n+="=".repeat(e)}return n}function sC(e,t){let r=new Map;for(let e=0;e<t.length;e++)r.set(t[e],e);let n=[],i=0,a=0;for(let t of e){if("="===t)break;let e=r.get(t);if(void 0===e)throw Error(`Invalid Base64 character: ${t}`);i=i<<6|e,(a+=6)>=8&&(a-=8,n.push(i>>a&255))}return Uint8Array.from(n)}let sD={encode(e,t={}){let r=sO(!1);return sP("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){"string"!=typeof e&&(e=new TextDecoder().decode(e));let t=sO(e.includes("-")||e.includes("_"));return sC(e,t)}},sL={encode(e,t={}){let r=sO(!0);return sP("string"==typeof e?new TextEncoder().encode(e):new Uint8Array(e),r,t.padding??!0)},decode(e){let t=sO(e.includes("-")||e.includes("_"));return sC(e,t)}},sz=new Map,s$={decode:(e,t="utf-8")=>(sz.has(t)||sz.set(t,new TextDecoder(t)),sz.get(t).decode(e)),encode:new TextEncoder().encode};function sN(){let e="u">typeof globalThis&&globalThis.crypto;if(e&&"object"==typeof e.subtle&&null!=e.subtle)return e.subtle;throw Error("crypto.subtle must be defined")}let sj=(e="SHA-256",t="none")=>{let r={importKey:async(t,r)=>sN().importKey("raw","string"==typeof t?new TextEncoder().encode(t):t,{name:"HMAC",hash:{name:e}},!1,[r]),sign:async(e,n)=>{"string"==typeof e&&(e=await r.importKey(e,"sign"));let i=await sN().sign("HMAC",e,"string"==typeof n?new TextEncoder().encode(n):n);return"hex"===t?(e=>{if("string"==typeof e&&(e=new TextEncoder().encode(e)),0===e.byteLength)return"";let t=new Uint8Array(e),r="";for(let e of t)r+=e.toString(16).padStart(2,"0");return r})(i):"base64"===t||"base64url"===t||"base64urlnopad"===t?sL.encode(i,{padding:"base64urlnopad"!==t}):i},verify:async(e,n,i)=>("string"==typeof e&&(e=await r.importKey(e,"verify")),"hex"===t&&(i=(e=>{if(!e)return"";if("string"==typeof e){if(e.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(e))throw Error("Invalid hexadecimal string");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return new TextDecoder().decode(t)}return new TextDecoder().decode(e)})(i)),("base64"===t||"base64url"===t||"base64urlnopad"===t)&&(i=await sD.decode(i)),sN().verify("HMAC",e,"string"==typeof i?new TextEncoder().encode(i):i,"string"==typeof n?new TextEncoder().encode(n):n))};return r};function sH(e){let t="string"==typeof e.baseURL?e.baseURL:void 0,r="object"==typeof e.baseURL&&null!==e.baseURL?e.baseURL.protocol:void 0,n=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:"https"===r||"http"!==r&&(t?t.startsWith("https://"):T.isProduction))?"__Secure-":"",i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!C(e.baseURL))throw new E.BetterAuthError("baseURL is required when crossSubdomainCookies are enabled.");return function(t,r={}){let o=e.advanced?.cookiePrefix||"better-auth",s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${n}${s}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...r,...c}}}}function sB(e){let t=sH(e),r=t("session_token",{maxAge:e.session?.expiresIn||Math.round(function(){let e,t=rU.exec("7d");if(!t||t[4]&&t[1])throw TypeError('Invalid time string format: "7d". Use formats like "7d", "30m", "1 hour", etc.');let r=parseFloat(t[2]),n=t[3].toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":e=315576e5*r;break;case"months":case"month":case"mo":e=2592e6*r;break;case"weeks":case"week":case"w":e=6048e5*r;break;case"days":case"day":case"d":e=864e5*r;break;case"hours":case"hour":case"hrs":case"hr":case"h":e=36e5*r;break;case"minutes":case"minute":case"mins":case"min":case"m":e=6e4*r;break;case"seconds":case"second":case"secs":case"sec":case"s":e=1e3*r;break;default:throw TypeError(`Unknown time unit: "${n}"`)}return"-"===t[1]||"ago"===t[4]?-e:e}()/1e3)}),n=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||300}),i=t("account_data",{maxAge:e.session?.cookieCache?.maxAge||300}),a=t("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function sV(e,t,r){let n;if(!e.context.options.session?.cookieCache?.enabled)return;let i=rE(t.session,e.context.options.session?.additionalFields),a=r_(e.context.options,t.user),o=e.context.options.session?.cookieCache?.version,s="1";if(o){if("string"==typeof o)s=o;else if("function"==typeof o){let e=o(t.session,t.user);s=$(e)?await e:e}}let c={session:i,user:a,updatedAt:Date.now(),version:s},l={...e.context.authCookies.sessionData.attributes,maxAge:r?void 0:e.context.authCookies.sessionData.attributes.maxAge},d=rI(l.maxAge||60,"sec").getTime(),u=e.context.options.session?.cookieCache?.strategy||"compact";if((n="jwe"===u?await rg(c,e.context.secretConfig,"better-auth-session",l.maxAge||300):"jwt"===u?await ru(c,e.context.secret,l.maxAge||300):sL.encode(JSON.stringify({session:c,expiresAt:d,signature:await sj("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify({...c,expiresAt:d}))}),{padding:!1})).length>4093){let t=sS(e.context.authCookies.sessionData.name,l,e),r=t.chunk(n,l);t.setCookies(r)}else{let t=sS(e.context.authCookies.sessionData.name,l,e);if(t.hasChunks()){let e=t.clean();t.setCookies(e)}e.setCookie(e.context.authCookies.sessionData.name,n,l)}if(e.context.options.account?.storeAccountCookie){let t=await sI(e);t&&await sR(e,t)}}async function sM(e,t,r,n){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);r=void 0!==r?r:!!i;let a=e.context.authCookies.sessionToken.attributes,o=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...n}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.attributes),await sV(e,t,r),e.context.setNewSession(t)}function sK(e,t){!function(e,t){let r=new Set;e.responseHeaders&&r.add(e.responseHeaders),e.context?.responseHeaders&&r.add(e.context.responseHeaders);let n=`${t}=`,i=`${t}.`;for(let e of r){let t="function"==typeof e.getSetCookie?e.getSetCookie():rP(e.get("set-cookie")||"");if(!t.length)continue;let r=t.filter(e=>!e.startsWith(n)&&!e.startsWith(i));if(r.length!==t.length)for(let t of(e.delete("set-cookie"),r))e.append("set-cookie",t)}}(e,t.name),e.setCookie(t.name,"",{...t.attributes,maxAge:0})}function sW(e,t){if(sK(e,e.context.authCookies.sessionToken),sK(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){sK(e,e.context.authCookies.accountData);let t=sx(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),r=t.clean();t.setCookies(r)}"cookie"===e.context.oauthConfig.storeStateStrategy&&sK(e,e.context.createAuthCookie("oauth_state"));let r=sS(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),n=r.clean();r.setCookies(n),t||sK(e,e.context.authCookies.dontRememberToken)}function sq(e){return aG(oH,void 0).safeParse(e).success||aQ(oB,void 0).safeParse(e).success}function sF(e){if(e.includes("::")){let t=e.split("::"),r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=Array(8-r.length-n.length).fill("0000");return[...r.map(e=>e.padStart(4,"0")),...i,...n.map(e=>e.padStart(4,"0"))]}return e.split(":").map(e=>e.padStart(4,"0"))}function sJ(e,t={}){if(aG(oH,void 0).safeParse(e).success||!aQ(oB,void 0).safeParse(e).success)return e.toLowerCase();let r=function(e){let t=e.toLowerCase();if(t.startsWith("::ffff:")){let e=t.substring(7);if(aG(oH,void 0).safeParse(e).success)return e}let r=e.split(":");if(7===r.length&&r[5]?.toLowerCase()==="ffff"){let e=r[6];if(e&&aG(oH,void 0).safeParse(e).success)return e}if(t.includes("::ffff:")||t.includes(":ffff:")){let t=sF(e);if(8===t.length&&"0000"===t[0]&&"0000"===t[1]&&"0000"===t[2]&&"0000"===t[3]&&"0000"===t[4]&&"ffff"===t[5]&&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}(e);if(r)return r.toLowerCase();var n=t.ipv6Subnet??64;let i=sF(e);if(void 0!==n&&n<128){let e=Math.max(0,Math.floor(n));return i.map(t=>{if(e<=0)return"0000";if(e>=16)return e-=16,t;let r=Number.parseInt(t,16)&(65535<<16-e&65535);return e=0,r.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return i.join(":").toLowerCase()}function sZ(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="headers"in e?e.headers:e;for(let e of t.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"]){let n="get"in r?r.get(e):r[e];if("string"==typeof n){let e=n.split(",")[0].trim();if(sq(e))return sJ(e,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet})}}return(0,T.isTest)()||(0,T.isDevelopment)()?"127.0.0.1":null}function sG(e,t){return{digest:async r=>{let n=new TextEncoder,i="string"==typeof r?n.encode(r):r,a=await sN().digest(e,i);return"hex"===t?Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join(""):"base64"===t||"base64url"===t||"base64urlnopad"===t?t.includes("url")?sL.encode(a,{padding:"base64urlnopad"!==t}):sD.encode(a):a}}}let sQ=async e=>{let t=await sG("SHA-256").digest(new TextEncoder().encode(e));return sL.encode(new Uint8Array(t),{padding:!1})};async function sY(e,t){return t&&"plain"!==t?"hashed"===t?sQ(e):"object"==typeof t&&"hash"in t?t.hash(e):e:e}function sX(e,t){if(t){if("object"==typeof t&&"default"in t){if(t.overrides){for(let[r,n]of Object.entries(t.overrides))if(e.startsWith(r))return n}return t.default}return t}}let s0=Symbol.for("better-auth:global"),s1=null,s2={},s6="1.6.12";function s5(){return globalThis[s0]||(globalThis[s0]={version:s6,epoch:1,context:s2},s1=globalThis[s0]),(s1=globalThis[s0]).version!==s6&&(s1.version=s6,s1.epoch++),globalThis[s0]}let s8=import("node:async_hooks").then(e=>e.AsyncLocalStorage).catch(e=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),e});async function s4(){let e=await s8;if(null!==e)return e;throw Error("getAsyncLocalStorage is only available in server code")}let s3=async()=>{let e=s5();if(!e.context.adapterAsyncStorage){let t=await s4();e.context.adapterAsyncStorage=new t}return e.context.adapterAsyncStorage},s9=async e=>s3().then(t=>t.getStore()?.adapter||e).catch(()=>e),s7=async(e,t)=>{let r=!1;return s3().then(async n=>{let i,a;r=!0;let o=[],s=!1;try{i=await n.run({adapter:e,pendingHooks:o},t)}catch(e){a=e,s=!0}for(let e of o)await e();if(s)throw a;return i}).catch(e=>{if(!r)return t();throw e})},ce=async(e,t)=>s3().then(async r=>{let n,i,a=[],o=!1;try{n=await e.transaction(async e=>r.run({adapter:e,pendingHooks:a},t))}catch(e){o=!0,i=e}for(let e of a)await e();if(o)throw i;return n}).catch(e=>{throw e}),ct=async e=>s3().then(t=>{let r=t.getStore();if(!r)return e();r.pendingHooks.push(e)}).catch(()=>e()),cr=async()=>{let e=s5();if(!e.context.endpointContextAsyncStorage){let t=await s4();e.context.endpointContextAsyncStorage=new t}return e.context.endpointContextAsyncStorage};async function cn(){let e=(await cr()).getStore();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function ci(e,t){return(await cr()).run(e,t)}var ca=e.i(897454);let co="better_auth.operation_id",cs="better_auth.hook.type",cc="better_auth.context";var cl=e.i(969746),cd=e.i(90750);function cu(e,t=Date.now()){return Math.max(Math.floor((("number"==typeof e?e:e.getTime())-t)/1e3),0)}let cp=(e,t)=>{let r,n=t.logger,i=t.options,a=i.secondaryStorage,o=new Map,s=i.session?.expiresIn||604800,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:d,deleteWithHooks:u,deleteManyWithHooks:p,consumeOneWithHooks:f}=(r=t.hooks,{createWithHooks:async function(t,n,i){let a=await cn().catch(()=>null),o=t;for(let{source:e,hooks:t}of r){let r=t[n]?.create?.before;if(r){let t=await (0,cl.withSpan)(`db create.before ${n}`,{[cs]:"create.before",[ca.ATTR_DB_COLLECTION_NAME]:n,[cc]:e},()=>r(o,a));if(!1===t)return null;"object"==typeof t&&"data"in t&&(o={...o,...t.data})}}let s=null;for(let{source:t,hooks:c}of((!i||i.executeMainFn)&&(s=await (await s9(e)).create({model:n,data:o,forceAllowId:!0})),i?.fn&&(s=await i.fn(s??o)),r)){let e=c[n]?.create?.after;e&&await ct(async()=>{await (0,cl.withSpan)(`db create.after ${n}`,{[cs]:"create.after",[ca.ATTR_DB_COLLECTION_NAME]:n,[cc]:t},()=>e(s,a))})}return s},updateWithHooks:async function(t,n,i,a){let o=await cn().catch(()=>null),s=t;for(let{source:e,hooks:n}of r){let r=n[i]?.update?.before;if(r){let n=await (0,cl.withSpan)(`db update.before ${i}`,{[cs]:"update.before",[ca.ATTR_DB_COLLECTION_NAME]:i,[cc]:e},()=>r(t,o));if(!1===n)return null;"object"==typeof n&&"data"in n&&(s={...s,...n.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await (await s9(e)).update({model:i,update:s,where:n}):c;for(let{source:e,hooks:t}of r){let r=t[i]?.update?.after;r&&await ct(async()=>{await (0,cl.withSpan)(`db update.after ${i}`,{[cs]:"update.after",[ca.ATTR_DB_COLLECTION_NAME]:i,[cc]:e},()=>r(l,o))})}return l},updateManyWithHooks:async function(t,n,i,a){let o=await cn().catch(()=>null),s=t;for(let{source:e,hooks:n}of r){let r=n[i]?.update?.before;if(r){let n=await (0,cl.withSpan)(`db updateMany.before ${i}`,{[cs]:"updateMany.before",[ca.ATTR_DB_COLLECTION_NAME]:i,[cc]:e},()=>r(t,o));if(!1===n)return null;"object"==typeof n&&"data"in n&&(s={...s,...n.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await (await s9(e)).updateMany({model:i,update:s,where:n}):c;for(let{source:e,hooks:t}of r){let r=t[i]?.update?.after;r&&await ct(async()=>{await (0,cl.withSpan)(`db updateMany.after ${i}`,{[cs]:"updateMany.after",[ca.ATTR_DB_COLLECTION_NAME]:i,[cc]:e},()=>r(l,o))})}return l},deleteWithHooks:async function(t,n,i){let a=await cn().catch(()=>null),o=null;try{o=(await (await s9(e)).findMany({model:n,where:t,limit:1}))[0]||null}catch{}if(o)for(let{source:e,hooks:t}of r){let r=t[n]?.delete?.before;if(r&&await (0,cl.withSpan)(`db delete.before ${n}`,{[cs]:"delete.before",[ca.ATTR_DB_COLLECTION_NAME]:n,[cc]:e},()=>r(o,a))===!1)return null}let s=i?await i.fn(t):null,c=(!i||i.executeMainFn)&&o?await (await s9(e)).delete({model:n,where:t}):s;if(o)for(let{source:e,hooks:t}of r){let r=t[n]?.delete?.after;r&&await ct(async()=>{await (0,cl.withSpan)(`db delete.after ${n}`,{[cs]:"delete.after",[ca.ATTR_DB_COLLECTION_NAME]:n,[cc]:e},()=>r(o,a))})}return c},deleteManyWithHooks:async function(t,n,i){let a=await cn().catch(()=>null),o=[];try{o=await (await s9(e)).findMany({model:n,where:t})}catch{}for(let e of o)for(let{source:t,hooks:i}of r){let r=i[n]?.delete?.before;if(r&&await (0,cl.withSpan)(`db delete.before ${n}`,{[cs]:"delete.before",[ca.ATTR_DB_COLLECTION_NAME]:n,[cc]:t},()=>r(e,a))===!1)return null}let s=i?await i.fn(t):null,c=!i||i.executeMainFn?await (await s9(e)).deleteMany({model:n,where:t}):s;for(let e of o)for(let{source:t,hooks:i}of r){let r=i[n]?.delete?.after;r&&await ct(async()=>{await (0,cl.withSpan)(`db delete.after ${n}`,{[cs]:"delete.after",[ca.ATTR_DB_COLLECTION_NAME]:n,[cc]:t},()=>r(e,a))})}return c},consumeOneWithHooks:async function(t,n,i,a){let o=await cn().catch(()=>null),s=r.flatMap(({source:e,hooks:r})=>{let n=r[t]?.delete?.before;return n?[{source:e,fn:n}]:[]}),c=a??null;if(s.length){if(!c)try{c=(await (await s9(e)).findMany({model:t,where:n,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:r}of s)if(await (0,cl.withSpan)(`db delete.before ${t}`,{[cs]:"delete.before",[ca.ATTR_DB_COLLECTION_NAME]:t,[cc]:e},()=>r(c,o))===!1)return null}}let l=await i();if(!l)return null;for(let{source:e,hooks:n}of r){let r=n[t]?.delete?.after;r&&await ct(async()=>{await (0,cl.withSpan)(`db delete.after ${t}`,{[cs]:"delete.after",[ca.ATTR_DB_COLLECTION_NAME]:t,[cc]:e},()=>r(l,o))})}return l}});async function h(e){if(!a)return;let t=await a.get(`active-sessions-${e.id}`);if(!t)return;let r=Date.now(),n=((0,rN.safeJSONParse)(t)||[]).filter(e=>e.expiresAt>r);await Promise.all(n.map(async({token:t})=>{let n=await a.get(t);if(!n)return;let i=(0,rN.safeJSONParse)(n);if(!i)return;let o=cu(i.session.expiresAt,r);await a.set(t,JSON.stringify({session:i.session,user:e}),Math.floor(o))}))}async function m(e,t){let r,n=o.get(e)??Promise.resolve(),i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);o.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),o.get(e)===a&&o.delete(e)}}return{createOAuthUser:async(t,r)=>ce(e,async()=>{let e=await c({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},"user",void 0);return{user:e,account:await c({...r,userId:e.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async e=>await c({createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()},"user",void 0),createAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),listSessions:async(r,n)=>{if(a){let e=await a.get(`active-sessions-${r}`);if(!e)return[];let n=(0,rN.safeJSONParse)(e)||[],i=Date.now(),o=new Set,s=[];for(let{token:e,expiresAt:r}of n){if(r<=i||o.has(e))continue;o.add(e);let n=await a.get(e);if(n)try{let e="string"==typeof n?JSON.parse(n):n;if(!e?.session)continue;s.push(rx(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await (await s9(e)).findMany({model:"session",where:[{field:"userId",value:r},...n?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(t,r,n,i)=>await (await s9(e)).findMany({model:"user",limit:t,offset:r,sortBy:n,where:i}),countTotalUsers:async t=>{let r=await (await s9(e)).count({model:"user",where:t});return"string"==typeof r?parseInt(r):r},deleteUser:async e=>{(!a||i.session?.storeSessionInDatabase)&&await p([{field:"userId",value:e}],"session",void 0),await p([{field:"userId",value:e}],"account",void 0),await u([{field:"id",value:e}],"user",void 0)},createSession:async(r,n,o,l)=>{let d,u=await (async()=>{let e=await cn().catch(()=>null);return e?.headers||e?.request?.headers})(),p=i.session?.storeSessionInDatabase,{id:f,...h}=o||{};if(a&&!p){let e=t.generateId({model:"session"});d=!1!==e?e:(0,cd.generateId)()}let m=function(e){let t=rk(e,"session","input"),r={};for(let e in t)void 0!==t[e].defaultValue&&(r[e]="function"==typeof t[e].defaultValue?t[e].defaultValue():t[e].defaultValue);return r}(i),y={...d?{id:d}:{},ipAddress:u&&sZ(u,i)||"",userAgent:u?.get("user-agent")||"",...h,expiresAt:n?rI(86400,"sec"):rI(s,"sec"),userId:r,token:(0,cd.generateId)(32),createdAt:new Date,updatedAt:new Date,...m,...l?h:{}};return await c(y,"session",a?{fn:async t=>{let n=await a.get(`active-sessions-${r}`),i=[],o=Date.now();n&&(i=(i=(0,rN.safeJSONParse)(n)||[]).filter(e=>e.expiresAt>o&&e.token!==y.token));let s=[...i,{token:y.token,expiresAt:y.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=cu(s.at(-1)?.expiresAt??y.expiresAt.getTime(),o);c>0&&await a.set(`active-sessions-${r}`,JSON.stringify(s),c);let l=await (await s9(e)).findOne({model:"user",where:[{field:"id",value:r}]}),d=cu(y.expiresAt,o);return d>0&&await a.set(y.token,JSON.stringify({session:t,user:l}),d),t},executeMainFn:p}:void 0)},findSession:async r=>{if(a){let e=await a.get(r);if(!e&&(!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let r=(0,rN.safeJSONParse)(e);return r?{session:rx(t.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),user:r_(t.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)})}:null}}let n=await (await s9(e)).findOne({model:"session",where:[{value:r,field:"token"}],join:{user:!0}});if(!n)return null;let{user:o,...s}=n;return o?{session:rx(t.options,s),user:r_(t.options,o)}:null},findSessions:async(t,r)=>{if(a){let e=[];for(let n of t){let t=await a.get(n);if(t)try{let n="string"==typeof t?JSON.parse(t):t;if(!n)return[];let i=new Date(n.session.expiresAt);if(r?.onlyActiveSessions&&i<=new Date)continue;let a={session:{...n.session,expiresAt:new Date(n.session.expiresAt)},user:{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)}};e.push(a)}catch{continue}}return e}let n=await (await s9(e)).findMany({model:"session",where:[{field:"token",value:t,operator:"in"},...r?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});return!n.length||n.some(e=>!e.user)?[]:n.map(e=>{let{user:t,...r}=e;return{session:r,user:t}})},updateSession:async(e,r)=>await l(r,[{field:"token",value:e}],"session",a?{async fn(r){let n=await a.get(e);if(!n)return null;let i=(0,rN.safeJSONParse)(n);if(!i)return null;let o={...i.session,...r,expiresAt:new Date(r.expiresAt??i.session.expiresAt),createdAt:new Date(i.session.createdAt),updatedAt:new Date(r.updatedAt??i.session.updatedAt)},s=rx(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),d=cu(l,c);if(d>0){await a.set(e,JSON.stringify({session:s,user:i.user}),d);let t=`active-sessions-${s.userId}`,r=await a.get(t),n=(r&&(0,rN.safeJSONParse)(r)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=n.at(-1)?.expiresAt;o&&o>c?await a.set(t,JSON.stringify(n),cu(o,c)):await a.delete(t)}return s},executeMainFn:i.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(a){let r=await a.get(e);if(r){let{session:t}=(0,rN.safeJSONParse)(r)??{};if(!t)return void n.error("Session not found in secondary storage");let i=t.userId,o=await a.get(`active-sessions-${i}`);if(o){let t=(0,rN.safeJSONParse)(o)||[],r=Date.now(),n=t.filter(t=>t.expiresAt>r&&t.token!==e),s=n.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;n.length>0&&s&&s>Date.now()?await a.set(`active-sessions-${i}`,JSON.stringify(n),cu(s,r)):await a.delete(`active-sessions-${i}`)}else n.error("Active sessions list not found in secondary storage")}if(await a.delete(e),!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await u([{field:"token",value:e}],"session",void 0)},deleteAccounts:async e=>{await p([{field:"userId",value:e}],"account",void 0)},deleteAccount:async e=>{await u([{field:"id",value:e}],"account",void 0)},deleteSessions:async e=>{if(a){if("string"==typeof e){let t=await a.get(`active-sessions-${e}`),r=t?(0,rN.safeJSONParse)(t):[];if(!r)return;for(let e of r)await a.delete(e.token);await a.delete(`active-sessions-${e}`)}else for(let t of e)await a.get(t)&&await a.delete(t);if(!i.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase)return}await p([{field:Array.isArray(e)?"token":"userId",value:e,operator:Array.isArray(e)?"in":void 0}],"session",void 0)},findOAuthUser:async(t,r,n)=>{let i=await (await s9(e)).findOne({model:"account",where:[{value:r,field:"accountId"},{value:n,field:"providerId"}],join:{user:!0}});if(i)if(i.user)return{user:i.user,linkedAccount:i,accounts:[i]};else{let r=await (await s9(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}]});return r?{user:r,linkedAccount:i,accounts:[i]}:null}{let r=await (await s9(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}]});return r?{user:r,linkedAccount:null,accounts:await (await s9(e)).findMany({model:"account",where:[{value:r.id,field:"userId"}]})||[]}:null}},findUserByEmail:async(t,r)=>{let n=await (await s9(e)).findOne({model:"user",where:[{value:t.toLowerCase(),field:"email"}],join:{...r?.includeAccounts?{account:!0}:{}}});if(!n)return null;let{account:i,...a}=n;return{user:a,accounts:i??[]}},findUserById:async t=>t?await (await s9(e)).findOne({model:"user",where:[{field:"id",value:t}]}):null,linkAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},"account",void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"id",value:e}],"user",void 0);return await h(r),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:"email",value:e.toLowerCase()}],"user",void 0);return await h(r),r},updatePassword:async(e,t)=>{await d({password:t},[{field:"userId",value:e},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async t=>await (await s9(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),findAccount:async t=>await (await s9(e)).findOne({model:"account",where:[{field:"accountId",value:t}]}),findAccountByProviderId:async(t,r)=>await (await s9(e)).findOne({model:"account",where:[{field:"accountId",value:t},{field:"providerId",value:r}]}),findAccountByUserId:async t=>await (await s9(e)).findMany({model:"account",where:[{field:"userId",value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:"id",value:e}],"account",void 0),createVerificationValue:async e=>{let t=sX(e.identifier,i.verification?.storeIdentifier),r=await sY(e.identifier,t);return await c({createdAt:new Date,updatedAt:new Date,...e,identifier:r},"verification",a?{async fn(e){let t=cu(e.expiresAt);return t>0&&await a.set(`verification:${r}`,JSON.stringify(e),t),e},executeMainFn:i.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let r=sX(t,i.verification?.storeIdentifier),n=await sY(t,r);if(a){let e=await a.get(`verification:${n}`);if(e){let t=(0,rN.safeJSONParse)(e);if(t)return t}if(r&&"plain"!==r){let e=await a.get(`verification:${t}`);if(e){let t=(0,rN.safeJSONParse)(e);if(t)return t}}if(!i.verification?.storeInDatabase)return null}let o=await s9(e);async function s(e){return o.findMany({model:"verification",where:[{field:"identifier",value:e}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let c=await s(n);return!c.length&&r&&"plain"!==r&&(c=await s(t)),i.verification?.disableCleanup||await p([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await sY(e,sX(e,i.verification?.storeIdentifier));a&&await a.delete(`verification:${t}`),(!a||i.verification?.storeInDatabase)&&await u([{field:"identifier",value:t}],"verification",void 0)},consumeVerificationValue:async t=>{let r=sX(t,i.verification?.storeIdentifier),n=await sY(t,r),o=r&&"plain"!==r?[n,t]:[n],s=e=>{if(!e)return null;let t="string"==typeof e?(0,rN.safeJSONParse)(e):"object"==typeof e?e:null;if(!t)return null;let r=new Date(t.expiresAt);return Number.isFinite(r.getTime())?{...t,expiresAt:r}:null},c=null;if(a&&!i.verification?.storeInDatabase){let e=async e=>a.getAndDelete?s(await a.getAndDelete(e)):m(e,async()=>{let t=s(await a.get(e));return t?(await a.delete(e),t):null});for(let t of o){let r=await e(`verification:${t}`);if(r){await Promise.all(o.filter(e=>e!==t).map(e=>a.delete(`verification:${e}`))),c=r;break}}}else{let t=async t=>m(`verification:${t}`,()=>ce(e,async()=>{let r=await s9(e),n=[{field:"identifier",value:t}],i=(await r.findMany({model:"verification",where:n,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;return i?f("verification",[{field:"id",value:i.id}],async()=>{let e=await r.consumeOne({model:"verification",where:[{field:"id",value:i.id}]});return e?(await r.deleteMany({model:"verification",where:n}),e):null},i):null}));for(let e of o)if(c=await t(e))break;c&&a&&await Promise.all(o.map(e=>a.delete(`verification:${e}`)))}return!c||c.expiresAt<new Date?null:c},updateVerificationByIdentifier:async(e,t)=>{let r=await sY(e,sX(e,i.verification?.storeIdentifier));if(a){let e=await a.get(`verification:${r}`);if(e){let n=(0,rN.safeJSONParse)(e);if(n){let e={...n,...t},o=e.expiresAt??n.expiresAt,s=cu(o instanceof Date?o:new Date(o));if(s>0&&await a.set(`verification:${r}`,JSON.stringify(e),s),!i.verification?.storeInDatabase)return e}}}return!a||i.verification?.storeInDatabase?await l(t,[{field:"identifier",value:r}],"verification",void 0):t},refreshUserSessions:h}};function cf(e){if(null===e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.iterator in e)&&(!(Symbol.toStringTag in e)||"[object Module]"===Object.prototype.toString.call(e))}function ch(e){return(...t)=>t.reduce((t,r)=>(function e(t,r,n=".",i){if(!cf(r))return e(t,{},n,i);let a={...r};for(let r of Object.keys(t)){if("__proto__"===r||"constructor"===r)continue;let o=t[r];null!=o&&(i&&i(a,r,o,n)||(Array.isArray(o)&&Array.isArray(a[r])?a[r]=[...o,...a[r]]:cf(o)&&cf(a[r])?a[r]=e(o,a[r],(n?`${n}.`:"")+r.toString(),i):a[r]=o))}return a})(t,r,"",e),{})}let cm=ch();ch((e,t,r)=>{if(void 0!==e[t]&&"function"==typeof r)return e[t]=r(e[t]),!0}),ch((e,t,r)=>{if(Array.isArray(e[t])&&"function"==typeof r)return e[t]=r(e[t]),!0});let cy=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function cg(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function cw(e){let t=e.split(".");return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function cb(e,t,r){if(0===r)return!0;let n=32===r?0xffffffff:-1<<32-r>>>0;return(e&n)==(t&n)}function cA(e){if("0.0.0.0"===e)return"unspecified";if("255.255.255.255"===e)return"broadcast";let t=cw(e);return cb(t,cw("127.0.0.0"),8)?"loopback":cb(t,cw("10.0.0.0"),8)||cb(t,cw("172.16.0.0"),12)||cb(t,cw("192.168.0.0"),16)?"private":cb(t,cw("169.254.0.0"),16)?"linkLocal":cb(t,cw("100.64.0.0"),10)?"sharedAddressSpace":cb(t,cw("192.0.2.0"),24)||cb(t,cw("198.51.100.0"),24)||cb(t,cw("203.0.113.0"),24)?"documentation":cb(t,cw("198.18.0.0"),15)?"benchmarking":cb(t,cw("224.0.0.0"),4)?"multicast":cb(t,cw("0.0.0.0"),8)||cb(t,cw("192.0.0.0"),24)||cb(t,cw("240.0.0.0"),4)?"reserved":"public"}function cE(e,t,r={}){let n=5*t,i=Number.parseInt(e.slice(n,n+4),16),a=Number.parseInt(e.slice(n+5,n+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return r.xor&&(o=(0xffffffff^o)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${255&o}`}async function cv(e){let t=e.options,r=t.plugins||[],n=[],i=[];for(let a of r)if(a.init){let r,o=a.init(e);if("object"==typeof(r=$(o)?await o:o)){if(r.options){let{databaseHooks:e,trustedOrigins:o,...s}=r.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),o&&n.push(o),t=cm(t,s)}r.context&&Object.assign(e,r.context)}}if(n.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...n],r=e.filter(Array.isArray).flat(),i=e.filter(e=>"function"==typeof e);i.length>0?t.trustedOrigins=async e=>[...r,...(await Promise.all(i.map(t=>t(e)))).flat()].filter(e=>"string"==typeof e&&""!==e):t.trustedOrigins=r}t.databaseHooks&&i.push({source:"user",hooks:t.databaseHooks}),e.internalAdapter=cp(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}async function ck(e,t){let r=[];if(C(e.baseURL)){let t=e.baseURL.allowedHosts,n=e.baseURL.protocol;for(let e of t)e.includes("://")?r.push(e):(n&&"https"!==n&&"auto"!==n||r.push(`https://${e}`),("http"===n||"auto"===n||function(e){let t=function(e){var t,r;let n,i=(-1===(n=(r=(t=function(e){if(e.startsWith("[")){let t=e.indexOf("]");return -1===t?e:e.slice(0,t+1)}let t=e.indexOf(":");return -1===t||-1!==e.indexOf(":",t+1)?e:e.slice(0,t)}(e.trim())).length>=2&&t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t).indexOf("%"))?r:r.slice(0,n)).replace(/\.+$/,"").toLowerCase();if(""===i)return{kind:"reserved",literal:"fqdn",canonical:""};if(!sq(i))return"localhost"===i||i.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:i}:cy.has(i)?{kind:"cloudMetadata",literal:"fqdn",canonical:i}:{kind:"public",literal:"fqdn",canonical:i};if(cg(i))return{kind:cA(i),literal:"ipv4",canonical:i};let a=sJ(i,{ipv6Subnet:128});return cg(a)?{kind:cA(a),literal:"ipv4",canonical:a}:{kind:function(e){if("0000:0000:0000:0000:0000:0000:0000:0000"===e)return"unspecified";if("0000:0000:0000:0000:0000:0000:0000:0001"===e)return"loopback";let t=Number.parseInt(e.slice(0,2),16),r=Number.parseInt(e.slice(2,4),16);if(255===t)return"multicast";if(254===t&&(192&r)==128)return"linkLocal";if((254&t)==252)return"private";if(e.startsWith("2001:0db8:"))return"documentation";if(e.startsWith("2002:")){let t=cE(e,1);return t&&"public"!==cA(t)?"reserved":"public"}if(e.startsWith("0064:ff9b:0000:0000:0000:0000:")){let t=cE(e,6);return t&&cA(t),"reserved"}if(e.startsWith("2001:0000:")){let t=cE(e,6,{xor:!0});return t&&cA(t),"reserved"}return e.startsWith("0100:0000:0000:0000:")?"reserved":"public"}(a),literal:"ipv6",canonical:a}}(e).kind;return"loopback"===t||"localhost"===t}(e))&&r.push(`http://${e}`));if(e.baseURL.fallback)try{r.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let n=O("string"==typeof e.baseURL?e.baseURL:void 0,e.basePath,t);n&&r.push(new URL(n).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&r.push(...e.trustedOrigins),"function"==typeof e.trustedOrigins)){let n=await e.trustedOrigins(t);r.push(...n)}let n=T.env.BETTER_AUTH_TRUSTED_ORIGINS;return n&&r.push(...n.split(",")),r.filter(e=>!!e)}function c_(e){return e.advanced?.trustedProxyHeaders??!0}async function cS(e,t,r){let n,i=e.options.baseURL,a=function(e,t,r,n,i){if(C(e)){if(r){let n=L(r,i);if(!n){if(e.fallback)return I(e.fallback,t);throw new E.BetterAuthError("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(e.allowedHosts.some(e=>((e,t)=>{if(!e||!t)return!1;let r=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?x(n)(r):r.toLowerCase()===n.toLowerCase()})(n,e)))return I(`${function(e,t,r){let n;if("http"===t||"https"===t)return t;let i=D(e)?e.headers:e;if(r){let e=i.get("x-forwarded-proto");if(e&&U(e,"proto"))return e}if(D(e))try{let t=new URL(e.url);if("http:"===t.protocol||"https:"===t.protocol)return t.protocol.slice(0,-1)}catch{}let a=L(e,r);return a&&("localhost"===(n=a.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||n.endsWith(".localhost")||"::1"===n||n.startsWith("127."))?"http":"https"}(r,e.protocol,i)}://${n}`,t);if(e.fallback)return I(e.fallback,t);throw new E.BetterAuthError(`Host "${n}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}return e.fallback?I(e.fallback,t):O(void 0,t,void 0,n,i)}let a=D(r)?r:void 0;return"string"==typeof e?O(e,t,a,n,i):O(void 0,t,a,n,i)}(i,e.options.basePath||"/api/auth",t,void 0,r);if(!a)throw new E.BetterAuthError("Could not resolve base URL from request. Check your allowedHosts config.");let o=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));o.baseURL=a,o.options={...e.options,baseURL:P(a)||void 0};let s={...o.options,baseURL:i};return n="function"==typeof e.options.trustedOrigins||"function"==typeof e.options.account?.accountLinking?.trustedProviders?D(t)?t:t?new Request(a,{headers:t}):void 0:void 0,o.trustedOrigins=await ck(s,n),o.trustedProviders=await cT(o.options,n),e.options.advanced?.crossSubDomainCookies?.enabled&&(o.authCookies=sB(o.options),o.createAuthCookie=sH(o.options)),o}async function cx(e,t){if(e)for(let r of e){let e="function"==typeof r?await r():r;if(e[t.field??"id"]===t.value)return e}}async function cT(e,t){let r=e.account?.accountLinking?.trustedProviders;return r?Array.isArray(r)?r.filter(e=>!!e):(await r(t)??[]).filter(e=>!!e):[]}async function cR(e,t){let r=(await e.context.internalAdapter.findAccounts(t.userId))?.find(e=>"credential"===e.providerId),n=r?.password;return!!r&&!!n&&await e.context.password.verify({hash:n,password:t.password})}async function cI(e,t){let r=(await t.context.internalAdapter.findAccounts(e))?.find(e=>"credential"===e.providerId),n=r?.password,i=t.body.password;if(!r||!n||!i)throw i&&await t.context.password.hash(i),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_PASSWORD);if(!await t.context.password.verify({hash:n,password:i}))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_PASSWORD);return!0}var cU=e.i(329604);let cO=/^application\/([a-z0-9.+-]*\+)?json/i;async function cP(e,t){let r=e.headers.get("content-type")||"",n=r.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=n.split(";")[0].trim(),r=e.toLowerCase().trim();return t===r||t.includes(r)})){if(!n)throw new cU.APIError(415,{message:`Content-Type is required. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new cU.APIError(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${t.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(cO.test(n))return await e.json();if(n.includes("application/x-www-form-urlencoded")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e.toString()}),r}if(n.includes("multipart/form-data")){let t=await e.formData(),r={};return t.forEach((e,t)=>{r[t]=e}),r}return n.includes("text/plain")?await e.text():n.includes("application/octet-stream")?await e.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await e.blob():n.includes("application/stream")||e.body instanceof ReadableStream?e.body:await e.text()}}function cC(e){return e instanceof cU.APIError||e?.name==="APIError"}async function cD(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function cL(e){return e instanceof Request||"[object Request]"===Object.prototype.toString.call(e)}let cz=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"]);function c$(e){for(let t of cz)e.delete(t)}function cN(e,t){if(e instanceof Response){if(t?.headers){let r=new Headers(t.headers);c$(r),r.forEach((t,r)=>{e.headers.set(r,t)})}return e}if(e&&"object"==typeof e&&"_flag"in e&&"json"===e._flag){let r=e.body,n=e.routerResponse;if(n instanceof Response)return n;let i=new Headers;if(n?.headers){let e=new Headers(n.headers);for(let[t,r]of e.entries())e.set(t,r)}if(e.headers)for(let[t,r]of new Headers(e.headers).entries())i.set(t,r);if(t?.headers){let e=new Headers(t.headers);for(let[t,r]of(c$(e),e.entries()))i.set(t,r)}return i.set("Content-Type","application/json"),new Response(JSON.stringify(r),{...n,headers:i,status:e.status??t?.status??n?.status,statusText:t?.statusText??n?.statusText})}if(cC(e))return cN(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let r=e,n=new Headers(t?.headers);if(c$(n),e){if("string"==typeof e)r=e,n.set("Content-Type","text/plain");else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=e,n.set("Content-Type","application/octet-stream");else if(e instanceof Blob)r=e,n.set("Content-Type",e.type||"application/octet-stream");else if(e instanceof FormData)r=e;else if(e instanceof URLSearchParams)r=e,n.set("Content-Type","application/x-www-form-urlencoded");else if(e instanceof ReadableStream)r=e,n.set("Content-Type","application/octet-stream");else if(function(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}(e)){let t,i;t=0,i=new WeakMap,r=JSON.stringify(e,(e,r)=>{if("bigint"==typeof r)return r.toString();if("object"==typeof r&&null!==r){if(i.has(r))return`[Circular ref-${i.get(r)}]`;i.set(r,t++)}return r},void 0),n.set("Content-Type","application/json")}}else null===e&&(r=JSON.stringify(null)),n.set("content-type","application/json");return new Response(r,{...t,headers:n})}let cj={name:"HMAC",hash:"SHA-256"},cH=async e=>{let t="string"==typeof e?new TextEncoder().encode(e):e;return await sN().importKey("raw",t,cj,!1,["sign","verify"])},cB=async(e,t,r)=>{try{let n=atob(e),i=new Uint8Array(n.length);for(let e=0,t=n.length;e<t;e++)i[e]=n.charCodeAt(e);return await sN().verify(cj,r,i,new TextEncoder().encode(t))}catch(e){return!1}},cV=async(e,t)=>{let r=await cH(t);return btoa(String.fromCharCode(...new Uint8Array(await sN().sign(cj.name,r,new TextEncoder().encode(e)))))},cM=async(e,t)=>{let r=await cV(e,t);return encodeURIComponent(e=`${e}.${r}`)},cK=(e,t)=>{let r=e;if(t)if("secure"===t)r="__Secure-"+e;else{if("host"!==t)return;r="__Host-"+e}return r},cW=(e,t,r={})=>{let n;if(n=r?.prefix==="secure"?`__Secure-${e}=${t}`:r?.prefix==="host"?`__Host-${e}=${t}`:`${e}=${t}`,e.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),e.startsWith("__Host-")&&(r.secure||(r.secure=!0),"/"!==r.path&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&"number"==typeof r.maxAge&&r.maxAge>=0){if(r.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&"host"!==r.prefix&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},cq=async(e,t,r,n)=>cW(e,t=await cM(t,r),n);async function cF(e,t={}){let r={body:t.body,query:t.query};if(e.body){let n=await e.body["~standard"].validate(t.body);if(n.issues)return{data:null,error:cJ(n.issues,"body")};r.body=n.value}if(e.query){let n=await e.query["~standard"].validate(t.query);if(n.issues)return{data:null,error:cJ(n.issues,"query")};r.query=n.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:"Headers is required",issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:r,error:null}}function cJ(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>"object"==typeof e?e.key:e).join("."):t}] ${e.message}`).join("; "),issues:e}}let cZ=async(e,{options:t,path:r})=>{let n,i=new Headers,{data:a,error:o}=await cF(t,e);if(o)throw new cU.ValidationError(o.message,o.issues);let s="headers"in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):"request"in e&&cL(e.request)?e.request.headers:null,c=s?.get("cookie"),l=c?function(e){if("string"!=typeof e)throw TypeError("argument str must be a string");let t=new Map,r=0;for(;r<e.length;){let n=e.indexOf("=",r);if(-1===n)break;let i=e.indexOf(";",r);if(-1===i)i=e.length;else if(i<n){r=e.lastIndexOf(";",n-1)+1;continue}let a=e.slice(r,n).trim();if(!t.has(a)){let r=e.slice(n+1,i).trim();34===r.codePointAt(0)&&(r=r.slice(1,-1)),t.set(a,function(e){try{return e.includes("%")?decodeURIComponent(e):e}catch{return e}}(r))}r=i+1}return t}(c):void 0,d={...e,body:a.body,query:a.query,path:e.path||r||"virtual:",context:"context"in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:"params"in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:"*"===t.method?"GET":t.method),setHeader:(e,t)=>{i.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let r=cK(e,t);return r&&l?.get(r)||null},getSignedCookie:async(e,t,r)=>{let n=cK(e,r);if(!n)return null;let i=l?.get(n);if(!i)return null;let a=i.lastIndexOf(".");if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return 44===s.length&&s.endsWith("=")?!!await cB(s,o,await cH(t))&&o:null},setCookie:(e,t,r)=>{var n;let a=cW(e,n=encodeURIComponent(n=t),r);return i.append("set-cookie",a),a},setSignedCookie:async(e,t,r,n)=>{let a=await cq(e,t,r,n);return i.append("set-cookie",a),a},redirect:e=>(i.set("location",e),new cU.APIError("FOUND",void 0,i)),error:(e,t,r)=>new cU.APIError(e,t,r),setStatus:e=>{n=e},json:(t,r)=>e.asResponse?{body:r?.body||t,routerResponse:r,_flag:"json"}:t,responseHeaders:i,get responseStatus(){return n}};for(let e of t.use||[]){let t=await e({...d,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(d.context,t.response),t.headers&&t.headers.forEach((e,t)=>{d.responseHeaders.set(t,e)})}return d};function cG(e,t,r){let n="string"==typeof e?e:void 0,i="object"==typeof t?t:e,a="function"==typeof t?t:r;if(("GET"===i.method||"HEAD"===i.method)&&i.body)throw new cU.BetterCallError("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new cU.BetterCallError("Path cannot contain consecutive slashes");let o=async(...e)=>{let t=e[0]||{},{data:r,error:o}=await cD(cZ(t,{options:i,path:n}));if(o){if(!(o instanceof cU.ValidationError))throw o;throw i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new cU.APIError(400,{message:o.message,code:"VALIDATION_ERROR"})}let s=await a(r).catch(async e=>{if(cC(e)){let r=i.onAPIError;if(r&&await r(e),t.asResponse)return e}throw e}),c=r.responseHeaders,l=r.responseStatus;return t.asResponse?cN(s,{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=n,o}function cQ(e,t){let r=async r=>{let n="function"==typeof e?e:t,i=await cZ(r,{options:"function"==typeof e?{}:e,path:"/"});if(!n)throw Error("handler must be defined");try{let e=await n(i),t=i.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw cC(e)&&Object.defineProperty(e,cU.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,get:()=>i.responseHeaders}),e}};return r.options="function"==typeof e?{}:e,r}cG.create=e=>(t,r,n)=>cG(t,{...r,use:[...r?.use||[],...e?.use||[]]},n),cQ.create=e=>function(t,r){if("function"==typeof t)return cQ({use:e?.use},t);if(!r)throw Error("Middleware handler is required");return cQ({...t,method:"*",use:[...e?.use||[],...t.use||[]]},r)};let cY={};function cX(e){switch(e.constructor.name){case"ZodString":default:return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array"}}function c0(e){let t=[];return e.metadata?.openapi?.parameters?t.push(...e.metadata.openapi.parameters):e.query instanceof o7&&Object.entries(e.query.shape).forEach(([e,r])=>{r instanceof o7&&t.push({name:e,in:"query",schema:{type:cX(r),..."minLength"in r&&r.minLength?{minLength:r.minLength}:{},description:r.description}})}),t}function c1(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function c2(e,t){return Object.entries(e).forEach(([e,t])=>{let r=t.options;if(!(!t.path||r.metadata?.SERVER_ONLY)&&("GET"===r.method&&(cY[t.path]={get:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:c0(r),responses:c1(r.metadata?.openapi?.responses)}}),"POST"===r.method)){let e=function(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof o7||e.body instanceof sc)){let t=e.body.shape;if(!t)return;let r={},n=[];return Object.entries(t).forEach(([e,t])=>{t instanceof o7&&(r[e]={type:cX(t),description:t.description},t instanceof sc||n.push(e))}),{required:!(e.body instanceof sc)&&!!e.body,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}(r);cY[t.path]={post:{tags:["Default",...r.metadata?.openapi?.tags||[]],description:r.metadata?.openapi?.description,operationId:r.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:c0(r),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:c1(r.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:cY}}let c6=((s=function(){}).prototype=Object.create(null),Object.freeze(s.prototype),s);function c5(){return{root:{key:""},static:new c6}}function c8(e){let[t,...r]=e.split("/");return""===r[r.length-1]?r.slice(0,-1):r}function c4(e,t){let r=new c6;for(let[n,i]of t){let t=n<0?e.slice(-(n+1)).join("/"):e[n];if("string"==typeof i)r[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)r[t]=e.groups[t]}}return r}function c3(e,t="",r,n){t=t.toUpperCase(),47!==r.charCodeAt(0)&&(r=`/${r}`);let i=c8(r=r.replace(/\\:/g,"%3A")),a=e.root,o=0,s=[],c=[];for(let e=0;e<i.length;e++){let t=i[e];if(t.startsWith("**")){a.wildcard||(a.wildcard={key:"**"}),a=a.wildcard,s.push([-(e+1),t.split(":")[1]||"_",2===t.length]);break}if("*"===t||t.includes(":")){if(a.param||(a.param={key:"*"}),a=a.param,"*"===t)s.push([e,`_${o++}`,!0]);else if(t.includes(":",1)){let r=function(e){let t=e.replace(/:(\w+)/g,(e,t)=>`(?<${t}>[^/]+)`).replace(/\./g,"\\.");return RegExp(`^${t}$`)}(t);c[e]=r,a.hasRegexParam=!0,s.push([e,r,!1])}else s.push([e,t.slice(1),!1]);continue}"\\*"===t?t=i[e]="*":"\\*\\*"===t&&(t=i[e]="**");let r=a.static?.[t];if(r)a=r;else{let e={key:t};a.static||(a.static=new c6),a.static[t]=e,a=e}}let l=s.length>0;a.methods||(a.methods=new c6),a.methods[t]??=[],a.methods[t].push({data:n||null,paramsRegexp:c,paramsMap:l?s:void 0}),l||(e.static["/"+i.join("/")]=a)}function c9(e){return e instanceof cU.APIError||e instanceof E.APIError||e?.name==="APIError"}let c7=cQ(async()=>({})),le=cQ.create({use:[c7,cQ(async()=>({}))]}),lt=[c7];function lr(e,t,r){let n="string"==typeof e?e:void 0,i="object"==typeof t?t:e,a="function"==typeof t?t:r,o=async e=>{try{return await ci(e,()=>a(e))}catch(r){var t;throw t=e.responseHeaders,c9(r)&&t&&Object.defineProperty(r,cU.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,value:t,writable:!1}),r}};return n?cG(n,{...i,use:[...i?.use||[],...lt]},o):cG({...i,use:[...i?.use||[],...lt]},o)}function ln(e,t){let r;try{r=new URL(e).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}return"/"===t||""===t?r:r===t?"/":r.startsWith(t+"/")?r.slice(t.length).replace(/\/+$/,"")||"/":r}function li(e){return!0===e.context.skipOriginCheck&&e.context.options.advanced?.disableCSRFCheck===void 0}function la(e){let t=e.context.skipOriginCheck;if(!0===t)return!0;if(Array.isArray(t)&&e.request)try{let r=new URL(e.context.baseURL).pathname,n=ln(e.request.url,r);return t.some(e=>n.startsWith(e))}catch{}return!1}let lo=(h=function(){},c=!1,function(...e){return c||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),c=!0),h.apply(this,e)}),ls=le(async e=>{if(e.request?.method==="GET"||e.request?.method==="OPTIONS"||e.request?.method==="HEAD"||!e.request||(await ll(e),la(e)))return;let{body:t,query:r}=e,n=t?.callbackURL||r?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,r)=>{if(t&&!e.context.isTrustedOrigin(t,{allowRelativePaths:"origin"!==r})){if(e.context.logger.error(`Invalid ${r}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config
63
+ `,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),"origin"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_ORIGIN);if("callbackURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_CALLBACK_URL);if("redirectURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);throw E.APIError.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};n&&s(n,"callbackURL"),i&&s(i,"redirectURL"),a&&s(a,"errorCallbackURL"),o&&s(o,"newUserCallbackURL")}),lc=e=>le(async t=>{if(!t.request||la(t))return;let r=e(t),n=(e,r)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:"origin"!==r})){if(t.context.logger.error(`Invalid ${r}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config
64
+ `,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),"origin"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_ORIGIN);if("callbackURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_CALLBACK_URL);if("redirectURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_REDIRECT_URL);if("errorCallbackURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===r)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_NEW_USER_CALLBACK_URL);throw E.APIError.fromStatus("FORBIDDEN",{message:`Invalid ${r}`})}};for(let e of Array.isArray(r)?r:[r])n(e,"callbackURL")});async function ll(e,t=!1){let r=e.request?.headers;if(!r||!e.request)return;let n=r.get("origin")||r.get("referer")||"",i=r.has("cookie");if(e.context.skipCSRFCheck)return;if(li(e)){e.context.options.advanced?.disableOriginCheck===!0&&lo();return}if(la(e)||!(t||i))return;if(!n||"null"===n)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN);let a=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!a.some(e=>z(n,e)))throw e.context.logger.error(`Invalid origin: ${n}`),e.context.logger.info(`If it's a valid URL, please add ${n} to trustedOrigins in your auth config
65
+ `,`Current list of trustedOrigins: ${a}`),E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.INVALID_ORIGIN)}let ld=le(async e=>{e.request&&await lu(e)});async function lu(e){let t=e.request;if(!t||e.context.skipCSRFCheck||li(e))return;let r=t.headers;if(r.has("cookie"))return await ll(e);let n=r.get("Sec-Fetch-Site"),i=r.get("Sec-Fetch-Mode"),a=r.get("Sec-Fetch-Dest");if(n&&n.trim()||i&&i.trim()||a&&a.trim()){if("cross-site"===n&&"navigate"===i)throw e.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:n,secFetchMode:i,secFetchDest:a}),E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await ll(e,!0)}}let lp=new Map;function lf(e,t){let r,n;if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let i=e.rateLimit.storage;return"secondary-storage"===i?{get:async t=>{let r=await e.options.secondaryStorage?.get(t);return r?(0,rN.safeJSONParse)(r):null},set:async(r,n,i)=>{let a=t?.window??e.options.rateLimit?.window??10;await e.options.secondaryStorage?.set?.(r,JSON.stringify(n),a)}}:"memory"===i?{async get(e){let t=lp.get(e);return t?Date.now()>=t.expiresAt?(lp.delete(e),null):t.data:null},async set(r,n,i){let a=t?.window??e.options.rateLimit?.window??10,o=Date.now()+1e3*a;lp.set(r,{data:n,expiresAt:o})}}:(r="rateLimit",n=e.adapter,{get:async e=>{let t=(await n.findMany({model:r,where:[{field:"key",value:e}]}))[0];return"bigint"==typeof t?.lastRequest&&(t.lastRequest=Number(t.lastRequest)),t},set:async(t,i,a)=>{try{a?await n.updateMany({model:r,where:[{field:"key",value:t}],update:{count:i.count,lastRequest:i.lastRequest}}):await n.create({model:r,data:{key:t,count:i.count,lastRequest:i.lastRequest}})}catch(t){e.logger.error("Error setting rate limit",t)}}})}let lh=!1;async function lm(e,t){let r=new URL(t.baseURL).pathname,n=ln(e.url,r),i=t.rateLimit.window,a=t.rateLimit.max,o=sZ(e,t.options);if(!o)return lh||(t.logger.warn("Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."),lh=!0),null;let s=`${o}|${n}`,c=[{pathMatcher:e=>e.startsWith("/sign-in")||e.startsWith("/sign-up")||e.startsWith("/change-password")||e.startsWith("/change-email"),window:10,max:3},{pathMatcher:e=>"/request-password-reset"===e||"/send-verification-email"===e||e.startsWith("/forget-password")||"/email-otp/send-verification-otp"===e||"/email-otp/request-password-reset"===e,window:60,max:3}].find(e=>e.pathMatcher(n));for(let e of(c&&(i=c.window,a=c.max),t.options.plugins||[]))if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(n));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let r=Object.keys(t.rateLimit.customRules).find(e=>e.includes("*")?x(e)(n):e===n);if(r){let n=t.rateLimit.customRules[r],o="function"==typeof n?await n(e,{window:i,max:a}):n;if(o&&(i=o.window,a=o.max),!1===o)return null}}return{key:s,currentWindow:i,currentMax:a}}async function ly(e,t){var r,n;if(!t.rateLimit.enabled)return;let i=await lm(e,t);if(!i)return;let{key:a,currentWindow:o,currentMax:s}=i,c=await lf(t,{window:o}).get(a);if(c&&Date.now()-c.lastRequest<1e3*o&&c.count>=s)return r=c.lastRequest,n=Math.ceil((r+1e3*o-Date.now())/1e3),new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":n.toString()}})}async function lg(e,t){if(!t.rateLimit.enabled)return;let r=await lm(e,t);if(!r)return;let{key:n,currentWindow:i}=r,a=lf(t,{window:i}),o=await a.get(n),s=Date.now();o?s-o.lastRequest>1e3*i?await a.set(n,{...o,count:1,lastRequest:s},!0):await a.set(n,{...o,count:o.count+1,lastRequest:s},!0):await a.set(n,{key:n,count:1,lastRequest:s})}let lw=async()=>{let e=s5();if(!e.context.requestStateAsyncStorage){let t=await s4();e.context.requestStateAsyncStorage=new t}return e.context.requestStateAsyncStorage};async function lb(){return void 0!==(await lw()).getStore()}async function lA(){let e=(await lw()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function lE(e,t){return(await lw()).run(e,t)}function lv(e){let t=Object.freeze({});return{get ref(){return t},async get(){let r=await lA();if(!r.has(t)){let n=await e();return r.set(t,n),n}return r.get(t)},async set(e){(await lA()).set(t,e)}}}let{get:lk,set:l_}=lv(()=>null),{get:lS,set:lx}=lv(()=>!1),lT=()=>lr("/get-session",{method:["GET","POST"],operationId:"getSession",query:sU,requireHeaders:!0,metadata:{openapi:{operationId:"getSession",description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:["object","null"],properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async e=>{let t=e.context.options.session?.deferSessionRefresh,r="POST"===e.method;if(r&&!t)throw E.APIError.from("METHOD_NOT_ALLOWED",rA.BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let n=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!n)return null;let i=sT(e,e.context.authCookies.sessionData.name),a=null;if(i){let t=e.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===t){let t=await rb(i,e.context.secretConfig,"better-auth-session");if(!t||!t.session||!t.user)return sK(e,e.context.authCookies.sessionData),e.json(null);a={session:{session:t.session,user:t.user,updatedAt:t.updatedAt,version:t.version},expiresAt:t.exp?1e3*t.exp:Date.now()}}else if("jwt"===t){let t=await rp(i,e.context.secret);if(!t||!t.session||!t.user)return sK(e,e.context.authCookies.sessionData),e.json(null);a={session:{session:t.session,user:t.user,updatedAt:t.updatedAt,version:t.version},expiresAt:t.exp?1e3*t.exp:Date.now()}}else{let t=(0,rN.safeJSONParse)(s$.decode(sL.decode(i)));if(t)if(!await sj("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify({...t.session,expiresAt:t.expiresAt}),t.signature))return sK(e,e.context.authCookies.sessionData),e.json(null);else a=t}}let o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(a?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let t=a.session,r=e.context.options.session?.cookieCache?.version,n="1";if(r){if("string"==typeof r)n=r;else if("function"==typeof r){let e=r(t.session,t.user);n=e instanceof Promise?await e:e}}if((t.version||"1")!==n)sK(e,e.context.authCookies.sessionData);else{let r=new Date(t.session.expiresAt);if(a.expiresAt<Date.now()||r<new Date)sK(e,e.context.authCookies.sessionData);else{let r=e.context.sessionConfig.cookieRefreshCache;if(!1===r){e.context.session=t;let r=rx(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),n=r_(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:r,user:n})}let n=a.expiresAt-Date.now(),i=1e3*r.updateAge,s=await lS();if(n<i&&!s){let r={session:{...t.session},user:t.user,updatedAt:Date.now()};await sV(e,r,!1);let n=e.context.authCookies.sessionToken.attributes,i=o?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i});let a=rx(e.context.options,{...r.session,expiresAt:new Date(r.session.expiresAt),createdAt:new Date(r.session.createdAt),updatedAt:new Date(r.session.updatedAt)}),s=r_(e.context.options,{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)});return e.context.session={session:a,user:s},e.json({session:a,user:s})}let c=rx(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=r_(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:c,user:l},e.json({session:c,user:l})}}}let s=await e.context.internalAdapter.findSession(n);if(e.context.session=s,!s||s.session.expiresAt<new Date)return sW(e),s&&(!t||r)&&await e.context.internalAdapter.deleteSession(s.session.token),e.json(null);if(o||e.query?.disableRefresh){let t=rx(e.context.options,s.session),r=r_(e.context.options,s.user);return e.json({session:t,user:r})}let c=e.context.sessionConfig.expiresIn,l=e.context.sessionConfig.updateAge,d=s.session.expiresAt.valueOf()-1e3*c+1e3*l<=Date.now(),u=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,p=await lS(),f=d&&!u&&!p;if(t&&!r){await sV(e,s,!!o);let t=rx(e.context.options,s.session),r=r_(e.context.options,s.user);return e.json({session:t,user:r,needsRefresh:f})}if(f){let t=await e.context.internalAdapter.updateSession(s.session.token,{expiresAt:rI(e.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!t)throw sW(e),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);let r=(t.expiresAt.valueOf()-Date.now())/1e3;await sM(e,{session:t,user:s.user},!1,{maxAge:r});let n=rx(e.context.options,t),i=r_(e.context.options,s.user);return e.json({session:n,user:i})}await sV(e,s,!!o);let h=rx(e.context.options,s.session),m=r_(e.context.options,s.user);return e.json({session:h,user:m})}catch(t){if(c9(t))throw t;throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),E.APIError.from("INTERNAL_SERVER_ERROR",rA.BASE_ERROR_CODES.FAILED_TO_GET_SESSION)}}),lR=async(e,t)=>{if(e.context.session)return e.context.session;let r=await lT()({...e,method:"GET",asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query}}).catch(()=>null);return r?(r.headers&&r.headers.forEach((t,r)=>{e.context.responseHeaders?"set-cookie"===r.toLowerCase()?e.context.responseHeaders.append(r,t):e.context.responseHeaders.set(r,t):e.context.responseHeaders=new Headers({[r]:t})}),e.context.session=r.response,r.response):(e.context.session=null,null)},lI=le(async e=>{let t=await lR(e);if(!t?.session)throw E.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}}),lU=le(async e=>{let t=await lR(e,{disableCookieCache:!0});if(!t?.session)throw E.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}});le(async e=>{let t=await lR(e);if(!t?.session&&(e.request||e.headers))throw E.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:t}});let lO=le(async e=>{let t=await lR(e);if(!t?.session)throw E.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),n=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=n)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.SESSION_NOT_FRESH)}return{session:t}}),lP=lr("/revoke-session",{method:"POST",body:se({token:oT().meta({description:"The token to revoke"})}),use:[lU],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),E.APIError.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),lC=lr("/revoke-sessions",{method:"POST",use:[lU],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&"object"==typeof t&&"name"in t?t.name:"",t),E.APIError.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return e.json({status:!0})}),lD=lr("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[lU],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw E.APIError.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let r=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(r.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function lL(e,t,r,n){let i=new URLSearchParams({error:r});n&&i.set("error_description",n);let a=t.includes("?")?"&":"?";throw e.redirect(`${t}${a}${i.toString()}`)}function lz(e,t){return`${t?.source==="generic"?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}var l$=e.i(602118);let lN=(0,l$.createRandomStringGenerator)("a-z","0-9","A-Z","-_");function lj(e){if("boolean"!=typeof e)throw TypeError(`boolean expected, not ${e}`)}function lH(e){if("number"!=typeof e)throw TypeError("number expected, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError("positive integer expected, got "+e)}function lB(e,t,r=""){let n=e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT,i=e?.length,a=void 0!==t;if(!n||a&&i!==t){let o=(r&&`"${r}" `)+"expected Uint8Array"+(a?` of length ${t}`:"")+", got "+(n?`length=${i}`:`type=${typeof e}`);if(!n)throw TypeError(o);throw RangeError(o)}return e}function lV(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function lM(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function lK(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}let lW=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],lq=e=>e<<24&0xff000000|e<<8&0xff0000|e>>>8&65280|e>>>24&255,lF=lW?e=>e:e=>lq(e)>>>0,lJ=lW?e=>e:e=>{for(let t=0;t<e.length;t++)e[t]=lq(e[t]);return e},lZ="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,lG=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function lQ(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function lY(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(lB(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!lX(t))throw Error("invalid output, must be aligned");return t}function lX(e){return e.byteOffset%4==0}function l0(e){return Uint8Array.from(lB(e))}function l1(e=32){lH(e);let t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}function l2(e,t=l1){let{nonceLength:r}=e;lH(r);let n=(e,t,r)=>{let n=function(...e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];lB(n),t+=n.length}let r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){let i=e[t];r.set(i,n),n+=i.length}return r}(e,t);return r.byteLength&&t.byteLength&&r.buffer===t.buffer&&r.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<r.byteOffset+r.byteLength||t.fill(0),n},i=(i,...a)=>({encrypt(o){lB(o);let s=t(r),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>n(s,e,o)):n(s,c,o)},decrypt(t){lB(t);let n=t.subarray(0,r),o=t.subarray(r);return e(i,n,...a).decrypt(o)}});return"blockSize"in e&&(i.blockSize=e.blockSize),"tagLength"in e&&(i.tagLength=e.tagLength),i}let l6=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),l5=lJ(lM(l6("expand 16-byte k"))),l8=lJ(lM(l6("expand 32-byte k")));function l4(e,t){return e<<t|e>>>32-t}let l3=0x100000000-1,l9=Uint32Array.of();function l7(e,t){return 255&e[t++]|(255&e[t++])<<8}class de{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){const t=l7(e=l0(lB(e,32,"key")),0),r=l7(e,2),n=l7(e,4),i=l7(e,6),a=l7(e,8),o=l7(e,10),s=l7(e,12),c=l7(e,14);this.r[0]=8191&t,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=l7(e,16+2*t)}process(e,t,r=!1){let{h:n,r:i}=this,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],d=i[5],u=i[6],p=i[7],f=i[8],h=i[9],m=l7(e,t+0),y=l7(e,t+2),g=l7(e,t+4),w=l7(e,t+6),b=l7(e,t+8),A=l7(e,t+10),E=l7(e,t+12),v=l7(e,t+14),k=n[0]+(8191&m),_=n[1]+((m>>>13|y<<3)&8191),S=n[2]+((y>>>10|g<<6)&8191),x=n[3]+((g>>>7|w<<9)&8191),T=n[4]+((w>>>4|b<<12)&8191),R=n[5]+(b>>>1&8191),I=n[6]+((b>>>14|A<<2)&8191),U=n[7]+((A>>>11|E<<5)&8191),O=n[8]+((E>>>8|v<<8)&8191),P=n[9]+(v>>>5|2048*!r),C=0,D=0+k*a+5*h*_+5*f*S+5*p*x+5*u*T;C=D>>>13,D&=8191,D+=5*d*R+5*l*I+5*c*U+5*s*O+5*o*P,C+=D>>>13,D&=8191;let L=C+k*o+_*a+5*h*S+5*f*x+5*p*T;C=L>>>13,L&=8191,L+=5*u*R+5*d*I+5*l*U+5*c*O+5*s*P,C+=L>>>13,L&=8191;let z=C+k*s+_*o+S*a+5*h*x+5*f*T;C=z>>>13,z&=8191,z+=5*p*R+5*u*I+5*d*U+5*l*O+5*c*P,C+=z>>>13,z&=8191;let $=C+k*c+_*s+S*o+x*a+5*h*T;C=$>>>13,$&=8191,$+=5*f*R+5*p*I+5*u*U+5*d*O+5*l*P,C+=$>>>13,$&=8191;let N=C+k*l+_*c+S*s+x*o+T*a;C=N>>>13,N&=8191,N+=5*h*R+5*f*I+5*p*U+5*u*O+5*d*P,C+=N>>>13,N&=8191;let j=C+k*d+_*l+S*c+x*s+T*o;C=j>>>13,j&=8191,j+=R*a+5*h*I+5*f*U+5*p*O+5*u*P,C+=j>>>13,j&=8191;let H=C+k*u+_*d+S*l+x*c+T*s;C=H>>>13,H&=8191,H+=R*o+I*a+5*h*U+5*f*O+5*p*P,C+=H>>>13,H&=8191;let B=C+k*p+_*u+S*d+x*l+T*c;C=B>>>13,B&=8191,B+=R*s+I*o+U*a+5*h*O+5*f*P,C+=B>>>13,B&=8191;let V=C+k*f+_*p+S*u+x*d+T*l;C=V>>>13,V&=8191,V+=R*c+I*s+U*o+O*a+5*h*P,C+=V>>>13,V&=8191;let M=C+k*h+_*f+S*p+x*u+T*d;C=M>>>13,M&=8191,M+=R*l+I*c+U*s+O*o+P*a,C+=M>>>13,M&=8191,D=8191&(C=(C=(C<<2)+C|0)+D|0),C>>>=13,L+=C,n[0]=D,n[1]=L,n[2]=z,n[3]=$,n[4]=N,n[5]=j,n[6]=H,n[7]=B,n[8]=V,n[9]=M}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let i=(1^n)-1;for(let e=0;e<10;e++)r[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|r[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=65535&a;for(let r=1;r<8;r++)a=(e[r]+t[r]|0)+(a>>>16)|0,e[r]=65535&a;lK(r)}update(e){lV(this),lB(e);let{buffer:t,blockLen:r}=this,n=(e=l0(e)).length;for(let i=0;i<n;){let a=Math.min(r-this.pos,n-i);if(a===r){for(;r<=n-i;i+=r)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,lK(this.h,this.r,this.buffer,this.pad)}digestInto(e){lV(this),function(e,t,r=!1){lB(e,void 0,"output");let n=t.outputLen;if(e.length<n)throw RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!lX(e))throw Error("invalid output, must be aligned")}(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=r[t]>>>0,e[i++]=r[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}let dt=(m=e=>new de(e),l=()=>[],(d=(e,t)=>m(t,...l(e)).update(e).digest()).outputLen=(u=m(new Uint8Array(32),...l(new Uint8Array(0)))).outputLen,d.blockLen=u.blockLen,d.create=(e,...t)=>m(e,...t),d),dr=function(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:a,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw Error("core must be a function");return lH(i),lH(o),lj(a),lj(r),(t,s,c,l,d=0)=>{let u,p;if(lB(t,void 0,"key"),lB(s,void 0,"nonce"),lB(c,void 0,"data"),l=lY(c.length,l,!1),lH(d),d<0||d>=l3)throw Error("arx: counter overflow");let f=[],h=t.length;if(32===h)f.push(u=l0(t)),p=l8;else if(16===h&&r)(u=new Uint8Array(32)).set(t),u.set(t,16),p=l5,f.push(u);else throw lB(t,32,"arx key"),Error("invalid key size");lW&&lX(s)||f.push(s=l0(s));let m=lM(u);if(n){if(24!==s.length)throw Error("arx: extended nonce must be 24 bytes");let e=s.subarray(0,16);if(lW)n(p,m,lM(e),m);else{let t=lJ(Uint32Array.from(p));n(t,m,lM(e),m),lK(t),lJ(m)}s=s.subarray(16)}else lW||lJ(m);let y=16-i;if(y!==s.length)throw Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let g=lJ(lM(s));try{return!function(e,t,r,n,i,a,o,s){let c=i.length,l=new Uint8Array(64),d=lM(l),u=lW&&lX(i)&&lX(a),p=u?lM(i):l9,f=u?lM(a):l9;if(!lW){for(let u=0;u<c;o++){if(e(t,r,n,d,o,s),lJ(d),o>=l3)throw Error("arx: counter overflow");let p=Math.min(64,c-u);for(let e=0,t;e<p;e++)a[t=u+e]=i[t]^l[e];u+=p}return}for(let h=0;h<c;o++){if(e(t,r,n,d,o,s),o>=l3)throw Error("arx: counter overflow");let m=Math.min(64,c-h);if(u&&64===m){let e=h/4;if(h%4!=0)throw Error("arx: invalid block position");for(let t=0,r;t<16;t++)f[r=e+t]=p[r]^d[t];h+=64;continue}for(let e=0,t;e<m;e++)a[t=h+e]=i[t]^l[e];h+=m}}(e,p,m,g,c,l,d,o),l}finally{lK(...f)}}}(function(e,t,r,n,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],d=t[0],u=t[1],p=t[2],f=t[3],h=t[4],m=t[5],y=t[6],g=t[7],w=r[0],b=r[1],A=r[2],E=o,v=s,k=c,_=l,S=d,x=u,T=p,R=f,I=h,U=m,O=y,P=g,C=i,D=w,L=b,z=A;for(let e=0;e<a;e+=2)I=I+(C=l4(C^(E=E+S|0),16))|0,E=E+(S=l4(S^I,12))|0,I=I+(C=l4(C^E,8))|0,S=l4(S^I,7),U=U+(D=l4(D^(v=v+x|0),16))|0,v=v+(x=l4(x^U,12))|0,U=U+(D=l4(D^v,8))|0,x=l4(x^U,7),O=O+(L=l4(L^(k=k+T|0),16))|0,k=k+(T=l4(T^O,12))|0,O=O+(L=l4(L^k,8))|0,T=l4(T^O,7),P=P+(z=l4(z^(_=_+R|0),16))|0,_=_+(R=l4(R^P,12))|0,P=P+(z=l4(z^_,8))|0,R=l4(R^P,7),O=O+(z=l4(z^(E=E+x|0),16))|0,E=E+(x=l4(x^O,12))|0,O=O+(z=l4(z^E,8))|0,x=l4(x^O,7),P=P+(C=l4(C^(v=v+T|0),16))|0,v=v+(T=l4(T^P,12))|0,P=P+(C=l4(C^v,8))|0,T=l4(T^P,7),I=I+(D=l4(D^(k=k+R|0),16))|0,k=k+(R=l4(R^I,12))|0,I=I+(D=l4(D^k,8))|0,R=l4(R^I,7),U=U+(L=l4(L^(_=_+S|0),16))|0,_=_+(S=l4(S^U,12))|0,U=U+(L=l4(L^_,8))|0,S=l4(S^U,7);let $=0;n[$++]=o+E|0,n[$++]=s+v|0,n[$++]=c+k|0,n[$++]=l+_|0,n[$++]=d+S|0,n[$++]=u+x|0,n[$++]=p+T|0,n[$++]=f+R|0,n[$++]=h+I|0,n[$++]=m+U|0,n[$++]=y+O|0,n[$++]=g+P|0,n[$++]=i+C|0,n[$++]=w+D|0,n[$++]=b+L|0,n[$++]=A+z|0},{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let i=lF(e[0]),a=lF(e[1]),o=lF(e[2]),s=lF(e[3]),c=lF(t[0]),l=lF(t[1]),d=lF(t[2]),u=lF(t[3]),p=lF(t[4]),f=lF(t[5]),h=lF(t[6]),m=lF(t[7]),y=lF(r[0]),g=lF(r[1]),w=lF(r[2]),b=lF(r[3]);for(let e=0;e<20;e+=2)p=p+(y=l4(y^(i=i+c|0),16))|0,i=i+(c=l4(c^p,12))|0,p=p+(y=l4(y^i,8))|0,c=l4(c^p,7),f=f+(g=l4(g^(a=a+l|0),16))|0,a=a+(l=l4(l^f,12))|0,f=f+(g=l4(g^a,8))|0,l=l4(l^f,7),h=h+(w=l4(w^(o=o+d|0),16))|0,o=o+(d=l4(d^h,12))|0,h=h+(w=l4(w^o,8))|0,d=l4(d^h,7),m=m+(b=l4(b^(s=s+u|0),16))|0,s=s+(u=l4(u^m,12))|0,m=m+(b=l4(b^s,8))|0,u=l4(u^m,7),h=h+(b=l4(b^(i=i+l|0),16))|0,i=i+(l=l4(l^h,12))|0,h=h+(b=l4(b^i,8))|0,l=l4(l^h,7),m=m+(y=l4(y^(a=a+d|0),16))|0,a=a+(d=l4(d^m,12))|0,m=m+(y=l4(y^a,8))|0,d=l4(d^m,7),p=p+(g=l4(g^(o=o+u|0),16))|0,o=o+(u=l4(u^p,12))|0,p=p+(g=l4(g^o,8))|0,u=l4(u^p,7),f=f+(w=l4(w^(s=s+c|0),16))|0,s=s+(c=l4(c^f,12))|0,f=f+(w=l4(w^s,8))|0,c=l4(c^f,7);let A=0;n[A++]=i,n[A++]=a,n[A++]=o,n[A++]=s,n[A++]=y,n[A++]=g,n[A++]=w,n[A++]=b,lJ(n)},allowShortKeys:!1}),dn=new Uint8Array(16),di=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(dn.subarray(r))},da=new Uint8Array(32);function ds(e,t,r,n,i){var a,o;let s,c;void 0!==i&&lB(i,void 0,"AAD");let l=e(t,r,da),d=(a=n.length,o=i?i.length:0,lH(a),lH(o),lj(!0),(c=new DataView((s=new Uint8Array(16)).buffer,s.byteOffset,s.byteLength)).setBigUint64(0,BigInt(o),!0),c.setBigUint64(8,BigInt(a),!0),s),u=dt.create(l);i&&di(u,i),di(u,n),u.update(d);let p=u.digest();return lK(l,d),p}let dc=((e,t)=>{function r(n,...i){lB(n,void 0,"key"),void 0!==e.nonceLength&&lB(i[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");let a=e.tagLength;a&&void 0!==i[1]&&lB(i[1],void 0,"AAD");let o=t(n,...i),s=(e,t)=>{if(void 0!==t){if(2!==e)throw Error("cipher output not supported");lB(t,void 0,"output")}},c=!1;return{encrypt(e,t){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,lB(e),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(lB(e),a&&e.length<a)throw Error('"ciphertext" expected length bigger than tagLength='+a);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(r,e),r})({blockSize:64,nonceLength:24,tagLength:16},(e,t,r)=>({encrypt(n,i){let a=n.length;(i=lY(a+16,i,!1)).set(n);let o=i.subarray(0,-16);dr(e,t,o,o,1);let s=ds(dr,e,t,o,r);return i.set(s,a),lK(s),i},decrypt(n,i){i=lY(n.length-16,i,!1);let a=n.subarray(0,-16),o=n.subarray(-16),s=ds(dr,e,t,a,r);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(o,s))throw lK(s),Error("invalid tag");return i.set(n.subarray(0,-16)),dr(e,t,i,i,1),lK(s),i}})),dl="$ba$";async function dd(e,t){let r=await sG("SHA-256").digest(e),n=function(e){if("string"!=typeof e)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}(t);var i=l2(dc)(new Uint8Array(r)).encrypt(n);if(lB(i),lZ)return i.toHex();let a="";for(let e=0;e<i.length;e++)a+=lG[i[e]];return a}async function du(e,t){let r=await sG("SHA-256").digest(e),n=function(e){if("string"!=typeof e)throw TypeError("hex string expected, got "+typeof e);if(lZ)try{return Uint8Array.fromHex(e)}catch(e){if(e instanceof SyntaxError)throw RangeError(e.message);throw e}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let t=0,i=0;t<r;t++,i+=2){let r=lQ(e.charCodeAt(i)),a=lQ(e.charCodeAt(i+1));if(void 0===r||void 0===a)throw RangeError('hex string expected, got non-hex character "'+(e[i]+e[i+1])+'" at index '+i);n[t]=16*r+a}return n}(t),i=l2(dc)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}let dp=async({key:e,data:t})=>{var r;if("string"==typeof e)return dd(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let i=await dd(n,t);return r=e.currentVersion,`${dl}${r}$${i}`},df=async({key:e,data:t})=>{if("string"==typeof e)return du(e,t);let r=function(e){if(!e.startsWith(dl))return null;let t=e.indexOf("$",4);if(-1===t)return null;let r=parseInt(e.slice(4,t),10);return!Number.isInteger(r)||r<0?null:{version:r,ciphertext:e.slice(t+1)}}(t);if(r){let t=e.keys.get(r.version);if(!t)throw Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return du(t,r.ciphertext)}if(e.legacySecret)return du(e.legacySecret,t);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};var dh=E,sE=sE;let dm=new o7({type:"object",shape:{callbackURL:oT(),codeVerifier:oT(),errorURL:oT().optional(),newUserURL:oT().optional(),expiresAt:oZ(),oauthState:oT().optional(),link:se({email:oT(),userId:sE.string()}).optional(),requestSignUp:oX().optional()},catchall:o5(),...a3.normalizeParams(void 0)});var dy=class extends dh.BetterAuthError{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function dg(e,t,r){let n=lN(32);if("cookie"===e.context.oauthConfig.storeStateStrategy){let i={...t,oauthState:n},a=await dp({key:e.context.secretConfig,data:JSON.stringify(i)}),o=e.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:n,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await e.setSignedCookie(i.name,n,e.context.secret,i.attributes);let a=new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:n}),identifier:n,expiresAt:a}))throw new dy("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:t.codeVerifier}}async function dw(e,t,r){let n;if(!t)throw new dy("State not found in OAuth callback",{code:"state_not_found"});if("cookie"===e.context.oauthConfig.storeStateStrategy){let i=e.context.createAuthCookie(r?.cookieName??"oauth_state"),a=e.getCookie(i.name);if(!a)throw new dy("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:t}});try{let t=await df({key:e.context.secretConfig,data:a});n=dm.parse(JSON.parse(t))}catch(e){throw new dy("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:t},cause:e})}if(!n.oauthState||n.oauthState!==t)throw new dy("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});sK(e,i)}else{let i=await e.context.internalAdapter.findVerificationValue(t);if(!i)throw new dy("State mismatch: verification not found",{code:"state_mismatch",details:{state:t}});if(void 0!==(n=dm.parse(JSON.parse(i.value))).oauthState&&n.oauthState!==t)throw new dy("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});let a=e.context.createAuthCookie(r?.cookieName??"state"),o=await e.getSignedCookie(a.name,e.context.secret);if(!(r?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new dy("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:t},errorURL:n.errorURL});sK(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(t)}if(n.expiresAt<Date.now())throw new dy("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:n.expiresAt},errorURL:n.errorURL});return n}async function db(e,t,r){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.CALLBACK_URL_REQUIRED);let i=lN(128),a={...r||{},callbackURL:n,codeVerifier:i,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp};await l_(a);try{return dg(e,a)}catch(t){throw e.context.logger.error("Failed to create verification",t),new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:t})}}async function dA(e){let t,r=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;try{t=await dw(e,r)}catch(i){e.context.logger.error("Failed to parse state",i);let t="internal_server_error",r=n;i instanceof dy&&(t="state_security_mismatch"===i.code?"state_mismatch":i.code,r=i.errorURL??n),lL(e,r,t)}return t.errorURL||(t.errorURL=n),t&&await l_(t),t}function dE(e,t){if(!e)return e;if(t.options.account?.encryptOAuthTokens)return e.startsWith("$ba$")||e.length%2==0&&/^[0-9a-f]+$/i.test(e)?df({key:t.secretConfig,data:e}):e;return e}function dv(e,t){return t.options.account?.encryptOAuthTokens&&e?dp({key:t.secretConfig,data:e}):e}function dk(e){let t=e=>new Date(new Date().getTime()+1e3*e);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:e?.scope?"string"==typeof e.scope?e.scope.split(" "):e.scope:[],idToken:e.id_token,raw:e}}function d_(e){let t=Array.isArray(e)?e[0]:e;return"string"==typeof t&&t.length>0?t:void 0}async function dS(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return sL.encode(new Uint8Array(r),{padding:!1})}async function dx({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:d,responseType:u,display:p,loginHint:f,hd:h,responseMode:m,additionalParams:y,scopeJoiner:g}){let w=new URL((t="function"==typeof t?await t():t).authorizationEndpoint||r);w.searchParams.set("response_type",u||"code");let b=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;if(w.searchParams.set("client_id",b),w.searchParams.set("state",n),a&&w.searchParams.set("scope",a.join(g||" ")),w.searchParams.set("redirect_uri",t.redirectURI||s),c&&w.searchParams.set("duration",c),p&&w.searchParams.set("display",p),f&&w.searchParams.set("login_hint",f),l&&w.searchParams.set("prompt",l),h&&w.searchParams.set("hd",h),d&&w.searchParams.set("access_type",d),m&&w.searchParams.set("response_mode",m),i){let e=await dS(i);w.searchParams.set("code_challenge_method","S256"),w.searchParams.set("code_challenge",e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});w.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}return y&&Object.entries(y).forEach(([e,t])=>{w.searchParams.set(e,t)}),w}var dT=Object.defineProperty,dR=Object.defineProperties,dI=Object.getOwnPropertyDescriptors,dU=Object.getOwnPropertySymbols,dO=Object.prototype.hasOwnProperty,dP=Object.prototype.propertyIsEnumerable,dC=(e,t,r)=>t in e?dT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,dD=(e,t)=>{for(var r in t||(t={}))dO.call(t,r)&&dC(e,r,t[r]);if(dU)for(var r of dU(t))dP.call(t,r)&&dC(e,r,t[r]);return e},dL=(e,t)=>dR(e,dI(t)),dz=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor)}},d$=async(e,t)=>{var r,n,i,a,o,s;let c=t||{},l={onRequest:[null==t?void 0:t.onRequest],onResponse:[null==t?void 0:t.onResponse],onSuccess:[null==t?void 0:t.onSuccess],onError:[null==t?void 0:t.onError],onRetry:[null==t?void 0:t.onRetry]};if(!t||!(null==t?void 0:t.plugins))return{url:e,options:c,hooks:l};for(let d of(null==t?void 0:t.plugins)||[]){if(d.init){let n=await (null==(r=d.init)?void 0:r.call(d,e.toString(),t));c=n.options||c,e=n.url}l.onRequest.push(null==(n=d.hooks)?void 0:n.onRequest),l.onResponse.push(null==(i=d.hooks)?void 0:i.onResponse),l.onSuccess.push(null==(a=d.hooks)?void 0:a.onSuccess),l.onError.push(null==(o=d.hooks)?void 0:o.onError),l.onRetry.push(null==(s=d.hooks)?void 0:s.onRetry)}return{url:e,options:c,hooks:l}},dN=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},dj=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}},dH=async e=>{let t={},r=async e=>"function"==typeof e?await e():e;if(null==e?void 0:e.auth){if("Bearer"===e.auth.type){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`}else if("Basic"===e.auth.type){let[n,i]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!i)return t;t.authorization=`Basic ${btoa(`${n}:${i}`)}`}else if("Custom"===e.auth.type){let[n,i]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!i)return t;t.authorization=`${null!=n?n:""} ${i}`}}return t},dB=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function dV(e){if(void 0===e)return!1;let t=typeof e;return"string"===t||"number"===t||"boolean"===t||null===t||"object"===t&&(!!Array.isArray(e)||!e.buffer&&(e.constructor&&"Object"===e.constructor.name||"function"==typeof e.toJSON))}function dM(e){try{return JSON.parse(e)}catch(t){return e}}async function dK(e){let t=new Headers(null==e?void 0:e.headers);for(let[r,n]of Object.entries(await dH(e)||{}))t.set(r,n);if(!t.has("content-type")){let r=dV(null==e?void 0:e.body)?"application/json":null;r&&t.set("content-type",r)}return t}var dW=class e extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function dq(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new dW(r.issues);return r.value}var dF=["get","post","put","patch","delete"],dJ=async(e,t)=>{var r,n,i,a,o,s,c,l;let d,{hooks:u,url:p,options:f}=await d$(e,t),h=function(e){if(null==e?void 0:e.customFetchImpl)return e.customFetchImpl;if("u">typeof globalThis&&"function"==typeof globalThis.fetch)return globalThis.fetch;throw Error("No fetch implementation found")}(f),m=new AbortController,y=null!=(r=f.signal)?r:m.signal,g=function(e,t){let{baseURL:r,params:n,query:i}=t||{query:{},params:{},baseURL:""},a=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let t=e.toString().split("@")[1].split("/")[0];dF.includes(t)&&(e=e.replace(`@${t}/`,"/"))}a.endsWith("/")||(a+="/");let[o,s]=e.replace(a,"").split("?"),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){let r;if(null!=t){if("string"==typeof t)r=t;else if(Array.isArray(t)){for(let r of t)c.append(e,r);continue}else r=JSON.stringify(t);c.set(e,r)}}if(n)if(Array.isArray(n))for(let[e,t]of o.split("/").filter(e=>e.startsWith(":")).entries()){let r=n[e];o=o.replace(t,r)}else for(let[e,t]of Object.entries(n))o=o.replace(`:${e}`,String(t));(o=o.split("/").map(encodeURIComponent).join("/")).startsWith("/")&&(o=o.slice(1));let l=c.toString();return(l=l.length>0?`?${l}`.replace(/\+/g,"%20"):"",a.startsWith("http"))?new URL(`${o}${l}`,a):`${a}${o}${l}`}(p,f),w=function(e){if(!(null==e?void 0:e.body))return null;let t=new Headers(null==e?void 0:e.headers);if(dV(e.body)&&!t.has("content-type")){for(let[t,r]of Object.entries(null==e?void 0:e.body))r instanceof Date&&(e.body[t]=r.toISOString());return JSON.stringify(e.body)}return t.has("content-type")&&"application/x-www-form-urlencoded"===t.get("content-type")&&dV(e.body)?new URLSearchParams(e.body).toString():e.body}(f),b=await dK(f),A=function(e,t){var r;if(null==t?void 0:t.method)return t.method.toUpperCase();if(e.startsWith("@")){let n=null==(r=e.split("@")[1])?void 0:r.split("/")[0];return dF.includes(n)?n.toUpperCase():(null==t?void 0:t.body)?"POST":"GET"}return(null==t?void 0:t.body)?"POST":"GET"}(p,f),E=dL(dD({},f),{url:g,headers:b,body:w,method:A,signal:y});for(let e of u.onRequest)if(e){let t=await e(E);"object"==typeof t&&null!==t&&(E=t)}("pipeTo"in E&&"function"==typeof E.pipeTo||"function"==typeof(null==(n=null==t?void 0:t.body)?void 0:n.pipe))&&!("duplex"in E)&&(E.duplex="half");let{clearTimeout:v}=(!(null==f?void 0:f.signal)&&(null==f?void 0:f.timeout)&&(d=setTimeout(()=>null==m?void 0:m.abort(),null==f?void 0:f.timeout)),{abortTimeout:d,clearTimeout:()=>{d&&clearTimeout(d)}}),k=await h(E.url,E);v();let _={response:k,request:E};for(let e of u.onResponse)if(e){let r=await e(dL(dD({},_),{response:(null==(i=null==t?void 0:t.hookOptions)?void 0:i.cloneResponse)?k.clone():k}));r instanceof Response?k=r:"object"==typeof r&&null!==r&&(k=r.response)}if(k.ok){if("HEAD"===E.method)return{data:"",error:null};let e=function(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let n=t.split(";").shift()||"";return dB.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}(k),r={data:null,response:k,request:E};if("json"===e||"text"===e){let e=await k.text(),t=null!=(a=E.jsonParser)?a:dM;r.data=await t(e)}else r.data=await k[e]();for(let e of((null==E?void 0:E.output)&&E.output&&!E.disableValidation&&(r.data=await dq(E.output,r.data)),u.onSuccess))e&&await e(dL(dD({},r),{response:(null==(o=null==t?void 0:t.hookOptions)?void 0:o.cloneResponse)?k.clone():k}));return(null==t?void 0:t.throw)?r.data:{data:r.data,error:null}}let S=null!=(s=null==t?void 0:t.jsonParser)?s:dM,x=await k.text(),T=function(e){try{return JSON.parse(e),!0}catch(e){return!1}}(x),R=T?await S(x):null,I={response:k,responseText:x,request:E,error:dL(dD({},R),{status:k.status,statusText:k.statusText})};for(let e of u.onError)e&&await e(dL(dD({},I),{response:(null==(c=null==t?void 0:t.hookOptions)?void 0:c.cloneResponse)?k.clone():k}));if(null==t?void 0:t.retry){let r=function(e){if("number"==typeof e)return new dN({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new dN(e);case"exponential":return new dj(e);default:throw Error("Invalid retry strategy")}}(t.retry),n=null!=(l=t.retryAttempt)?l:0;if(await r.shouldAttemptRetry(n,k)){for(let e of u.onRetry)e&&await e(_);let i=r.getDelay(n);return await new Promise(e=>setTimeout(e,i)),await dJ(e,dL(dD({},t),{retryAttempt:n+1}))}}if(null==t?void 0:t.throw)throw new dz(k.status,k.statusText,T?R:x);return{data:null,error:dL(dD({},R),{status:k.status,statusText:k.statusText})}};async function dZ({refreshToken:e,options:t,tokenEndpoint:r,authentication:n,extraParams:i}){let{body:a,headers:o}=await function({refreshToken:e,options:t,authentication:r,extraParams:n,resource:i}){let a=new URLSearchParams,o={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(a.set("grant_type","refresh_token"),a.set("refresh_token",e),"basic"===r){let e=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;e?o.authorization="Basic "+sD.encode(`${e}:${t.clientSecret??""}`):o.authorization="Basic "+sD.encode(`:${t.clientSecret??""}`)}else{let e=Array.isArray(t.clientId)?t.clientId[0]:t.clientId;a.set("client_id",e),t.clientSecret&&a.set("client_secret",t.clientSecret)}if(i)if("string"==typeof i)a.append("resource",i);else for(let e of i)a.append("resource",e);if(n)for(let[e,t]of Object.entries(n))a.set(e,t);return{body:a,headers:o}}({refreshToken:e,options:t,authentication:n,extraParams:i}),{data:s,error:c}=await dJ(r,{method:"POST",body:a,headers:o});if(c)throw c;let l={accessToken:s.access_token,refreshToken:s.refresh_token,tokenType:s.token_type,scopes:s.scope?.split(" "),idToken:s.id_token};return s.expires_in&&(l.accessTokenExpiresAt=new Date(new Date().getTime()+1e3*s.expires_in)),s.refresh_token_expires_in&&(l.refreshTokenExpiresAt=new Date(new Date().getTime()+1e3*s.refresh_token_expires_in)),l}function dG(e){return tT(e)}class dQ{#h;#m=new WeakMap;constructor(e){if(!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(dG)}(e))throw new eJ("JSON Web Key Set malformed");this.#h=structuredClone(e)}jwks(){return this.#h}async getKey(e,t){let{alg:r,kid:n}={...e,...t?.header},i=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new eV('Unsupported "alg" value for a JSON Web Key Set')}}(r),a=this.#h.keys.filter(e=>{let t=i===e.kty;if(t&&"string"==typeof n&&(t=n===e.kid),t&&("string"==typeof e.alg||"AKP"===i)&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:o,length:s}=a;if(0===s)throw new eZ;if(1!==s){let e=new eG,t=this.#m;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await dY(t,e,r)}catch{}},e}return dY(this.#m,o,r)}}async function dY(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){let e=await tL({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new eJ("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function dX(e){let t=new dQ(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}("u"<typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(r="jose/v6.2.3");let d0=Symbol();async function d1(e,t,r,n=fetch){let i=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{if("TimeoutError"===e.name)throw new eQ;throw e});if(200!==i.status)throw new eN("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new eN("Failed to parse the JSON Web Key Set HTTP response as JSON")}}let d2=Symbol();class d6{#y;#g;#w;#b;#A;#E;#v;#k;#_;#S;constructor(e,t){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");this.#y=new URL(e.href),this.#g="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this.#w="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this.#b="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,this.#v=new Headers(t?.headers),r&&!this.#v.has("User-Agent")&&this.#v.set("User-Agent",r),this.#v.has("accept")||(this.#v.set("accept","application/json"),this.#v.append("accept","application/jwk-set+json")),this.#k=t?.[d0],t?.[d2]!==void 0&&(this.#S=t?.[d2],function(e,t){return!("object"!=typeof e||null===e||!("uat"in e)||"number"!=typeof e.uat||Date.now()-e.uat>=t)&&"jwks"in e&&!!tT(e.jwks)&&!!Array.isArray(e.jwks.keys)&&!!Array.prototype.every.call(e.jwks.keys,tT)}(t?.[d2],this.#b)&&(this.#A=this.#S.uat,this.#_=dX(this.#S.jwks)))}pendingFetch(){return!!this.#E}coolingDown(){return"number"==typeof this.#A&&Date.now()<this.#A+this.#w}fresh(){return"number"==typeof this.#A&&Date.now()<this.#A+this.#b}jwks(){return this.#_?.jwks()}async getKey(e,t){this.#_&&this.fresh()||await this.reload();try{return await this.#_(e,t)}catch(r){if(r instanceof eZ&&!1===this.coolingDown())return await this.reload(),this.#_(e,t);throw r}}async reload(){this.#E&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this.#E=void 0),this.#E||=d1(this.#y.href,this.#v,AbortSignal.timeout(this.#g),this.#k).then(e=>{this.#_=dX(e),this.#S&&(this.#S.uat=Date.now(),this.#S.jwks=e),this.#A=Date.now(),this.#E=void 0}).catch(e=>{throw this.#E=void 0,e}),await this.#E}}async function d5({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,deviceId:a,headers:o,additionalParams:s={},resource:c}){return d8({code:e,codeVerifier:t,redirectURI:r,options:n="function"==typeof n?await n():n,authentication:i,deviceId:a,headers:o,additionalParams:s,resource:c})}function d8({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:i,deviceId:a,headers:o,additionalParams:s={},resource:c}){let l=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...o};if(l.set("grant_type","authorization_code"),l.set("code",e),t&&l.set("code_verifier",t),n.clientKey&&l.set("client_key",n.clientKey),a&&l.set("device_id",a),l.set("redirect_uri",n.redirectURI||r),c)if("string"==typeof c)l.append("resource",c);else for(let e of c)l.append("resource",e);if("basic"===i){let e=Array.isArray(n.clientId)?n.clientId[0]:n.clientId;d.authorization=`Basic ${sD.encode(`${e}:${n.clientSecret??""}`)}`}else{let e=Array.isArray(n.clientId)?n.clientId[0]:n.clientId;l.set("client_id",e),n.clientSecret&&l.set("client_secret",n.clientSecret)}for(let[e,t]of Object.entries(s))l.has(e)||l.append(e,t);return{body:l,headers:d}}async function d4({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:i,authentication:a,deviceId:o,headers:s,additionalParams:c={},resource:l}){let{body:d,headers:u}=await d5({code:e,codeVerifier:t,redirectURI:r,options:n,authentication:a,deviceId:o,headers:s,additionalParams:c,resource:l}),{data:p,error:f}=await dJ(i,{method:"POST",body:d,headers:u});if(f)throw f;return dk(p)}function d3(e){let t,r;if("string"!=typeof e)throw new eq("JWTs must use Compact JWS serialization, JWT must be a string");let{1:n,length:i}=e.split(".");if(5===i)throw new eq("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new eq("Invalid JWT");if(!n)throw new eq("JWTs must contain a payload");try{t=eS(n)}catch{throw new eq("Failed to base64url decode the payload")}try{r=JSON.parse(eb.decode(t))}catch{throw new eq("Failed to parse the decoded payload as JSON")}if(!tT(r))throw new eq("Invalid JWT Claims Set");return r}async function d9(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function d7(e,t){return"string"==typeof e&&(e===t||e===await d9(t))}let ue=async e=>{let{data:t}=await dJ("https://appleid.apple.com/auth/keys");if(!t?.keys)throw new E.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await tL(r,r.alg)},ut=async(e,t,r)=>{let n=`https://cognito-idp.${t}.amazonaws.com/${r}/.well-known/jwks.json`;try{let{data:t}=await dJ(n);if(!t?.keys)throw new E.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await tL(r,r.alg)}catch(e){throw b.logger.error("Failed to fetch Cognito public key:",e),e}},ur=(e="")=>e.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),un=async e=>{let{data:t}=await dJ("https://www.googleapis.com/oauth2/v3/certs");if(!t?.keys)throw new E.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(t=>t.kid===e);if(!r)throw Error(`JWK with kid ${e} not found`);return await tL(r,r.alg)},ui=async(e,t,r)=>{let{data:n}=await dJ(`${r}/${t}/discovery/v2.0/keys`);if(!n?.keys)throw new E.APIError("BAD_REQUEST",{message:"Keys not found"});let i=n.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await tL(i,i.alg)},ua="https://backboard.railway.com/oauth/token",uo={apple:e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:t,scopes:r,redirectURI:n}){if(!d_(e.clientId)||!e.clientSecret)throw b.logger.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let i=e.disableDefaultScope?[]:["email","name"];return e.scope&&i.push(...e.scope),r&&i.push(...r),await dx({id:"apple",options:e,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:i,state:t,redirectURI:n,responseMode:"form_post",responseType:"code id_token"})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=rn(t);if(!n||!i)return!1;let{payload:a}=await rd(t,await ue(n),{algorithms:[i],issuer:"https://appleid.apple.com",audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:"1h"});if(["email_verified","is_private_email"].forEach(e=>{void 0!==a[e]&&(a[e]=!!a[e])}),r&&!await d7(a.nonce,r))return!1;return!!a}catch{return!1}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:e,tokenEndpoint:t}),async getUserInfo(t){let r;if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=d3(t.idToken);if(!n)return null;r=t.user?.name?`${t.user.name.firstName||""} ${t.user.name.lastName||""}`.trim():n.name||"";let i="boolean"==typeof n.email_verified?n.email_verified:"true"===n.email_verified,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{id:n.sub,name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},atlassian:e=>{let t="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw b.logger.error("Client Id and Secret are required for Atlassian"),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new E.BetterAuthError("codeVerifier is required for Atlassian");let a=e.disableDefaultScope?[]:["read:jira-user","offline_access"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"atlassian",options:e,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i,additionalParams:{audience:"api.atlassian.com"},prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:r}=await dJ("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name,email:r.email,image:r.picture,emailVerified:!1,...n},data:r}}catch(e){return b.logger.error("Failed to fetch user info from Figma:",e),null}},options:e}},cognito:e=>{if(!e.domain||!e.region||!e.userPoolId)throw b.logger.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new E.BetterAuthError("DOMAIN_AND_REGION_REQUIRED");let t=e.domain.replace(/^https?:\/\//,""),r=`https://${t}/oauth2/authorize`,n=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a}){if(!d_(e.clientId))throw b.logger.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(e.requireClientSecret&&!e.clientSecret)throw b.logger.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new E.BetterAuthError("CLIENT_SECRET_REQUIRED");let o=e.disableDefaultScope?[]:["openid","profile","email"];e.scope&&o.push(...e.scope),n&&o.push(...n);let s=await dx({id:"cognito",options:{...e},authorizationEndpoint:r,scopes:o,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt}),c=s.searchParams.get("scope");if(c){s.searchParams.delete("scope");let e=encodeURIComponent(c),t=s.toString(),r=t.includes("?")?"&":"?";return new URL(`${t}${r}scope=${e}`)}return s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>d4({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=rn(t);if(!n||!i)return!1;let a=await ut(n,e.region,e.userPoolId),o=`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,{payload:s}=await rd(t,a,{algorithms:[i],issuer:o,audience:e.clientId,maxTokenAge:"1h"});if(r&&s.nonce!==r)return!1;return!0}catch(e){return b.logger.error("Failed to verify ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let r=d3(t.idToken);if(!r)return null;let n=r.name||r.given_name||r.username||"",i={...r,name:n},a=await e.mapProfileToUser?.(i);return{user:{id:r.sub,name:i.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:i}}catch(e){b.logger.error("Failed to decode ID token:",e)}if(t.accessToken)try{let{data:r}=await dJ(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r){let t=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.given_name||r.username||"",email:r.email,image:r.picture,emailVerified:r.email_verified,...t},data:r}}}catch(e){b.logger.error("Failed to fetch user info from Cognito:",e)}return null},options:e}},discord:e=>{let t="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["identify","email"];r&&i.push(...r),e.scope&&i.push(...e.scope);let a=i.includes("bot")&&void 0!==e.permissions?`&permissions=${e.permissions}`:"";return new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"none"}${a}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;if(null===r.avatar)r.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===r.discriminator?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5}.png`;else{let e=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${e}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.global_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}},options:e}},facebook:e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:n,loginHint:i}){if(!d_(e.clientId)||!e.clientSecret)throw b.logger.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let a=e.disableDefaultScope?[]:["email","public_profile"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await dx({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:a,state:t,redirectURI:n,loginHint:i,additionalParams:e.configId?{config_id:e.configId}:{}})},validateAuthorizationCode:async({code:t,redirectURI:r})=>d4({code:t,redirectURI:r,options:e,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);if(3===t.split(".").length)try{var n;let i,a,{payload:o}=await rd(t,(n=new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/"),i=new d6(n,void 0),a=async(e,t)=>i.getKey(e,t),Object.defineProperties(a,{coolingDown:{get:()=>i.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>i.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>i.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>i.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>i.jwks(),enumerable:!0,configurable:!1,writable:!1}}),a),{algorithms:["RS256"],audience:e.clientId,issuer:"https://www.facebook.com"});if(r&&o.nonce!==r)return!1;return!!o}catch{return!1}return!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken&&3===t.idToken.split(".").length){let r=d3(t.idToken),n={id:r.sub,name:r.name,email:r.email,picture:{data:{url:r.picture,height:100,width:100,is_silhouette:!1}}},i=await e.mapProfileToUser?.({...n,email_verified:!1});return{user:{...n,emailVerified:!1,...i},data:r}}let{data:r,error:n}=await dJ("https://graph.facebook.com/me?fields="+["id","name","email","picture",...e?.fields||[]].join(","),{auth:{type:"Bearer",token:t.accessToken}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified??!1,...i},data:r}},options:e}),figma:e=>{let t="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw b.logger.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new E.BetterAuthError("codeVerifier is required for Figma");let a=e.disableDefaultScope?[]:["current_user:read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await dx({id:"figma",options:e,authorizationEndpoint:"https://www.figma.com/oauth",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await dJ("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return b.logger.error("Failed to fetch user from Figma"),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.handle,email:r.email,image:r.img_url,emailVerified:!1,...n},data:r}}catch(e){return b.logger.error("Failed to fetch user info from Figma:",e),null}},options:e}},github:e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:r,loginHint:n,codeVerifier:i,redirectURI:a}){let o=e.disableDefaultScope?[]:["read:user","user:email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),dx({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:o,state:t,codeVerifier:i,redirectURI:a,loginHint:n,prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>{let{body:a,headers:o}=d8({code:r,codeVerifier:n,redirectURI:i,options:e}),{data:s,error:c}=await dJ(t,{method:"POST",body:a,headers:o});return c?(b.logger.error("GitHub OAuth token exchange failed:",c),null):"error"in s?(b.logger.error("GitHub OAuth token exchange failed:",s),null):dk(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let{data:i}=await dJ("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});!r.email&&i&&(r.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===r.email)?.verified??!1,o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name||r.login||"",email:r.email,image:r.avatar_url,emailVerified:a,...o},data:r}},options:e}},microsoft:e=>{let t=e.tenantId||"common",r=e.authority||"https://login.microsoftonline.com",n=`${r}/${t}/oauth2/v2.0/authorize`,i=`${r}/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(t){if(!d_(e.clientId))throw b.logger.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),dx({id:"microsoft",options:e,authorizationEndpoint:n,state:t.state,codeVerifier:t.codeVerifier,scopes:r,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint})},validateAuthorizationCode:({code:t,codeVerifier:r,redirectURI:n})=>d4({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:i}),async verifyIdToken(n,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(n,i);try{let{kid:a,alg:o}=rn(n);if(!a||!o)return!1;let s=await ui(a,t,r),c={algorithms:[o],audience:e.clientId,maxTokenAge:"1h"};"common"!==t&&"organizations"!==t&&"consumers"!==t&&(c.issuer=`${r}/${t}/v2.0`);let{payload:l}=await rd(n,s,c);if(i&&l.nonce!==i)return!1;return!0}catch(e){return b.logger.error("Failed to verify ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=d3(t.idToken),n=e.profilePhotoSize||48;await dJ(`https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(t){if(!e.disableProfilePhoto&&t.response.ok)try{let e=await t.response.clone().arrayBuffer();r.picture=`data:image/jpeg;base64, ${sD.encode(e)}`}catch(e){b.logger.error(e&&"object"==typeof e&&"name"in e?e.name:"",e)}}});let i=await e.mapProfileToUser?.(r),a=void 0!==r.email_verified?r.email_verified:!!(r.email&&(r.verified_primary_email?.includes(r.email)||r.verified_secondary_email?.includes(r.email)));return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:a,...i},data:r}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=e.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return e.scope&&r.push(...e.scope),dZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:r.join(" ")},tokenEndpoint:i})},options:e}},google:e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:a,display:o}){if(!d_(e.clientId)||!e.clientSecret)throw b.logger.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new E.BetterAuthError("codeVerifier is required for Google");let s=e.disableDefaultScope?[]:["email","profile","openid"];return e.scope&&s.push(...e.scope),r&&s.push(...r),await dx({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:s,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{include_granted_scopes:"true"}})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>d4({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{let{kid:n,alg:i}=rn(t);if(!n||!i)return!1;let{payload:a}=await rd(t,await un(n),{algorithms:[i],issuer:["https://accounts.google.com","accounts.google.com"],audience:e.clientId,maxTokenAge:"1h"});if(r&&a.nonce!==r)return!1;return!0}catch{return!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=d3(t.idToken),n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}},options:e}),huggingface:e=>{let t="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"huggingface",options:e,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e}},slack:e=>{let t="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["openid","profile","email"];r&&i.push(...r),e.scope&&i.push(...e.scope);let a=new URL("https://slack.com/openid/connect/authorize");return a.searchParams.set("scope",i.join(" ")),a.searchParams.set("response_type","code"),a.searchParams.set("client_id",e.clientId),a.searchParams.set("redirect_uri",e.redirectURI||n),a.searchParams.set("state",t),a},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r["https://slack.com/user_id"],name:r.name||"",email:r.email,emailVerified:r.email_verified,image:r.picture||r["https://slack.com/user_image_512"],...i},data:r}},options:e}},spotify:e=>{let t="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["user-read-email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}},options:e}},twitch:e=>{let t="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["user:read:email","openid"];return e.scope&&i.push(...e.scope),r&&i.push(...r),dx({id:"twitch",redirectURI:n,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return b.logger.error("No idToken found in token"),null;let n=d3(r),i=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.preferred_username,email:n.email,image:n.picture,emailVerified:n.email_verified,...i},data:n}},options:e}},twitter:e=>{let t="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return e.scope&&r.push(...e.scope),t.scopes&&r.push(...t.scopes),dx({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,authentication:"basic",redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let{data:i,error:a}=await dJ("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(r.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.email||r.data.username||null,image:r.data.profile_image_url,emailVerified:o,...s},data:r}},options:e}},dropbox:e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:r,codeVerifier:n,redirectURI:i})=>{let a=e.disableDefaultScope?[]:["account_info.read"];e.scope&&a.push(...e.scope),r&&a.push(...r);let o={};return e.accessType&&(o.token_access_type=e.accessType),await dx({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:t,redirectURI:i,codeVerifier:n,additionalParams:o})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>await d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...i},data:r}},options:e}},kick:e=>({id:"kick",name:"Kick",createAuthorizationURL({state:t,scopes:r,redirectURI:n,codeVerifier:i}){let a=e.disableDefaultScope?[]:["user:read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"kick",redirectURI:n,options:e,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:a,codeVerifier:i,state:t})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:n})=>d4({code:t,redirectURI:r,options:e,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=r.data[0],a=await e.mapProfileToUser?.(i);return{user:{id:i.user_id,name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),linear:e=>{let t="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",createAuthorizationURL({state:t,scopes:r,loginHint:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["read"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"linear",options:e,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:a,state:t,redirectURI:i,loginHint:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
66
+ query {
67
+ viewer {
68
+ id
69
+ name
70
+ email
71
+ avatarUrl
72
+ active
73
+ createdAt
74
+ updatedAt
75
+ }
76
+ }
77
+ `})});if(n||!r?.data?.viewer)return null;let i=r.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{id:r.data.viewer.id,name:r.data.viewer.name,email:r.data.viewer.email,image:r.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},linkedin:e=>{let t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:r,redirectURI:n,loginHint:i})=>{let a=e.disableDefaultScope?[]:["profile","email","openid"];return e.scope&&a.push(...e.scope),r&&a.push(...r),await dx({id:"linkedin",options:e,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:a,state:t,loginHint:i,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>await d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified??!1,image:r.picture,...i},data:r}},options:e}},gitlab:e=>{let t,{authorizationEndpoint:r,tokenEndpoint:n,userinfoEndpoint:i}=(t=e.issuer||"https://gitlab.com",{authorizationEndpoint:ur(`${t}/oauth/authorize`),tokenEndpoint:ur(`${t}/oauth/token`),userinfoEndpoint:ur(`${t}/api/v4/user`)}),a="gitlab";return{id:a,name:"Gitlab",createAuthorizationURL:async({state:t,scopes:n,codeVerifier:i,loginHint:o,redirectURI:s})=>{let c=e.disableDefaultScope?[]:["read_user"];return e.scope&&c.push(...e.scope),n&&c.push(...n),await dx({id:a,options:e,authorizationEndpoint:r,scopes:c,state:t,redirectURI:s,codeVerifier:i,loginHint:o})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>d4({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ(i,{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||"active"!==r.state||r.locked)return null;let a=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name??r.username??"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...a},data:r}},options:e}},tiktok:e=>{let t="https://open.tiktokapis.com/v2/oauth/token/";return{id:"tiktok",name:"TikTok",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["user.info.profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${i.join(",")}&response_type=code&client_key=${e.clientKey}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:e.redirectURI||n,options:{clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientSecret:e.clientSecret},tokenEndpoint:t,authentication:"post",extraParams:{client_key:e.clientKey}}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_large_url,display_name,username",{headers:{authorization:`Bearer ${t.accessToken}`}});return n?null:{user:{email:r.data.user.email||r.data.user.username,id:r.data.user.open_id,name:r.data.user.display_name||r.data.user.username||"",image:r.data.user.avatar_large_url,emailVerified:!1},data:r}},options:e}},reddit:e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["identity"];return e.scope&&i.push(...e.scope),r&&i.push(...r),dx({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:n,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let n=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),{data:i,error:a}=await dJ("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${sD.encode(`${e.clientId}:${e.clientSecret}`)}`},body:n.toString()});if(a)throw a;return dk(i)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:"basic",tokenEndpoint:"https://www.reddit.com/api/v1/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...i},data:r}},options:e}),roblox:e=>{let t="https://apis.roblox.com/oauth/v1/token";return{id:"roblox",name:"Roblox",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["openid","profile"];return e.scope&&i.push(...e.scope),r&&i.push(...r),new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"select_account consent"}`)},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t,authentication:"post"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.nickname||r.preferred_username||"",image:r.picture,email:r.preferred_username||null,emailVerified:!1,...i},data:{...r}}},options:e}},salesforce:e=>{let t=(e.environment??"production")==="sandbox",r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a}){if(!e.clientId||!e.clientSecret)throw b.logger.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new E.BetterAuthError("codeVerifier is required for Salesforce");let o=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&o.push(...e.scope),n&&o.push(...n),dx({id:"salesforce",options:e,authorizationEndpoint:r,scopes:o,state:t,codeVerifier:i,redirectURI:e.redirectURI||a})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>d4({code:t,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:r}=await dJ(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!r)return b.logger.error("Failed to fetch user info from Salesforce"),null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.user_id,name:r.name,email:r.email,image:r.photos?.picture||r.photos?.thumbnail,emailVerified:r.email_verified??!1,...n},data:r}}catch(e){return b.logger.error("Failed to fetch user info from Salesforce:",e),null}},options:e}},vk:e=>{let t="https://id.vk.com/oauth2/auth";return{id:"vk",name:"VK",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["email","phone"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"vk",options:e,authorizationEndpoint:"https://id.vk.com/authorize",scopes:a,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i,deviceId:a})=>d4({code:r,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let r=new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString(),{data:n,error:i}=await dJ("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r});if(i)return null;let a=await e.mapProfileToUser?.(n);return n.user.email||a?.email?{user:{id:n.user.user_id,first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...a},data:n}:null},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:"zoom",name:"Zoom",createAuthorizationURL:async({state:e,redirectURI:r,codeVerifier:n})=>{let i=new URLSearchParams({response_type:"code",redirect_uri:t.redirectURI?t.redirectURI:r,client_id:t.clientId,state:e});if(t.pkce){let e=await dS(n);i.set("code_challenge_method","S256"),i.set("code_challenge",e)}let a=new URL("https://zoom.us/oauth/authorize");return a.search=i.toString(),a},validateAuthorizationCode:async({code:e,redirectURI:r,codeVerifier:n})=>d4({code:e,redirectURI:t.redirectURI||r,codeVerifier:n,options:t,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>dZ({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:r,error:n}=await dJ("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(n)return null;let i=await t.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,image:r.pic_url,email:r.email,emailVerified:!!r.verified,...i},data:{...r}}}}},notion:e=>{let t="https://api.notion.com/v1/oauth/token";return{id:"notion",name:"Notion",createAuthorizationURL({state:t,scopes:r,loginHint:n,redirectURI:i}){let a=(e.disableDefaultScope,[]);return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"notion",options:e,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:a,state:t,redirectURI:i,loginHint:n,additionalParams:{owner:"user"}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":"2022-06-28"}});if(n||!r)return null;let i=r.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name||"",email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},kakao:e=>{let t="https://kauth.kakao.com/oauth/token";return{id:"kakao",name:"Kakao",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];return e.scope&&i.push(...e.scope),r&&i.push(...r),dx({id:"kakao",options:e,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r),a=r.kakao_account||{},o=a.profile||{};return{user:{id:String(r.id),name:o.nickname||a.name||"",email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:r}},options:e}},naver:e=>{let t="https://nid.naver.com/oauth2.0/token";return{id:"naver",name:"Naver",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["profile","email"];return e.scope&&i.push(...e.scope),r&&i.push(...r),dx({id:"naver",options:e,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:n})=>d4({code:r,redirectURI:n,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r||"00"!==r.resultcode)return null;let i=await e.mapProfileToUser?.(r),a=r.response||{};return{user:{id:a.id,name:a.name||a.nickname||"",email:a.email,image:a.profile_image,emailVerified:!1,...i},data:r}},options:e}},line:e=>{let t="https://api.line.me/oauth2/v2.1/token";return{id:"line",name:"LINE",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i,loginHint:a}){let o=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&o.push(...e.scope),r&&o.push(...r),await dx({id:"line",options:e,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:o,state:t,codeVerifier:n,redirectURI:i,loginHint:a})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let n=new URLSearchParams;n.set("id_token",t),n.set("client_id",e.clientId),r&&n.set("nonce",r);let{data:i,error:a}=await dJ("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n});return!a&&!!i&&i.aud===e.clientId&&(!i.nonce||i.nonce===r)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=null;if(t.idToken)try{r=d3(t.idToken)}catch{}if(!r){let{data:e}=await dJ("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${t.accessToken}`}});r=e||null}if(!r)return null;let n=await e.mapProfileToUser?.(r),i=r.sub||r.userId,a=r.name||r.displayName||"",o=r.picture||r.pictureUrl||void 0;return{user:{id:i,name:a,email:r.email,image:o,emailVerified:!1,...n},data:r}},options:e}},paybin:e=>{let t=e.issuer||"https://idp.paybin.io",r=`${t}/oauth2/authorize`,n=`${t}/oauth2/token`;return{id:"paybin",name:"Paybin",async createAuthorizationURL({state:t,scopes:n,codeVerifier:i,redirectURI:a,loginHint:o}){if(!e.clientId||!e.clientSecret)throw b.logger.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new E.BetterAuthError("codeVerifier is required for Paybin");let s=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&s.push(...e.scope),n&&s.push(...n),await dx({id:"paybin",options:e,authorizationEndpoint:r,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:i})=>d4({code:t,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=d3(t.idToken),n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name||r.preferred_username||"",email:r.email,image:r.picture,emailVerified:r.email_verified||!1,...n},data:r}},options:e}},paypal:e=>{let t="sandbox"===(e.environment||"sandbox"),r=t?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",n=t?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",i=t?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo";return{id:"paypal",name:"PayPal",async createAuthorizationURL({state:t,codeVerifier:n,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw b.logger.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new E.BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED");return await dx({id:"paypal",options:e,authorizationEndpoint:r,scopes:[],state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let i=sD.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await dJ(n,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r}).toString()});if(!e.data)throw new E.BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN");let a=e.data;return{accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?new Date(Date.now()+1e3*a.expires_in):void 0,idToken:a.id_token}}catch(e){throw b.logger.error("PayPal token exchange failed:",e),new E.BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let r=sD.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await dJ(n,{method:"POST",headers:{Authorization:`Basic ${r}`,Accept:"application/json","Accept-Language":"en_US","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t}).toString()});if(!e.data)throw new E.BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN");let i=e.data;return{accessToken:i.access_token,refreshToken:i.refresh_token,accessTokenExpiresAt:i.expires_in?new Date(Date.now()+1e3*i.expires_in):void 0}}catch(e){throw b.logger.error("PayPal token refresh failed:",e),new E.BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);try{return!!d3(t).sub}catch(e){return b.logger.error("Failed to verify PayPal ID token:",e),!1}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return b.logger.error("Access token is required to fetch PayPal user info"),null;try{let r=await dJ(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:"application/json"}});if(!r.data)return b.logger.error("Failed to fetch user info from PayPal"),null;let n=r.data,a=await e.mapProfileToUser?.(n);return{user:{id:n.user_id,name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:n}}catch(e){return b.logger.error("Failed to fetch user info from PayPal:",e),null}},options:e}},polar:e=>{let t="https://api.polar.sh/v1/oauth2/token";return{id:"polar",name:"Polar",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","profile","email"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"polar",options:e,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i,prompt:e.prompt})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:i})=>d4({code:r,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async r=>dZ({refreshToken:r,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.public_name||r.username||"",email:r.email,image:r.avatar_url,emailVerified:r.email_verified??!1,...i},data:r}},options:e}},railway:e=>({id:"railway",name:"Railway",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a=e.disableDefaultScope?[]:["openid","email","profile"];return e.scope&&a.push(...e.scope),r&&a.push(...r),dx({id:"railway",options:e,authorizationEndpoint:"https://backboard.railway.com/oauth/auth",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>d4({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:ua,authentication:"basic"}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>dZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:ua,authentication:"basic"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://backboard.railway.com/oauth/me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}},options:e}),vercel:e=>({id:"vercel",name:"Vercel",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:i}){let a;if(!n)throw new E.BetterAuthError("codeVerifier is required for Vercel");return(void 0!==e.scope||void 0!==r)&&(a=[],e.scope&&a.push(...e.scope),r&&a.push(...r)),dx({id:"vercel",options:e,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:a,state:t,codeVerifier:n,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>d4({code:t,codeVerifier:r,redirectURI:n,options:e,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await dJ("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n||!r)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name??r.preferred_username??"",email:r.email,image:r.picture,emailVerified:r.email_verified??!1,...i},data:r}},options:e}),wechat:e=>({id:"wechat",name:"WeChat",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let i=e.disableDefaultScope?[]:["snsapi_login"];e.scope&&i.push(...e.scope),r&&i.push(...r);let a=new URL("https://open.weixin.qq.com/connect/qrconnect");return a.searchParams.set("scope",i.join(",")),a.searchParams.set("response_type","code"),a.searchParams.set("appid",e.clientId),a.searchParams.set("redirect_uri",e.redirectURI||n),a.searchParams.set("state",t),a.searchParams.set("lang",e.lang||"cn"),a.hash="wechat_redirect",a},validateAuthorizationCode:async({code:t})=>{let{data:r,error:n}=await dJ("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:"authorization_code"}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to validate authorization code: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(","),openid:r.openid,unionid:r.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:r,error:n}=await dJ("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:e.clientId,grant_type:"refresh_token",refresh_token:t}).toString(),{method:"GET"});if(n||!r||r.errcode)throw Error(`Failed to refresh access token: ${r?.errmsg||n?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:new Date(Date.now()+1e3*r.expires_in),scopes:r.scope.split(",")}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.openid;if(!r)return null;let{data:n,error:i}=await dJ("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:t.accessToken||"",openid:r,lang:"zh_CN"}).toString(),{method:"GET"});if(i||!n||n.errcode)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.unionid||n.openid||r,name:n.nickname,email:n.email||null,image:n.headimgurl,emailVerified:!1,...a},data:n}},options:e})},us=so(Object.keys(uo)).or(oT()),uc=lr("/list-accounts",{method:"GET",use:[lI],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(t=>{let{scope:r,...n}=function(e,t){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=rE(t,rk(e,"account","output"));return c}(e.context.options,t);return{...n,scopes:r?.split(",")||[]}}))}),ul=lr("/link-social",{method:"POST",requireHeaders:!0,body:se({callbackURL:oT().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:us,idToken:se({token:oT(),nonce:oT().optional(),accessToken:oT().optional(),refreshToken:oT().optional(),scopes:o9(oT()).optional()}).optional(),requestSignUp:oX().optional(),scopes:o9(oT()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:oT().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:oX().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),additionalData:si(oT(),o2()).optional()}),use:[lI],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=e.context.session,r=await cx(e.context.socialProviders,{value:e.body.provider});if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),E.APIError.from("NOT_FOUND",rA.BASE_ERROR_CODES.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),E.APIError.from("NOT_FOUND",rA.BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:i}=e.body.idToken;if(!await r.verifyIdToken(n,i))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.INVALID_TOKEN);let a=await r.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);let o=String(a.user.id);if(!a.user.email)throw e.context.logger.error(lz(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);if((await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>e.providerId===r.id&&e.accountId===o))return e.json({url:"",status:!0,redirect:!1});if(!e.context.trustedProviders.includes(r.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw E.APIError.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw E.APIError.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await e.context.internalAdapter.createAccount({userId:t.user.id,providerId:r.id,accountId:o,accessToken:e.body.idToken.accessToken,idToken:n,refreshToken:e.body.idToken.refreshToken,scope:e.body.idToken.scopes?.join(",")})}catch(e){throw E.APIError.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{await e.context.internalAdapter.updateUser(t.user.id,{name:a.user?.name,image:a.user?.image})}catch(e){console.warn("Could not update user - "+e.toString())}return e.json({url:"",status:!0,redirect:!1})}let n=await db(e,{userId:t.user.id,email:t.user.email},e.body.additionalData),i=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`,scopes:e.body.scopes});return e.body.disableRedirect||e.setHeader("Location",i.toString()),e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),ud=lr("/unlink-account",{method:"POST",body:se({providerId:oT(),accountId:oT().optional()}),use:[lO],metadata:{openapi:{description:"Unlink an account",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let{providerId:t,accountId:r}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(1===n.length&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT);let i=n.find(e=>r?e.accountId===r&&e.providerId===t:e.providerId===t);if(!i)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(i.id),e.json({status:!0})}),uu=lr("/get-access-token",{method:"POST",body:se({providerId:oT().meta({description:"The provider ID for the OAuth provider"}),accountId:oT().meta({description:"The account ID associated with the refresh token"}).optional(),userId:oT().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let t,{providerId:r,accountId:n,userId:i}=e.body||{},a=e.request,o=await lR(e);if(a&&!o)throw e.error("UNAUTHORIZED");let s=o?.user?.id||i;if(!s)throw e.error("UNAUTHORIZED");let c=await cx(e.context.socialProviders,{value:r});if(!c)throw E.APIError.from("BAD_REQUEST",{message:`Provider ${r} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});let l=await sI(e);if(!(t=l&&l.userId===s&&r===l.providerId&&(!n||l.accountId===n)?l:(await e.context.internalAdapter.findAccounts(s)).find(e=>n?e.accountId===n&&e.providerId===r:e.providerId===r)))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);try{let r=null,n=t.accessTokenExpiresAt&&new Date(t.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(t.refreshToken&&n&&c.refreshAccessToken){let n=await dE(t.refreshToken,e.context);r=await c.refreshAccessToken(n);let i={accessToken:await dv(r?.accessToken,e.context),accessTokenExpiresAt:r?.accessTokenExpiresAt,refreshToken:r?.refreshToken?await dv(r.refreshToken,e.context):t.refreshToken,refreshTokenExpiresAt:r?.refreshTokenExpiresAt??t.refreshTokenExpiresAt,idToken:r?.idToken||t.idToken},a=null;t.id&&(a=await e.context.internalAdapter.updateAccount(t.id,i)),e.context.options.account?.storeAccountCookie&&await sR(e,{...t,...a??i})}let i=r?.accessTokenExpiresAt?"string"==typeof r.accessTokenExpiresAt?new Date(r.accessTokenExpiresAt):r.accessTokenExpiresAt:t.accessTokenExpiresAt?"string"==typeof t.accessTokenExpiresAt?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt:void 0,a={accessToken:r?.accessToken??await dE(t.accessToken??"",e.context),accessTokenExpiresAt:i,scopes:t.scope?.split(",")??[],idToken:r?.idToken??t.idToken??void 0};return e.json(a)}catch(e){throw E.APIError.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}),up=lr("/refresh-token",{method:"POST",body:se({providerId:oT().meta({description:"The provider ID for the OAuth provider"}),accountId:oT().meta({description:"The account ID associated with the refresh token"}).optional(),userId:oT().meta({description:"The user ID associated with the account"}).optional()}),metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async e=>{let t,r,{providerId:n,accountId:i,userId:a}=e.body,o=e.request,s=await lR(e);if(o&&!s)throw e.error("UNAUTHORIZED");let c=s?.user?.id||a;if(!c)throw E.APIError.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});let l=await cx(e.context.socialProviders,{value:n});if(!l)throw E.APIError.from("BAD_REQUEST",{message:`Provider ${n} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!l.refreshAccessToken)throw E.APIError.from("BAD_REQUEST",{message:`Provider ${n} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let d=await sI(e);if(!(t=d&&d.userId===c&&(!n||n===d?.providerId)?d:(await e.context.internalAdapter.findAccounts(c)).find(e=>i?e.accountId===i&&e.providerId===n:e.providerId===n)))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);if(!(r=d&&n===d.providerId?d.refreshToken??void 0:t.refreshToken??void 0))throw E.APIError.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let i=await dE(r,e.context),a=await l.refreshAccessToken(i),o=a.refreshToken?await dv(a.refreshToken,e.context):r,s=a.refreshTokenExpiresAt??t.refreshTokenExpiresAt;if(t.id){let r={...t||{},accessToken:await dv(a.accessToken,e.context),refreshToken:o,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:s,scope:a.scopes?.join(",")||t.scope,idToken:a.idToken||t.idToken};await e.context.internalAdapter.updateAccount(t.id,r)}return d&&n===d.providerId&&e.context.options.account?.storeAccountCookie&&await sR(e,{...d,accessToken:await dv(a.accessToken,e.context),refreshToken:o,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:s,scope:a.scopes?.join(",")||d.scope,idToken:a.idToken||d.idToken}),e.json({accessToken:a.accessToken,refreshToken:a.refreshToken??i,accessTokenExpiresAt:a.accessTokenExpiresAt,refreshTokenExpiresAt:s,scope:a.scopes?.join(",")||t.scope,idToken:a.idToken||t.idToken,providerId:t.providerId,accountId:t.accountId})}catch(e){throw E.APIError.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),uf=lr("/account-info",{method:"GET",use:[lI],metadata:{openapi:{description:"Get the account info provided by the provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},email:{type:"string"},image:{type:"string"},emailVerified:{type:"boolean"}},required:["id","emailVerified"]},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data"],additionalProperties:!1}}}}}}},query:sl(se({accountId:oT().meta({description:"The provider given account id for which to get the account info"}).optional()}))},async e=>{let t,r=e.query?.accountId;if(r){let n=await e.context.internalAdapter.findAccount(r);n&&(t=n)}else if(e.context.options.account?.storeAccountCookie){let r=await sI(e);r&&(t=r)}if(!t||t.userId!==e.context.session.user.id)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.ACCOUNT_NOT_FOUND);let n=await cx(e.context.socialProviders,{value:t.providerId});if(!n)throw E.APIError.from("INTERNAL_SERVER_ERROR",{message:`Provider account provider is ${t.providerId} but it is not configured`,code:"PROVIDER_NOT_CONFIGURED"});let i=await uu({...e,method:"POST",body:{accountId:t.accountId,providerId:t.providerId},returnHeaders:!1,returnStatus:!1});if(!i.accessToken)throw E.APIError.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let a=await n.getUserInfo({...i,accessToken:i.accessToken});return e.json(a)});async function uh(e,t,r,n=3600,i){return await ru({email:t.toLowerCase(),updateTo:r?.toLowerCase(),...i},e,n)}async function um(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED);let r=await uh(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${n}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:r},e.request?.clone()))}let uy=lr("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:se({email:aJ(oI,void 0).meta({description:"The email to send the verification email to"}),callbackURL:oT().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},400:{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,r=await lR(e);if(!r){let r=await e.context.internalAdapter.findUserByEmail(t);return!r||r.user.emailVerified?await uh(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn):await um(e,r.user),e.json({status:!0})}if(r?.user.email.toLowerCase()!==t.toLowerCase())throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.EMAIL_MISMATCH);if(r?.user.emailVerified)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED);return await um(e,r.user),e.json({status:!0})}),ug=lr("/verify-email",{method:"GET",operationId:"verifyEmail",query:se({token:oT().meta({description:"The token to verify the email"}),callbackURL:oT().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[lc(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async e=>{let t;function r(t){if(e.query.callbackURL){if(e.query.callbackURL.includes("?"))throw e.redirect(`${e.query.callbackURL}&error=${t.code}`);throw e.redirect(`${e.query.callbackURL}?error=${t.code}`)}throw E.APIError.from("UNAUTHORIZED",t)}let{token:n}=e.query;try{t=await rd(n,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(e){if(e instanceof eH)return r(rA.BASE_ERROR_CODES.TOKEN_EXPIRED);return r(rA.BASE_ERROR_CODES.INVALID_TOKEN)}let i=se({email:aJ(oI,void 0),updateTo:oT().optional(),requestType:oT().optional()}).parse(t.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return r(rA.BASE_ERROR_CODES.USER_NOT_FOUND);if(i.updateTo){let t=await lR(e);if(t&&t.user.email!==i.email)return r(rA.BASE_ERROR_CODES.INVALID_USER);switch(i.requestType){case"change-email-confirmation":{let t=await uh(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),r=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/"),n=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:n,token:t},e.request?.clone())),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case"change-email-verification":{let r=t;if(!r){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.APIError.from("INTERNAL_SERVER_ERROR",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);r={session:t,user:a.user}}let n=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(n,e.request),await sM(e,{session:r.session,user:{...r.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:r_(e.context.options,n)})}default:{let r=t;if(!r){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.APIError.from("INTERNAL_SERVER_ERROR",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);r={session:t,user:a.user}}let n=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await uh(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):encodeURIComponent("/");if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:n,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},e.request?.clone())),await sM(e,{session:r.session,user:{...r.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:r_(e.context.options,n)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await lR(e);if(t&&t.user.email===i.email)await sM(e,{session:t.session,user:{...t.user,emailVerified:!0}});else{let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.APIError.from("INTERNAL_SERVER_ERROR",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);await sM(e,{session:t,user:{...a.user,emailVerified:!0}})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function uw(e,t){let{userInfo:r,account:n,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=await e.context.internalAdapter.findOAuthUser(r.email.toLowerCase(),n.accountId,n.providerId).catch(t=>{b.logger.error("Better auth was unable to query your database.\nError: ",t),lL(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,"internal_server_error")}),c=s?.user,l=!c;if(s){let i=s.linkedAccount??s.accounts.find(e=>e.providerId===n.providerId&&e.accountId===n.accountId);if(i){let t=e.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({idToken:n.idToken,accessToken:await dv(n.accessToken,e.context),refreshToken:await dv(n.refreshToken,e.context),accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope}).filter(([e,t])=>void 0!==t)):{};e.context.options.account?.storeAccountCookie&&await sR(e,{...i,...t}),Object.keys(t).length>0&&await e.context.internalAdapter.updateAccount(i.id,t),r.emailVerified&&!s.user.emailVerified&&r.email.toLowerCase()===s.user.email&&await e.context.internalAdapter.updateUser(s.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||e.context.trustedProviders.includes(n.providerId),o=i?.requireLocalEmailVerified??!0;if(!a&&!r.emailVerified||o&&!s.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0)return(0,T.isDevelopment)()&&b.logger.warn(`User already exist but account isn't linked to ${n.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:n.providerId,accountId:r.id.toString(),userId:s.user.id,accessToken:await dv(n.accessToken,e.context),refreshToken:await dv(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope})}catch(e){return b.logger.error("Unable to link account",e),{error:"unable to link account",data:null}}r.emailVerified&&!s.user.emailVerified&&r.email.toLowerCase()===s.user.email&&await e.context.internalAdapter.updateUser(s.user.id,{emailVerified:!0})}if(o){let{id:t,...n}=r;c=await e.context.internalAdapter.updateUser(s.user.id,{...n,email:r.email.toLowerCase(),emailVerified:r.email.toLowerCase()===s.user.email&&s.user.emailVerified||r.emailVerified})}}else{if(a)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:t,...a}=r,o={accessToken:await dv(n.accessToken,e.context),refreshToken:await dv(n.refreshToken,e.context),idToken:n.idToken,accessTokenExpiresAt:n.accessTokenExpiresAt,refreshTokenExpiresAt:n.refreshTokenExpiresAt,scope:n.scope,providerId:n.providerId,accountId:r.id.toString()},{user:s,account:l}=await e.context.internalAdapter.createOAuthUser({...a,email:r.email.toLowerCase()},o);if(c=s,e.context.options.account?.storeAccountCookie&&await sR(e,l),!r.emailVerified&&c&&e.context.options.emailVerification?.sendOnSignUp&&e.context.options.emailVerification?.sendVerificationEmail){let t=await uh(e.context.secret,c.email,void 0,e.context.options.emailVerification?.expiresIn),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${encodeURIComponent(i||"/")}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:c,url:r,token:t},e.request))}}catch(e){if(b.logger.error(e),c9(e))return{error:e.message,data:null,isRegister:!1};return{error:"unable to create user",data:null,isRegister:!1}}}if(!c)return{error:"unable to create user",data:null,isRegister:!1};let d=await e.context.internalAdapter.createSession(c.id);return d?{data:{session:d,user:c},error:null,isRegister:l}:{error:"unable to create session",data:null,isRegister:!1}}let ub={scope:"server"},uA=se({code:oT().optional(),error:oT().optional(),device_id:oT().optional(),error_description:oT().optional(),state:oT().optional(),user:oT().optional()}),uE=lr("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:uA.optional(),query:uA.optional(),metadata:{...ub,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async e=>{let t,r,n,i,a=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if("POST"===e.method){let t=e.body?uA.parse(e.body):{},r=e.query?uA.parse(e.query):{},n=uA.parse({...t,...r}),i=new URLSearchParams;for(let[e,t]of Object.entries(n))null!=t&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if("GET"===e.method)t=uA.parse(e.query);else if("POST"===e.method)t=uA.parse(e.body);else throw Error("Unsupported method")}catch(t){e.context.logger.error("INVALID_CALLBACK_REQUEST",t),lL(e,a,"invalid_callback_request")}let{code:o,error:s,error_description:c,device_id:l,user:d}=t,{codeVerifier:u,callbackURL:p,link:f,errorURL:h,newUserURL:m,requestSignUp:y}=await dA(e),g=h??a;s&&lL(e,g,s,c),o||(e.context.logger.error("Code not found"),lL(e,g,"no_code"));let w=await cx(e.context.socialProviders,{value:e.params.id});w||(e.context.logger.error("Oauth provider with id",e.params.id,"not found"),lL(e,g,"oauth_provider_not_found"));try{r=await w.validateAuthorizationCode({code:o,codeVerifier:u,deviceId:l,redirectURI:`${e.context.baseURL}/callback/${w.id}`})}catch(t){e.context.logger.error("",t),lL(e,g,"invalid_code")}r||lL(e,g,"invalid_code");let b=d?(0,rN.safeJSONParse)(d):null,A=await w.getUserInfo({...r,user:b??void 0}).then(e=>e?.user);A&&void 0!==A.id&&null!==A.id||(e.context.logger.error("Unable to get user info"),lL(e,g,"unable_to_get_user_info"));let E=String(A.id);if(p||(e.context.logger.error("No callback URL found"),lL(e,g,"no_callback_url")),f){let t;(e.context.trustedProviders.includes(w.id)||A.emailVerified)&&e.context.options.account?.accountLinking?.enabled!==!1||(e.context.logger.error("Unable to link account - untrusted provider"),lL(e,g,"unable_to_link_account")),A.email?.toLowerCase()!==f.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0&&lL(e,g,"email_doesn't_match");let n=await e.context.internalAdapter.findAccountByProviderId(E,w.id);if(n){n.userId.toString()!==f.userId.toString()&&lL(e,g,"account_already_linked_to_different_user");let t=Object.fromEntries(Object.entries({accessToken:await dv(r.accessToken,e.context),refreshToken:await dv(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scopes?.join(",")}).filter(([e,t])=>void 0!==t));await e.context.internalAdapter.updateAccount(n.id,t)}else await e.context.internalAdapter.createAccount({userId:f.userId,providerId:w.id,accountId:E,...r,accessToken:await dv(r.accessToken,e.context),refreshToken:await dv(r.refreshToken,e.context),scope:r.scopes?.join(",")})||lL(e,g,"unable_to_link_account");try{t=p.toString()}catch{t=p}throw e.redirect(t)}A.email||(e.context.logger.error(lz(w.id)),lL(e,g,"email_not_found"));let v={providerId:w.id,accountId:E,...r,scope:r.scopes?.join(",")};try{n=await uw(e,{userInfo:{...A,id:E,email:A.email,name:A.name||""},account:v,callbackURL:p,disableSignUp:w.disableImplicitSignUp&&!y||w.options?.disableSignUp,overrideUserInfo:w.options?.overrideUserInfoOnSignIn})}catch(t){throw c9(t)&&t.body?.code&&lL(e,g,t.body.code,t.body.message),t}n.error&&(e.context.logger.error(n.error.split(" ").join("_")),lL(e,g,n.error.split(" ").join("_")));let{session:k,user:_}=n.data;await sM(e,{session:k,user:_});try{i=(n.isRegister&&m||p).toString()}catch{i=n.isRegister&&m||p}throw e.redirect(i)});function uv(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&amp;")}let uk=lr("/error",{method:"GET",metadata:{...ub,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async e=>{let t=new URL(e.request?.url||""),r=t.searchParams.get("error")||"UNKNOWN",n=t.searchParams.get("error_description")||null,i=/^[\'A-Za-z0-9_-]+$/.test(r||"")?r:"UNKNOWN",a=n?uv(n):null,o=new URLSearchParams;o.set("error",i),n&&o.set("error_description",n);let s=e.context.options,c=s.onAPIError?.errorURL;return c?new Response(null,{status:302,headers:{Location:`${c}${c.includes("?")?"&":"?"}${o.toString()}`}}):T.isProduction&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(((e,t="Unknown",r=null)=>{let n=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
78
+ <html lang="en">
79
+ <head>
80
+ <meta charset="UTF-8" />
81
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
82
+ <title>Error</title>
83
+ <style>
84
+ * {
85
+ box-sizing: border-box;
86
+ }
87
+ body {
88
+ font-family: ${n?.font?.defaultFamily||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"};
89
+ background: ${n?.colors?.background||"var(--background)"};
90
+ color: var(--foreground);
91
+ margin: 0;
92
+ }
93
+ :root,
94
+ :host {
95
+ --spacing: 0.25rem;
96
+ --container-md: 28rem;
97
+ --text-sm: ${n?.size?.textSm||"0.875rem"};
98
+ --text-sm--line-height: calc(1.25 / 0.875);
99
+ --text-2xl: ${n?.size?.text2xl||"1.5rem"};
100
+ --text-2xl--line-height: calc(2 / 1.5);
101
+ --text-4xl: ${n?.size?.text4xl||"2.25rem"};
102
+ --text-4xl--line-height: calc(2.5 / 2.25);
103
+ --text-6xl: ${n?.size?.text6xl||"3rem"};
104
+ --text-6xl--line-height: 1;
105
+ --font-weight-medium: 500;
106
+ --font-weight-semibold: 600;
107
+ --font-weight-bold: 700;
108
+ --default-transition-duration: 150ms;
109
+ --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
110
+ --radius: ${n?.size?.radiusSm||"0.625rem"};
111
+ --default-mono-font-family: ${n?.font?.monoFamily||"var(--font-geist-mono)"};
112
+ --primary: ${n?.colors?.primary||"black"};
113
+ --primary-foreground: ${n?.colors?.primaryForeground||"white"};
114
+ --background: ${n?.colors?.background||"white"};
115
+ --foreground: ${n?.colors?.foreground||"oklch(0.271 0 0)"};
116
+ --border: ${n?.colors?.border||"oklch(0.89 0 0)"};
117
+ --destructive: ${n?.colors?.destructive||"oklch(0.55 0.15 25.723)"};
118
+ --muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.545 0 0)"};
119
+ --corner-border: ${n?.colors?.cornerBorder||"#404040"};
120
+ }
121
+
122
+ button, .btn {
123
+ cursor: pointer;
124
+ background: none;
125
+ border: none;
126
+ color: inherit;
127
+ font: inherit;
128
+ transition: all var(--default-transition-duration)
129
+ var(--default-transition-timing-function);
130
+ }
131
+ button:hover, .btn:hover {
132
+ opacity: 0.8;
133
+ }
134
+
135
+ @media (prefers-color-scheme: dark) {
136
+ :root,
137
+ :host {
138
+ --primary: ${n?.colors?.primary||"white"};
139
+ --primary-foreground: ${n?.colors?.primaryForeground||"black"};
140
+ --background: ${n?.colors?.background||"oklch(0.15 0 0)"};
141
+ --foreground: ${n?.colors?.foreground||"oklch(0.98 0 0)"};
142
+ --border: ${n?.colors?.border||"oklch(0.27 0 0)"};
143
+ --destructive: ${n?.colors?.destructive||"oklch(0.65 0.15 25.723)"};
144
+ --muted-foreground: ${n?.colors?.mutedForeground||"oklch(0.65 0 0)"};
145
+ --corner-border: ${n?.colors?.cornerBorder||"#a0a0a0"};
146
+ }
147
+ }
148
+ @media (max-width: 640px) {
149
+ :root, :host {
150
+ --text-6xl: 2.5rem;
151
+ --text-2xl: 1.25rem;
152
+ --text-sm: 0.8125rem;
153
+ }
154
+ }
155
+ @media (max-width: 480px) {
156
+ :root, :host {
157
+ --text-6xl: 2rem;
158
+ --text-2xl: 1.125rem;
159
+ }
160
+ }
161
+ </style>
162
+ </head>
163
+ <body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
164
+ <div
165
+ style="
166
+ display: flex;
167
+ flex-direction: column;
168
+ align-items: center;
169
+ justify-content: center;
170
+ gap: 1.5rem;
171
+ position: relative;
172
+ width: 100%;
173
+ min-height: 100vh;
174
+ padding: 1rem;
175
+ "
176
+ >
177
+ ${n?.disableBackgroundGrid?"":`
178
+ <div
179
+ style="
180
+ position: absolute;
181
+ inset: 0;
182
+ background-image: linear-gradient(to right, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px),
183
+ linear-gradient(to bottom, ${n?.colors?.gridColor||"var(--border)"} 1px, transparent 1px);
184
+ background-size: 40px 40px;
185
+ opacity: 0.6;
186
+ pointer-events: none;
187
+ width: 100vw;
188
+ height: 100vh;
189
+ "
190
+ ></div>
191
+ <div
192
+ style="
193
+ position: absolute;
194
+ inset: 0;
195
+ display: flex;
196
+ align-items: center;
197
+ justify-content: center;
198
+ background: ${n?.colors?.background||"var(--background)"};
199
+ mask-image: radial-gradient(ellipse at center, transparent 20%, black);
200
+ -webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
201
+ pointer-events: none;
202
+ "
203
+ ></div>
204
+ `}
205
+
206
+ <div
207
+ style="
208
+ position: relative;
209
+ z-index: 10;
210
+ border: 2px solid var(--border);
211
+ background: ${n?.colors?.cardBackground||"var(--background)"};
212
+ padding: 1.5rem;
213
+ max-width: 42rem;
214
+ width: 100%;
215
+ "
216
+ >
217
+ ${n?.disableCornerDecorations?"":`
218
+ <!-- Corner decorations -->
219
+ <div
220
+ style="
221
+ position: absolute;
222
+ top: -2px;
223
+ left: -2px;
224
+ width: 2rem;
225
+ height: 2rem;
226
+ border-top: 4px solid var(--corner-border);
227
+ border-left: 4px solid var(--corner-border);
228
+ "
229
+ ></div>
230
+ <div
231
+ style="
232
+ position: absolute;
233
+ top: -2px;
234
+ right: -2px;
235
+ width: 2rem;
236
+ height: 2rem;
237
+ border-top: 4px solid var(--corner-border);
238
+ border-right: 4px solid var(--corner-border);
239
+ "
240
+ ></div>
241
+
242
+ <div
243
+ style="
244
+ position: absolute;
245
+ bottom: -2px;
246
+ left: -2px;
247
+ width: 2rem;
248
+ height: 2rem;
249
+ border-bottom: 4px solid var(--corner-border);
250
+ border-left: 4px solid var(--corner-border);
251
+ "
252
+ ></div>
253
+ <div
254
+ style="
255
+ position: absolute;
256
+ bottom: -2px;
257
+ right: -2px;
258
+ width: 2rem;
259
+ height: 2rem;
260
+ border-bottom: 4px solid var(--corner-border);
261
+ border-right: 4px solid var(--corner-border);
262
+ "
263
+ ></div>`}
264
+
265
+ <div style="text-align: center; margin-bottom: 1.5rem;">
266
+ <div style="margin-bottom: 1.5rem;">
267
+ <div
268
+ style="
269
+ display: inline-block;
270
+ border: 2px solid ${n?.disableTitleBorder?"transparent":n?.colors?.titleBorder||"var(--destructive)"};
271
+ padding: 0.375rem 1rem;
272
+ "
273
+ >
274
+ <h1
275
+ style="
276
+ font-size: var(--text-6xl);
277
+ font-weight: var(--font-weight-semibold);
278
+ color: ${n?.colors?.titleColor||"var(--foreground)"};
279
+ letter-spacing: -0.02em;
280
+ margin: 0;
281
+ "
282
+ >
283
+ ERROR
284
+ </h1>
285
+ </div>
286
+ <div
287
+ style="
288
+ height: 2px;
289
+ background-color: var(--border);
290
+ width: calc(100% + 3rem);
291
+ margin-left: -1.5rem;
292
+ margin-top: 1.5rem;
293
+ "
294
+ ></div>
295
+ </div>
296
+
297
+ <h2
298
+ style="
299
+ font-size: var(--text-2xl);
300
+ font-weight: var(--font-weight-semibold);
301
+ color: var(--foreground);
302
+ margin: 0 0 1rem;
303
+ "
304
+ >
305
+ Something went wrong
306
+ </h2>
307
+
308
+ <div
309
+ style="
310
+ display: inline-flex;
311
+ align-items: center;
312
+ gap: 0.5rem;
313
+ border: 2px solid var(--border);
314
+ background-color: var(--muted);
315
+ padding: 0.375rem 0.75rem;
316
+ margin: 0 0 1rem;
317
+ flex-wrap: wrap;
318
+ justify-content: center;
319
+ "
320
+ >
321
+ <span
322
+ style="
323
+ font-size: 0.75rem;
324
+ color: var(--muted-foreground);
325
+ font-weight: var(--font-weight-semibold);
326
+ "
327
+ >
328
+ CODE:
329
+ </span>
330
+ <span
331
+ style="
332
+ font-size: var(--text-sm);
333
+ font-family: var(--default-mono-font-family, monospace);
334
+ color: var(--foreground);
335
+ word-break: break-all;
336
+ "
337
+ >
338
+ ${uv(t)}
339
+ </span>
340
+ </div>
341
+
342
+ <p
343
+ style="
344
+ color: var(--muted-foreground);
345
+ max-width: 28rem;
346
+ margin: 0 auto;
347
+ font-size: var(--text-sm);
348
+ line-height: 1.5;
349
+ text-wrap: pretty;
350
+ "
351
+ >
352
+ ${!r?`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`:r}
353
+ </p>
354
+ </div>
355
+
356
+ <div
357
+ style="
358
+ display: flex;
359
+ gap: 0.75rem;
360
+ margin-top: 1.5rem;
361
+ justify-content: center;
362
+ flex-wrap: wrap;
363
+ "
364
+ >
365
+ <a
366
+ href="/"
367
+ style="
368
+ text-decoration: none;
369
+ "
370
+ >
371
+ <div
372
+ style="
373
+ border: 2px solid var(--border);
374
+ background: var(--primary);
375
+ color: var(--primary-foreground);
376
+ padding: 0.5rem 1rem;
377
+ border-radius: 0;
378
+ white-space: nowrap;
379
+ "
380
+ class="btn"
381
+ >
382
+ Go Home
383
+ </div>
384
+ </a>
385
+ <a
386
+ href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
387
+ target="_blank"
388
+ rel="noopener noreferrer"
389
+ style="
390
+ text-decoration: none;
391
+ "
392
+ >
393
+ <div
394
+ style="
395
+ border: 2px solid var(--border);
396
+ background: transparent;
397
+ color: var(--foreground);
398
+ padding: 0.5rem 1rem;
399
+ border-radius: 0;
400
+ white-space: nowrap;
401
+ "
402
+ class="btn"
403
+ >
404
+ Ask AI
405
+ </div>
406
+ </a>
407
+ </div>
408
+ </div>
409
+ </div>
410
+ </body>
411
+ </html>`})(e.context.options,i,a),{headers:{"Content-Type":"text/html"}})}),u_=lr("/ok",{method:"GET",metadata:{...ub,openapi:{description:"Check if the API is working",responses:{200:{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async e=>e.json({ok:!0}));function uS(e,t,r){let n=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([e,t])=>n.searchParams.set(e,t)),n.href}let ux=lr("/request-password-reset",{method:"POST",body:se({email:aJ(oI,void 0).meta({description:"The email address of the user to send a password reset email to"}),redirectTo:oT().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[lc(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),E.APIError.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return(0,cd.generateId)(24),await e.context.internalAdapter.findVerificationValue("dummy-verification-token"),e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let i=rI(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),a=(0,cd.generateId)(24);await e.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=r?encodeURIComponent(r):"",s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:n.user,url:s,token:a},e.request)),e.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),uT=lr("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:se({callbackURL:oT().meta({description:"The URL to redirect the user to reset their password"})}),use:[lc(e=>e.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{var t,r;let n,{token:i}=e.params,{callbackURL:a}=e.query;if(!i||!a)throw e.redirect(uS(e.context,a,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);if(!o||o.expiresAt<new Date)throw e.redirect(uS(e.context,a,{error:"INVALID_TOKEN"}));throw e.redirect((t=e.context,r={token:i},n=new URL(a,t.baseURL),r&&Object.entries(r).forEach(([e,t])=>n.searchParams.set(e,t)),n.href))}),uR=lr("/reset-password",{method:"POST",operationId:"resetPassword",query:se({token:oT().optional()}).optional(),body:se({newPassword:oT().meta({description:"The new password to set"}),token:oT().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_TOKEN);let{newPassword:r}=e.body,n=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<n)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);if(r.length>i)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=`reset-password:${t}`,o=await e.context.internalAdapter.findVerificationValue(a);if(!o||o.expiresAt<new Date)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_TOKEN);let s=o.value,c=await e.context.password.hash(r);if((await e.context.internalAdapter.findAccounts(s)).find(e=>"credential"===e.providerId)?await e.context.internalAdapter.updatePassword(s,c):await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:c,accountId:s}),await e.context.internalAdapter.deleteVerificationByIdentifier(a),e.context.options.emailAndPassword?.onPasswordReset){let t=await e.context.internalAdapter.findUserById(s);t&&await e.context.options.emailAndPassword.onPasswordReset({user:t},e.request)}return e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteSessions(s),e.json({status:!0})}),uI=lr("/verify-password",{method:"POST",body:se({password:oT().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[lU]},async e=>{let{password:t}=e.body,r=e.context.session;if(!await cR(e,{password:t,userId:r.user.id}))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_PASSWORD);return e.json({status:!0})}),uU=se({callbackURL:oT().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:oT().optional(),errorCallbackURL:oT().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:us,disableRedirect:oX().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:sl(se({token:oT().meta({description:"ID token from the provider"}),nonce:oT().meta({description:"Nonce used to generate the token"}).optional(),accessToken:oT().meta({description:"Access token from the provider"}).optional(),refreshToken:oT().meta({description:"Refresh token from the provider"}).optional(),expiresAt:oZ().meta({description:"Expiry date of the token"}).optional(),user:se({name:se({firstName:oT().optional(),lastName:oT().optional()}).optional(),email:oT().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:o9(oT()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:oX().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:oT().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalData:si(oT(),o2()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),uO=lr("/sign-out",{method:"POST",operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error("Failed to delete session from database",t)}return sW(e),e.json({success:!0})}),uP=se({name:oT(),email:aJ(oI,void 0),password:oT().nonempty(),image:oT().optional(),callbackURL:oT().optional(),rememberMe:oX().optional()}).and(si(oT(),o2())),uC=si(oT().meta({description:"Field name must be a string"}),o2()),uD=si(oT().meta({description:"Field name must be a string"}),o2()),uL=lr("/change-password",{method:"POST",operationId:"changePassword",body:se({newPassword:oT().meta({description:"The new password to set"}),currentPassword:oT().meta({description:"The current password is required"}),revokeOtherSessions:oX().meta({description:"Must be a boolean value"}).optional()}),use:[lU],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{200:{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,i=e.context.session,a=e.context.password.config.minPasswordLength;if(t.length<a)throw e.context.logger.error("Password is too short"),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.error("Password is too long"),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!s||!s.password)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:s.password,password:r}))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_PASSWORD);await e.context.internalAdapter.updateAccount(s.id,{password:c});let l=null;if(n){await e.context.internalAdapter.deleteSessions(i.user.id);let t=await e.context.internalAdapter.createSession(i.user.id);if(!t)throw E.APIError.from("INTERNAL_SERVER_ERROR",rA.BASE_ERROR_CODES.FAILED_TO_GET_SESSION);await sM(e,{session:t,user:i.user}),l=t.token}return e.json({token:l,user:r_(e.context.options,i.user)})}),uz=lr({method:"POST",body:se({newPassword:oT().meta({description:"The new password to set is required"})}),use:[lU]},async e=>{let{newPassword:t}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(e=>"credential"===e.providerId&&e.password),o=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:o}),e.json({status:!0});throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_ALREADY_SET)}),u$=lr("/delete-user",{method:"POST",use:[lU],body:se({callbackURL:oT().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:oT().meta({description:"The password of the user is required to delete the user"}).optional(),token:oT().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{200:{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),E.APIError.fromStatus("NOT_FOUND");let t=e.context.session;if(e.body.password){let r=(await e.context.internalAdapter.findAccounts(t.user.id)).find(e=>"credential"===e.providerId&&e.password);if(!r||!r.password)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:r.password,password:e.body.password}))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_PASSWORD)}if(e.body.token)return await uN({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=lN(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400))});let n=`${e.context.baseURL}/delete-user/callback?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:r},e.request)),e.json({success:!0,message:"Verification email sent"})}if(!e.body.password&&0!==e.context.sessionConfig.freshAge){let r=new Date(t.session.createdAt).getTime(),n=1e3*e.context.sessionConfig.freshAge;if(Date.now()-r>=n)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.SESSION_EXPIRED)}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),sW(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),uN=lr("/delete-user/callback",{method:"GET",query:se({token:oT().meta({description:"The token to verify the deletion request"}),callbackURL:oT().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[lc(e=>e.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{200:{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),E.APIError.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let t=await lR(e);if(!t)throw E.APIError.from("NOT_FOUND",rA.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date||r.value!==t.user.id)throw E.APIError.from("NOT_FOUND",rA.BASE_ERROR_CODES.INVALID_TOKEN);let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationByIdentifier(`delete-account-${e.query.token}`),sW(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),uj=lr("/change-email",{method:"POST",body:se({newEmail:aJ(oI,void 0).meta({description:"The new email address to set must be a valid email address"}),callbackURL:oT().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[lU],metadata:{openapi:{operationId:"changeEmail",responses:{200:{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.error("Email is the same"),E.APIError.fromStatus("BAD_REQUEST",{message:"Email is the same"});let r=!0!==e.context.session.user.emailVerified&&e.context.options.user.changeEmail.updateEmailWithoutVerification,n=e.context.options.emailVerification?.sendVerificationEmail,i=n&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!r&&!i&&!n)throw e.context.logger.error("Verification email isn't enabled."),E.APIError.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await e.context.internalAdapter.findUserByEmail(t))return await uh(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info("Change email attempt for existing email"),e.json({status:!0});if(r){if(await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:t}),await sM(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),n){let r=await uh(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:i,token:r},e.request))}return e.json({status:!0})}if(i){let r=await uh(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:n,token:r},e.request)),e.json({status:!0})}if(!n)throw e.context.logger.error("Verification email isn't enabled."),E.APIError.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let a=await uh(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||"/")}`;return await e.context.runInBackgroundOrAwait(n({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),uH=ch((e,t,r)=>{if(Array.isArray(e[t])&&Array.isArray(r))return e[t]=r,!0}),uB=new WeakMap;async function uV(e,t){if(e.baseURL)return e;let r=function(e){if(D(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has("host")||t.has("x-forwarded-host"))return t}(t),n=e.options.baseURL,i=C(n)&&!!n.fallback;if(void 0===r&&!i)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await cS(e,r,c_(e.options))}catch(e){if(e instanceof E.BetterAuthError)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:e.message});throw e}}async function uM(e,t,r,n){let i={};for(let a of t){let t=!1;try{t=a.matcher(e)}catch(r){let t=uB.get(a.handler)??"unknown";throw e.context.logger.error(`An error occurred during ${t} hook matcher execution:`,r),new E.APIError("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(t){let t=uB.get(a.handler)??"unknown",o=r.path??"/:virtual",s=await (0,cl.withSpan)(`hook before ${o} ${t}`,{[cs]:"before",[ca.ATTR_HTTP_ROUTE]:o,[cc]:t,[co]:n},()=>a.handler({...e,returnHeaders:!1})).catch(t=>{throw c9(t)&&(0,b.shouldPublishLog)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),t});if(s&&"object"==typeof s){if("context"in s&&"object"==typeof s.context){let{headers:e,...t}=s.context;e instanceof Headers&&(i.headers?e.forEach((e,t)=>{i.headers?.set(t,e)}):i.headers=e),i=uH(t,i);continue}return s}}}return{context:i}}async function uK(e,t,r,n){for(let i of t)if(i.matcher(e)){let t=uB.get(i.handler)??"unknown",a=r.path??"/:virtual",o=await (0,cl.withSpan)(`hook after ${a} ${t}`,{[cs]:"after",[ca.ATTR_HTTP_ROUTE]:a,[cc]:t,[co]:n},()=>i.handler(e)).catch(t=>{if(c9(t)){let r=t[cU.kAPIErrorHeaderSymbol];return(0,b.shouldPublishLog)(e.context.logger.level,"debug")&&(t.stack=t.errorStack),{response:t,headers:r||(t.headers?new Headers(t.headers):null)}}throw t});o.headers&&o.headers.forEach((t,r)=>{e.context.responseHeaders?"set-cookie"===r.toLowerCase()?e.context.responseHeaders.append(r,t):e.context.responseHeaders.set(r,t):e.context.responseHeaders=new Headers({[r]:t})}),o.response&&(e.context.returned=o.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function uW(e,t){let r=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},n=t.plugins?.map(t=>t.middlewares?.map(r=>{let n=async n=>{let i=await e;return(0,cl.withSpan)(`middleware ${r.path} ${t.id}`,{[cs]:"middleware",[ca.ATTR_HTTP_ROUTE]:r.path,[cc]:`plugin:${t.id}`},()=>r.middleware({...n,context:{...i,...n.context}}))};return n.options=r.middleware.options,{path:r.path,middleware:n}})).filter(e=>void 0!==e).flat()||[];return{api:function(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=async e=>{let r=function(e,t){if(!e?.options)return t;let r=e.options;return r.operationId??r.metadata?.openapi?.operationId??t}(i,n),a=i?.options?.method,o=Array.isArray(a)?a[0]:a,s=async()=>{let n=await t,a=e?.method??e?.request?.method??o??"?",s=i.path??"/:virtual",c=C(n.options.baseURL)?await uV(n,e):n,l={...e,context:{...c,returned:void 0,responseHeaders:void 0,session:null},path:i.path,headers:e?.headers?new Headers(e?.headers):void 0},d=D(e?.request),u=e?.asResponse??d;return(0,cl.withSpan)(`${a} ${s}`,{[ca.ATTR_HTTP_ROUTE]:s,[co]:r},async()=>ci(l,async()=>{let{beforeHooks:t,afterHooks:n}=function(e){let t=e.options.plugins||[],r=[],n=[],i=e.options.hooks?.before;i&&(uB.set(i,"user"),r.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(uB.set(a,"user"),n.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(uB.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(uB.set(t.handler,`plugin:${e.id}`),t)));return o.length&&r.push(...o),s.length&&n.push(...s),{beforeHooks:r,afterHooks:n}}(c),a=await uM(l,t,i,r);if("context"in a&&a.context&&"object"==typeof a.context){let{headers:e,...t}=a.context;e&&e.forEach((e,t)=>{l.headers.set(t,e)}),l=uH(t,l)}else if(a)return u?cN(a,{headers:e?.headers}):e?.returnHeaders?{headers:e?.headers,response:a}:a;l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let o=await ci(l,()=>(0,cl.withSpan)(`handler ${s}`,{[ca.ATTR_HTTP_ROUTE]:s,[co]:r},()=>i(l))).catch(e=>{if(c9(e)){let t=e[cU.kAPIErrorHeaderSymbol],r=e.headers&&e.headers!==t?new Headers(e.headers):null,n=null;return(t||r)&&(n=new Headers,t?.forEach((e,t)=>{n.append(t,e)}),r?.forEach((e,t)=>{"set-cookie"===t.toLowerCase()?n.append(t,e):n.set(t,e)})),{response:e,status:e.statusCode,headers:n}}throw e});if(o&&o instanceof Response)return o;l.context.returned=o.response,l.context.responseHeaders=o.headers;let d=await uK(l,n,i,r);if(d.response&&(o.response=d.response),c9(o.response)&&(0,b.shouldPublishLog)(c.logger.level,"debug")&&(o.response.stack=o.response.errorStack),c9(o.response)&&!u)throw o.headers&&Object.defineProperty(o.response,cU.kAPIErrorHeaderSymbol,{enumerable:!1,configurable:!0,writable:!1,value:o.headers}),o.response;return u?cN(o.response,{headers:o.headers,status:o.status}):e?.returnHeaders?e?.returnStatus?{headers:o.headers,response:o.response,status:o.status}:{headers:o.headers,response:o.response}:e?.returnStatus?{response:o.response,status:o.status}:o.response}))};return await lb()?s():lE(new WeakMap,s)},r[n].path=i.path,r[n].options=i.options;return r}({signInSocial:lr("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:uU,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{200:{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async e=>{let t=await cx(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),E.APIError.from("NOT_FOUND",rA.BASE_ERROR_CODES.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),E.APIError.from("NOT_FOUND",rA.BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:n}=e.body.idToken;if(!await t.verifyIdToken(r,n))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.INVALID_TOKEN);let i=await t.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user});if(!i||!i?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO);if(!i.user.email)throw e.context.logger.error(lz(e.body.provider,{source:"id_token"}),{provider:e.body.provider}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND);let a=await uw(e,{userInfo:{...i.user,email:i.user.email,id:String(i.user.id),name:i.user.name||"",image:i.user.image,emailVerified:i.user.emailVerified||!1},account:{providerId:t.id,accountId:String(i.user.id),accessToken:e.body.idToken.accessToken},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp});if(a.error)throw E.APIError.from("UNAUTHORIZED",{message:a.error,code:"OAUTH_LINK_ERROR"});return await sM(e,a.data),e.json({redirect:!1,token:a.data.session.token,url:void 0,user:r_(e.context.options,a.data.user)})}let{codeVerifier:r,state:n}=await db(e,void 0,e.body.additionalData),i=await t.createAuthorizationURL({state:n,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`,scopes:e.body.scopes,loginHint:e.body.loginHint});return e.body.disableRedirect||e.setHeader("Location",i.toString()),e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),callbackOAuth:uE,getSession:lT(),signOut:uO,signUpEmail:lr("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[ld],body:uP,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{200:{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},422:{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async e=>ce(e.context.adapter,async()=>{let t;if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw E.APIError.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=e.body,{name:n,email:i,password:a,image:o,callbackURL:s,rememberMe:c,...l}=r;if(!aJ(oI,void 0).safeParse(i).success)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_EMAIL);if(!a||"string"!=typeof a)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_PASSWORD);let d=e.context.password.config.minPasswordLength;if(a.length<d)throw e.context.logger.error("Password is too short"),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let u=e.context.password.config.maxPasswordLength;if(a.length>u)throw e.context.logger.error("Password is too long"),E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let p=e.context.options.emailAndPassword.requireEmailVerification||!1===e.context.options.emailAndPassword.autoSignIn,f=!1===e.context.options.emailAndPassword.autoSignIn||p,h=rR(e.context.options,l,"create"),m=i.toLowerCase(),y=await e.context.internalAdapter.findUserByEmail(m);if(y?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${i}`),p){let t;await e.context.password.hash(a),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:y.user},e.request?.clone()));let r=new Date,i=e.context.generateId({model:"user"})||(0,cd.generateId)(),s={name:n,email:m,emailVerified:!1,image:o??null,createdAt:r,updatedAt:r},c=e.context.options.emailAndPassword?.customSyntheticUser;if(c){let r=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of r)e in h&&(n[e]=h[e]);let a=c({coreFields:s,additionalFields:n,id:i});t=rS(e.context.options,a)}else t=rS(e.context.options,{...s,...h,id:i});return e.json({token:null,user:r_(e.context.options,t)})}throw E.APIError.from("UNPROCESSABLE_ENTITY",rA.BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let g=await e.context.password.hash(a);try{if(!(t=await e.context.internalAdapter.createUser({email:m,name:n,image:o,...h,emailVerified:!1})))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_USER)}catch(t){if((0,T.isDevelopment)()&&e.context.logger.error("Failed to create user",t),c9(t))throw t;throw e.context.logger?.error("Failed to create user",t),E.APIError.from("UNPROCESSABLE_ENTITY",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_USER)}if(!t)throw E.APIError.from("UNPROCESSABLE_ENTITY",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:t.id,providerId:"credential",accountId:t.id,password:g}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await uh(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),i=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),a=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${i}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:t,url:a,token:n},e.request?.clone()))}if(f)return e.json({token:null,user:r_(e.context.options,t)});let w=await e.context.internalAdapter.createSession(t.id,!1===c);if(!w)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);return await sM(e,{session:w,user:t},!1===c),e.json({token:w.token,user:r_(e.context.options,t)})})),signInEmail:lr("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[ld],cloneRequest:!0,body:se({email:oT().meta({description:"Email of the user"}),password:oT().meta({description:"Password of the user"}),callbackURL:oT().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:oX().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{200:{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),E.APIError.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!aJ(oI,void 0).safeParse(t).success)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.INVALID_EMAIL);let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);let i=n.accounts.find(e=>"credential"===e.providerId);if(!i)throw await e.context.password.hash(r),e.context.logger.error("Credential account not found",{email:t}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);let a=i?.password;if(!a)throw await e.context.password.hash(r),e.context.logger.error("Password not found",{email:t}),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:a,password:r}))throw e.context.logger.error("Invalid password"),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await uh(e.context.secret,n.user.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):encodeURIComponent("/"),i=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${r}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:i,token:t},e.request?.clone()))}throw E.APIError.from("FORBIDDEN",rA.BASE_ERROR_CODES.EMAIL_NOT_VERIFIED)}let o=await e.context.internalAdapter.createSession(n.user.id,!1===e.body.rememberMe);if(!o)throw e.context.logger.error("Failed to create session"),E.APIError.from("UNAUTHORIZED",rA.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);return await sM(e,{session:o,user:n.user},!1===e.body.rememberMe),e.body.callbackURL&&e.setHeader("Location",e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:o.token,url:e.body.callbackURL,user:r_(e.context.options,n.user)})}),resetPassword:uR,verifyPassword:uI,verifyEmail:ug,sendVerificationEmail:uy,changeEmail:uj,changePassword:uL,setPassword:uz,updateSession:lr("/update-session",{method:"POST",operationId:"updateSession",body:uC,use:[lI],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{var t;let r=e.body;if("object"!=typeof r||Array.isArray(r))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,i=(t=e.context.options,rT(r,{fields:rk(t,"session","input"),action:"update"}));if(0===Object.keys(i).length)throw E.APIError.fromStatus("BAD_REQUEST",{message:"No fields to update"});let a=await e.context.internalAdapter.updateSession(n.session.token,{...i,updatedAt:new Date})??{...n.session,...i,updatedAt:new Date};return await sM(e,{session:a,user:n.user}),e.json({session:rx(e.context.options,a)})}),updateUser:lr("/update-user",{method:"POST",operationId:"updateUser",body:uD,use:[lI],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let t=e.body;if("object"!=typeof t||Array.isArray(t))throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.BODY_MUST_BE_AN_OBJECT);if(t.email)throw E.APIError.from("BAD_REQUEST",rA.BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED);let{name:r,image:n,...i}=t,a=e.context.session,o=rR(e.context.options,i,"update");if(void 0===n&&void 0===r&&0===Object.keys(o).length)throw E.APIError.fromStatus("BAD_REQUEST",{message:"No fields to update"});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:r,image:n,...o})??{...a.user,...void 0!==r&&{name:r},...void 0!==n&&{image:n},...o};return await sM(e,{session:a.session,user:s}),e.json({status:!0})}),deleteUser:u$,requestPasswordReset:ux,requestPasswordResetCallback:uT,listSessions:lr("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[lI],requireHeaders:!0,metadata:{openapi:{operationId:"listUserSessions",description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>new Date);return e.json(t.map(t=>rx(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error("INTERNAL_SERVER_ERROR")}}),revokeSession:lP,revokeSessions:lC,revokeOtherSessions:lD,linkSocialAccount:ul,listUserAccounts:uc,deleteUserCallback:uN,unlinkAccount:ud,refreshToken:up,getAccessToken:uu,accountInfo:uf,...r,ok:u_,error:uk},e),middlewares:n}}var uq=e.i(902157),uF=e.i(912714),uJ=e.i(660526),uZ=e.i(750227);async function uG(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let r=e.socialProviders?.[t];if(!r)return{};let n="function"==typeof r?await r():r;return{id:t,mapProfileToUser:!!n.mapProfileToUser,disableDefaultScope:!!n.disableDefaultScope,disableIdTokenSignIn:!!n.disableIdTokenSignIn,disableImplicitSignUp:n.disableImplicitSignUp,disableSignUp:n.disableSignUp,getUserInfo:!!n.getUserInfo,overrideUserInfoOnSignIn:!!n.overrideUserInfoOnSignIn,prompt:n.prompt,verifyIdToken:!!n.verifyIdToken,scope:n.scope,refreshAccessToken:!!n.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}async function uQ(e){let t=await sG("SHA-256").digest(e);return sD.encode(t)}async function uY(){if(n)return n;try{let e=process.cwd();if(!e)return;let t=await uF.default.readFile(uZ.default.join(e,"package.json"),"utf-8");return n=JSON.parse(t)}catch{}}async function uX(e){if(n)return n.dependencies?.[e]||n.devDependencies?.[e]||n.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error("no-cwd");let r=uZ.default.join(t,"node_modules",e,"package.json"),n=await uF.default.readFile(r,"utf-8");return JSON.parse(n).version||await u0(e)||void 0}catch{}return u0(e)}async function u0(e){let t=await uY();if(t)return({...t.dependencies,...t.devDependencies,...t.peerDependencies})[e]}async function u1(){return(await uY())?.name}async function u2(){try{let e,t,r=uJ.default.cpus();return{deploymentVendor:(e=process.env,(t=(...t)=>t.some(t=>!!e[t]))("CF_PAGES","CF_PAGES_URL","CF_ACCOUNT_ID")||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent?"cloudflare":t("VERCEL","VERCEL_URL","VERCEL_ENV")?"vercel":t("NETLIFY","NETLIFY_URL")?"netlify":t("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":t("AWS_LAMBDA_FUNCTION_NAME","AWS_EXECUTION_ENV","LAMBDA_TASK_ROOT")?"aws":t("GOOGLE_CLOUD_FUNCTION_NAME","GOOGLE_CLOUD_PROJECT","GCP_PROJECT","K_SERVICE")?"gcp":t("AZURE_FUNCTION_NAME","FUNCTIONS_WORKER_RUNTIME","WEBSITE_INSTANCE_ID","WEBSITE_SITE_NAME")?"azure":t("DENO_DEPLOYMENT_ID","DENO_REGION")?"deno-deploy":t("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":t("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":t("DYNO","HEROKU_APP_NAME")?"heroku":t("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":t("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null),systemPlatform:uJ.default.platform(),systemRelease:uJ.default.release(),systemArchitecture:uJ.default.arch(),cpuCount:r.length,cpuModel:r.length?r[0].model:null,cpuSpeed:r.length?r[0].speed:null,memory:uJ.default.totalmem(),isWSL:await u9(),isDocker:await u8(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}async function u6(){try{return uq.default.statSync("/.dockerenv"),!0}catch{return!1}}async function u5(){try{return uq.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}async function u8(){return void 0===i&&(i=await u6()||await u5()),i}let u4=async()=>{try{return uq.default.statSync("/run/.containerenv"),!0}catch{return!1}};async function u3(){return void 0===a&&(a=await u4()||await u8()),a}async function u9(){try{if(uJ.default.release().toLowerCase().includes("microsoft")){if(await u3())return!1;return!0}return!!uq.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!await u3()}catch{return!1}}let u7=null;async function pe(e){if(u7)return u7;let t=await u1();return t?u7=await uQ(e?e+t:t):e?u7=await uQ(e):u7=(0,l$.createRandomStringGenerator)("a-z","A-Z","0-9")(32)}async function pt(){for(let[e,t]of Object.entries({pg:"postgresql",mysql:"mysql",mariadb:"mariadb",sqlite3:"sqlite","better-sqlite3":"sqlite","@prisma/client":"prisma",mongoose:"mongodb",mongodb:"mongodb","drizzle-orm":"drizzle"})){let r=await uX(e);if(r)return{name:t,version:r}}}async function pr(){for(let[e,t]of Object.entries({next:"next",nuxt:"nuxt","react-router":"react-router",astro:"astro","@sveltejs/kit":"sveltekit","solid-start":"solid-start","tanstack-start":"tanstack-start",hono:"hono",express:"express",elysia:"elysia",expo:"expo"})){let r=await uX(e);if(r)return{name:t,version:r}}}let pn=async function(){};async function pi(e,t){let r,n=e.telemetry?.debug||(0,T.getBooleanEnvVar)("BETTER_AUTH_TELEMETRY_DEBUG",!1),i=T.ENV.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!i&&!t?.customTrack)return{publish:pn};let a=async e=>{t?.customTrack?await t.customTrack(e).catch(b.logger.error):i&&(n?b.logger.info("telemetry event",JSON.stringify(e,null,2)):await dJ(i,{method:"POST",body:e}).catch(b.logger.error))},o=async()=>{let r=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return((0,T.getBooleanEnvVar)("BETTER_AUTH_TELEMETRY",!1)||r)&&(t?.skipTestCheck||!(0,T.isTest)())},s=await o();return s&&(r=await pe("string"==typeof e.baseURL?e.baseURL:void 0),a({type:"init",payload:{config:await uG(e,t),runtime:"u">typeof Deno?{name:"deno",version:Deno?.version?.deno??null}:"u">typeof Bun?{name:"bun",version:Bun?.version??null}:"u">typeof process&&process?.versions?.node?{name:"node",version:process.versions.node??null}:{name:"edge",version:null},database:await pt(),framework:await pr(),environment:"production"===(0,T.getEnvVar)("NODE_ENV")?"production":"false"!==T.env.CI&&("BUILD_ID"in T.env||"BUILD_NUMBER"in T.env||"CI"in T.env||"CI_APP_ID"in T.env||"CI_BUILD_ID"in T.env||"CI_BUILD_NUMBER"in T.env||"CI_NAME"in T.env||"CONTINUOUS_INTEGRATION"in T.env||"RUN_ID"in T.env)?"ci":(0,T.isTest)()?"test":"development",systemInfo:await u2(),packageManager:function(){let e=T.env.npm_config_user_agent;if(!e)return;let t=e.split(" ")[0],r=t.lastIndexOf("/"),n=t.substring(0,r);return{name:"npminstall"===n?"cnpm":n,version:t.substring(r+1)}}()},anonymousId:r})),{publish:async t=>{s&&(r||(r=await pe("string"==typeof e.baseURL?e.baseURL:void 0)),await a({type:t.type,payload:t.payload,anonymousId:r}))}}}async function pa(e,t,r){let n,i,a,o;t.database||(t=cm(t,{session:{cookieCache:{enabled:!0,strategy:"jwe",refreshCache:!0,maxAge:t.session?.expiresIn||604800}},account:{storeStateStrategy:"cookie",storeAccountCookie:!0}}));let s=t.plugins||[],c=(h=t,h.advanced?.crossSubDomainCookies?.enabled,[]),l=(0,b.createLogger)(t.logger),d=C(t.baseURL);if(C(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||0===e.length)throw new E.BetterAuthError('baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).')}let u=d?void 0:O("string"==typeof t.baseURL?t.baseURL:void 0,t.basePath);u||d||l.warn("[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_URL environment variable. Without this, callbacks and redirects may not work correctly."),"memory"===e.id&&t.advanced?.database?.generateId===!1&&l.error(`[better-auth] Misconfiguration detected.
412
+ You are using the memory DB with generateId: false.
413
+ This will cause no id to be generated for any model.
414
+ Most of the features of Better Auth will not work correctly.`);let p=t.secrets??((m=T.env.BETTER_AUTH_SECRETS)?m.split(",").map(e=>{let t=(e=e.trim()).indexOf(":");if(-1===t)throw new E.BetterAuthError(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let r=parseInt(e.slice(0,t),10);if(!Number.isInteger(r)||r<0)throw new E.BetterAuthError(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let n=e.slice(t+1).trim();if(!n)throw new E.BetterAuthError(`Empty secret value for version ${r} in BETTER_AUTH_SECRETS.`);return{version:r,value:n}}):null),f=t.secret||T.env.BETTER_AUTH_SECRET||T.env.AUTH_SECRET||"";if(p)!function(e,t){var r;let n;if(0===e.length)throw new E.BetterAuthError("`secrets` array must contain at least one entry.");let i=new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new E.BetterAuthError(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new E.BetterAuthError(`Empty secret value for version ${e} in \`secrets\`.`);if(i.has(e))throw new E.BetterAuthError(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);i.add(e)}let a=e[0];a.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${a.version}) should be at least 32 characters long for adequate security.`),120>(0===(n=new Set(r=a.value).size)?0:Math.log2(Math.pow(n,r.length)))&&t.warn("[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.")}(p,l),n=p[0].value,i=function(e,t){let r=new Map;for(let t of e)r.set(parseInt(String(t.version),10),t.value);return{keys:r,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&"better-auth-secret-12345678901234567890"!==t?t:void 0}}(p,f);else{var h,m,y=n=f||"better-auth-secret-12345678901234567890";let e="better-auth-secret-12345678901234567890"===y;if(!(0,T.isTest)()){let t;if(e&&T.isProduction)throw new E.BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!y)throw new E.BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");y.length<32&&l.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),120>(0===(t=new Set(y).size)?0:Math.log2(Math.pow(t,y.length)))&&l.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.")}i=n}!function(e,t){let r=new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,n]of Object.entries(e.endpoints))if(n&&"path"in n&&"string"==typeof n.path){let i=n.path,a=[];n.options&&"method"in n.options&&(Array.isArray(n.options.method)?a=n.options.method:"string"==typeof n.options.method&&(a=[n.options.method])),0===a.length&&(a=["*"]),r.has(i)||r.set(i,[]),r.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let n=[];for(let[e,t]of r.entries())if(t.length>1){let r=new Map,i=!1;for(let e of t)for(let n of e.methods)r.has(n)||r.set(n,[]),r.get(n).push(e.pluginId),r.get(n).length>1&&(i=!0),"*"===n&&t.length>1?i=!0:"*"!==n&&r.has("*")&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,n]of r.entries())(n.length>1||"*"===e&&t.length>1||"*"!==e&&r.has("*"))&&a.push(e);n.push({path:e,plugins:i,conflictingMethods:a})}}if(n.length>0){let e=n.map(e=>` - "${e.path}" [${e.conflictingMethods.join(", ")}] used by plugins: ${e.plugins.join(", ")}`).join("\n");t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
415
+ ${e}
416
+
417
+ To resolve this, you can:
418
+ 1. Use only one of the conflicting plugins
419
+ 2. Configure the plugins to use different paths (if supported)
420
+ 3. Ensure plugins use different HTTP methods for the same path
421
+ `)}}(t={...t,secret:n,baseURL:d?t.baseURL:u?new URL(u).origin:"",basePath:t.basePath||"/api/auth",plugins:s.concat(c)},l);let g=sB(t),A=(0,w.getAuthTables)(t),v=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let r="function"==typeof t?await t():t;if(null==r||!1===r.enabled)return null;r.clientId||l.warn(`Social provider ${e} is missing clientId or clientSecret`);let n=uo[e](r);return n.disableImplicitSignUp=r.disableImplicitSignUp,n}))).filter(e=>null!==e),k=({model:e,size:r})=>{if("function"==typeof t.advanced?.generateId)return t.advanced.generateId({model:e,size:r});let n=t?.advanced?.database?.generateId;return"function"==typeof n?n({model:e,size:r}):"uuid"===n?crypto.randomUUID():"serial"!==n&&!1!==n&&(0,cd.generateId)(r)},{publish:_}=await pi(t,{adapter:e.id,database:"function"==typeof t.database?"adapter":r(t.database)}),S=new Set(t.plugins.map(e=>e.id)),x=await ck(t),R=await cT(t),I={appName:t.appName||"Better Auth",baseURL:u||"",version:s5().version,socialProviders:v,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(t.database?"database":"cookie"),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:A,trustedOrigins:x,trustedProviders:R,isTrustedOrigin(e,t){return this.trustedOrigins.some(r=>z(e,r,t))},sessionConfig:{updateAge:t.session?.updateAge!==void 0?t.session.updateAge:86400,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(a=t.session?.cookieCache?.refreshCache,o=t.session?.cookieCache?.maxAge||300,(t.database||t.secondaryStorage)&&a?(l.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==a&&void 0!==a&&(!0===a?{enabled:!0,updateAge:Math.floor(.2*o)}:{enabled:!0,updateAge:void 0!==a.updateAge?a.updateAge:Math.floor(.2*o)}))},secret:n,secretConfig:i,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??T.isProduction,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?"secondary-storage":"memory")},authCookies:g,logger:l,generateId:k,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||H,verify:t.emailAndPassword?.password?.verify||V,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:cI},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:cp(e,{options:t,logger:l,hooks:t.databaseHooks?[{source:"user",hooks:t.databaseHooks}]:[],generateId:k}),createAuthCookie:sH(t),async runMigrations(){throw new E.BetterAuthError("runMigrations will be set by the specific init implementation")},publishTelemetry:_,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck!==void 0?t.advanced.disableOriginCheck:!!(0,T.isTest)(),runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{l.error("Failed to run background task:",e)})):await e}catch(e){l.error("Failed to run background task:",e)}},getPlugin:e=>t.plugins.find(t=>t.id===e)??null,hasPlugin:e=>S.has(e)},U=cv(I);return $(U)&&await U,I}var po=e.i(877727);let ps=async e=>{let t=await v(e),r=await pa(t,e,e=>(0,po.getKyselyDatabaseType)(e)||"unknown");return r.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new E.BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:t}=await (0,k.getMigrations)(e);await t()},r},pc=()=>{let t=!1;return{id:"next-cookies",version:"1.6.12",hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:le(async r=>{let n;if(t||(!function(e,t){let r=e.options.plugins||[];if(0===r.length)return;let n=r.findIndex(e=>e.id===t);-1===n||r.slice(n+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${t}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(r.context,"next-cookies"),t=!0),"_flag"in r&&"router"===r._flag)return;try{let{headers:t}=await e.A(84040);n=await t()}catch{return}let i="1"===n.get("RSC"),a=!!n.get("next-action");i&&!a&&await lx(!0)})}],after:[{matcher:e=>!0,handler:le(async t=>{let r=t.context.responseHeaders;if((!("_flag"in t)||"router"!==t._flag)&&r instanceof Headers){let t,n,i=r?.get("set-cookie");if(!i)return;let a=(n=new Map,rP(i).forEach(e=>{let[t,...r]=e.split(";").map(e=>e.trim()),[i,...a]=(t||"").split("="),o=rL(a.join("="));if(!i)return;let s={value:rO(o)};r.forEach(e=>{let[t,...r]=e.split("="),n=r.join("="),i=t.trim().toLowerCase();switch(i){case"max-age":s["max-age"]=n?parseInt(n.trim(),10):void 0;break;case"expires":s.expires=n?new Date(n.trim()):void 0;break;case"domain":s.domain=n?n.trim():void 0;break;case"path":s.path=n?n.trim():void 0;break;case"secure":s.secure=!0;break;case"httponly":s.httponly=!0;break;case"samesite":s.samesite=n?n.trim().toLowerCase():void 0;break;case"partitioned":s.partitioned=!0;break;default:s[i]=!n||n.trim()}}),n.set(i,s)}),n);try{let{cookies:r}=await e.A(84040);t=await r()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}a.forEach((e,r)=>{if(r)try{t.set(r,e.value,{maxAge:e["max-age"],expires:e.expires,domain:e.domain,path:e.path,secure:e.secure,httpOnly:e.httponly,sameSite:e.samesite,partitioned:e.partitioned})}catch{}});return}})}]}}};e.s(["nextCookies",0,pc,"toNextJsHandler",0,function(e){let t=async t=>"handler"in e?e.handler(t):e(t);return{GET:t,POST:t,PATCH:t,PUT:t,DELETE:t}}],473845);var pl=e.i(286607),pd=e.i(478500),pu=e.i(798003);function pp(e){return(e??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)}async function pf(){let e=await (0,pu.readConfig)();return{emails:e.allowedEmails&&e.allowedEmails.length>0?e.allowedEmails.map(e=>e.trim().toLowerCase()).filter(Boolean):pp(process.env.AUTH_ALLOWED_EMAILS),domains:e.allowedDomains&&e.allowedDomains.length>0?e.allowedDomains.map(e=>e.trim().toLowerCase()).filter(Boolean):pp(process.env.AUTH_ALLOWED_DOMAIN)}}async function ph(e){let{emails:t,domains:r}=await pf();if(0===t.length&&0===r.length)return!0;let n=e.toLowerCase();if(t.includes(n))return!0;let i=n.lastIndexOf("@");return!!(i>=0&&r.includes(n.slice(i+1)))}e.s(["getAllowlist",0,pf,"isEmailAllowed",0,ph],860780);let pm=new pd.AsyncLocalStorage;if("phase-production-build"!==process.env.NEXT_PHASE&&"1"!==process.env.WIKI_ALLOW_INSECURE){let e=process.env.BETTER_AUTH_URL??"";if(!e)throw Error("BETTER_AUTH_URL is required in production. Set it to https://your-domain so cookies and OAuth callbacks resolve correctly. Set WIKI_ALLOW_INSECURE=1 to bypass (development only).");if(!e.startsWith("https://"))throw Error(`BETTER_AUTH_URL must be https:// in production (got: ${e}). Set WIKI_ALLOW_INSECURE=1 to bypass (development only).`)}let py=uZ.default.join(process.env.HOME??uJ.default.homedir(),".wiki-viewer");(0,uq.mkdirSync)(py,{recursive:!0});let pg=uZ.default.join(py,"auth.db"),pw=uZ.default.join(py,"auth.secret"),pb=new pl.default(pg);pb.pragma("journal_mode = WAL");let pA={};process.env.GOOGLE_CLIENT_ID&&process.env.GOOGLE_CLIENT_SECRET&&(pA.google={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET});let pE=Object.keys(pA).length>0,pv="1"===process.env.AUTH_DISABLE_PASSWORD||"true"===process.env.AUTH_DISABLE_PASSWORD,pk=!(pv&&pE);pv&&!pE&&console.warn("[wiki-viewer] AUTH_DISABLE_PASSWORD is set but no social provider is configured. Keeping email/password enabled so you are not locked out. Configure GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET to disable password auth.");let p_=(process.env.AUTH_TRUSTED_PROVIDERS??"").split(",").map(e=>e.trim()).filter(Boolean),pS=((e,t)=>{let r=t(e),{api:n}=uW(r,e);return{handler:async t=>{let n,i=await r,a=i.options.basePath||"/api/auth";if(C(e.baseURL))n=await cS(i,t,c_(i.options));else{if(n=i,!i.options.baseURL){let e=O(void 0,a,t,void 0,i.options.advanced?.trustedProxyHeaders);if(e)i.baseURL=e,i.options.baseURL=P(i.baseURL)||void 0;else throw new E.BetterAuthError("Could not get base URL from request. Please provide a valid base URL.")}n.trustedOrigins=await ck(i.options,t),n.trustedProviders=await cT(i.options,t)}let{handler:o}=((e,t)=>{let{api:r,middlewares:n}=uW(e,t),i=new URL(e.baseURL).pathname;return((e,t)=>{if(!t?.openapi?.disabled){let r={path:"/api/reference",...t?.openapi};e.openapi=cG(r.path,{method:"GET"},async t=>{let n,i;return new Response((n=await c2(e),i=r.scalar,`<!doctype html>
422
+ <html>
423
+ <head>
424
+ <title>Scalar API Reference</title>
425
+ <meta charset="utf-8" />
426
+ <meta
427
+ name="viewport"
428
+ content="width=device-width, initial-scale=1" />
429
+ </head>
430
+ <body>
431
+ <script
432
+ id="api-reference"
433
+ type="application/json">
434
+ ${JSON.stringify(n)}
435
+ </script>
436
+ <script>
437
+ var configuration = {
438
+ favicon: ${i?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(i.logo)}`:void 0} ,
439
+ theme: ${i?.theme||"saturn"},
440
+ metaData: {
441
+ title: ${i?.title||"Open API Reference"},
442
+ description: ${i?.description||"Better Call Open API"},
443
+ }
444
+ }
445
+ document.getElementById('api-reference').dataset.configuration =
446
+ JSON.stringify(configuration)
447
+ </script>
448
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
449
+ </body>
450
+ </html>`),{headers:{"Content-Type":"text/html"}})})}let r=c5(),n=c5();for(let t of Object.values(e))if(!(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY))for(let e of Array.isArray(t.options?.method)?t.options.method:[t.options?.method])c3(r,e,t.path,t);if(t?.routerMiddleware?.length)for(let{path:e,middleware:r}of t.routerMiddleware)c3(n,"*",e,r);let i=async e=>{let i=new URL(e.url),a=i.pathname,o=t?.basePath&&"/"!==t.basePath?a.split(t.basePath).reduce((e,r,n)=>(0!==n&&(n>1?e.push(`${t.basePath}${r}`):e.push(r)),e),[]).join(""):i.pathname;if(!o?.length||/\/{2,}/.test(o))return new Response(null,{status:404,statusText:"Not Found"});let s=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let n=e.static[r];if(n&&n.methods){let e=n.methods[t]||n.methods[""];if(void 0!==e)return e[0]}let i=c8(r),a=function e(t,r,n,i,a){if(a===i.length){if(r.methods){let e=r.methods[n]||r.methods[""];if(e)return e}if(r.param&&r.param.methods){let e=r.param.methods[n]||r.param.methods[""];if(e){let t=e[0].paramsMap;if(t?.[t?.length-1]?.[2])return e}}if(r.wildcard&&r.wildcard.methods){let e=r.wildcard.methods[n]||r.wildcard.methods[""];if(e){let t=e[0].paramsMap;if(t?.[t?.length-1]?.[2])return e}}return}let o=i[a];if(r.static){let s=r.static[o];if(s){let r=e(t,s,n,i,a+1);if(r)return r}}if(r.param){let s=e(t,r.param,n,i,a+1);if(s){if(r.param.hasRegexParam){let e=s.find(e=>e.paramsRegexp[a]?.test(o))||s.find(e=>!e.paramsRegexp[a]);return e?[e]:void 0}return s}}if(r.wildcard&&r.wildcard.methods)return r.wildcard.methods[n]||r.wildcard.methods[""]}(e,e.root,t,i,0)?.[0];if(void 0!==a)return{data:a.data,params:a.paramsMap?c4(i,a.paramsMap):void 0}}(r,e.method,o);if(o.endsWith("/")!==s?.data?.path?.endsWith("/")&&!t?.skipTrailingSlashes||!s?.data)return new Response(null,{status:404,statusText:"Not Found"});let c={};i.searchParams.forEach((e,t)=>{t in c?Array.isArray(c[t])?c[t].push(e):c[t]=[c[t],e]:c[t]=e});let l=s.data;try{let r=l.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:o,method:e.method,headers:e.headers,params:s.params?JSON.parse(JSON.stringify(s.params)):{},request:e,body:l.options.disableBody?void 0:await cP(l.options.cloneRequest?e.clone():e,r),query:c,_flag:"router",asResponse:!0,context:t?.routerContext},a=function(e,t="",r){47===r.charCodeAt(r.length-1)&&(r=r.slice(0,-1));let n=c8(r);return(function e(t,r,n,i,a,o=[]){let s=i[a];if(r.wildcard&&r.wildcard.methods){let e=r.wildcard.methods[n]||r.wildcard.methods[""];e&&o.push(...e)}if(r.param&&(e(t,r.param,n,i,a+1,o),a===i.length&&r.param.methods)){let e=r.param.methods[n]||r.param.methods[""];if(e){let t=e[0].paramsMap;t?.[t?.length-1]?.[2]&&o.push(...e)}}let c=r.static?.[s];if(c&&e(t,c,n,i,a+1,o),a===i.length&&r.methods){let e=r.methods[n]||r.methods[""];e&&o.push(...e)}return o})(e,e.root,t,n,0).map(e=>({data:e.data,params:e.paramsMap?c4(n,e.paramsMap):void 0}))}(n,"*",o);if(a?.length)for(let{data:e,params:t}of a){let r=await e({...i,params:t,asResponse:!1});if(r instanceof Response)return r}return await l(i)}catch(r){if(t?.onError)try{let n=await t.onError(r,e);if(n instanceof Response)return cN(n)}catch(e){if(cC(e))return cN(e);throw e}if(t?.throwError)throw r;if(cC(r))return cN(r);return console.error("# SERVER_ERROR: ",r),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async e=>{let r=await t?.onRequest?.(e);if(r instanceof Response)return r;let n=cL(r)?r:e,a=await i(n),o=await t?.onResponse?.(a,n);return o instanceof Response?o:a},endpoints:e}})(r,{routerContext:e,openapi:{disabled:!0},basePath:i,routerMiddleware:[{path:"/**",middleware:ls},...n],allowedMediaTypes:["application/json"],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],n=ln(t.url,i);if(r.includes(n))return new Response("Not Found",{status:404});let a=t;for(let t of e.options.plugins||[])if(t.onRequest){let r=await (0,cl.withSpan)(`onRequest ${t.id}`,{[cs]:"onRequest",[cc]:`plugin:${t.id}`},()=>t.onRequest(a,e));if(r&&"response"in r)return r.response;r&&"request"in r&&(a=r.request)}return await ly(a,e)||a},async onResponse(t,r){for(let n of(await lg(r,e),e.options.plugins||[]))if(n.onResponse){let r=await (0,cl.withSpan)(`onResponse ${n.id}`,{[cs]:"onResponse",[cc]:`plugin:${n.id}`,[ca.ATTR_HTTP_RESPONSE_STATUS_CODE]:t.status},()=>n.onResponse(t,e));if(r)return r.response}return t},onError(r){if(c9(r)&&"FOUND"===r.status)return;if(t.onAPIError?.throw)throw r;if(t.onAPIError?.onError)return void t.onAPIError.onError(r,e);let n=t.logger?.level,i="error"===n||"warn"===n||"debug"===n?b.logger:void 0;if(t.logger?.disabled!==!0){if(r&&"object"==typeof r&&"message"in r&&"string"==typeof r.message&&(r.message.includes("no column")||r.message.includes("column")||r.message.includes("relation")||r.message.includes("table")||r.message.includes("does not exist")))return void e.logger?.error(r.message);c9(r)?("INTERNAL_SERVER_ERROR"===r.status&&e.logger.error(r.status,r),i?.error(r.message)):e.logger?.error(r&&"object"==typeof r&&"name"in r?r.name:"",r)}}})})(n,e);return s7(n.adapter,()=>o(t))},api:n,options:e,$context:r,$ERROR_CODES:{...e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),...rA.BASE_ERROR_CODES}}})({database:pb,secret:function(){if(process.env.BETTER_AUTH_SECRET)return process.env.BETTER_AUTH_SECRET;if((0,uq.existsSync)(pw))return(0,uq.readFileSync)(pw,"utf-8").trim();let e=(0,N.randomBytes)(32).toString("base64");(0,uq.writeFileSync)(pw,e,{mode:384});try{(0,uq.chmodSync)(pw,384)}catch{}return e}(),baseURL:process.env.BETTER_AUTH_URL,account:{accountLinking:{enabled:!0,...p_.length?{trustedProviders:p_,requireLocalEmailVerified:!1}:{}}},emailAndPassword:{enabled:pk,requireEmailVerification:!1,autoSignIn:!0},rateLimit:{enabled:!0,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:20},"/sign-up/email":{window:60,max:10}}},socialProviders:pA,databaseHooks:{user:{create:{before:async e=>{if(!pm.getStore()&&!await ph(e.email))throw Error("SIGNUP_NOT_ALLOWED");return{data:e}}}}},plugins:[pc()],trustedOrigins:(p=(process.env.WIKI_OWNER_HOSTS??"").split(",").map(e=>e.trim()).filter(Boolean),f=["",":3000",":3003"],Array.from(new Set(["http://localhost:3000","http://localhost:3003",...p.flatMap(e=>f.flatMap(t=>[`http://${e}${t}`,`https://${e}${t}`]))])))},ps),px=Symbol.for("wiki-viewer.better-auth.migration-promise"),pT=globalThis;async function pR(e){return pS.api.getSession({headers:e.headers})}async function pI(e){let t=await pR(e);return t?.user?{ok:!0,user:{id:t.user.id,email:t.user.email,name:t.user.name}}:{ok:!1}}pT[px]||(pT[px]=(async()=>{let t=await e.A(427669),{runMigrations:r}=await t.getMigrations(pS.options);await r()})()),e.s(["auth",0,pS,"authReady",0,function(){return pT[px]??Promise.resolve()},"db",0,pb,"getSessionFromRequest",0,pR,"passwordAuthEnabled",0,pk,"requireUser",0,pI,"withAdminUserCreate",0,function(e){return pm.run(!0,e)}],254226)}];
451
+
452
+ //# sourceMappingURL=src_lib_auth_server_ts_00f4e0h._.js.map