superfactory 0.0.0-stage → 0.4.30

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 (308) hide show
  1. package/README.md +34 -2
  2. package/THIRD-PARTY-NOTICES.md +27604 -0
  3. package/bin/superfactory.js +57 -0
  4. package/cli/agent-rf446fr1.js +2 -0
  5. package/cli/agent-state-wv62c1td.js +2 -0
  6. package/cli/bin-0cvfmkhh.js +33 -0
  7. package/cli/bin-0t68hf99.js +3 -0
  8. package/cli/bin-19vpzq7g.js +4 -0
  9. package/cli/bin-37w316c6.js +3 -0
  10. package/cli/bin-3dsqxzbz.js +3 -0
  11. package/cli/bin-4j0jjd8g.js +3 -0
  12. package/cli/bin-4tdqjbbd.js +229 -0
  13. package/cli/bin-4zvje4sn.js +502 -0
  14. package/cli/bin-674kd343.js +7 -0
  15. package/cli/bin-8jdkg4ke.js +3 -0
  16. package/cli/bin-d99yte0j.js +5 -0
  17. package/cli/bin-fgvkq9cq.js +867 -0
  18. package/cli/bin-fkp3j5f3.js +3 -0
  19. package/cli/bin-fypan1f6.js +951 -0
  20. package/cli/bin-gg19acwr.js +4 -0
  21. package/cli/bin-ghp5x0x5.js +139 -0
  22. package/cli/bin-gk00mnmn.js +5 -0
  23. package/cli/bin-gne2w036.js +29 -0
  24. package/cli/bin-grxzwpe8.js +3 -0
  25. package/cli/bin-h57gajkz.js +8 -0
  26. package/cli/bin-mbpvzx2b.js +8 -0
  27. package/cli/bin-nnq8kd9z.js +4 -0
  28. package/cli/bin-ven2efjq.js +3 -0
  29. package/cli/bin-yqb1d1mw.js +22 -0
  30. package/cli/bin-z5b3tt05.js +20 -0
  31. package/cli/bin-za1by1n5.js +3 -0
  32. package/cli/bin-zpfe0pxz.js +1 -0
  33. package/cli/bin.js +3 -0
  34. package/cli/child-agent-qgeqvs03.js +4 -0
  35. package/cli/connect-chn8pxyf.js +2 -0
  36. package/cli/container-j6zr9gww.js +4 -0
  37. package/cli/dev-gsaehf19.js +7 -0
  38. package/cli/health-nqzge5kh.js +2 -0
  39. package/cli/home-lock-5seng0k3.js +2 -0
  40. package/cli/host-7dfjhf0z.js +1507 -0
  41. package/cli/index-1wseh1tm.js +2 -0
  42. package/cli/index-axfe8zef.js +2 -0
  43. package/cli/index-s9pw90xe.js +2 -0
  44. package/cli/install-17r8t45e.js +2 -0
  45. package/cli/join-551zg7yr.js +31 -0
  46. package/cli/local-server-2smsafvg.js +2 -0
  47. package/cli/machine-zfjmpw7h.js +2 -0
  48. package/cli/main-0mxhd968.js +33 -0
  49. package/cli/main-53qmhxmd.js +303 -0
  50. package/cli/move-to-xrr2b135.js +2 -0
  51. package/cli/npm-package.json +1 -0
  52. package/cli/pair-phone-070c9ztt.js +5 -0
  53. package/cli/prompt-psc4drtd.js +2 -0
  54. package/cli/reached-vwzx2cdg.js +2 -0
  55. package/cli/sessions-bm4mk37y.js +3 -0
  56. package/cli/sf-cli-s42gkp0b.js +2 -0
  57. package/cli/sf-db-r8f1a20b.js +23 -0
  58. package/cli/sf-deploy-wqaa4fdm.js +21 -0
  59. package/cli/sf-pr-rg3q3tn6.js +13 -0
  60. package/cli/sf-test-pff158qc.js +10 -0
  61. package/cli/tart-isolation-wr3xwfmw.js +3 -0
  62. package/cli/tray-4rr0y1dv.png +0 -0
  63. package/cli/tray-mac-offline-89dva0gs.png +0 -0
  64. package/cli/tray-mac-paused-hq3a1cxv.png +0 -0
  65. package/cli/tray-mac-tvtavf0g.png +0 -0
  66. package/cli/tray-offline-xj6b5ta4.png +0 -0
  67. package/cli/tray-paused-6pzdv5ze.png +0 -0
  68. package/cli/vm-keeper-p0ggcw3z.js +3 -0
  69. package/package.json +50 -4
  70. package/plugins/sf-video-review/.claude-plugin/plugin.json +17 -0
  71. package/plugins/sf-video-review/.mcp.json +9 -0
  72. package/plugins/sf-video-review/dist/video-review.mjs +135 -0
  73. package/plugins/sf-video-review/skills/video-review/SKILL.md +65 -0
  74. package/plugins/sf-video-studio/.claude-plugin/plugin.json +17 -0
  75. package/plugins/sf-video-studio/.mcp.json +19 -0
  76. package/plugins/sf-video-studio/dist/demo-video.mjs +139 -0
  77. package/plugins/sf-video-studio/dist/narration-voice.mjs +134 -0
  78. package/plugins/sf-video-studio/dist/video-generation.mjs +131 -0
  79. package/plugins/sf-video-studio/fonts/DejaVuSansMono-Bold.ttf +0 -0
  80. package/plugins/sf-video-studio/fonts/DejaVuSansMono.ttf +0 -0
  81. package/plugins/sf-video-studio/fonts/LICENSE-DejaVu +187 -0
  82. package/plugins/sf-video-studio/hooks/hooks.json +17 -0
  83. package/plugins/sf-video-studio/hooks/no-robot-voice.sh +77 -0
  84. package/plugins/sf-video-studio/kokoro/package-lock.json +1137 -0
  85. package/plugins/sf-video-studio/kokoro/package.json +11 -0
  86. package/plugins/sf-video-studio/skills/demo-video/SKILL.md +101 -0
  87. package/plugins/sf-video-studio/skills/narration-voice/SKILL.md +49 -0
  88. package/plugins/sf-video-studio/skills/video-generation/SKILL.md +30 -0
  89. package/server/dist/account.js +3 -0
  90. package/server/dist/backup-process.js +2 -0
  91. package/server/dist/backup.js +3 -0
  92. package/server/dist/chunk-0tbq288f.js +3055 -0
  93. package/server/dist/chunk-18n7tr66.js +3 -0
  94. package/server/dist/chunk-1kgfrgmv.js +3 -0
  95. package/server/dist/chunk-1rnmxaav.js +209 -0
  96. package/server/dist/chunk-26zhqbyn.js +25 -0
  97. package/server/dist/chunk-34mn2zj2.js +2 -0
  98. package/server/dist/chunk-3psgsw9t.js +2 -0
  99. package/server/dist/chunk-8zbwppny.js +391 -0
  100. package/server/dist/chunk-9pn7q001.js +3 -0
  101. package/server/dist/chunk-9y7a9gkf.js +2 -0
  102. package/server/dist/chunk-bhm6jzch.js +8 -0
  103. package/server/dist/chunk-dbzjsqvb.js +17 -0
  104. package/server/dist/chunk-fxn504n0.js +2 -0
  105. package/server/dist/chunk-g6pwaap3.js +2 -0
  106. package/server/dist/chunk-gefgv8rg.js +7 -0
  107. package/server/dist/chunk-jg8b833v.js +2 -0
  108. package/server/dist/chunk-jy148bhn.js +3 -0
  109. package/server/dist/chunk-ky4nz39j.js +7 -0
  110. package/server/dist/chunk-mbd1y9qk.js +2 -0
  111. package/server/dist/chunk-neyhk32g.js +13 -0
  112. package/server/dist/chunk-nrz953bx.js +2 -0
  113. package/server/dist/chunk-padvv31s.js +2 -0
  114. package/server/dist/chunk-q1s2ez77.js +3 -0
  115. package/server/dist/chunk-q403h2bh.js +10 -0
  116. package/server/dist/chunk-t64r6enn.js +4 -0
  117. package/server/dist/chunk-vccappg7.js +59 -0
  118. package/server/dist/chunk-vj60fbhw.js +2 -0
  119. package/server/dist/chunk-xj26rwda.js +3 -0
  120. package/server/dist/chunk-xyw98jst.js +5 -0
  121. package/server/dist/main.js +43 -0
  122. package/server/dist/move.js +3 -0
  123. package/server/drizzle/pg/0000_baseline.sql +632 -0
  124. package/server/drizzle/pg/0001_transcripts_packed.sql +2 -0
  125. package/server/drizzle/pg/0002_vm_server_origin.sql +1 -0
  126. package/server/drizzle/pg/0003_reached_machines.sql +1 -0
  127. package/server/drizzle/pg/0004_link_records.sql +2 -0
  128. package/server/drizzle/pg/0005_task_columns.sql +7 -0
  129. package/server/drizzle/pg/0006_task_bundle.sql +3 -0
  130. package/server/drizzle/pg/0007_server_log.sql +9 -0
  131. package/server/drizzle/pg/0008_notification_pauses.sql +6 -0
  132. package/server/drizzle/pg/0009_vm_replaces.sql +1 -0
  133. package/server/drizzle/pg/0010_question_told_once.sql +10 -0
  134. package/server/drizzle/pg/0011_node_next_key.sql +3 -0
  135. package/server/drizzle/pg/0012_task_work.sql +8 -0
  136. package/server/drizzle/pg/0013_task_secret_grants.sql +9 -0
  137. package/server/drizzle/pg/0014_node_paused.sql +2 -0
  138. package/server/drizzle/pg/0015_ssh_machines.sql +19 -0
  139. package/server/drizzle/pg/0016_node_wake.sql +1 -0
  140. package/server/drizzle/pg/0017_node_uninstall_key.sql +1 -0
  141. package/server/drizzle/pg/0018_release_starts.sql +6 -0
  142. package/server/drizzle/pg/0019_session_memory.sql +7 -0
  143. package/server/drizzle/pg/meta/_journal.json +146 -0
  144. package/server/drizzle/sqlite/0000_pre_drizzle_schema.sql +351 -0
  145. package/server/drizzle/sqlite/0001_cluster.sql +36 -0
  146. package/server/drizzle/sqlite/0002_task_records.sql +22 -0
  147. package/server/drizzle/sqlite/0003_indexes.sql +12 -0
  148. package/server/drizzle/sqlite/0004_project_machines.sql +19 -0
  149. package/server/drizzle/sqlite/0005_session_events.sql +7 -0
  150. package/server/drizzle/sqlite/0006_task_platforms.sql +8 -0
  151. package/server/drizzle/sqlite/0007_session_event_tags.sql +7 -0
  152. package/server/drizzle/sqlite/0008_sprints.sql +7 -0
  153. package/server/drizzle/sqlite/0009_project_vms.sql +19 -0
  154. package/server/drizzle/sqlite/0010_server_repairs.sql +4 -0
  155. package/server/drizzle/sqlite/0011_drop_todos.sql +2 -0
  156. package/server/drizzle/sqlite/0012_hypervisors.sql +14 -0
  157. package/server/drizzle/sqlite/0013_manager_leads.sql +2 -0
  158. package/server/drizzle/sqlite/0014_session_text.sql +35 -0
  159. package/server/drizzle/sqlite/0015_vm_resize_machine_instructions_access.sql +22 -0
  160. package/server/drizzle/sqlite/0016_tunnel.sql +23 -0
  161. package/server/drizzle/sqlite/0017_session_secret_grants.sql +7 -0
  162. package/server/drizzle/sqlite/0018_https.sql +18 -0
  163. package/server/drizzle/sqlite/0019_secret_grant_runs.sql +1 -0
  164. package/server/drizzle/sqlite/0020_session_transcripts.sql +16 -0
  165. package/server/drizzle/sqlite/0021_claude_signed_out.sql +2 -0
  166. package/server/drizzle/sqlite/0022_machine_disabled.sql +1 -0
  167. package/server/drizzle/sqlite/0023_machine_access_granted_by.sql +1 -0
  168. package/server/drizzle/sqlite/0024_machine_vms.sql +27 -0
  169. package/server/drizzle/sqlite/0025_machine_tunnel_fallback.sql +1 -0
  170. package/server/drizzle/sqlite/0026_tunnel_peer_linked.sql +3 -0
  171. package/server/drizzle/sqlite/0027_tunnel_upgrade_grace.sql +2 -0
  172. package/server/drizzle/sqlite/0028_dialed_machines.sql +2 -0
  173. package/server/drizzle/sqlite/0029_node_link.sql +3 -0
  174. package/server/drizzle/sqlite/0030_sprint_calendar.sql +1 -0
  175. package/server/drizzle/sqlite/0031_transcripts_packed.sql +2 -0
  176. package/server/drizzle/sqlite/0032_vm_server_origin.sql +1 -0
  177. package/server/drizzle/sqlite/meta/_journal.json +237 -0
  178. package/server/src/account.ts +2 -0
  179. package/server/src/backup.ts +2 -0
  180. package/server/src/features/backups/backup-process.ts +2 -0
  181. package/server/src/main.ts +2 -0
  182. package/server/src/move.ts +2 -0
  183. package/ui/dist/_expo/static/css/global-d378e211074d97e633bc15418ccf57d4.css +2 -0
  184. package/ui/dist/_expo/static/css/xterm-8a7c4e0dca731c11dbe6bdff98fb667c.css +1 -0
  185. package/ui/dist/_expo/static/js/web/Network-f300a5960620f5029c91c06cae29dba5.js +3 -0
  186. package/ui/dist/_expo/static/js/web/[...rest]-9e454d985f211f5c983f42bec15b6ad9.js +1 -0
  187. package/ui/dist/_expo/static/js/web/[managerId]-2580b90e8d862ad66197eecb1dc04a12.js +1 -0
  188. package/ui/dist/_expo/static/js/web/[managerId]-39308153b42eed025c0abb9242ae6c71.js +1 -0
  189. package/ui/dist/_expo/static/js/web/[managerId]-8b7a94ec818e50a371b6b2750b73df6a.js +1 -0
  190. package/ui/dist/_expo/static/js/web/[managerId]-ac3a14c7607e4576d7e6c39c1014bcaf.js +1 -0
  191. package/ui/dist/_expo/static/js/web/[managerId]-e8549b2313a119437c373e30207518c0.js +1 -0
  192. package/ui/dist/_expo/static/js/web/[ref]-9b46f1ec4348f980e9838b68d47c34bf.js +2 -0
  193. package/ui/dist/_expo/static/js/web/[sessionId]-09e376674fb8b3edc4ae8aa9b3a189d7.js +1 -0
  194. package/ui/dist/_expo/static/js/web/[sessionId]-0e5fdba25c9f78220cea4cb66227743d.js +1 -0
  195. package/ui/dist/_expo/static/js/web/[sessionId]-104af3c3885009e6a8d204b6fd6e2c3a.js +1 -0
  196. package/ui/dist/_expo/static/js/web/[sessionId]-863a34ca3835b469134ddbc4ebc6fafc.js +1 -0
  197. package/ui/dist/_expo/static/js/web/[taskId]-1218e1dd3ecf175ffb7701fc886d62c9.js +1 -0
  198. package/ui/dist/_expo/static/js/web/[taskId]-31a48c7017dbd096f8ece9dc102a9762.js +1 -0
  199. package/ui/dist/_expo/static/js/web/[taskId]-a56cf85bcfd14f2d6b5d4180ea17e8d7.js +1 -0
  200. package/ui/dist/_expo/static/js/web/[taskId]-f2a157b3cb676b3c5d04c8eadfe90cdd.js +1 -0
  201. package/ui/dist/_expo/static/js/web/__common-1ad58e53e08528a67b99f53a1690b669.js +2078 -0
  202. package/ui/dist/_expo/static/js/web/__expo-metro-runtime-1f8f5d3ca6b7f58204d51e14506d73fb.js +5 -0
  203. package/ui/dist/_expo/static/js/web/_layout-057457e97e0af20433ed41b39cb5e809.js +1 -0
  204. package/ui/dist/_expo/static/js/web/_layout-2a7d73d5356823e1f7d2dab23e440d09.js +7 -0
  205. package/ui/dist/_expo/static/js/web/_layout-42e6a6b7855655d456015ce41aefdd39.js +1 -0
  206. package/ui/dist/_expo/static/js/web/_layout-a5e5a5b2fb3bfbfcc2914131976679e7.js +1 -0
  207. package/ui/dist/_expo/static/js/web/_layout-b2cbba92506f66815a5d744fd7cd5d8c.js +1 -0
  208. package/ui/dist/_expo/static/js/web/_layout-b4d13dc52bbcb65b18b4e52813d53883.js +198 -0
  209. package/ui/dist/_expo/static/js/web/_layout-fb0f75b354800de2e1582dc963f5c148.js +1 -0
  210. package/ui/dist/_expo/static/js/web/index-41299a961569cc8e5410ec53ba2b87c4.js +4 -0
  211. package/ui/dist/_expo/static/js/web/index-6c2bb0d3b6d00c5c007a663e9f4ce108.js +1 -0
  212. package/ui/dist/_expo/static/js/web/index-70484f7d2769d9ae01dac1fdb22aef1d.js +14 -0
  213. package/ui/dist/_expo/static/js/web/index-7d764cb7cefe0a217728c24d44990057.js +14 -0
  214. package/ui/dist/_expo/static/js/web/index-a5eb3d0c6aa4c483674beb5de428634c.js +12 -0
  215. package/ui/dist/_expo/static/js/web/index-b1c2543003cba86eeb3abfa4d21fd8da.js +14 -0
  216. package/ui/dist/_expo/static/js/web/index-d200aded5448966e5e05d9ccb77b56a4.js +5 -0
  217. package/ui/dist/_expo/static/js/web/index-ea43f51ceec4a981c942fc6dce9cedc4.js +2378 -0
  218. package/ui/dist/_expo/static/js/web/index-efa68d817a7febbf8c0163303bf4cd49.js +29 -0
  219. package/ui/dist/_expo/static/js/web/licenses-30f8c0555f7f4d434a68ee4706fa433d.js +1 -0
  220. package/ui/dist/_expo/static/js/web/pair-3f6f72208023894f43f4f07db5116cca.js +1 -0
  221. package/ui/dist/_expo/static/js/web/rich-markdown-editor-dea9c0f7c0306da4146e54ee44cce173.js +228 -0
  222. package/ui/dist/_expo/static/js/web/sign-in-67d2a0c00232e0e6f40efade1a83dc4b.js +4 -0
  223. package/ui/dist/_expo/static/js/web/terminal-view-32db8e6f8a21dd073f6a310862d36db8.js +90 -0
  224. package/ui/dist/apple-touch-icon.png +0 -0
  225. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/100Thin/GeistMono_100Thin.95eed4519d8c395e41b3b837ca97edea.ttf +0 -0
  226. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/100Thin_Italic/GeistMono_100Thin_Italic.2e50fb9a43d70ceb4925a2c54502097c.ttf +0 -0
  227. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/200ExtraLight/GeistMono_200ExtraLight.0714ea94ac265d76bc16698dd1808599.ttf +0 -0
  228. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/200ExtraLight_Italic/GeistMono_200ExtraLight_Italic.107f2670e94507223548f1d38eb14087.ttf +0 -0
  229. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/300Light/GeistMono_300Light.d6a3533adfd5834dd9f68ee37faa1e2d.ttf +0 -0
  230. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/300Light_Italic/GeistMono_300Light_Italic.09420cdceda8d1f1612daceae1e4890e.ttf +0 -0
  231. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/400Regular/GeistMono_400Regular.3656dcb247d3a6cd141f7601c2101125.ttf +0 -0
  232. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/400Regular_Italic/GeistMono_400Regular_Italic.88343c321b266476ad3bc56735cc6ac7.ttf +0 -0
  233. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/500Medium/GeistMono_500Medium.a298cd61aebdb709299e2a7deb73ed93.ttf +0 -0
  234. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/500Medium_Italic/GeistMono_500Medium_Italic.e149441dd9360bd7dbffeb1de9aa1685.ttf +0 -0
  235. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/600SemiBold/GeistMono_600SemiBold.cae945cb3b6156e396a1008b6252af21.ttf +0 -0
  236. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/600SemiBold_Italic/GeistMono_600SemiBold_Italic.e939ba436795ee2f0a379e7271bb957d.ttf +0 -0
  237. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/700Bold/GeistMono_700Bold.7fcc8478bc1dcadc865d97626ba3206b.ttf +0 -0
  238. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/700Bold_Italic/GeistMono_700Bold_Italic.8cc57ff1f3c45e7ed84e74853c141e06.ttf +0 -0
  239. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/800ExtraBold/GeistMono_800ExtraBold.b09b5457204e06ea7bacff03f0880065.ttf +0 -0
  240. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/800ExtraBold_Italic/GeistMono_800ExtraBold_Italic.0b4dd8c1b0e6d8791ea34c8f1417edfd.ttf +0 -0
  241. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/900Black/GeistMono_900Black.9ec025adf049c8a476588eeac81a36e4.ttf +0 -0
  242. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+geist-mono@0.4.3-2a25012349fb7712/node_modules/@expo-google-fonts/geist-mono/900Black_Italic/GeistMono_900Black_Italic.8dfe24b2fef43fb3d535316e2412be7d.ttf +0 -0
  243. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/100Thin/HankenGrotesk_100Thin.2d9c9415d97b66fb3bbca06b538f11d8.ttf +0 -0
  244. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/100Thin_Italic/HankenGrotesk_100Thin_Italic.5ad53da9f1ff702f55cf870763a159ff.ttf +0 -0
  245. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/200ExtraLight/HankenGrotesk_200ExtraLight.2cae1a1078b5af081aff084011b07522.ttf +0 -0
  246. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/200ExtraLight_Italic/HankenGrotesk_200ExtraLight_Italic.5d4eff887cdb33164b4fba2066c687e3.ttf +0 -0
  247. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/300Light/HankenGrotesk_300Light.2be9fd730ff95b91631e3f99bc449709.ttf +0 -0
  248. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/300Light_Italic/HankenGrotesk_300Light_Italic.4ae6910889ffdf69093da607b369b0a8.ttf +0 -0
  249. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/400Regular/HankenGrotesk_400Regular.2e544d6119b4e635f6cc5a47800523bb.ttf +0 -0
  250. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/400Regular_Italic/HankenGrotesk_400Regular_Italic.ed9d322cffe9e614205ce9512f144834.ttf +0 -0
  251. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/500Medium/HankenGrotesk_500Medium.a822d33614b51eb05478e0e29cf757f3.ttf +0 -0
  252. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/500Medium_Italic/HankenGrotesk_500Medium_Italic.bc71c45237e12974e52335b615fab7da.ttf +0 -0
  253. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/600SemiBold/HankenGrotesk_600SemiBold.b016ff502f15ce9b59c453304c74fb48.ttf +0 -0
  254. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/600SemiBold_Italic/HankenGrotesk_600SemiBold_Italic.94428d43b74e372dc47910fd4fc6b552.ttf +0 -0
  255. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/700Bold/HankenGrotesk_700Bold.14d2af6df606492d846389d2108dae50.ttf +0 -0
  256. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/700Bold_Italic/HankenGrotesk_700Bold_Italic.d075966aaf26126d8aaac0802735e310.ttf +0 -0
  257. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/800ExtraBold/HankenGrotesk_800ExtraBold.b419489745bc870b4e4288e969945f31.ttf +0 -0
  258. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/800ExtraBold_Italic/HankenGrotesk_800ExtraBold_Italic.ea7ac4778026e067a5d637f4a494b2d2.ttf +0 -0
  259. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/900Black/HankenGrotesk_900Black.55e860e6549b53fa530d9eda7c7518a2.ttf +0 -0
  260. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+hanken-grotesk@0.4.3-9a0105bf7cbf8f8b/node_modules/@expo-google-fonts/hanken-grotesk/900Black_Italic/HankenGrotesk_900Black_Italic.dcad6f722a66aae93f70a72604112754.ttf +0 -0
  261. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/200ExtraLight/Newsreader_200ExtraLight.1ee07dc260606863f8bf8101308d85f2.ttf +0 -0
  262. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/200ExtraLight_Italic/Newsreader_200ExtraLight_Italic.52c51abab458715d1205b8732b55735f.ttf +0 -0
  263. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/300Light/Newsreader_300Light.bf0dfa126654b01f65e1c53a4507ec12.ttf +0 -0
  264. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/300Light_Italic/Newsreader_300Light_Italic.03190fe46aa9b7083610981ac13b10f3.ttf +0 -0
  265. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/400Regular/Newsreader_400Regular.b1d919187d5645f84124ef065868ba9e.ttf +0 -0
  266. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/400Regular_Italic/Newsreader_400Regular_Italic.f7b81d92eb42d85de96b6dc1c72d2c36.ttf +0 -0
  267. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/500Medium/Newsreader_500Medium.df89e83cfd4e37176dda53076a01b3b7.ttf +0 -0
  268. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/500Medium_Italic/Newsreader_500Medium_Italic.fb45099c4fb3c395e8f12e181475230c.ttf +0 -0
  269. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/600SemiBold/Newsreader_600SemiBold.20bce29dc5180892ce1fbf4a563737a0.ttf +0 -0
  270. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/600SemiBold_Italic/Newsreader_600SemiBold_Italic.93e2816e201fa363d3289e741f757ff0.ttf +0 -0
  271. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/700Bold/Newsreader_700Bold.bf7c54edbd2afe9b289d5da777f489e9.ttf +0 -0
  272. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/700Bold_Italic/Newsreader_700Bold_Italic.e2f5e5260513d7d4f9f3edbdcbc9f43f.ttf +0 -0
  273. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/800ExtraBold/Newsreader_800ExtraBold.702211ca77927e4c276b28169dc3694c.ttf +0 -0
  274. package/ui/dist/assets/_____.bun/install/cache/links/@expo-google-fonts+newsreader@0.4.1-869d74885c3fd9d6/node_modules/@expo-google-fonts/newsreader/800ExtraBold_Italic/Newsreader_800ExtraBold_Italic.9b9eacc7d72e5152e692cb144ef7a9fd.ttf +0 -0
  275. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
  276. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
  277. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
  278. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
  279. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
  280. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/drawer/toggle-drawer-icon.ae74bb20586a731af545e6b00fe14a09.png +0 -0
  281. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
  282. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
  283. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
  284. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
  285. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
  286. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
  287. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
  288. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
  289. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
  290. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
  291. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
  292. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
  293. package/ui/dist/assets/_____.bun/install/cache/links/expo-router@57.0.24+dc951f634b001cec-a06b318b98b13101/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
  294. package/ui/dist/favicon.ico +0 -0
  295. package/ui/dist/favicon.svg +10 -0
  296. package/ui/dist/icon-192.png +0 -0
  297. package/ui/dist/icon-512.png +0 -0
  298. package/ui/dist/index.html +45 -0
  299. package/ui/dist/legal/privacy-policy.md +174 -0
  300. package/ui/dist/legal/terms-of-use.md +76 -0
  301. package/ui/dist/load-again.js +42 -0
  302. package/ui/dist/manifest.webmanifest +12 -0
  303. package/ui/dist/metadata.json +1 -0
  304. package/ui/dist/sounds/bell.wav +0 -0
  305. package/ui/dist/sounds/chime.wav +0 -0
  306. package/ui/dist/sounds/knock.wav +0 -0
  307. package/ui/dist/sounds/pop.wav +0 -0
  308. package/ui/dist/sw.js +121 -0
@@ -0,0 +1,391 @@
1
+ // @bun
2
+ import{Dn,fd,Ha,md,vs,jt,S,l,ae,Ln,ai,fn,ci,Dt,xt,It,uo,O,li,Lt,Va,Un,za,po,wd,Br,Sd,Fr,ty,bd,ry,ny,Ga,sy,de,F,fo,Xe,et,or}from"./chunk-gefgv8rg.js";import{Fi}from"./chunk-neyhk32g.js";import{bs,bp}from"./chunk-9y7a9gkf.js";import{di,mo,e,je,dy,uy,b,o,st,ne,Pt,a,Es,t,br,Fn,ee,j,d,p,_s,ho}from"./chunk-vccappg7.js";var Zd={};di(Zd,{accountSchema:()=>ba,coreSchema:()=>tt,getAuthTables:()=>It,rateLimitSchema:()=>Ea,sessionSchema:()=>Oo,userSchema:()=>Lo,verificationSchema:()=>ka});function Ni(r){return Object.fromEntries(Object.entries(r).map(([n,i])=>[n,{code:n,message:i,toString:()=>n}]))}var Tt,Js=!1;function Ql(){try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage}catch{return}}async function fr(){if(Tt)return Tt;let r=Ql();if(r)return Tt??=r,Tt;try{let{AsyncLocalStorage:n}=await import("async_hooks");return Tt??=n,Tt}catch(n){let i=globalThis.AsyncLocalStorage;if(typeof i==="function")return Tt??=i,Tt;if(typeof window<"u")throw Error("getAsyncLocalStorage is only available in server code");if(!Js)Js=!0,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");throw n}}var Zl=()=>Dn().context.endpointContextAsyncStorage,Yl=async()=>{let r=Zl();if(r)return r;let n=await fr(),i=Dn().context;return i.endpointContextAsyncStorage??=new n};function Ve(){return fd()}function Yn(){let r=Ve();if(!r)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return r}async function pr(r,n){return(await Yl()).run(r,n)}var x=Ni({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CHANGE_EMAIL_DISABLED:"Change email is disabled",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"});function qe(){let r=typeof globalThis<"u"&&globalThis.crypto;if(r&&typeof r.subtle==="object"&&r.subtle!=null)return r.subtle;throw Error("crypto.subtle must be defined")}var Xn={name:"HMAC",hash:"SHA-256"},ei=async(r)=>{let n=typeof r==="string"?new TextEncoder().encode(r):r;return await qe().importKey("raw",n,Xn,!1,["sign","verify"])},Gs=async(r,n,i)=>{try{let s=atob(r),c=new Uint8Array(s.length);for(let u=0,f=s.length;u<f;u++)c[u]=s.charCodeAt(u);return await qe().verify(Xn,i,c,new TextEncoder().encode(n))}catch{return!1}},Xl=async(r,n)=>{let i=await ei(n),s=await qe().sign(Xn.name,i,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(s)))},Qs=async(r,n)=>{let i=await Xl(r,n);return r=`${r}.${i}`,r=encodeURIComponent(r),r};var ef=/^application\/([a-z0-9.+-]*\+)?json/i;async function Zs(r,n){let i=r.headers.get("content-type")||"",s=i.toLowerCase();if(!r.body)return;if(n&&n.length>0){if(!n.some((c)=>{let u=s.split(";")[0].trim(),f=c.toLowerCase().trim();return u===f||u.includes(f)})){if(!s)throw new jt(415,{message:`Content-Type is required. Allowed types: ${n.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new jt(415,{message:`Content-Type "${i}" is not allowed. Allowed types: ${n.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}}if(ef.test(s))try{return await r.json()}catch(c){if(c instanceof SyntaxError)throw new jt(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw c}if(s.includes("application/x-www-form-urlencoded")){let c=await r.formData(),u={};return c.forEach((f,m)=>{u[m]=f.toString()}),u}if(s.includes("multipart/form-data")){let c=await r.formData(),u={};return c.forEach((f,m)=>{u[m]=f}),u}if(s.includes("text/plain"))return await r.text();if(s.includes("application/octet-stream"))return await r.arrayBuffer();if(s.includes("application/pdf")||s.includes("image/")||s.includes("video/"))return await r.blob();if(s.includes("application/stream")||r.body instanceof ReadableStream)return r.body;return await r.text()}function ft(r){return r instanceof jt||r?.name==="APIError"}function Ys(r){try{return r.includes("%")?decodeURIComponent(r):r}catch{return r}}async function Xs(r){try{return{data:await r,error:null}}catch(n){return{data:null,error:n}}}function Ro(r){return r instanceof Request||Object.prototype.toString.call(r)==="[object Request]"}var tf={secure:"__Secure-",host:"__Host-"},$r=(r,n)=>{if(!n)return r;if(n!=="secure"&&n!=="host")return;return tf[n]+r};function ti(r){if(typeof r!=="string")throw TypeError("argument str must be a string");let n=new Map,i=0;while(i<r.length){let s=r.indexOf("=",i);if(s===-1)break;let c=r.indexOf(";",i);if(c===-1)c=r.length;else if(c<s){i=r.lastIndexOf(";",s-1)+1;continue}let u=r.slice(i,s).trim();if(!n.has(u)){let f=r.slice(s+1,c).trim();if(f.codePointAt(0)===34)f=f.slice(1,-1);n.set(u,Ys(f))}i=c+1}return n}function ea(r,n,i={}){let s=$r(r,i.prefix)??r,c={...i},u=s.toLowerCase();if(u.startsWith("__host-"))c.secure=!0,c.path="/",c.domain=void 0;else if(u.startsWith("__secure-"))c.secure=!0;if(c.partitioned===!0||c.sameSite?.toLowerCase()==="none")c.secure=!0;return{name:s,value:n,options:c}}function ta({name:r,value:n,options:i}){let s=`${r}=${n}`;if(typeof i.maxAge==="number"&&i.maxAge>=0){if(i.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");s+=`; Max-Age=${Math.floor(i.maxAge)}`}if(i.domain)s+=`; Domain=${i.domain}`;if(i.path)s+=`; Path=${i.path}`;if(i.expires){if(i.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");s+=`; Expires=${i.expires.toUTCString()}`}if(i.httpOnly)s+="; HttpOnly";if(i.secure)s+="; Secure";if(i.sameSite)s+=`; SameSite=${i.sameSite.charAt(0).toUpperCase()+i.sameSite.slice(1)}`;if(i.partitioned)s+="; Partitioned";return s}var jr=(r,n,i)=>(n=encodeURIComponent(n),ta(ea(r,n,i))),Vo=async(r,n,i,s)=>(n=await Qs(n,i),ta(ea(r,n,s)));async function oa(r,n={}){let i={body:n.body,query:n.query};if(r.body){let s=await r.body["~standard"].validate(n.body);if(s.issues)return{data:null,error:ra(s.issues,"body")};i.body=s.value}if(r.query){let s=await r.query["~standard"].validate(n.query);if(s.issues)return{data:null,error:ra(s.issues,"query")};i.query=s.value}if(r.requireHeaders&&!n.headers)return{data:null,error:{message:"Headers is required",issues:[]}};if(r.requireRequest&&!n.request)return{data:null,error:{message:"Request is required",issues:[]}};return{data:i,error:null}}function ra(r,n){return{message:r.map((i)=>`[${i.path?.length?`${n}.`+i.path.map((s)=>typeof s==="object"?s.key:s).join("."):n}] ${i.message}`).join("; "),issues:r}}var Hr=async(r,{options:n,path:i})=>{let s=new Headers,c=void 0,{data:u,error:f}=await oa(n,r);if(f)throw new Ha(f.message,f.issues);let m=r.headers!==void 0?r.headers instanceof Headers?r.headers:new Headers(r.headers):("request"in r)&&Ro(r.request)?r.request.headers:null,h=m?.get("cookie"),y=h?ti(h):void 0,w={...r,body:u.body,query:u.query,path:r.path||i||"virtual:",context:"context"in r&&r.context?r.context:{},returned:void 0,headers:r?.headers,request:r?.request,params:"params"in r?r.params:void 0,method:r.method??(Array.isArray(n.method)?n.method[0]:n.method==="*"?"GET":n.method),setHeader:(g,A)=>{s.set(g,A)},getHeader:(g)=>{if(!m)return null;return m.get(g)},getCookie:(g,A)=>{let E=$r(g,A);if(!E)return null;return y?.get(E)||null},getSignedCookie:async(g,A,E)=>{let v=$r(g,E);if(!v)return null;let _=y?.get(v);if(!_)return null;let P=_.lastIndexOf(".");if(P<1)return null;let I=_.substring(0,P),T=_.substring(P+1);if(T.length!==44||!T.endsWith("="))return null;return await Gs(T,I,await ei(A))?I:!1},setCookie:(g,A,E)=>{let v=jr(g,A,E);return s.append("set-cookie",v),v},setSignedCookie:async(g,A,E,v)=>{let _=await Vo(g,A,E,v);return s.append("set-cookie",_),_},redirect:(g)=>(s.set("location",g),new jt("FOUND",void 0,s)),error:(g,A,E)=>new jt(g,A,E),setStatus:(g)=>{c=g},json:(g,A)=>{if(!r.asResponse)return g;return{body:A?.body||g,routerResponse:A,_flag:"json"}},responseHeaders:s,get responseStatus(){return c}};for(let g of n.use||[]){let A=await g({...w,returnHeaders:!0,asResponse:!1});if(A.response)Object.assign(w.context,A.response);if(A.headers)A.headers.forEach((E,v)=>{w.responseHeaders.set(v,E)})}return w};function rf(r){if(r===void 0)return!1;let n=typeof r;if(n==="string"||n==="number"||n==="boolean"||n===null)return!0;if(n!=="object")return!1;if(Array.isArray(r))return!0;if(r.buffer)return!1;return r.constructor&&r.constructor.name==="Object"||typeof r.toJSON==="function"}function of(r){let n=new WeakMap,i=new WeakMap,s=0,c=(u,f)=>{let m=f;while(m){if(m===u)return!0;m=n.get(m)}return!1};return JSON.stringify(r,function(u,f){if(typeof f==="bigint")return f.toString();if(typeof f==="object"&&f!==null){if(c(f,this))return`[Circular ref-${i.get(f)}]`;if(n.set(f,this),!i.has(f))i.set(f,s++)}return f})}function nf(r){if(!r||typeof r!=="object")return!1;return"_flag"in r&&r._flag==="json"}var sf=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 ri(r){for(let n of sf)r.delete(n)}function Io(r,n){if(!n)return;for(let[i,s]of new Headers(n).entries())if(i.toLowerCase()==="set-cookie")r.append(i,s);else r.set(i,s)}function Fe(r,n){if(r instanceof Response){if(n?.headers){let c=new Headers(n.headers);ri(c),Io(r.headers,c)}return r}if(nf(r)){let{body:c,routerResponse:u}=r;if(u instanceof Response)return u;let f=new Headers;if(Io(f,u?.headers),Io(f,r.headers),n?.headers){let y=new Headers(n.headers);ri(y),Io(f,y)}f.set("Content-Type","application/json");let m=r.status??n?.status??u?.status,h=n?.statusText??u?.statusText;return new Response(JSON.stringify(c),{...u,headers:f,...m===void 0?{}:{status:m},...h===void 0?{}:{statusText:h}})}if(ft(r))return Fe(r.body,{status:n?.status??r.statusCode,statusText:r.status.toString(),headers:n?.headers||r.headers});let i=r,s=new Headers(n?.headers);if(ri(s),!r){if(r===null)i=JSON.stringify(null);s.set("content-type","application/json")}else if(typeof r==="string")i=r,s.set("Content-Type","text/plain");else if(r instanceof ArrayBuffer||ArrayBuffer.isView(r))i=r,s.set("Content-Type","application/octet-stream");else if(r instanceof Blob)i=r,s.set("Content-Type",r.type||"application/octet-stream");else if(r instanceof FormData)i=r;else if(r instanceof URLSearchParams)i=r,s.set("Content-Type","application/x-www-form-urlencoded");else if(r instanceof ReadableStream)i=r,s.set("Content-Type","application/octet-stream");else if(rf(r))i=of(r),s.set("Content-Type","application/json");return new Response(i,{...n,headers:s})}function Rt(r,n,i){let s=typeof r==="string"?r:void 0,c=typeof n==="object"?n:r,u=typeof n==="function"?n:i;if((c.method==="GET"||c.method==="HEAD")&&c.body)throw new md("Body is not allowed with GET or HEAD methods");if(s&&/\/{2,}/.test(s))throw new md("Path cannot contain consecutive slashes");let f=async(...m)=>{let h=m[0]||{},{data:y,error:w}=await Xs(Hr(h,{options:c,path:s}));if(w){if(!(w instanceof Ha))throw w;if(c.onValidationError)await c.onValidationError({message:w.message,issues:w.issues});throw new jt(400,{message:w.message,code:"VALIDATION_ERROR"})}let g=await u(y).catch(async(v)=>{if(ft(v)){let _=c.onAPIError;if(_)await _(v);if(h.asResponse)return v}throw v}),{responseHeaders:A,responseStatus:E}=y;return h.asResponse?Fe(g,E===void 0?{headers:A}:{headers:A,status:E}):h.returnHeaders?h.returnStatus?{headers:A,response:g,status:E}:{headers:A,response:g}:h.returnStatus?{response:g,status:E}:g};return f.options=c,f.path=s,f}function na(r,n){return[...r??[],...n??[]]}Rt.create=(r)=>{function n(...i){if(i.length===3){let[u,f,m]=i;return Rt(u,{...f,use:na(f.use,r?.use)},m)}let[s,c]=i;return Rt({...s,use:na(s.use,r?.use)},c)}return n};function Ut(r,n){let i=async(s)=>{let c=s,u=typeof r==="function"?r:n,f=await Hr(c,{options:typeof r==="function"?{}:r,path:"/"});if(!u)throw Error("handler must be defined");try{let m=await u(f),h=f.responseHeaders;return c.returnHeaders?{headers:h,response:m}:m}catch(m){if(ft(m))Object.defineProperty(m,vs,{enumerable:!1,configurable:!0,get(){return f.responseHeaders}});throw m}};return i.options=typeof r==="function"?{}:r,i}Ut.create=(r)=>{function n(i,s){if(typeof i==="function")return Ut({use:r?.use},i);if(!s)throw Error("Middleware handler is required");return Ut({...i,method:"*",use:[...r?.use||[],...i.use||[]]},s)}return n};var oi={};function aa(r){switch(r.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function ia(r){let n=[];if(r.metadata?.openapi?.parameters)return n.push(...r.metadata.openapi.parameters),n;if(r.query instanceof Es)Object.entries(r.query.shape).forEach(([i,s])=>{if(s instanceof Es)n.push({name:i,in:"query",schema:{type:aa(s),..."minLength"in s&&s.minLength?{minLength:s.minLength}:{},description:s.description}})});return n}function af(r){if(r.metadata?.openapi?.requestBody)return r.metadata.openapi.requestBody;if(!r.body)return;if(r.body instanceof Es||r.body instanceof _s){let n=r.body.shape;if(!n)return;let i={},s=[];return Object.entries(n).forEach(([c,u])=>{if(u instanceof Es){if(i[c]={type:aa(u),description:u.description},!(u instanceof _s))s.push(c)}}),{required:r.body instanceof _s?!1:r.body?!0:!1,content:{"application/json":{schema:{type:"object",properties:i,required:s}}}}}}function sa(r){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."},...r}}async function ni(r,n){let i={schemas:{}};return Object.entries(r).forEach(([s,c])=>{let u=c.options;if(!c.path||u.metadata?.SERVER_ONLY)return;if(u.method==="GET")oi[c.path]={get:{tags:["Default",...u.metadata?.openapi?.tags||[]],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:ia(u),responses:sa(u.metadata?.openapi?.responses)}};if(u.method==="POST"){let f=af(u);oi[c.path]={post:{tags:["Default",...u.metadata?.openapi?.tags||[]],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:ia(u),...f?{requestBody:f}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:sa(u.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:i,security:[{apiKeyCookie:[]}],servers:[{url:n?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:oi}}var ii=(r,n)=>`<!doctype html>
3
+ <html>
4
+ <head>
5
+ <title>Scalar API Reference</title>
6
+ <meta charset="utf-8" />
7
+ <meta
8
+ name="viewport"
9
+ content="width=device-width, initial-scale=1" />
10
+ </head>
11
+ <body>
12
+ <script
13
+ id="api-reference"
14
+ type="application/json">
15
+ ${JSON.stringify(r)}
16
+ </script>
17
+ <script>
18
+ var configuration = {
19
+ favicon: ${n?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(n.logo)}`:void 0} ,
20
+ theme: ${n?.theme||"saturn"},
21
+ metaData: {
22
+ title: ${n?.title||"Open API Reference"},
23
+ description: ${n?.description||"Better Call Open API"},
24
+ }
25
+ }
26
+ document.getElementById('api-reference').dataset.configuration =
27
+ JSON.stringify(configuration)
28
+ </script>
29
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
30
+ </body>
31
+ </html>`;var Co=(()=>{let r=function(){};return r.prototype=Object.create(null),Object.freeze(r.prototype),r})();function fi(){return{root:{key:""},static:new Co}}function cf(r){let n=0,i=0;for(;n<r.length;n++){let f=r.charCodeAt(n);if(f===92)n++;else if(f===40)i++;else if(f===41&&i>0)i--;else if(f===123&&i===0)break}if(n>=r.length)return;let s=n+1;i=0;for(;s<r.length;s++){let f=r.charCodeAt(s);if(f===92)s++;else if(f===40)i++;else if(f===41&&i>0)i--;else if(f===125&&i===0)break}if(s>=r.length)return;let c=r[s+1],u=c==="?"||c==="+"||c==="*";return[r.slice(0,n),r.slice(n+1,s),r.slice(s+(u?2:1)),u?c:void 0]}function uf(r){if(!r.includes("{"))return;let n=cf(r);if(!n)return;let[i,s,c,u]=n;if(!u)return[i+s+c];if(u==="?")return[i+s+c,i+c];if(s.includes("/"))throw Error("unsupported group repetition across segments");return[`${i}(?:${s})${u}${c}`]}var df="__rou3_unnamed_",lf="__rou3_esc_";function ca(r){return`${df}${r}`}function ff(r){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(r)?r:lf+r.replace(/[_-]/g,(n)=>n==="_"?"__":"_h")}function pf(r){if(r.charCodeAt(0)!==95)return r;if(r.startsWith("__rou3_esc_"))return r.slice(11).replace(/__|_h/g,(n)=>n==="__"?"_":"-");return r.startsWith("__rou3_unnamed_")?r.slice(15):r}function mf(r){let n=0;for(let i=0;i<r.length;i++){let s=r.charCodeAt(i);if(s===92){i++;continue}if(s===40){n++;continue}if(s===41&&n>0){n--;continue}if(s===42&&n===0)return!0}return!1}function hf(r,n,i=ca){let s=0,c=n,u="";for(let f=0;f<r.length;f++){let m=r.charCodeAt(f);if(m===92){if(u+=r[f],f+1<r.length)u+=r[++f];continue}if(m===40){s++,u+=r[f];continue}if(m===41&&s>0){s--,u+=r[f];continue}if(m===42&&s===0){u+=`(?<${i(c++)}>[^/]*)`;continue}u+=r[f]}return[u,c]}function yf(r){if(!r.includes("\\"))return r;return r.replace(/\\([:(){}])/g,(n,i)=>"\uFFFD"+"ABCDE"[":(){}".indexOf(i)])}function wf(r){if(r.startsWith("**"))return 2;if(r==="*"||r.includes(":")||r.includes("(")||mf(r))return 1;if(r==="\\*")return"*";if(r==="\\*\\*")return"**";if(!r.includes("\uFFFD"))return r;return r.replace(/\uFFFD([A-E])/g,(n,i)=>i==="A"?":":i==="B"?"(":i==="C"?")":i==="D"?"{":"}")}function gf(r){for(let n=0;n<r.length;n++){let i=r[n].charCodeAt(r[n].length-1);if(i!==63&&i!==43&&i!==42)continue;let s=r[n].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!s)continue;let c=r.slice(0,n),u=r.slice(n+1);if(s[2]==="?")return["/"+c.concat(s[1]).concat(u).join("/"),"/"+c.concat(u).join("/")];let f=s[1].match(/:([\w-]+)/)?.[1]||"_",m="/"+[...c,`**:${f}`,...u].join("/"),h="/"+[...c,...u].join("/");return s[2]==="+"?[m]:[m,h]}}function ua(r){if(!r.includes("/."))return r;let n=[];for(let i of r.split("/"))if(i===".")continue;else if(i===".."&&n.length>1)n.pop();else n.push(i);return n.join("/")||"/"}function pi(r){let n=r.split("/");if(n.shift(),n[n.length-1]==="")n.pop();return n}function Af(r){let n=pi(r);while(n[n.length-1]==="")n.pop();return n}function da(r,n){let i=new Co;for(let[s,c]of n){let u=s<0?r.slice(-(s+1)).join("/"):r[s];if(typeof c==="string")i[c]=u;else{let f=u.match(c);if(f)for(let m in f.groups)i[pf(m)]=f.groups[m]}}return i}function Mr(r,n="",i,s){if(n=n.toUpperCase(),i.charCodeAt(0)!==47)i=`/${i}`;let c=uf(i);if(c){for(let E of c)Mr(r,n,E,s);return}i=yf(i);let u=Af(i),f=gf(u);if(f){for(let E of f)Mr(r,n,E,s);return}let m=r.root,h=0,y=[],w=[];for(let E=0;E<u.length;E++){let v=u[E],_=wf(v);if(_===2){if(!m.wildcard)m.wildcard={key:"**"};m=m.wildcard,y.push([-(E+1),v.split(":")[1]||"_",v.length===2]);break}if(_===1){if(!m.param)m.param={key:"*"};if(m=m.param,v==="*")y.push([E,String(h++),!0]);else if(v.includes("(")||v.includes(":",1)||!/^:[\w-]+$/.test(v)){let[I,T]=bf(v,h);h=T,w[E]=I,m.hasRegexParam=!0,y.push([E,I,!1])}else y.push([E,v.slice(1),!1]);continue}v=u[E]=_;let P=m.static?.[v];if(P)m=P;else{let I={key:v};if(!m.static)m.static=new Co;m.static[v]=I,m=I}}let g=y.length>0,A=m.methods??=new Co;if((A[n]??=[]).push({data:s||null,paramsRegexp:w,paramsMap:g?y:void 0}),!g)r.static["/"+u.join("/")]=m}function bf(r,n=0){let i=n,s="",c=0;for(let f=0;f<r.length;f++){let m=r.charCodeAt(f);if(m===40)c++;else if(m===41&&c>0)c--;else if(m===92&&c===0&&f+1<r.length){let h=r[f+1];if(h!==":"&&h!=="("&&h!=="*"&&h!=="\\"){s+="\uFFFE"+h,f++;continue}}else if(m===46&&c===0){s+="\\.";continue}s+=r[f]}[s,i]=hf(s,i);let u=s.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(f,m,h)=>`(?<${ff(m)}>${h||"[^/]+"})`).replace(/\((?![?<])/g,()=>`(?<${ca(i++)}>`).replace(/\uFFFE(.)/g,(f,m)=>/[.*+?^${}()|[\]\\]/.test(m)?`\\${m}`:m);return[new RegExp(`^${u}$`),i]}function la(r,n="",i,s){if(s?.normalize)i=ua(i);if(i.charCodeAt(i.length-1)===47)i=i.slice(0,-1);let c=r.static[i];if(c&&c.methods){let m=c.methods[n]||c.methods[""];if(m!==void 0)return m[0]}let u=pi(i),f=si(r.root,n,u,0);if(f===void 0)return;if(s?.params===!1)return f;return{data:f.data,params:f.paramsMap?da(u,f.paramsMap):void 0}}function si(r,n,i,s){if(s===i.length){if(r.methods){let u=_o(r.methods,n,i,r.key==="*",!1);if(u)return u}return r.param?.methods&&_o(r.param.methods,n,i,!0,!0)||r.wildcard?.methods&&_o(r.wildcard.methods,n,i,!0,!0)||void 0}let c=i[s];if(r.static){let u=r.static[c];if(u){let f=si(u,n,i,s+1);if(f)return f}}if(r.param){let u=si(r.param,n,i,s+1);if(u)return u}if(r.wildcard&&r.wildcard.methods)return _o(r.wildcard.methods,n,i,!0,!1)}function _o(r,n,i,s,c){let u=r[n]||r[""];if(!u)return;let f=u[0];if(u.length===1&&f.paramsRegexp.length===0){if(!c)return f;let y=f.paramsMap;return y?.[y.length-1]?.[2]?f:void 0}let m,h=-1;for(let y of u){let w=y.paramsMap,g=w?.[w.length-1]?.[2];if(c&&!g)continue;let A=s&&w&&!g?1:0,E=y.paramsRegexp;for(let v=0;v<E.length;v++)if(E[v]){if(!E[v].test(i[v])){A=-1;break}A++}if(A>h)m=y,h=A}return m}function fa(r,n="",i,s){if(s?.normalize)i=ua(i);if(i.charCodeAt(i.length-1)===47)i=i.slice(0,-1);let c=pi(i),u=ui(r.root,n,c,0);if(s?.params===!1)return u;return u.map((f)=>({data:f.data,params:f.paramsMap?da(c,f.paramsMap):void 0}))}function ui(r,n,i,s,c=[]){let u=i[s];if(r.wildcard&&r.wildcard.methods){let f=r.wildcard.methods[n]||r.wildcard.methods[""];if(f)if(s<i.length)Uo(c,f,!0);else{let m=[];for(let h of f){let y=h.paramsMap;if(y?.[y.length-1]?.[2])m.push(h)}Uo(c,m,!0)}}if(r.param){if(s<i.length){let f=c.length;if(ui(r.param,n,i,s+1,c),r.param.hasRegexParam){for(let m=c.length-1;m>=f;m--)if(c[m].paramsRegexp[s]?.test(u)===!1)c.splice(m,1)}}else if(r.param.methods){let f=r.param.methods[n]||r.param.methods[""];if(f){let m=[];for(let h of f){let y=h.paramsMap;if(y?.[y.length-1]?.[2])m.push(h)}Uo(c,m,!0)}}}if(s<i.length){let f=r.static?.[u];if(f)ui(f,n,i,s+1,c)}if(s===i.length&&r.methods){let f=r.methods[n]||r.methods[""];if(f)Uo(c,f,r.key==="*")}return c}function Uo(r,n,i){if(n.length>1)n=n.map((s)=>{let c=0,{paramsRegexp:u,paramsMap:f}=s;for(let m=0;m<u.length;m++)if(u[m])c++;if(i&&f&&!f[f.length-1][2])c++;return[s,c]}).sort((s,c)=>s[1]-c[1]).map((s)=>s[0]);for(let s of n)r.push(s)}var mi=(r,n)=>{if(!n?.openapi?.disabled){let f={path:"/api/reference",...n?.openapi};r.openapi=Rt(f.path,{method:"GET"},async(m)=>{let h=await ni(r);return new Response(ii(h,f.scalar),{headers:{"Content-Type":"text/html"}})})}let i=fi(),s=fi();for(let f of Object.values(r)){if(!f.options||!f.path)continue;if(f.options?.metadata?.SERVER_ONLY)continue;let m=Array.isArray(f.options?.method)?f.options.method:[f.options?.method];for(let h of m)Mr(i,h,f.path,f)}if(n?.routerMiddleware?.length)for(let{path:f,middleware:m}of n.routerMiddleware)Mr(s,"*",f,m);let c=n?.basePath&&n.basePath!=="/"?n.basePath.replace(/\/+$/,""):"",u=async(f)=>{let m=new URL(f.url),h=m.pathname,y;if(c){if(!h.startsWith(`${c}/`))return new Response(null,{status:404,statusText:"Not Found"});y=h.slice(c.length)}else y=h;if(y.length===0||/\/{2,}/.test(y))return new Response(null,{status:404,statusText:"Not Found"});let w=la(i,f.method,y);if(y.endsWith("/")!==w?.data?.path?.endsWith("/")&&!n?.skipTrailingSlashes)return new Response(null,{status:404,statusText:"Not Found"});if(!w?.data)return new Response(null,{status:404,statusText:"Not Found"});let g={};m.searchParams.forEach((E,v)=>{if(v in g)if(Array.isArray(g[v]))g[v].push(E);else g[v]=[g[v],E];else g[v]=E});let A=w.data;try{let E=A.options.metadata?.allowedMediaTypes||n?.allowedMediaTypes,v={path:y,method:f.method,headers:f.headers,params:w.params?{...w.params}:{},request:f,body:A.options.disableBody?void 0:await Zs(A.options.cloneRequest?f.clone():f,E),query:g,_flag:"router",asResponse:!0,context:n?.routerContext},_=fa(s,"*",y);if(_?.length)for(let{data:P,params:I}of _){let T=await P({...v,params:I?{...I}:{},asResponse:!1});if(T instanceof Response)return T}return await A(v)}catch(E){if(n?.onError)try{let v=await n.onError(E,f);if(v instanceof Response)return Fe(v)}catch(v){if(ft(v))return Fe(v);throw v}if(n?.throwError)throw E;if(ft(E))return Fe(E);return console.error("# SERVER_ERROR: ",E),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async(f)=>{let m=await n?.onRequest?.(f);if(m instanceof Response)return m;let h=Ro(m)?m:f,y=await u(h),w=await n?.onResponse?.(y,h);if(w instanceof Response)return w;return y},endpoints:r}};function Oe(r){return r instanceof jt||r instanceof l||r?.name==="APIError"}var ha={"Cache-Control":"no-store",Pragma:"no-cache"};function Ef(r,n){if(!Oe(n)||!r)return;Object.defineProperty(n,vs,{enumerable:!1,configurable:!0,value:r,writable:!1})}var hi=Ut(async()=>({})),We=Ut.create({use:[hi,Ut(async()=>({}))]}),pa=Rt.create({use:[hi]});function ma(r,n){let i=n.metadata?.noStore===!0;return async(s)=>{if(i)for(let[c,u]of Object.entries(ha))s.setHeader(c,u);try{return await pr(s,()=>r(s))}catch(c){throw Ef(s.responseHeaders,c),c}}}function U(...r){if(r.length===3){let[s,c,u]=r;return pa(s,c,ma(u,c))}let[n,i]=r;return pa(n,ma(i,n))}function kf(r){return{...r,metadata:{...r.metadata,SERVER_ONLY:!0}}}U.serverOnly=(r,n)=>U(kf(r),n);var Sf=dy(),vf=uy();function yi(r){return Kr(r)||wi(r)}function Kr(r){return mo(Sf,r)}function wi(r){return mo(vf,r)}function ya(r){let n=r.toLowerCase();if(n.startsWith("::ffff:")){let s=n.substring(7);if(Kr(s))return s}let i=r.split(":");if(i.length===7&&i[5]?.toLowerCase()==="ffff"){let s=i[6];if(s&&Kr(s))return s}if(n.includes("::ffff:")||n.includes(":ffff:")){let s=gi(r);if(s.length===8&&s[0]==="0000"&&s[1]==="0000"&&s[2]==="0000"&&s[3]==="0000"&&s[4]==="0000"&&s[5]==="ffff"&&s[6]&&s[7])return`${Number.parseInt(s[6].substring(0,2),16)}.${Number.parseInt(s[6].substring(2,4),16)}.${Number.parseInt(s[7].substring(0,2),16)}.${Number.parseInt(s[7].substring(2,4),16)}`}return null}function gi(r){if(r.includes("::")){let n=r.split("::"),i=n[0]?n[0].split(":"):[],s=n[1]?n[1].split(":"):[],c=8-i.length-s.length,u=Array(c).fill("0000"),f=i.map((h)=>h.padStart(4,"0")),m=s.map((h)=>h.padStart(4,"0"));return[...f,...u,...m]}return r.split(":").map((n)=>n.padStart(4,"0"))}function Tf(r,n){let i=gi(r);if(n!==void 0&&n<128){let s=Math.max(0,Math.floor(n));return i.map((c)=>{if(s<=0)return"0000";if(s>=16)return s-=16,c;let u=Number.parseInt(c,16)&(65535<<16-s&65535);return s=0,u.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return i.join(":").toLowerCase()}function xo(r,n={}){if(Kr(r))return r.toLowerCase();if(!wi(r))return r.toLowerCase();let i=ya(r);if(i)return i.toLowerCase();return Tf(r,n.ipv6Subnet??64)}function wa(r){if(Kr(r))return Uint8Array.from(r.split(".").map((c)=>Number(c)));if(!wi(r))return null;let n=ya(r);if(n)return Uint8Array.from(n.split(".").map((c)=>Number(c)));let i=gi(r),s=new Uint8Array(16);for(let c=0;c<8;c++){let u=Number.parseInt(i[c]??"0",16);s[c*2]=u>>8&255,s[c*2+1]=u&255}return s}var Rf=/^\d+$/;function ga(r){let n=r.lastIndexOf("/"),i=wa(n===-1?r:r.slice(0,n));if(!i)return null;let s=i.length*8;if(n===-1)return{bytes:i,prefix:s};let c=r.slice(n+1);if(!Rf.test(c))return null;let u=Number(c);return u<=s?{bytes:i,prefix:u}:null}function If(r,n){if(r.length!==n.bytes.length)return!1;let i=n.prefix;for(let s=0;s<r.length&&i>0;s++){let c=i>=8?8:i,u=c===8?255:255<<8-c&255;if(((r[s]??0)&u)!==((n.bytes[s]??0)&u))return!1;i-=8}return!0}function Df(r){return r.filter((n)=>ga(n)===null)}function _f(r,n={}){let i=r.split(",").map((u)=>u.trim()).filter(Boolean);if(i.length===0)return null;let s=(n.trustedProxies??[]).map(ga).filter((u)=>u!==null);if(s.length>0){for(let u=i.length-1;u>=0;u--){let f=i[u],m=f?wa(f):null;if(!f||!m)return null;if(s.some((h)=>If(m,h)))continue;return xo(f,{ipv6Subnet:n.ipv6Subnet})}return null}if(i.length!==1)return null;let c=i[0];if(!c||!yi(c))return null;return xo(c,{ipv6Subnet:n.ipv6Subnet})}var Cf="127.0.0.1",xf=["x-forwarded-for"];function Oi(r,n){if(n.advanced?.ipAddress?.disableIpTracking)return null;let i="headers"in r?r.headers:r,s=n.advanced?.ipAddress?.ipAddressHeaders||xf;for(let c of s){let u="get"in i?i.get(c):i[c];if(typeof u==="string"){let f=_f(u,{ipv6Subnet:n.advanced?.ipAddress?.ipv6Subnet,trustedProxies:n.advanced?.ipAddress?.trustedProxies});if(f)return f}}if(fn()||ai())return Cf;return null}function Aa(r,n){return`${r}|${n}`}function Er(r,n){return{digest:async(i)=>{let s=ci(i),c=await qe().digest(r,s);if(n==="hex")return Array.from(new Uint8Array(c)).map((u)=>u.toString(16).padStart(2,"0")).join("");if(n==="base64"||n==="base64url"||n==="base64urlnopad"){if(n.includes("url"))return xt.encode(c,{padding:n!=="base64urlnopad"});return Dt.encode(c)}return c}}}var En={scope:"server"};var tt=t({id:e(),createdAt:Pt().default(()=>new Date),updatedAt:Pt().default(()=>new Date)});var ba=tt.extend({providerId:e(),accountId:e(),userId:bs(),accessToken:e().nullish(),refreshToken:e().nullish(),idToken:e().nullish(),accessTokenExpiresAt:Pt().nullish(),refreshTokenExpiresAt:Pt().nullish(),scope:e().nullish(),password:e().nullish()});var Ea=t({key:e(),count:b(),lastRequest:b()});var Oo=tt.extend({userId:bs(),expiresAt:Pt(),token:e(),ipAddress:e().nullish(),userAgent:e().nullish()});var Lo=tt.extend({email:e().transform((r)=>r.toLowerCase()),emailVerified:o().default(!1),name:e(),image:e().nullish()});var ka=tt.extend({value:e(),expiresAt:Pt(),identifier:e()});function bi(r){if(r==="-"||r==="^"||r==="$"||r==="+"||r==="."||r==="("||r===")"||r==="|"||r==="["||r==="]"||r==="{"||r==="}"||r==="*"||r==="?"||r==="\\")return`\\${r}`;else return r}function Of(r){let n="";for(let i=0;i<r.length;i++)n+=bi(r[i]);return n}function Sa(r,n=!0){if(Array.isArray(r))return`(?:${r.map((y)=>`^${Sa(y,n)}$`).join("|")})`;let i="",s="",c=".";if(n===!0)i="/",s="[/\\\\]",c="[^/\\\\]";else if(n)if(i=n,s=Of(i),s.length>1)s=`(?:${s})`,c=`((?!${s}).)`;else c=`[^${s}]`;let u=n?`${s}+?`:"",f=n?`${s}*?`:"",m=n?r.split(i):[r],h="";for(let y=0;y<m.length;y++){let w=m[y],g=m[y+1],A="";if(!w&&y>0)continue;if(n)if(y===m.length-1)A=f;else if(g!=="**")A=u;else A="";if(n&&w==="**"){if(A)h+=y===0?"":A,h+=`(?:${c}*?${A})*?`;continue}for(let E=0;E<w.length;E++){let v=w[E];if(v==="\\"){if(E<w.length-1)h+=bi(w[E+1]),E++}else if(v==="?")h+=c;else if(v==="*")h+=`${c}*?`;else h+=bi(v)}h+=A}return h}function Pf(r,n){if(typeof n!=="string")throw TypeError(`Sample must be a string, but ${typeof n} given`);return r.test(n)}function Jt(r,n){if(typeof r!=="string"&&!Array.isArray(r))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof r} given`);if(typeof n==="string"||typeof n==="boolean")n={separator:n};if(arguments.length===2&&!(typeof n>"u"||typeof n==="object"&&n!==null&&!Array.isArray(n)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof n} given`);if(n=n||{},n.separator==="\\")throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let i=Sa(r,n.separator),s=new RegExp(`^${i}$`,n.flags),c=Pf.bind(null,s);return c.options=n,c.pattern=r,c.regexp=s,c}var Nf=47;function $f(r){let n=r.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return n==="localhost"||n.endsWith(".localhost")||n==="::1"||n.startsWith("127.")}function va(r){let n=r.length;while(n>0&&r.charCodeAt(n-1)===Nf)n--;return n===r.length?r:r.slice(0,n)}function jf(r){try{return(va(new URL(r).pathname)||"/")!=="/"}catch{throw new S(`Invalid base URL: ${r}. Please provide a valid base URL.`)}}function Mf(r){try{let n=new URL(r);if(n.protocol!=="http:"&&n.protocol!=="https:")throw new S(`Invalid base URL: ${r}. URL must include 'http://' or 'https://'`)}catch(n){if(n instanceof S)throw n;throw new S(`Invalid base URL: ${r}. Please provide a valid base URL.`,{cause:n})}}function pt(r,n="/api/auth"){if(Mf(r),jf(r))return r;let i=va(r);if(!n||n==="/")return i;return n=n.startsWith("/")?n:`/${n}`,`${i}${n}`}function Wr(r,n){if(!r||r.trim()==="")return!1;if(n==="proto")return r==="http"||r==="https";if(n==="host"){if([/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some((i)=>i.test(r)))return!1;return/^[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(r)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(r)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(r)||/^localhost(:[0-9]{1,5})?$/i.test(r)}return!1}function _r(r,n,i,s,c){if(r)return pt(r,n);if(s!==!1){let m=ae.BETTER_AUTH_URL||ae.NEXT_PUBLIC_BETTER_AUTH_URL||ae.PUBLIC_BETTER_AUTH_URL||ae.NUXT_PUBLIC_BETTER_AUTH_URL||ae.NUXT_PUBLIC_AUTH_URL||(ae.BASE_URL!=="/"?ae.BASE_URL:void 0);if(m)return pt(m,n)}let u=i?.headers.get("x-forwarded-host"),f=i?.headers.get("x-forwarded-proto");if(u&&f&&c){if(Wr(f,"proto")&&Wr(u,"host"))try{return pt(`${f}://${u}`,n)}catch(m){}}if(i){let m=tn(i.url);if(!m)throw new S("Could not get origin from request. Please provide a valid base URL.");return pt(m,n)}if(typeof window<"u"&&window.location)return pt(window.location.origin,n)}function tn(r){try{let n=new URL(r);return n.origin==="null"?null:n.origin}catch{return null}}function Ta(r){try{return new URL(r).protocol}catch{return null}}function Ra(r){try{return new URL(r).host}catch{return null}}function er(r){return typeof r==="object"&&r!==null&&"allowedHosts"in r&&Array.isArray(r.allowedHosts)}function He(r){if(r instanceof Request)return!0;if(typeof r!=="object"||r===null||Object.prototype.toString.call(r)!=="[object Request]")return!1;let n=r;return typeof n.url==="string"&&typeof n.headers==="object"&&n.headers!==null&&typeof n.headers.get==="function"}function Ia(r,n){let i=He(r)?r.headers:r;if(n){let c=i.get("x-forwarded-host");if(c&&Wr(c,"host"))return c}let s=i.get("host");if(s&&Wr(s,"host"))return s;if(He(r))try{return new URL(r.url).host}catch{return null}return null}function Kf(r,n,i){if(n==="http"||n==="https")return n;let s=He(r)?r.headers:r;if(i){let u=s.get("x-forwarded-proto");if(u&&Wr(u,"proto"))return u}if(He(r))try{let u=new URL(r.url);if(u.protocol==="http:"||u.protocol==="https:")return u.protocol.slice(0,-1)}catch{}let c=Ia(r,i);if(c&&$f(c))return"http";return"https"}var Wf=(r,n)=>{if(!r||!n)return!1;let i=r.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),s=n.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();if(s.includes("*")||s.includes("?"))return Jt(s)(i);return i.toLowerCase()===s.toLowerCase()};function Jf(r,n,i,s){let c=Ia(n,s);if(!c){if(r.fallback)return pt(r.fallback,i);throw new S("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(r.allowedHosts.some((u)=>Wf(c,u)))return pt(`${Kf(n,r.protocol,s)}://${c}`,i);if(r.fallback)return pt(r.fallback,i);throw new S(`Host "${c}" is not in the allowed hosts list. Allowed hosts: ${r.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function _a(r,n,i,s,c){if(er(r)){if(i)return Jf(r,i,n,c);if(r.fallback)return pt(r.fallback,n);return _r(void 0,n,void 0,s,c)}let u=He(i)?i:void 0;if(typeof r==="string")return _r(r,n,u,s,c);return _r(void 0,n,u,s,c)}var xa=/[\u0000-\u001f\u007f-\u009f]/,Ua="https://better-auth.invalid",Gf=/%2[fF]|%5[cC]/,Qf=(r)=>{let n=r;try{n=decodeURIComponent(r)}catch{}let i=[];for(let s of n.split("/"))if(s==="..")i.pop();else if(s!=="."&&s!=="")i.push(s);return i.length>0?`/${i.join("/")}`:""},Ca=(r)=>{if(xa.test(r))return null;let n=r.indexOf(":");if(n<=0)return null;let i=r.slice(0,n).toLowerCase(),s=r.slice(n+1),c="";if(s.startsWith("//")){s=s.slice(2);let m=s.search(/[/?#]/);if(m===-1)c=s,s="";else c=s.slice(0,m),s=s.slice(m)}let u=s.search(/[?#]/),f=Qf(u===-1?s:s.slice(0,u));return{scheme:i,authority:c.toLowerCase(),path:f}},Zf=(r)=>{if(!r.startsWith("/")||r.startsWith("//")||r.includes("\\")||xa.test(r))return!1;let n=r.search(/[?#]/),i=n===-1?r:r.slice(0,n);if(Gf.test(i))return!1;try{return new URL(r,Ua).origin===Ua}catch{return!1}},Gc=(r,n,i)=>{if(r.startsWith("/"))return i?.allowRelativePaths===!0&&Zf(r);if(n.includes("*")||n.includes("?")){if(n.includes("://"))return Jt(n)(tn(r)||r);let f=Ra(r);if(!f)return!1;return Jt(n)(f)}let s=Ta(r);if(s==="http:"||s==="https:"||!s)return n===tn(r);let c=Ca(r),u=Ca(n);if(!c||!u||c.scheme!==u.scheme)return!1;if(u.authority&&c.authority!==u.authority)return!1;if(!u.path)return!0;return c.path===u.path||c.path.startsWith(`${u.path}/`)};function Kc(r){return!!r.database||!!r.secondaryStorage}function Yf(r){return!!r.database}function Do(r){return Yf(r)}function Ci(r){return!!r&&(typeof r==="object"||typeof r==="function")&&typeof r.then==="function"}class Ei{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(r,n){if(za(r),Un(n,void 0,"key"),this.iHash=r.create(),typeof this.iHash.update!=="function")throw Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?r.create().update(n).digest():n);for(let c=0;c<s.length;c++)s[c]^=54;this.iHash.update(s),this.oHash=r.create();for(let c=0;c<s.length;c++)s[c]^=106;this.oHash.update(s),Br(s)}update(r){return po(this),this.iHash.update(r),this}digestInto(r){po(this),wd(r,this),this.finished=!0;let n=r.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){let r=new Uint8Array(this.oHash.outputLen);return this.digestInto(r),r}_cloneInto(r){r||=Object.create(Object.getPrototypeOf(this),{});let{oHash:n,iHash:i,finished:s,destroyed:c,blockLen:u,outputLen:f,canXOF:m}=this;return r=r,r.finished=s,r.destroyed=c,r.blockLen=u,r.outputLen=f,r.canXOF=m,r.oHash=n._cloneInto(r.oHash),r.iHash=i._cloneInto(r.iHash),r}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var ki=(()=>{let r=(n,i,s)=>new Ei(n,i).update(s).digest();return r.create=(n,i)=>new Ei(n,i),r})();var Vr=Uint8Array.of(0),Xf=Uint8Array.of();function ep(r,n,i,s=32,c){za(r),Va(s,"length"),Un(n,void 0,"prk");let u=r.outputLen;if(n.length<u)throw Error('"prk" must be at least HashLen octets');if(s>255*u)throw Error("Length must be <= 255*HashLen");let f=Math.ceil(s/u);if(i===void 0)i=Xf;else Un(i,void 0,"info");if(!f){if(c)Br(n);return new Uint8Array}let m=c&&f===1?n:new Uint8Array(f*u),{iHash:h,oHash:y}=ki.create(r,n),w=c?n:new Uint8Array(u),g=f>1?c?.iHash||r.create():void 0;for(let E=0;E<f-1;E++){Vr[0]=E+1;let v=h._cloneInto(g);if(E)v.update(w);v.update(i).update(Vr).digestInto(w),y._cloneInto(g).update(w).digestInto(w),m.set(w,u*E)}if(Vr[0]=f,f>1)h.update(w);if(h.update(i).update(Vr).digestInto(w),y.update(w).digestInto(w),m.set(w,u*(f-1)),h.destroy(),y.destroy(),g?.destroy(),w!==m)Br(w);if(Br(Vr),s===m.length)return m;let A=m.slice(0,s);return Br(m),A}var Po=(r,n,i,s,c)=>{if(za(r),i===void 0)i=new Uint8Array(r.outputLen);let u=ki.create(r,i).update(n);return ep(r,u.digest(),s,c,u)};var tp=(r)=>r/4294967296|0,rp=(r)=>r>>>0;function Oa(r,n,i,s){let c=tp(i),u=rp(i);r.setUint32(n,s?u:c,s),r.setUint32(n+4,s?c:u,s)}function La(r,n,i){return r&n^~r&i}function Da(r,n,i){return r&n^r&i^n&i}class Si{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(r,n,i,s){this.blockLen=r,this.outputLen=n,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(r),this.view=Sd(this.buffer)}update(r){po(this),Un(r);let{view:n,buffer:i,blockLen:s}=this,c=r.length,u=!1;for(let f=0;f<c;){let m=Math.min(s-this.pos,c-f);if(m===s){let h=Sd(r);for(;s<=c-f;f+=s)this.process(h,f);u=!0;continue}if(i.set(f===0&&m===c?r:r.subarray(f,f+m),this.pos),this.pos+=m,f+=m,this.pos===s)this.process(n,0),this.pos=0,u=!0}if(this.length+=r.length,u)this.roundClean();return this}digestInto(r){po(this),wd(r,this),this.finished=!0;let{buffer:n,view:i,blockLen:s,isLE:c}=this,{pos:u}=this;if(n[u++]=128,n.fill(0,u),this.padOffset>s-u)this.process(i,0),n.fill(0);Oa(i,s-8,this.length*8,c),this.process(i,0),this.roundClean();let f=r===n?i:Sd(r),m=this.outputLen,h=m/4,y=this.get();if(m%4||h>y.length)throw Error("invalid outputLen");for(let w=0;w<h;w++)f.setUint32(4*w,y[w],c)}digest(){let{buffer:r,outputLen:n}=this;this.digestInto(r);let i=r.slice(0,n);return this.destroy(),i}_cloneIntoMeta(r){let{buffer:n,length:i,finished:s,destroyed:c,pos:u}=this;if(r.destroyed=c,r.finished=s,r.length=i,r.pos=u,u)r.buffer.set(n);return r}clone(){return this._cloneInto()}}var Pa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var op=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ct=new Uint32Array(64);class Na extends Si{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(r,n){super(64,r,8,!1);this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:r,B:n,C:i,D:s,E:c,F:u,G:f,H:m}=this;return[r,n,i,s,c,u,f,m]}set(r,n,i,s,c,u,f,m){this.A=r|0,this.B=n|0,this.C=i|0,this.D=s|0,this.E=c|0,this.F=u|0,this.G=f|0,this.H=m|0}_cloneInto(r){return(r||=new this.constructor).set(...this.get()),this._cloneIntoMeta(r)}process(r,n){for(let w=0;w<16;w++,n+=4)Ct[w]=r.getUint32(n,!1);for(let w=16;w<64;w++){let g=Ct[w-15],A=Ct[w-2],E=Fr(g,7)^Fr(g,18)^g>>>3,v=Fr(A,17)^Fr(A,19)^A>>>10;Ct[w]=v+Ct[w-7]+E+Ct[w-16]|0}let{A:i,B:s,C:c,D:u,E:f,F:m,G:h,H:y}=this;for(let w=0;w<64;w++){let g=Fr(f,6)^Fr(f,11)^Fr(f,25),A=y+g+La(f,m,h)+op[w]+Ct[w]|0,v=(Fr(i,2)^Fr(i,13)^Fr(i,22))+Da(i,s,c)|0;y=h,h=m,m=f,f=u+A|0,u=c,c=s,s=i,i=A+v|0}i=i+this.A|0,s=s+this.B|0,c=c+this.C|0,u=u+this.D|0,f=f+this.E|0,m=m+this.F|0,h=h+this.G|0,y=y+this.H|0,this.set(i,s,c,u,f,m,h,y)}roundClean(){Br(Ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Br(this.buffer)}}class $a extends Na{constructor(){super(32,Pa)}}var No=ry(()=>new $a,ny(1));var Ot=new TextEncoder,mr=new TextDecoder,hr=new TextDecoder("utf-8",{fatal:!0});function Ie(...r){let n=r.reduce((c,{length:u})=>c+u,0),i=new Uint8Array(n),s=0;for(let c of r)i.set(c,s),s+=c.length;return i}function vi(r,n,i){if(n<0||n>=4294967296)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${n}`);r.set([n>>>24,n>>>16,n>>>8,n&255],i)}function Ti(r){let n=Math.floor(r/4294967296),i=r%4294967296,s=new Uint8Array(8);return vi(s,n,0),vi(s,i,4),s}function $o(r){let n=new Uint8Array(4);return vi(n,r),n}var np=/[^\x00-\x7f]/;function Ee(r){if(typeof r=="string"&&r.length>=128){if(np.test(r))throw TypeError("non-ASCII string encountered in encode()");return Ot.encode(r)}let n=new Uint8Array(r.length);for(let i=0;i<r.length;i++){let s=r.charCodeAt(i);if(s>127)throw TypeError("non-ASCII string encountered in encode()");n[i]=s}return n}function ja(r,n=!1){if(Uint8Array.prototype.toBase64)return r.toBase64({alphabet:n?"base64url":"base64",omitPadding:n});let i=32768,s=[];for(let u=0;u<r.length;u+=i)s.push(String.fromCharCode.apply(null,r.subarray(u,u+i)));let c=btoa(s.join(""));return n?c.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):c}function Ba(r,n=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r,{alphabet:n?"base64url":"base64"});if(n){if(r.includes("+")||r.includes("/"))throw TypeError("Invalid base64url");r=r.replace(/-/g,"+").replace(/_/g,"/")}let i=atob(r),s=new Uint8Array(i.length);for(let c=0;c<i.length;c++)s[c]=i.charCodeAt(c);return s}async function jo(r,n){let i=`SHA-${r.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(i,n))}class be extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(r,n){super(r,n),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class rt extends be{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(r,n,i="unspecified",s="unspecified"){super(r,{cause:{claim:i,reason:s,payload:n}}),this.claim=i,this.reason=s,this.payload=n}}class yr extends be{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(r,n,i="unspecified",s="unspecified"){super(r,{cause:{claim:i,reason:s,payload:n}}),this.claim=i,this.reason=s,this.payload=n}}class wr extends be{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class ue extends be{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Ho extends be{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(r="decryption operation failed",n){super(r,n)}}class Y extends be{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class fe extends be{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class _e extends be{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class Bo extends be{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class Mo extends be{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class qr extends be{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(r="no applicable key found in the JSON Web Key Set",n){super(r,n)}}class Ri extends be{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(r="multiple matching keys found in the JSON Web Key Set",n){super(r,n)}}class Ii extends be{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(r="request timed out",n){super(r,n)}}class _i extends be{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(r="signature verification failed",n){super(r,n)}}var ip="The input to be decoded is not correctly encoded.";function mt(r){try{return Ba(typeof r=="string"?r:mr.decode(r),!0)}catch(n){throw TypeError(ip,{cause:n})}}function pe(r){return ja(typeof r=="string"?Ot.encode(r):r,!0)}function Gt(r,n){if(!(r instanceof Uint8Array))throw TypeError(`${n} must be an instance of Uint8Array`)}function he(r){if(typeof r!="object"||r===null||Object.prototype.toString.call(r)!=="[object Object]")return!1;let n=Object.getPrototypeOf(r);return n===null||Object.getPrototypeOf(n)===null}function qo(r){return he(r)&&Array.isArray(r.keys)&&Array.from(r.keys).every(he)}function Nt(...r){let n=new Set;for(let i of r)if(i)for(let s of Object.keys(i)){if(n.has(s))return!1;n.add(s)}return!0}function Qt(r,n){if(r!==void 0)throw TypeError(`${n} can only be called once`)}function xe(r,n,i){try{return mt(r)}catch{throw new i(`Failed to base64url decode the ${n}`)}}function Fo(r,n,i){try{return Ee(r)}catch{throw new i(`The ${n} is not a valid base64url string`)}}function gr(r,n,i){let s;try{s=JSON.parse(hr.decode(mt(r)))}catch{throw new n(i)}if(!he(s))throw new n(i);return s}var Zo={__proto__:null,b64:!0},Xo={__proto__:null};function Jr(r,n){if(n!==void 0&&(!Array.isArray(n)||n.some((i)=>typeof i!="string")))throw TypeError(`"${r}" option must be an array of strings`);return n===void 0?void 0:new Set(n)}function en(r,n){let{crit:i}=n??{};if(Array.isArray(i)&&new Set(i).size!==i.length)throw new r('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function zt(r,n,i,s,c){if(c.crit!==void 0&&s?.crit===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||s.crit===void 0)return[];if(!Array.isArray(s.crit)||s.crit.length===0||s.crit.some((f)=>typeof f!="string"||f.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let u=i===void 0?n:{__proto__:null,...i,...n};for(let f of s.crit){if(!(f in u))throw new ue(`Extension Header Parameter "${f}" is not recognized`);if(!Object.hasOwn(c,f)||c[f]===void 0)throw new r(`Extension Header Parameter "${f}" is missing`);if(u[f]&&(!Object.hasOwn(s,f)||s[f]===void 0))throw new r(`Extension Header Parameter "${f}" MUST be integrity protected`)}return s.crit}function rn(r,n){if(n.includes("b64")){let i=r.b64;if(typeof i!="boolean")throw new fe('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return i}return!0}function Zt(r,n){let i,s;try{i=JSON.stringify(n),s=JSON.parse(i)}catch(c){throw new r("JOSE Header is not valid JSON",{cause:c})}if(!he(s))throw new r("JOSE Header is not a JSON object");return[s,i]}var sp=(r)=>r[Symbol.toStringTag],ap=(r,n,i)=>{let{alg:s}=r;if(n.use!==void 0){let c=i==="sign"||i==="verify"?"sig":"enc";if(n.use!==c)throw TypeError(`Invalid key for this operation, its "use" must be "${c}" when present`)}if(n.alg!==void 0&&n.alg!==s)throw TypeError(`Invalid key for this operation, its "alg" must be "${s}" when present`);if(Array.isArray(n.key_ops)){let c=i==="encrypt"||i==="decrypt"?r.ops?.[i==="encrypt"?0:1]:i;if(c&&!n.key_ops.includes(c))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${c}" when present`)}};async function Je(r,n,i){let{alg:s,secret:c}=r,u=i==="decrypt"||i==="sign";if(c&&n instanceof Uint8Array)return n;let f,m;if(he(n)){if(f=Hi(n),typeof f.kty!="string")throw Ka(s,n,c);if(!(c?f.kty==="oct"&&typeof f.k=="string":f.kty!=="oct"&&(u?f.kty==="AKP"&&typeof f.priv=="string"||typeof f.d=="string":f.d===void 0&&f.priv===void 0)))throw TypeError(c?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${u?"private":"public"} JWK`);if(ap(r,f,i),f.kty==="oct")return mt(f.k);if(!Object.isFrozen(n)){let{key_ops:w}=n;Array.isArray(w)&&Object.freeze(w),Object.freeze(n)}}else{if(!Li(n))throw Ka(s,n,c);let w=c?"secret":u?"private":"public";if(n.type!==w&&(c||["secret","public","private"].includes(n.type)))throw TypeError(`${sp(n)} instances must be of type "${w}" for the ${s} algorithm`);if($t(n))return n;if(m=n,m.type==="secret")return m.export()}Ui||=new WeakMap;let h=n,y=Ui.get(h);if(y?.[s])return y[s];if(y||Ui.set(h,y={}),m&&typeof m.toCryptoKey=="function"){let w=m.type==="public",g=cp[m.asymmetricKeyDetails?.namedCurve],A=r.resolve?.({crv:g,asymmetricKeyType:m.asymmetricKeyType})??r.subtle;return y[s]=m.toCryptoKey(A,w,r.usages[w?0:1])}return f??=m.export({format:"jwk"}),f.alg=s,y[s]=await Bt(r,f)}var Ui,cp={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function nn(r){if(!$t(r))throw Error("CryptoKey instance expected")}var $t=(r)=>{if(r?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return r instanceof CryptoKey}catch{return!1}},xi=(r)=>r?.[Symbol.toStringTag]==="KeyObject",Li=(r)=>$t(r)||xi(r);function Wa(r,n,...i){if(i.length>2){let s=i.pop();r+=`one of type ${i.join(", ")}, or ${s}.`}else i.length===2?r+=`one of type ${i[0]} or ${i[1]}.`:r+=`of type ${i[0]}.`;return n==null?r+=` Received ${n}`:typeof n=="function"&&n.name?r+=` Received function ${n.name}`:typeof n=="object"&&n!=null&&n.constructor?.name&&(r+=` Received an instance of ${n.constructor.name}`),r}var ht=(r,...n)=>Wa("Key must be ",r,...n);function Ka(r,n,i){let s=["CryptoKey","KeyObject","JSON Web Key"];return i&&s.push("Uint8Array"),TypeError(Wa(`Key for the ${r} algorithm must be `,n,...s))}var on=(r,n="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${n} must be ${r}`);function Pi(r,n){if(n&&!r.usages.includes(n))throw TypeError(`CryptoKey does not support this operation, its usages must include ${n}.`)}function Ar(r,n){let{modulusLength:i}=n.algorithm;if(typeof i!="number"||i<2048)throw TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}function zi(r,n,i){let s=r.algorithm;if(s.name!==n.name)throw on(n.name);if(n.hash&&s.hash?.name!==n.hash)throw on(n.hash,"algorithm.hash");if(n.namedCurve&&s.namedCurve!==n.namedCurve)throw on(n.namedCurve,"algorithm.namedCurve");if(n.length!==void 0&&s.length!==n.length)throw on(n.length,"algorithm.length");Pi(r,i)}function kr(r){return{__proto__:null,...r}}function Hi(r){let n=kr(r);if(n.ext!==void 0&&typeof n.ext!="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(n.key_ops!==void 0){let i=n.key_ops,s=Array.isArray(i)?[...i]:void 0;if(!s||s.some((c)=>typeof c!="string")||new Set(s).size!==s.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');n.key_ops=s}return n}function qa(r){if(r!==void 0&&typeof r!="boolean")throw TypeError('"extractable" option must be a boolean');return r}async function Bt(r,n,i){if(!r.kty.includes(n.kty))throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let s=r.resolve?.({kty:n.kty,crv:n.crv})??r.subtle,c=!!(n.d||n.priv),u={...n,ext:i??n.ext};return u.kty!=="AKP"&&delete u.alg,delete u.use,crypto.subtle.importKey("jwk",u,s,u.ext??!c,n.key_ops??r.usages[c?1:0])}async function Ge(r,n,i,s=!1){return r instanceof Uint8Array&&(r=await crypto.subtle.importKey("raw",r,n,s,[i])),zi(r,n,i),r}var Gr=(r)=>crypto.getRandomValues(new Uint8Array(r.cekBits>>3));function sn(r,n){let i=r.byteLength<<3;if(i!==n)throw new Y(`Invalid Content Encryption Key length. Expected ${n} bits, got ${i} bits`)}var up=(r)=>crypto.getRandomValues(new Uint8Array(r.ivBits>>3));function Fa(r,n){if(n.length<<3!==r.ivBits)throw new Y("Invalid Initialization Vector length")}async function Ja(r,n,i){if(!(n instanceof Uint8Array))throw TypeError(ht(n,"Uint8Array"));let s=r.cekBits>>1,c=await crypto.subtle.importKey("raw",n.subarray(s>>3),"AES-CBC",!1,[i]),u=await crypto.subtle.importKey("raw",n.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]);return[c,u,s]}async function Qa(r,n,i){return new Uint8Array((await crypto.subtle.sign("HMAC",r,n)).slice(0,i>>3))}async function dp(r,n,i,s,c){let[u,f,m]=await Ja(r,i,"encrypt"),h=new Uint8Array(await crypto.subtle.encrypt({iv:s,name:"AES-CBC"},u,n)),y=Ie(c,s,h,Ti(c.length*8)),w=await Qa(f,y,m);return{ciphertext:h,tag:w,iv:s}}async function lp(r,n){let i={name:"HMAC",hash:"SHA-256"},s=await crypto.subtle.generateKey(i,!1,["sign","verify"]),c=await crypto.subtle.sign(i,s,r);return crypto.subtle.verify(i,s,c,n)}async function fp(r,n,i,s,c,u){let[f,m,h]=await Ja(r,n,"decrypt"),y=Ie(u,s,i,Ti(u.length*8)),w=await Qa(m,y,h);try{if(await lp(c,w))return new Uint8Array(await crypto.subtle.decrypt({iv:s,name:"AES-CBC"},f,i))}catch{}throw new Ho}async function an(r,n,i,s,c){if(!$t(i)&&!(i instanceof Uint8Array))throw TypeError(ht(i,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(s?Fa(r,s):s=up(r),i instanceof Uint8Array&&sn(i,r.cekBits),r.cbc)return dp(r,n,i,s,c);let u=await Ge(i,r.subtle,"encrypt"),f=new Uint8Array(await crypto.subtle.encrypt({additionalData:c,iv:s,name:"AES-GCM",tagLength:128},u,n));return{ciphertext:f.subarray(0,-16),tag:f.subarray(-16),iv:s}}async function cn(r,n,i,s,c,u){if(!$t(n)&&!(n instanceof Uint8Array))throw TypeError(ht(n,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!s)throw new Y("JWE Initialization Vector missing");if(!c)throw new Y("JWE Authentication Tag missing");if(!r.cbc&&c.length!==16)throw new Y("Invalid Authentication Tag length");if(Fa(r,s),n instanceof Uint8Array&&sn(n,r.cekBits),r.cbc)return fp(r,n,i,s,c,u);let f=await Ge(n,r.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:u,iv:s,name:"AES-GCM",tagLength:128},f,Ie(i,c)))}catch{throw new Ho}}function Qr(r){let n={__proto__:null};for(let i in r)n[i]={...r[i],alg:i};return n}var pp=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],mp=[[],["deriveBits"]],ln=[[],[]];function un(r){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${r}`},usages:pp,ops:["wrapKey","unwrapKey"]}}function dn(r){return{kty:["EC","OKP"],mode:r,subtle:{name:"ECDH"},resolve:({kty:n,crv:i,asymmetricKeyType:s})=>{if(i==="X25519"||s==="x25519")return{name:"X25519"};if(n==="OKP")throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:i}},usages:mp,ops:[void 0,"deriveBits"]}}function Sr(r,n=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:n?"AES-GCM":"AES-KW",length:r},usages:ln,ops:n?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function Bi(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:ln,ops:["deriveBits","deriveBits"]}}var Yt=Qr({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:ln,ops:["encrypt","decrypt"]},"RSA-OAEP":un(1),"RSA-OAEP-256":un(256),"RSA-OAEP-384":un(384),"RSA-OAEP-512":un(512),"ECDH-ES":dn("direct-key-agreement"),"ECDH-ES+A128KW":dn("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":dn("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":dn("key-agreement-with-key-wrapping"),A128KW:Sr(128),A192KW:Sr(192),A256KW:Sr(256),A128GCMKW:Sr(128,!0),A192GCMKW:Sr(192,!0),A256GCMKW:Sr(256,!0),"PBES2-HS256+A128KW":Bi(),"PBES2-HS384+A192KW":Bi(),"PBES2-HS512+A256KW":Bi()}),hp=["encrypt","decrypt"];function vr(r,n=!1){return{kty:["oct"],secret:!0,subtle:{name:n?"AES-CBC":"AES-GCM",length:r},usages:ln,ops:hp,cekBits:r,ivBits:n?128:96,cbc:n}}var yp=Qr({A128GCM:vr(128),A192GCM:vr(192),A256GCM:vr(256),"A128CBC-HS256":vr(256,!0),"A192CBC-HS384":vr(384,!0),"A256CBC-HS512":vr(512,!0)});function Za(r,n){throw new ue(`Invalid or unsupported "${r}" (JWE ${n}) header value`)}function yt(r){return(typeof r=="string"?Yt[r]:void 0)??Za("alg","Algorithm")}function Xt(r){return r.mode==="key-wrapping"||r.mode==="key-encryption"||r.mode==="key-agreement-with-key-wrapping"}function tr(r){return(typeof r=="string"?yp[r]:void 0)??Za("enc","Encryption Algorithm")}function Ya(r,n){if(r.algorithm.name!=="ECDH"&&r.algorithm.name!=="X25519")throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");Pi(r,n)}async function wp(r,n,i){let s=await Ge(n,yt(r).subtle,"wrapKey",!0),c=await crypto.subtle.importKey("raw",i,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",c,s,"AES-KW"))}async function gp(r,n,i){let s=await Ge(n,yt(r).subtle,"unwrapKey",!0),c=await crypto.subtle.unwrapKey("raw",i,s,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",c))}function ec(r,n,i){zi(n,yt(r).subtle,i),Ar(r,n)}async function tc(r,n,i,s){if(!(r instanceof Uint8Array)||r.length<8)throw new Y("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(i)||Math.sign(i)!==1)throw new Y("PBES2 Count Input must be a positive integer");let c=Ie(Ee(n),Uint8Array.of(0),r),u=parseInt(n.slice(13,16),10),f={hash:`SHA-${n.slice(8,11)}`,iterations:i,name:"PBKDF2",salt:c},m=await Ge(s,yt(n).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(f,m,u))}function Ki(r){return Ie($o(r.length),r)}async function Ap(r,n,i){let s=n>>3,u=Math.ceil(s/32),f=new Uint8Array(u*32);for(let m=1;m<=u;m++){let h=await jo("sha256",Ie($o(m),r,i));f.set(h,(m-1)*32)}return f.slice(0,s)}async function rc(r,n,i,s,c=new Uint8Array,u=new Uint8Array){Ya(r),Ya(n,"deriveBits");let f=Ie(Ki(Ee(i)),Ki(c),Ki(u),$o(s)),m=new Uint8Array(await crypto.subtle.deriveBits({name:r.algorithm.name,public:r},n,r.algorithm.name==="X25519"?256:Math.ceil(parseInt(r.algorithm.namedCurve.slice(-3),10)/8)<<3));return Ap(m,s,f)}function oc(r){nn(r);let n=r.algorithm.namedCurve;if(n!=="P-256"&&n!=="P-384"&&n!=="P-521"&&r.algorithm.name!=="X25519")throw new ue("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function pn(r,n){let i=r[n];if(i!==void 0){if(typeof i!="string")throw new Y(`JOSE Header "${n}" (Agreement Party${n==="apu"?"U":"V"}Info) invalid`);return xe(i,n,Y)}}function nc(r,n){if(!(r===void 0||n===void 0||r.byteLength!==n.byteLength)){for(let i=0;i<r.byteLength;i++)if(r[i]!==n[i])return;throw new Y('JOSE Header "apu" and "apv" values must be distinct')}}function Ep(r){if(r===void 0)throw new Y("JWE Encrypted Key missing")}function Xa(r){if(r!==void 0)throw new Y("Encountered unexpected JWE Encrypted Key")}function kp(r){if(r!==void 0&&r!==1/0&&(!Number.isSafeInteger(r)||r<1))throw TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function ic(r,n,i,s,c,u){let{alg:f}=r,m=r.mode;if(m==="direct-encryption")return Xa(s),i;let h=m==="direct-key-agreement";switch(h?Xa(s):Ep(s),r.subtle.name){case"ECDH":{let{epk:y}=c;if(!he(y)||["d","k","p","q","dp","dq","qi","oth","priv"].some((v)=>Object.hasOwn(y,v)))throw new Y('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');oc(i);let w=await Bt(r,y),g=pn(c,"apu"),A=pn(c,"apv");nc(g,A);let E=await rc(w,i,h?n.alg:f,h?n.cekBits:parseInt(f.slice(-5,-2),10),g,A);if(h)return E;i=E;break}case"RSA-OAEP":return nn(i),ec(f,i,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",i,s));case"PBKDF2":{if(typeof c.p2c!="number")throw new Y('JOSE Header "p2c" (PBES2 Count) missing or invalid');kp(u);let y=u??1e4;if(c.p2c>y)throw new Y('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof c.p2s!="string")throw new Y('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let w=xe(c.p2s,"p2s",Y);i=await tc(w,f,c.p2c,i);break}case"AES-GCM":{if(typeof c.iv!="string")throw new Y('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof c.tag!="string")throw new Y('JOSE Header "tag" (Authentication Tag) missing or invalid');let y=xe(c.iv,"iv",Y),w=xe(c.tag,"tag",Y);if(y.byteLength!==12)throw new Y("Invalid Initialization Vector length");if(w.byteLength!==16)throw new Y("Invalid Authentication Tag length");return cn(tr(f.slice(0,-2)),i,s,y,w,new Uint8Array)}}return gp(f.slice(-6),i,s)}async function sc(r,n,i,s,c,u={}){let{alg:f,mode:m}=r,h=Xt(r);if(c!==void 0&&!h)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);let y=await Je(m==="direct-encryption"?n:r,i,"encrypt");if(m==="direct-encryption")return[y,void 0,void 0];let w=h?c??Gr(n):void 0;w&&sn(w,n.cekBits);let g,A;switch(r.subtle.name){case"ECDH":{oc(y);let{apu:E,apv:v}=u;E!==void 0&&Gt(E,'"apu"'),v!==void 0&&Gt(v,'"apv"');let _=E??pn(s,"apu"),P=v??pn(s,"apv");nc(_,P);let I;u.epk!==void 0?I=await Je(r,u.epk,"decrypt"):I=(await crypto.subtle.generateKey(y.algorithm,!0,["deriveBits"])).privateKey;let T=crypto.subtle,D=I;if(!D.extractable){if(typeof T.getPublicKey!="function")throw TypeError('CryptoKey for "epk" must be extractable');D=await T.getPublicKey(I,[])}let{x:k,y:R,crv:L,kty:M}=await T.exportKey("jwk",D),N=m==="direct-key-agreement",H=await rc(y,I,N?n.alg:f,N?n.cekBits:parseInt(f.slice(-5,-2),10),_,P),z={x:k,crv:L,kty:M};if(M==="EC"&&(z.y=R),A={epk:z},E!==void 0&&(A.apu=pe(E)),v!==void 0&&(A.apv=pe(v)),N)return[H,void 0,A];y=H;break}case"RSA-OAEP":{nn(y),ec(f,y,"encrypt"),g=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",y,w));break}case"PBKDF2":{let{p2c:E=2048,p2s:v=crypto.getRandomValues(new Uint8Array(16))}=u;y=await tc(v,f,E,y),A={p2c:E,p2s:pe(v)};break}case"AES-GCM":{let E=u.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):u.iv;if(!(E instanceof Uint8Array))throw TypeError('"iv" must be an instance of Uint8Array');let v=await an(tr(f.slice(0,-2)),w,y,E,new Uint8Array);g=v.ciphertext,A={iv:pe(v.iv),tag:pe(v.tag)}}}if(g??=await wp(f.slice(-6),y,w),!(g instanceof Uint8Array)||!g.byteLength)throw TypeError("JWE key management algorithm did not produce an Encrypted Key");return[w,g,A]}function mn(r,n){if(r.zip!==void 0&&r.zip!=="DEF")throw new ue('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(r.zip!==void 0&&!n?.zip)throw new Y('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function ac(r){if(typeof globalThis[r]>"u")throw new ue(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${r} API.`)}async function cc(r,n,i=1/0){let s=r.writable.getWriter();s.write(n).catch(()=>{}),s.close().catch(()=>{});let c=[],u=0,f=r.readable.getReader();for(;;){let{value:m,done:h}=await f.read();if(h)break;if(c.push(m),u+=m.byteLength,i!==1/0&&u>i)throw new Y("Decompressed plaintext exceeded the configured limit")}return Ie(...c)}async function uc(r){return ac("CompressionStream"),cc(new CompressionStream("deflate-raw"),r)}async function dc(r,n){return ac("DecompressionStream"),cc(new DecompressionStream("deflate-raw"),r,n)}function Sp(r){let{protected:n,ciphertext:i,iv:s,tag:c,aad:u}=r,f;return n!==void 0&&(f=gr(n,Y,"JWE Protected Header is invalid")),[f,xe(i,"ciphertext",Y),s!==void 0?xe(s,"iv",Y):void 0,c!==void 0?xe(c,"tag",Y):void 0,Fo((n??"")+(u!==void 0?`.${u}`:""),"aad",Y)]}function lc(r){return[r&&Jr("keyManagementAlgorithms",r.keyManagementAlgorithms),r&&Jr("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms),r?.crit,r?.maxPBES2Count,r?.maxDecompressedLength]}async function vp(r,n,i,s=Sp(r)){let[c,u,f,m,h]=s,{header:y,unprotected:w,aad:g}=r,A;if(y!==void 0||w!==void 0){if(!Nt(c,y,w))throw new Y("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");A={...c,...y,...w}}else A=c??{};let[E,v,_,P,I]=n,{encrypted_key:T}=r;zt(Y,Xo,_,c,A),mn(A,c);let{alg:D,enc:k}=A;if(typeof D!="string"||!D)throw new Y("missing JWE Algorithm (alg) in JWE Header");let R=Yt[D];if(T===""&&(!R||!Xt(R)))throw new Y("JWE Encrypted Key incorrect type");let L=R?.mode==="integrated-encryption";if(!L&&(typeof k!="string"||!k))throw new Y("missing JWE Encryption Algorithm (enc) in JWE Header");if(E&&!E.has(D)||!E&&D.startsWith("PBES2"))throw new wr('"alg" (Algorithm) Header Parameter value not allowed');let M;if(L){if(k!==void 0)throw new Y('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(f?.byteLength)throw new Y("JWE Initialization Vector must be empty for integrated encryption");if(m?.byteLength)throw new Y("JWE Authentication Tag must be empty for integrated encryption")}else{if(v&&!v.has(k))throw new wr('"enc" (Encryption Algorithm) Header Parameter value not allowed');M=tr(k)}let N;if(T!==void 0)try{N=xe(T,"encrypted_key",Y)}catch(W){if(!R||!Xt(R))throw W;N=new Uint8Array}let H=!1;typeof i=="function"&&(i=await i(c,r),H=!0);let z=R??yt(D);Xt(z)&&N===void 0&&(N=new Uint8Array);let B=await Je(z.mode==="direct-encryption"?M:z,i,"decrypt"),K;if(z.mode==="integrated-encryption")K=await z.decrypt(B,N,u,h,c,A);else{let W=M,V;try{V=await ic(z,W,B,N,A,P),Xt(z)&&V instanceof Uint8Array&&V.byteLength<<3!==W.cekBits&&(V=Gr(W))}catch(J){if(J instanceof TypeError||J instanceof Y||J instanceof ue)throw J;V=Gr(W)}K=await cn(W,V,u,f,m,h)}if(A.zip==="DEF"){let W=I??250000;if(W===0)throw new ue('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(W!==1/0&&(!Number.isSafeInteger(W)||W<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");K=await dc(K,W).catch((V)=>{throw V instanceof Y?V:new Y("Failed to decompress plaintext",{cause:V})})}return{plaintext:K,...c&&{protectedHeader:c},...g!==void 0&&{additionalAuthenticatedData:xe(g,"aad",Y)},...w&&{sharedUnprotectedHeader:w},...y&&{unprotectedHeader:y},...H&&{key:B}}}async function fc(r,n,i){if(r instanceof Uint8Array&&(r=mr.decode(r)),typeof r!="string")throw new Y("Compact JWE must be a string or Uint8Array");let{0:s,1:c,2:u,3:f,4:m,length:h}=r.split(".");if(h!==5)throw new Y("Invalid Compact JWE");return vp({ciphertext:f,iv:u||void 0,protected:s,tag:m||void 0,encrypted_key:c||void 0},n,i)}function pc(r,n,i){if(!Nt(r,n,i))throw new Y("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function Tp(r,n,i=!1){if(!r[1]&&!r[2]&&!r[3])throw new Y("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");n!==void 0&&(r[8]=n?.crit);let[,s,c,u,f,m,h,y,w]=r;if(f!==void 0&&Gt(f,"JWE Additional Authenticated Data"),m!==void 0&&Gt(m,"JWE Content Encryption Key"),h!==void 0&&Gt(h,"JWE Initialization Vector"),!i&&s!==void 0&&(s=Zt(Y,s)[0],r[1]=s),c!==void 0&&(c=Zt(Y,c)[0],r[2]=c),!i&&u!==void 0&&(u=Zt(Y,u)[0],r[3]=u),y!==void 0&&!he(y))throw TypeError("JWE Key Management Parameters must be an object");pc(s,c,u);let g={...s,...c,...u};en(Y,s),zt(Y,Xo,w,s,g),mn(g,s);let{alg:A,enc:E}=g;if(typeof A!="string"||!A)throw new Y('JWE "alg" (Algorithm) Header Parameter missing or invalid');let v=Yt[A];if(v?.mode==="integrated-encryption"){if(E!==void 0)throw new Y('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(m!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${A}`);if(h!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${A}`);return[g,void 0,v]}if(typeof E!="string"||!E)throw new Y('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[g,tr(E),v]}async function Rp(r,n,i){let[s,c,u]=n,[f,m,h,y,w,g,A,E,,v]=r,_=m,P=h,I=u??yt(s.alg),T,D,k;I.mode==="integrated-encryption"?k=await Je(I,i,"encrypt"):[k,T,D]=await sc(I,c,i,s,g,E),D&&(v?P=P?{...P,...D}:D:_=_?{..._,...D}:D,pc(_,P,y));let R=_?pe(JSON.stringify(_)):"",L=w?.byteLength?pe(w):void 0,M=Ee(L?`${R}.${L}`:R),N=f;s.zip==="DEF"&&(N=await uc(N).catch((W)=>{throw new Y("Failed to compress plaintext",{cause:W})}));let H,z,B;I.mode==="integrated-encryption"?[T,H]=await I.encrypt(k,N,M,_,s,E):{ciphertext:H,tag:z,iv:B}=await an(c,N,k,A,M);let K={ciphertext:pe(H)};return B&&(K.iv=pe(B)),z&&(K.tag=pe(z)),T?.byteLength&&(K.encrypted_key=pe(T)),L&&(K.aad=L),_&&(K.protected=R),y&&(K.unprotected=y),P&&(K.header=P),K}async function mc(r,n,i){return Rp(r,Tp(r,i),n)}function hc(r){return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}var Zr=[["verify"],["sign"]];function Wi(r){let n={name:"HMAC",hash:`SHA-${r}`};return{kty:["oct"],secret:!0,subtle:n,signing:n,usages:Zr}}function Tr(r,n){let i={name:n?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${r}`};return{kty:["RSA"],subtle:i,signing:n?{...i,saltLength:n}:i,usages:Zr,minRsaBits:2048}}function Vi(r,n){return{kty:["EC"],crv:r,subtle:{name:"ECDSA",namedCurve:r},signing:{name:"ECDSA",hash:`SHA-${n}`},usages:Zr}}function yc(){let r={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:r,signing:r,usages:Zr}}function qi(r){let n={name:`ML-DSA-${r}`};return{kty:["AKP"],subtle:n,signing:n,usages:Zr}}var Yr=Qr({HS256:Wi(256),HS384:Wi(384),HS512:Wi(512),RS256:Tr(256),RS384:Tr(384),RS512:Tr(512),PS256:Tr(256,32),PS384:Tr(384,48),PS512:Tr(512,64),ES256:Vi("P-256",256),ES384:Vi("P-384",384),ES512:Vi("P-521",512),EdDSA:yc(),Ed25519:yc(),"ML-DSA-44":qi(44),"ML-DSA-65":qi(65),"ML-DSA-87":qi(87)});function hn(r){let n=typeof r=="string"?Yr[r]:void 0;if(!n)throw new ue(`alg ${r} is not supported either by JOSE or your javascript runtime`);return n}function wc(r){return[r&&Jr("algorithms",r.algorithms),r?.crit]}function Ip(r){return r===void 0?{}:gr(r,fe,"JWS Protected Header is invalid")}function _p(r){try{return Ee(r)}catch{throw new fe("JWS Compact Serialization payload must use only ASCII characters")}}async function Up(r,n,i,s,c){let{protected:u,header:f,payload:m}=r,h=c??Ip(u);if(!Nt(h,f))throw new fe("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let y={...h,...f},w=rn(h,zt(fe,Zo,n[1],h,y)),{alg:g}=y;if(typeof g!="string"||!g)throw new fe('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(n[0]&&!n[0].has(g))throw new wr('"alg" (Algorithm) Header Parameter value not allowed');if(w){if(typeof m!="string")throw new fe("JWS Payload must be a string")}else if(typeof m!="string"&&!(m instanceof Uint8Array))throw new fe("JWS Payload must be a string or an Uint8Array instance");let A=w||typeof m!="string"?m:s(m),E=!1;typeof i=="function"&&(i=await i(h,r),E=!0);let v=hn(g),_=Ie(u!==void 0?Ee(u):new Uint8Array,Ee("."),typeof A=="string"?n[2]??=Fo(A,"payload",fe):A),P=xe(r.signature,"signature",fe),I=await Je(v,i,"verify"),T=await Ge(I,v.subtle,"verify");v.minRsaBits&&Ar(v.alg,T);let D=!1;try{D=await crypto.subtle.verify(v.signing,T,P,_)}catch{}if(!D)throw new _i;let k={payload:typeof A=="string"?xe(A,"payload",fe):A};return u!==void 0&&(k.protectedHeader=h),f!==void 0&&(k.unprotectedHeader=f),E?[{...k,key:I},w]:[k,w]}async function gc(r,n,i){if(r instanceof Uint8Array&&(r=mr.decode(r)),typeof r!="string")throw new fe("Compact JWS must be a string or Uint8Array");let{0:s,1:c,2:u,length:f}=r.split(".");if(f!==3)throw new fe("Invalid Compact JWS");return Up({payload:c,protected:s,signature:u},n,i,_p)}var Xr=(r)=>Math.floor(r.getTime()/1000),Cp={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},xp=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Rr="check_failed";function Ji(){throw TypeError("Invalid time period format")}function yn(r){typeof r!="string"&&Ji();let n=xp.exec(r);(!n||n[4]&&n[1])&&Ji();let i=parseFloat(n[2]),s=Math.round(i*Cp[n[3][0].toLowerCase()]);return Number.isFinite(s)||Ji(),n[1]==="-"||n[4]==="ago"?-s:s}function Ir(r,n){if(!Number.isFinite(n))throw TypeError(`Invalid ${r} input`);return n}function Gi(r,n){if(typeof n!="string")throw TypeError(`"${r}" claim must be a string`)}function Op(r){if(typeof r!="string"&&(!Array.isArray(r)||Array.from(r).some((n)=>typeof n!="string")))throw TypeError('"aud" claim must be a string or an array of strings')}function Qi(r,n){return typeof r=="number"?Ir(n,r):r instanceof Date?Ir(n,Xr(r)):Xr(new Date)+yn(r)}var Ac=(r)=>{let n=r.toLowerCase();return r.includes("/")?n:`application/${n}`},Lp=(r,n)=>typeof r=="string"?n.includes(r):Array.isArray(r)?n.some((i)=>r.includes(i)):!1;function Zi(r,n,i=!1){let s=r[n];if(!(s===void 0&&!i)){if(typeof s!="number")throw new rt(`"${n}" claim must be a number`,r,n,"invalid");return s}}function Yi(r,n){throw new rt(`unexpected "${n}" claim value`,r,n,Rr)}function wn(r,n,i={}){let s;try{s=JSON.parse(hr.decode(n))}catch{}if(!he(s))throw new _e("JWT Claims Set must be a top-level JSON object");let{typ:c}=i;if(c!==void 0&&(typeof r.typ!="string"||Ac(r.typ)!==Ac(c)))throw new rt('unexpected "typ" JWT header value',s,"typ",Rr);let{requiredClaims:u=[],issuer:f,subject:m,audience:h,maxTokenAge:y}=i,w=[...u];y!==void 0&&w.push("iat"),h!==void 0&&w.push("aud"),m!==void 0&&w.push("sub"),f!==void 0&&w.push("iss");for(let T of new Set(w.reverse()))if(!Object.hasOwn(s,T))throw new rt(`missing required "${T}" claim`,s,T,"missing");f!==void 0&&!(Array.isArray(f)?f:[f]).includes(s.iss)&&Yi(s,"iss"),m!==void 0&&s.sub!==m&&Yi(s,"sub"),h!==void 0&&!Lp(s.aud,typeof h=="string"?[h]:h)&&Yi(s,"aud");let{clockTolerance:g}=i,A=0;if(typeof g=="string")A=yn(g);else if(g!==void 0){if(typeof g!="number")throw TypeError("Invalid clockTolerance option type");A=g}Ir("clockTolerance option",A);let{currentDate:E}=i,v=Ir("currentDate option",Xr(E===void 0?new Date:E)),_=Zi(s,"iat",y!==void 0),P=Zi(s,"nbf");if(P!==void 0&&P>v+A)throw new rt('"nbf" claim timestamp check failed',s,"nbf",Rr);let I=Zi(s,"exp");if(I!==void 0&&I<=v-A)throw new yr('"exp" claim timestamp check failed',s,"exp",Rr);if(y!==void 0){let T=v-_,D=Ir("maxTokenAge option",typeof y=="number"?y:yn(y));if(T-A>D)throw new yr('"iat" claim timestamp check failed (too far in the past)',s,"iat",Rr);if(T<-A)throw new rt('"iat" claim timestamp check failed (it should be in the past)',s,"iat",Rr)}return s}var bc;function wt(r){return bc.get(r)}function gn(r){let n=wt(r);for(let i of["iat","nbf","exp"]){let s=n[i];if(typeof s=="number"&&!Number.isFinite(s))throw TypeError(`"${i}" claim must be a finite number`)}return Ot.encode(JSON.stringify(n))}function An(r,n){return wt(r)[n]}class eo{constructor(r={}){if(!he(r))throw TypeError("JWT Claims Set MUST be an object");(bc||=new WeakMap).set(this,structuredClone(r))}setIssuer(r){return Gi("iss",r),wt(this).iss=r,this}setSubject(r){return Gi("sub",r),wt(this).sub=r,this}setAudience(r){return Op(r),wt(this).aud=r,this}setJti(r){return Gi("jti",r),wt(this).jti=r,this}setNotBefore(r){return wt(this).nbf=Qi(r,"setNotBefore"),this}setExpirationTime(r){return wt(this).exp=Qi(r,"setExpirationTime"),this}setIssuedAt(r){let n=wt(this);return r===void 0?n.iat=Xr(new Date):typeof r=="string"?n.iat=Ir("setIssuedAt",Xr(new Date)+yn(r)):n.iat=Qi(r,"setIssuedAt"),this}}async function Mt(r,n,i){let[s,c]=await gc(r,wc(i),n);if(!c)throw new _e("JWTs MUST NOT use unencoded payload");let u=wn(s.protectedHeader,s.payload,i);return{...s,payload:u}}async function bn(r,n,i){let{plaintext:s,...c}=await fc(r,lc(i),n),{protectedHeader:u}=c,f=wn(u,s,i);for(let m of["iss","sub","aud"])if(u[m]!==void 0&&(m==="aud"?JSON.stringify(u.aud)!==JSON.stringify(f.aud):u[m]!==f[m]))throw new rt(`replicated "${m}" claim header parameter mismatch`,f,m,"mismatch");return{payload:f,...c}}async function Dp(r,n,i){let[s,c,u,f]=r,m="";if(c!==void 0){let I=Zt(fe,c);c=I[0],m=pe(I[1])}if(u!==void 0&&(u=Zt(fe,u)[0]),!c&&!u)throw new fe("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Nt(c,u))throw new fe("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let h={...c,...u};en(fe,c);let y=rn(c,zt(fe,Zo,f,c,h));y||i?.();let{alg:w}=h;if(typeof w!="string"||!w)throw new fe('JWS "alg" (Algorithm) Header Parameter missing or invalid');let g=hn(w),A="",E=s,v;if(y){let I=r[4];I?(A=I[0]??=pe(s),E=I[1]??=Ee(A)):(A=pe(s),v=Ot.encode(`${m}.${A}`))}v??=Ie(Ee(m),Ee("."),E);let _=await Ge(await Je(g,n,"sign"),g.subtle,"sign");g.minRsaBits&&Ar(g.alg,_);let P={signature:pe(new Uint8Array(await crypto.subtle.sign(g.signing,_,v))),payload:A};return c&&(P.protected=m),u&&(P.header=u),[P,y]}async function Ec(r,n,i,s,c){let[u]=await Dp([r,n,void 0,i],s,c);return`${u.protected}.${u.payload}.${u.signature}`}var Pp=eo;class kn extends Pp{#e;setProtectedHeader(r){return Qt(this.#e,"setProtectedHeader"),this.#e=r,this}async sign(r,n){return Ec(gn(this),this.#e,n?.crit,r,()=>{throw new _e("JWTs MUST NOT use unencoded payload")})}}var Np=eo;class Sn extends Np{#e=[void 0];#t;#r;#o;setProtectedHeader(r){return Qt(this.#e[1],"setProtectedHeader"),this.#e[1]=r,this}setKeyManagementParameters(r){return Qt(this.#e[7],"setKeyManagementParameters"),this.#e[7]=r,this}setContentEncryptionKey(r){return Qt(this.#e[5],"setContentEncryptionKey"),this.#e[5]=r,this}setInitializationVector(r){return Qt(this.#e[6],"setInitializationVector"),this.#e[6]=r,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#r=!0,this}replicateAudienceAsHeader(){return this.#o=!0,this}async encrypt(r,n){let i=gn(this);this.#e[1]&&(this.#t||this.#r||this.#o)&&(this.#e[1]={...this.#e[1],iss:this.#t?An(this,"iss"):void 0,sub:this.#r?An(this,"sub"):void 0,aud:this.#o?An(this,"aud"):void 0});let s=[...this.#e];return s[0]=i,hc(await mc(s,r,n))}}function zp(r='JWK "alg" (Algorithm) Parameter'){throw new ue(`Invalid or unsupported ${r} value`)}function Xi(r,n){return(typeof r=="string"?Yr[r]??Yt[r]:void 0)??zp(n)}async function kc(r){if(xi(r))if(r.type==="secret")r=r.export();else return r.export({format:"jwk"});if(r instanceof Uint8Array)return{kty:"oct",k:pe(r)};if(!$t(r))throw TypeError(ht(r,"CryptoKey","KeyObject","Uint8Array"));if(!r.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let n=await crypto.subtle.exportKey("jwk",r);delete n.ext,delete n.key_ops,delete n.use,n.kty!=="AKP"&&delete n.alg;for(let i of Object.keys(n))n[i]===void 0&&delete n[i];return n}var gt=(r,n)=>{if(typeof r!="string"||!r)throw new Bo(`${n} missing or invalid`)};async function vn(r,n){let i;if(he(r)){if(i=kr(r),typeof i.kty!="string")throw TypeError(ht(r,"CryptoKey","KeyObject","JSON Web Key"))}else if(Li(r))i=kr(await kc(r));else throw TypeError(ht(r,"CryptoKey","KeyObject","JSON Web Key"));if(n??="sha256",n!=="sha256"&&n!=="sha384"&&n!=="sha512")throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let s;switch(i.kty){case"AKP":gt(i.alg,'"alg" (Algorithm) Parameter'),gt(i.pub,'"pub" (Public key) Parameter'),s={alg:i.alg,kty:i.kty,pub:i.pub};break;case"EC":gt(i.crv,'"crv" (Curve) Parameter'),gt(i.x,'"x" (X Coordinate) Parameter'),gt(i.y,'"y" (Y Coordinate) Parameter'),s={crv:i.crv,kty:i.kty,x:i.x,y:i.y};break;case"OKP":gt(i.crv,'"crv" (Subtype of Key Pair) Parameter'),gt(i.x,'"x" (Public Key) Parameter'),s={crv:i.crv,kty:i.kty,x:i.x};break;case"RSA":gt(i.e,'"e" (Exponent) Parameter'),gt(i.n,'"n" (Modulus) Parameter'),s={e:i.e,kty:i.kty,n:i.n};break;case"oct":if(typeof i.k!="string")throw new Bo('"k" (Key Value) Parameter missing or invalid');s={k:i.k,kty:i.kty};break;default:throw new ue('"kty" (Key Type) Parameter missing or unsupported')}let c=Ee(JSON.stringify(s));return pe(await jo(n,c))}function $p(r,n,i,s){let{kty:c,key_ops:u,ext:f,kid:m,alg:h,use:y,crv:w}=r;return(f===void 0||typeof f=="boolean")&&(u===void 0||Array.isArray(u)&&u.every((g,A)=>typeof g=="string"&&u.indexOf(g)===A)&&u.includes("verify"))&&n.kty.includes(c)&&(s===void 0||typeof s=="string"&&s===m)&&(h===void 0?c!=="AKP":i===h)&&(y===void 0||y==="sig")&&(!n.crv||w===n.crv)}async function Sc(r,n,i){let s=r.get(n)||r.set(n,{}).get(n),{alg:c}=i;if(s[c]===void 0){let u=Bt(i,n,!0).then((f)=>{if(f.type!=="public")throw new Mo("JSON Web Key Set members must be public keys");return s[c]=f,f}).catch((f)=>{throw s[c]===u&&delete s[c],f});s[c]=u}return s[c]}function es(r){let n;try{n=structuredClone(r)}catch{}if(!qo(n))throw new Mo("JSON Web Key Set malformed");let i=n.keys.map((c)=>{let u=kr(c);return Array.isArray(u.key_ops)&&(u.key_ops=[...u.key_ops]),u}),s=new WeakMap;return Object.defineProperty(async(c,u)=>{let{alg:f,kid:m}={...c,...u?.header},h=typeof f=="string"?Yr[f]:void 0;if(!h||h.secret)throw new ue('Unsupported "alg" value for a JSON Web Key Set');let y=n.keys.filter((A,E)=>$p(i[E],h,f,m)),{0:w,length:g}=y;if(!g)throw new qr;if(g!==1){let A=new Ri;throw A[Symbol.asyncIterator]=async function*(){for(let E of y)try{yield await Sc(s,E,h)}catch{}},A}return Sc(s,w,h)},"jwks",{value:()=>structuredClone(n)})}function jp(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ts;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ts="jose/v6.2.12");var Tc=Symbol();async function Hp(r,n,i,s=fetch){let c=await s(r,{method:"GET",signal:i,redirect:"manual",headers:n}).catch((u)=>{throw u.name==="TimeoutError"?new Ii:u});if(c.status!==200)throw new be("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await c.json()}catch{throw new be("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var Rc=Symbol();function to(r,n){return Number.isFinite(r)&&Date.now()<r+n}function vc(r,n,i){if(Number.isNaN(r))throw TypeError(`"${i}" option must not be NaN`);return typeof r=="number"?r:n}function rs(r,n){if(!(r instanceof URL))throw TypeError("url must be an instance of URL");let i=new URL(r.href).href,s=n??{},c=s.timeoutDuration;if(typeof c=="number"&&(!Number.isInteger(c)||c<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let u=typeof c=="number"?c:5000,f=vc(s.cooldownDuration,30000,"cooldownDuration"),m=vc(s.cacheMaxAge,600000,"cacheMaxAge"),h=new Headers(s.headers);ts&&!h.has("User-Agent")&&h.set("User-Agent",ts),h.has("accept")||h.set("accept","application/json, application/jwk-set+json");let y=s[Tc],w=s[Rc],g,A,E=0,v=0,_;if(w&&typeof w=="object"){let{uat:I,jwks:T}=w;to(I,m)&&qo(T)&&(g=I,_=es(T))}let P=async()=>{if(A&&jp()&&(A=void 0),!A){let I=++E,T=A=Hp(i,h,AbortSignal.timeout(u),y).then((D)=>{let k=es(D);if(I<=v)return;_=k;let R=Date.now();w&&(w.uat=R,w.jwks=D),g=R,v=I}).finally(()=>{A===T&&(A=void 0)})}await A};return Object.defineProperties(async(I,T)=>{(!_||!to(g,m))&&await P();try{return await _(I,T)}catch(D){if(D instanceof qr&&!to(g,f))return await P(),_(I,T);throw D}},{coolingDown:{get:()=>to(g,f),enumerable:!0},fresh:{get:()=>to(g,m),enumerable:!0},reload:{value:P,enumerable:!0},reloading:{get:()=>!!A,enumerable:!0},jwks:{value:()=>_?.jwks(),enumerable:!0}})}async function At(r,n,i){if(!he(r))throw TypeError("JWK must be an object");let s=Hi(r),c=qa(i?.extractable),{alg:u}=s;if(n??=u,s.kty!=="oct"&&!n)throw TypeError('"alg" argument is required when "jwk.alg" is not present');switch(s.kty){case"oct":if(typeof s.k!="string")throw TypeError('missing "k" (Key Value) Parameter value');return mt(s.k);case"AKP":{if(typeof u!="string"||!u)throw TypeError('missing "alg" (Algorithm) Parameter value');if(n!==u)throw TypeError("JWK alg and alg option value mismatch");return Bt(Xi(n),s,c)}case"RSA":case"EC":case"OKP":return Bt(Xi(n),s,c);default:throw new ue('Unsupported "kty" (Key Type) Parameter value')}}function Ur(r){let n;if(typeof r=="string"){let s=r.split(".");(s.length===3||s.length===5)&&([n]=s)}else if(typeof r=="object"&&r)if("protected"in r)n=r.protected;else throw TypeError("Token does not contain a Protected Header");let i="Invalid Token or Protected Header formatting";if(typeof n!="string"||!n)throw TypeError(i);return gr(n,TypeError,i)}function ge(r){if(typeof r!="string")throw new _e("JWTs must use Compact JWS serialization, JWT must be a string");let{1:n,length:i}=r.split(".");if(i===5)throw new _e("Only JWTs using Compact JWS serialization can be decoded");if(i!==3)throw new _e("Invalid JWT");if(!n)throw new _e("JWTs must contain a payload");let s;try{s=mt(n)}catch{throw new _e("Failed to base64url decode the payload")}let c;try{c=JSON.parse(hr.decode(s))}catch{throw new _e("Failed to parse the decoded payload as JSON")}if(!he(c))throw new _e("Invalid JWT Claims Set");return c}async function Tn(r,n,i=3600){return await new kn(r).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+i).sign(new TextEncoder().encode(n))}async function Uc(r,n){try{return(await Mt(r,new TextEncoder().encode(n))).payload}catch{return null}}var Bp=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]),Mp=()=>Date.now()/1000|0,Cc="dir",xc="A256CBC-HS512";function ro(r,n){return Po(No,new TextEncoder().encode(r),new TextEncoder().encode(n),Bp,64)}function Kp(r){if(typeof r==="string")return r;let n=r.keys.get(r.currentVersion);if(!n)throw Error(`Secret version ${r.currentVersion} not found in keys`);return n}function Ic(r){if(typeof r==="string")return[{version:0,value:r}];let n=[];for(let[i,s]of r.keys)n.push({version:i,value:s});if(r.legacySecret&&!n.some((i)=>i.value===r.legacySecret))n.push({version:-1,value:r.legacySecret});return n}async function Rn(r,n,i,s=3600){let c=ro(Kp(n),i),u=await vn({kty:"oct",k:pe(c)},"sha256");return await new Sn(r).setProtectedHeader({alg:Cc,enc:xc,kid:u}).setIssuedAt().setExpirationTime(Mp()+s).setJti(crypto.randomUUID()).encrypt(c)}var _c={clockTolerance:15,keyManagementAlgorithms:[Cc],contentEncryptionAlgorithms:[xc,"A256GCM"]};async function In(r,n,i){if(!r)return null;let s=!1;try{s=Ur(r).kid!==void 0}catch{return null}try{let c=Ic(n),{payload:u}=await bn(r,async(f)=>{let m=f.kid;if(m!==void 0){for(let h of c){let y=ro(h.value,i);if(m===await vn({kty:"oct",k:pe(y)},"sha256"))return y}throw Error("no matching decryption secret")}if(c.length===1)return ro(c[0].value,i);return ro(c[0].value,i)},_c);return u}catch{if(s)return null;let c=Ic(n);if(c.length<=1)return null;for(let u=1;u<c.length;u++)try{let f=c[u],{payload:m}=await bn(r,ro(f.value,i),_c);return m}catch{continue}return null}}function Cr(r,n){if(!r||!n)return r;let i=Object.entries(n).filter(([,{returned:s}])=>s===!1).map(([s])=>s);return Object.entries(structuredClone(r)).filter(([s])=>!i.includes(s)).reduce((s,[c,u])=>({...s,[c]:u}),{})}var os=new WeakMap;function ot(r,n,i){let s=`${n}:${i}`;if(!os.has(r))os.set(r,new Map);let c=os.get(r);if(c.has(s))return c.get(s);let u=i==="output"?It(r)[n]?.fields??{}:{},f=n==="user"||n==="session"||n==="account"?r[n]?.additionalFields:void 0,m={...u,...f??{}};for(let h of r.plugins||[])if(h.schema&&h.schema[n])m={...m,...h.schema[n].fields};return c.set(s,m),m}function ke(r,n){return Cr(n,ot(r,"user","output"))}function zo(r,n){let i=ot(r,"user","output"),s={};for(let c in i){let u=i[c];if(u.returned===!1)continue;if(c in n&&n[c]!==void 0)s[c]=n[c];else if(u.defaultValue!==void 0)s[c]=typeof u.defaultValue==="function"?u.defaultValue():u.defaultValue;else if(!u.required)s[c]=null}if("id"in n)s.id=n.id;return s}function at(r,n){return Cr(n,ot(r,"session","output"))}function Wc(r,n){let{accessToken:i,refreshToken:s,idToken:c,accessTokenExpiresAt:u,refreshTokenExpiresAt:f,password:m,...h}=Cr(n,ot(r,"account","output"));return h}function js(r,n){let i=n.action||"create",s=n.fields,c=Object.create(null);for(let u in s){if(u in r){if(s[u].input===!1){if(s[u].defaultValue!==void 0){if(i!=="update"){c[u]=s[u].defaultValue;continue}}if(r[u])throw l.from("BAD_REQUEST",{...x.FIELD_NOT_ALLOWED,message:`${u} is not allowed to be set`});continue}if(s[u].validator?.input&&r[u]!==void 0){let f=s[u].validator.input["~standard"].validate(r[u]);if(f instanceof Promise)throw l.from("INTERNAL_SERVER_ERROR",x.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in f&&f.issues)throw l.from("BAD_REQUEST",{...x.VALIDATION_ERROR,message:f.issues[0]?.message||"Validation Error"});c[u]=f.value;continue}if(s[u].transform?.input&&r[u]!==void 0){c[u]=s[u].transform?.input(r[u]);continue}c[u]=r[u];continue}if(s[u].defaultValue!==void 0&&i==="create"){if(typeof s[u].defaultValue==="function"){c[u]=s[u].defaultValue();continue}c[u]=s[u].defaultValue;continue}if(s[u].required&&i==="create")throw l.from("BAD_REQUEST",{...x.MISSING_FIELD,message:`${u} is required`})}return c}function Mi(r,n={},i){return js(n,{fields:ot(r,"user","input"),action:i})}function $i(r,n={},i){let s=ot(r,"user","input"),c=Object.create(null);for(let u of Object.keys(n)){if(s[u]?.input===!1)continue;c[u]=n[u]}return js(c,{fields:s,action:i})}function Lf(r,n){let i=ot(r,"user","input");return js(n||{},{fields:i})}function Uf(r,n){return js(n,{fields:ot(r,"account","input")})}function Yc(r,n,i){return js(n,{fields:ot(r,"session","input"),action:i})}function Jc(r){let n=ot(r,"session","input"),i={};for(let s in n)if(n[s].defaultValue!==void 0)i[s]=typeof n[s].defaultValue==="function"?n[s].defaultValue():n[s].defaultValue;return i}function ji(r,n){if(!n)return r;for(let i in n){let s=n[i]?.modelName;if(s)r[i].modelName=s;for(let c in r[i].fields){let u=n[i]?.fields?.[c];if(!u)continue;r[i].fields[c].fieldName=u}}return r}var bt=(r,n="ms")=>new Date(Date.now()+(n==="sec"?r*1000:r));var Wp=/^(\+|\-)? ?(\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 Vp(r){let n=Wp.exec(r);if(!n||n[4]&&n[1])throw TypeError(`Invalid time string format: "${r}". Use formats like "7d", "30m", "1 hour", etc.`);let i=parseFloat(n[2]),s=n[3].toLowerCase(),c;switch(s){case"years":case"year":case"yrs":case"yr":case"y":c=i*31557600000;break;case"months":case"month":case"mo":c=i*2592000000;break;case"weeks":case"week":case"w":c=i*604800000;break;case"days":case"day":case"d":c=i*86400000;break;case"hours":case"hour":case"hrs":case"hr":case"h":c=i*3600000;break;case"minutes":case"minute":case"mins":case"min":case"m":c=i*60000;break;case"seconds":case"second":case"secs":case"sec":case"s":c=i*1000;break;default:throw TypeError(`Unknown time unit: "${s}"`)}if(n[1]==="-"||n[4]==="ago")return-c;return c}function Oc(r){return Math.round(Vp(r)/1000)}var qp=Fn({session:Oo.loose(),user:Lo.loose(),updatedAt:b(),version:e().optional()}),Fp=t({session:j(e(),ne()),expiresAt:b(),signature:e()});function _n(r){let n=de(r);if(n===null)return null;let i=qp.safeParse(n);if(i.success)return i.data;return O.warn("Cookie cache payload failed schema validation",{issues:i.error.issues.map(({code:s,path:c})=>({code:s,path:c}))}),null}function Lc(r){let n=Fp.safeParse(r);return n.success?n.data:null}function Pc(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}var Nc="__Secure-";function Cn(r){if(!r)return[];let n=[],i=0,s=0;while(s<r.length){if(r[s]===","){let u=s+1;while(u<r.length&&r[u]===" ")u++;while(u<r.length&&r[u]!=="="&&r[u]!==";"&&r[u]!==",")u++;if(u<r.length&&r[u]==="="){let f=r.slice(i,s).trim();if(f)n.push(f);i=s+1;while(i<r.length&&r[i]===" ")i++;s=i;continue}}s++}let c=r.slice(i).trim();if(c)n.push(c);return n}function Xd(r){let n=new Map;return Cn(r).forEach((i)=>{let[s,...c]=i.split(";").map((y)=>y.trim()),[u,...f]=(s||"").split("="),m=zc(f.join("="));if(!u)return;let h={value:Pc(m)};c.forEach((y)=>{let[w,...g]=y.split("="),A=g.join("="),E=w.trim().toLowerCase();switch(E){case"max-age":h["max-age"]=A?parseInt(A.trim(),10):void 0;break;case"expires":h.expires=A?new Date(A.trim()):void 0;break;case"domain":h.domain=A?A.trim():void 0;break;case"path":h.path=A?A.trim():void 0;break;case"secure":h.secure=!0;break;case"httponly":h.httponly=!0;break;case"samesite":h.samesite=A?A.trim().toLowerCase():void 0;break;case"partitioned":h.partitioned=!0;break;default:h[E]=A?A.trim():!0;break}}),n.set(u,h)}),n}var ns=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Jp=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function zc(r){if(r.length<2||!r.startsWith('"')||!r.endsWith('"'))return r;return r.slice(1,-1)}function Dc(r){let n=0,i=r.length;while(n<i){let s=r.charCodeAt(n);if(s!==32&&s!==9)break;n++}while(i>n){let s=r.charCodeAt(i-1);if(s!==32&&s!==9)break;i--}return n===0&&i===r.length?r:r.slice(n,i)}function oo(r){let n=new Map;if(r.length<2)return n;for(let i of r.split(";")){let s=i.indexOf("=");if(s===-1)continue;let c=Dc(i.slice(0,s)),u=zc(Dc(i.slice(s+1)));if(ns.test(c)&&Jp.test(u))n.set(c,Pc(u))}return n}function eu(r,n,i){let s=oo(r.get("cookie")||"");if(ns.test(n))s.set(n,i);r.set("cookie",Array.from(s,([c,u])=>`${c}=${encodeURIComponent(u)}`).join("; "))}var jc=4050,$c=100;function Gp(r,n){return jc-jr(r,"",{...n}).length}function Hc(r,n){let i=`${r}.`;if(!n.startsWith(i))return null;let s=n.slice(i.length),c=Number(s);if(!Number.isSafeInteger(c)||c<0||String(c)!==s)return null;return c}function Qp(r,n){let i={},s=oo(n.headers?.get("cookie")||"");for(let[c,u]of s){if(c!==r&&Hc(r,c)===null)continue;i[c]=u}return i}function Zp(r,n,i,s){let c=Gp(`${n.name}.${$c-1}`,n.attributes),u=c>0?Math.ceil(n.value.length/c):1/0;if(u<=1)return i[n.name]=n.value,[n];if(u>$c)return s.warn(`${r} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let f=[];for(let m=0;m<u;m++){let h=`${n.name}.${m}`,y=m*c,w=n.value.substring(y,y+c);f.push({...n,name:h,value:w}),i[h]=w}return s.debug(`CHUNKING_${r.toUpperCase()}_COOKIE`,{message:`${r} cookie exceeds the ${jc} byte limit and was split into ${u} chunks.`,valueSize:n.value.length,chunkCount:u,chunkSizes:f.map((m)=>m.value.length)}),f}function Yp(r,n){let i={};for(let s in r)i[s]={name:s,value:"",attributes:{...n,maxAge:0}};return i}var Bc=(r)=>(n,i,s)=>{let c=Qp(n,s),u=s.context.logger,f=()=>{let m=Yp(c,i);for(let h in c)delete c[h];return m};return{chunk(m,h){let y=f(),w=Zp(r,{name:n,value:m,attributes:{...i,...h}},c,u);for(let g of w)y[g.name]=g;return Object.values(y)},clean(){return Object.values(f())},setCookies(m){for(let h of m)s.setCookie(h.name,h.value,h.attributes)}}},no=Bc("Session"),xn=Bc("Account");function On(r,n){let i=r.getCookie(n);if(i)return i;let s=[],c=r.headers?.get("cookie");if(!c)return null;for(let[u,f]of oo(c)){let m=Hc(n,u);if(m===null)continue;s.push({index:m,value:f})}if(s.length>0)return s.sort((u,f)=>u.index-f.index),s.map((u)=>u.value).join("");return null}async function Et(r,n){let i=r.context.authCookies.accountData,s={maxAge:300,...i.attributes},c=await Rn(n,r.context.secretConfig,"better-auth-account",s.maxAge),u=xn(i.name,s,r);u.setCookies(u.chunk(c,s))}async function Pn(r){let n=On(r,r.context.authCookies.accountData.name);if(n){let i=de(await In(n,r.context.secretConfig,"better-auth-account"));if(i)return i}return null}var Mc=ho(t({disableCookieCache:bp().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:bp().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));var is=new Map,Xp=new TextEncoder,Vc={decode:(r,n="utf-8")=>{if(!is.has(n))is.set(n,new TextDecoder(n));return is.get(n).decode(r)},encode:(r)=>Xp.encode(r)};var Go=(r="SHA-256",n="none")=>{let i={importKey:async(s,c)=>qe().importKey("raw",ci(s),{name:"HMAC",hash:{name:r}},!1,[c]),sign:async(s,c)=>{if(typeof s==="string")s=await i.importKey(s,"sign");let u=await qe().sign("HMAC",s,ci(c));if(n==="hex")return Ga.encode(u);if(n==="base64")return Dt.encode(u);if(n==="base64url"||n==="base64urlnopad")return xt.encode(u,{padding:n!=="base64urlnopad"});return u},verify:async(s,c,u)=>{if(typeof s==="string")s=await i.importKey(s,"verify");if(n==="hex")u=typeof u==="string"?Ga.toBytes(u):u;if(n==="base64"||n==="base64url"||n==="base64urlnopad")u=await Dt.decode(u);return qe().verify("HMAC",s,ci(u),ci(c))}};return i};function Ko(r){let n=typeof r.baseURL==="string"?r.baseURL:void 0,i=typeof r.baseURL==="object"&&r.baseURL!==null?r.baseURL.protocol:void 0,s=(r.advanced?.useSecureCookies!==void 0?r.advanced?.useSecureCookies:i==="https"?!0:i==="http"?!1:n?n.startsWith("https://"):Ln)?Nc:"",c=!!r.advanced?.crossSubDomainCookies?.enabled,u=c?r.advanced?.crossSubDomainCookies?.domain||(n?new URL(n).hostname:void 0):void 0;if(c&&!u&&!er(r.baseURL))throw new S("baseURL is required when crossSubdomainCookies are enabled.");function f(m,h={}){let y=r.advanced?.cookiePrefix||"better-auth",w=r.advanced?.cookies?.[m]?.name||`${y}.${m}`,g=r.advanced?.cookies?.[m]?.attributes??{};return{name:`${s}${w}`,attributes:{secure:!!s,sameSite:"lax",path:"/",httpOnly:!0,...c?{domain:u}:{},...r.advanced?.defaultCookieAttributes,...h,...g}}}return f}function Qc(r){let n=Ko(r),i=n("session_token",{maxAge:r.session?.expiresIn||Oc("7d")}),s=n("session_data",{maxAge:r.session?.cookieCache?.maxAge||300}),c=n("account_data",{maxAge:r.session?.cookieCache?.maxAge||300}),u=n("dont_remember");return{sessionToken:{name:i.name,attributes:i.attributes},sessionData:{name:s.name,attributes:s.attributes},dontRememberToken:{name:u.name,attributes:u.attributes},accountData:{name:c.name,attributes:c.attributes}}}async function io(r,n,i){if(!r.context.options.session?.cookieCache?.enabled)return;let s=Cr(n.session,r.context.options.session?.additionalFields),c=ke(r.context.options,n.user),u=r.context.options.session?.cookieCache?.version,f="1";if(u){if(typeof u==="string")f=u;else if(typeof u==="function"){let E=u(n.session,n.user);f=Ci(E)?await E:E}}let m={session:s,user:c,updatedAt:Date.now(),version:f},h={...r.context.authCookies.sessionData.attributes,maxAge:i?void 0:r.context.authCookies.sessionData.attributes.maxAge},y=bt(h.maxAge||60,"sec").getTime(),w=r.context.options.session?.cookieCache?.strategy||"compact",g;if(w==="jwe")g=await Rn(m,r.context.secretConfig,"better-auth-session",h.maxAge||300);else if(w==="jwt"){let E=r.context.sessionConfig.cookieCacheSigner;g=E?await E.sign(r,m,h.maxAge||300):await Tn(m,r.context.secret,h.maxAge||300)}else g=xt.encode(JSON.stringify({session:m,expiresAt:y,signature:await Go("SHA-256","base64urlnopad").sign(r.context.secret,JSON.stringify({...m,expiresAt:y}))}),{padding:!1});let A=no(r.context.authCookies.sessionData.name,h,r);if(A.setCookies(A.chunk(g,h)),r.context.options.account?.storeAccountCookie&&!tm(r,r.context.authCookies.accountData.name)){let E=await Pn(r);if(E)if(!Do(r.context.options)||E.userId===n.user.id)await Et(r,E);else{Be(r,r.context.authCookies.accountData);let v=xn(r.context.authCookies.accountData.name,r.context.authCookies.accountData.attributes,r);v.setCookies(v.clean())}}}async function qc(r,n){let i=r.context.options.session?.cookieCache?.strategy||"compact";if(i==="jwe"){let u=await In(n,r.context.secretConfig,"better-auth-session"),f=_n(u);if(!f)return null;return{session:f,expiresAt:u?.exp?u.exp*1000:Date.now()}}if(i==="jwt"){let u=r.context.sessionConfig.cookieCacheSigner;if(u){let h=await u.verify(r,n);if(!h)return null;return{session:h.payload,expiresAt:h.expiresAt}}let f=await Uc(n,r.context.secret),m=_n(f);if(!m)return null;return{session:m,expiresAt:f?.exp?f.exp*1000:Date.now()}}let s=Lc(de(Vc.decode(xt.decode(n))));if(!s)return null;if(!await Go("SHA-256","base64urlnopad").verify(r.context.secret,JSON.stringify({...s.session,expiresAt:s.expiresAt}),s.signature))return null;let c=_n(s.session);return c?{session:c,expiresAt:s.expiresAt}:null}async function Le(r,n,i,s){let c=await r.getSignedCookie(r.context.authCookies.dontRememberToken.name,r.context.secret);i=i!==void 0?i:!!c;let u=r.context.authCookies.sessionToken.attributes,f=i?void 0:r.context.sessionConfig.expiresIn;if(await r.setSignedCookie(r.context.authCookies.sessionToken.name,n.session.token,r.context.secret,{...u,maxAge:f,...s}),i)await r.setSignedCookie(r.context.authCookies.dontRememberToken.name,"true",r.context.secret,r.context.authCookies.dontRememberToken.attributes);await io(r,n,i),r.context.setNewSession(n)}function em(r,n){let i=r,s=new Set;if(i.responseHeaders)s.add(i.responseHeaders);if(i.context?.responseHeaders)s.add(i.context.responseHeaders);let c=`${n}=`,u=`${n}.`;for(let f of s){let m=typeof f.getSetCookie==="function"?f.getSetCookie():Cn(f.get("set-cookie")||"");if(!m.length)continue;let h=m.filter((y)=>!y.startsWith(c)&&!y.startsWith(u));if(h.length===m.length)continue;f.delete("set-cookie");for(let y of h)f.append("set-cookie",y)}}function tm(r,n){let i=r,s=new Set;if(i.responseHeaders)s.add(i.responseHeaders);if(i.context?.responseHeaders)s.add(i.context.responseHeaders);let c=`${n}=`,u=`${n}.`;for(let f of s)if((typeof f.getSetCookie==="function"?f.getSetCookie():Cn(f.get("set-cookie")||"")).some((m)=>m.startsWith(c)||m.startsWith(u)))return!0;return!1}function Be(r,n){em(r,n.name),r.setCookie(n.name,"",{...n.attributes,maxAge:0})}function dr(r,n){if(Be(r,r.context.authCookies.sessionToken),Be(r,r.context.authCookies.sessionData),r.context.options.account?.storeAccountCookie){Be(r,r.context.authCookies.accountData);let c=xn(r.context.authCookies.accountData.name,r.context.authCookies.accountData.attributes,r),u=c.clean();c.setCookies(u)}if(r.context.oauthConfig.storeStateStrategy==="cookie")Be(r,r.context.createAuthCookie("oauth_state"));let i=no(r.context.authCookies.sessionData.name,r.context.authCookies.sessionData.attributes,r),s=i.clean();if(i.setCookies(s),!n)Be(r,r.context.authCookies.dontRememberToken)}function ss(r){if(!r?.method)throw new l("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if(r.method==="oauth"&&!r.oauth?.providerId)throw new l("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if((r.method==="sso-oidc"||r.method==="sso-saml")&&!r.sso?.providerId)throw new l("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function xr(r,n){let i=r.context.options.user?.validateUserInfo;if(!i)return;ss(n.source);let s;try{s=await i(n,r)}catch(c){throw r.context.logger.error("validateUserInfo callback threw",c),new l("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(s?.error)throw new l("FORBIDDEN",{code:s.error,message:s.errorDescription||s.error})}var rm=async(r)=>{let n=await Er("SHA-256").digest(new TextEncoder().encode(r));return xt.encode(new Uint8Array(n),{padding:!1})};async function rr(r,n){if(!n||n==="plain")return r;if(n==="hashed")return rm(r);if(typeof n==="object"&&"hash"in n)return n.hash(r);return r}function nr(r,n){if(!n)return;if(typeof n==="object"&&"default"in n){if(n.overrides){for(let[i,s]of Object.entries(n.overrides))if(r.startsWith(i))return s}return n.default}return n}var cs=async()=>{let r=Dn(),n=r.context.requestStateAsyncStorage;if(n)return n;let i=await fr();return r.context.requestStateAsyncStorage??=new i,r.context.requestStateAsyncStorage};async function us(){return(await cs()).getStore()!==void 0}async function as(){let r=(await cs()).getStore();if(!r)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return r}async function ds(r,n){return(await cs()).run(r,n)}function Or(r){let n=Object.freeze({});return{get ref(){return n},async get(){let i=await as();if(!i.has(n)){let s=await r();return i.set(n,s),s}return i.get(n)},async set(i){(await as()).set(n,i)}}}var Nn=async()=>{let r=Dn(),n=r.context.adapterAsyncStorage;if(n)return n;let i=await fr();return r.context.adapterAsyncStorage??=new i,r.context.adapterAsyncStorage};var we=async(r)=>Nn().then((n)=>n.getStore()?.adapter||r).catch(()=>r),tu=async(r,n)=>{let i=!1;return Nn().then(async(s)=>{i=!0;let c=[],u,f,m=!1;try{u=await s.run({adapter:r,pendingHooks:c,isTransactionActive:!1},n)}catch(h){f=h,m=!0}for(let h of c)await h();if(m)throw f;return u}).catch((s)=>{if(!i)return n();throw s})},Ht=async(r,n,i)=>{let s=!1;return Nn().then(async(c)=>{if(s=!0,c.getStore()?.isTransactionActive)return n();let u=Fi(r)?.();if(u)await u;let f=[],m,h,y=!1;try{m=await r.transaction(async(g)=>(f=[],c.run({adapter:g,pendingHooks:f,isTransactionActive:!0},n)))}catch(g){y=!0,h=g}let w=async(g)=>{for(let A of f)try{await A()}catch(E){if(!i?.onAfterCommitHookError){if(g==="throw")throw E;try{O.error("Failed to run an after-commit hook for work that could not roll back",E)}catch{}continue}try{await i.onAfterCommitHookError(E)}catch{}}};if(y){if(r.options?.adapterConfig.transaction===!1)await w("log");throw h}return await w("throw"),m}).catch((c)=>{if(!s)return n();throw c})},Ue=async(r,n)=>{let i=async()=>{try{await r()}catch(u){if(!n?.onError)throw u;await n.onError(u)}},s;try{s=await Nn()}catch{return i()}let c=s.getStore();if(!c?.isTransactionActive)return i();c.pendingHooks.push(i)};function Zc(r,n){let i=or(n.options),s=n.hooks;async function c(w,g,A){let E=Ve(),v=w;for(let{source:P,hooks:I}of s){let T=I[g]?.create?.before;if(T){let D=await i(`db create.before ${g}`,{[Xe]:"create.before",[F.ATTR_DB_COLLECTION_NAME]:g,[et]:P},()=>T(v,E));if(D===!1)return null;if(typeof D==="object"&&"data"in D)v={...v,...D.data}}}let _=null;if(!A||A.executeMainFn)_=await(await we(r)).create({model:g,data:v,forceAllowId:!0});if(A?.fn)_=await A.fn(_??v);for(let{source:P,hooks:I}of s){let T=I[g]?.create?.after;if(T)await Ue(async()=>{await i(`db create.after ${g}`,{[Xe]:"create.after",[F.ATTR_DB_COLLECTION_NAME]:g,[et]:P},()=>T(_,E))})}return _}async function u(w,g,A,E){let v=Ve(),_=w;for(let{source:T,hooks:D}of s){let k=D[A]?.update?.before;if(k){let R=await i(`db update.before ${A}`,{[Xe]:"update.before",[F.ATTR_DB_COLLECTION_NAME]:A,[et]:T},()=>k(w,v));if(R===!1)return null;if(typeof R==="object"&&"data"in R)_={..._,...R.data}}}let P=E?await E.fn(_):null,I=!E||E.executeMainFn?await(await we(r)).update({model:A,update:_,where:g}):P;for(let{source:T,hooks:D}of s){let k=D[A]?.update?.after;if(k)await Ue(async()=>{await i(`db update.after ${A}`,{[Xe]:"update.after",[F.ATTR_DB_COLLECTION_NAME]:A,[et]:T},()=>k(I,v))})}return I}async function f(w,g,A,E){let v=Ve(),_=w;for(let{source:T,hooks:D}of s){let k=D[A]?.update?.before;if(k){let R=await i(`db updateMany.before ${A}`,{[Xe]:"updateMany.before",[F.ATTR_DB_COLLECTION_NAME]:A,[et]:T},()=>k(w,v));if(R===!1)return null;if(typeof R==="object"&&"data"in R)_={..._,...R.data}}}let P=E?await E.fn(_):null,I=!E||E.executeMainFn?await(await we(r)).updateMany({model:A,update:_,where:g}):P;for(let{source:T,hooks:D}of s){let k=D[A]?.update?.after;if(k)await Ue(async()=>{await i(`db updateMany.after ${A}`,{[Xe]:"updateMany.after",[F.ATTR_DB_COLLECTION_NAME]:A,[et]:T},()=>k(I,v))})}return I}async function m(w,g,A){let E=Ve(),v=null;try{v=(await(await we(r)).findMany({model:g,where:w,limit:1}))[0]||null}catch{}if(v)for(let{source:I,hooks:T}of s){let D=T[g]?.delete?.before;if(D){if(await i(`db delete.before ${g}`,{[Xe]:"delete.before",[F.ATTR_DB_COLLECTION_NAME]:g,[et]:I},()=>D(v,E))===!1)return null}}let _=A?await A.fn(w):null,P=(!A||A.executeMainFn)&&v?await(await we(r)).delete({model:g,where:w}):_;if(v)for(let{source:I,hooks:T}of s){let D=T[g]?.delete?.after;if(D)await Ue(async()=>{await i(`db delete.after ${g}`,{[Xe]:"delete.after",[F.ATTR_DB_COLLECTION_NAME]:g,[et]:I},()=>D(v,E))})}return P}async function h(w,g,A){let E=Ve(),v=[];try{v=await(await we(r)).findMany({model:g,where:w})}catch{}for(let I of v)for(let{source:T,hooks:D}of s){let k=D[g]?.delete?.before;if(k){if(await i(`db delete.before ${g}`,{[Xe]:"delete.before",[F.ATTR_DB_COLLECTION_NAME]:g,[et]:T},()=>k(I,E))===!1)return null}}let _=A?await A.fn(w):null,P=!A||A.executeMainFn?await(await we(r)).deleteMany({model:g,where:w}):_;for(let I of v)for(let{source:T,hooks:D}of s){let k=D[g]?.delete?.after;if(k)await Ue(async()=>{await i(`db delete.after ${g}`,{[Xe]:"delete.after",[F.ATTR_DB_COLLECTION_NAME]:g,[et]:T},()=>k(I,E))})}return P}async function y(w,g,A,E){let v=Ve(),_=s.flatMap(({source:T,hooks:D})=>{let k=D[w]?.delete?.before;return k?[{source:T,fn:k}]:[]}),P=E??null;if(_.length){if(!P)try{P=(await(await we(r)).findMany({model:w,where:g,limit:1}))[0]||null}catch{}if(P){for(let{source:T,fn:D}of _)if(await i(`db delete.before ${w}`,{[Xe]:"delete.before",[F.ATTR_DB_COLLECTION_NAME]:w,[et]:T},()=>D(P,v))===!1)return null}}let I=await A();if(!I)return null;for(let{source:T,hooks:D}of s){let k=D[w]?.delete?.after;if(k)await Ue(async()=>{await i(`db delete.after ${w}`,{[Xe]:"delete.after",[F.ATTR_DB_COLLECTION_NAME]:w,[et]:T},()=>k(I,v))})}return I}return{createWithHooks:c,updateWithHooks:u,updateManyWithHooks:f,deleteWithHooks:m,deleteManyWithHooks:h,consumeOneWithHooks:y}}function nt(r,n=Date.now()){let i=typeof r==="number"?r:r.getTime();return Math.max(Math.floor((i-n)/1000),0)}var Di=(r,n)=>{let{logger:i,options:s}=n,c=s.secondaryStorage,u=new Map,f=s.session?.expiresIn||604800,m=!!c&&s.session?.storeSessionInDatabase===!0&&s.session?.preserveSessionInDatabase!==!0,{createWithHooks:h,updateWithHooks:y,updateManyWithHooks:w,deleteWithHooks:g,deleteManyWithHooks:A,consumeOneWithHooks:E}=Zc(r,n),v=(k)=>{let R=[...k,{field:"expiresAt",value:new Date,operator:"gt"}];return A(R,"session",{fn:async()=>{await(await we(r)).updateMany({model:"session",where:R,update:{expiresAt:new Date}})},executeMainFn:!1})};async function _(k){if(!c)return;let R=await c.get(`active-sessions-${k.id}`);if(!R)return;let L=Date.now(),M=(de(R)||[]).filter((N)=>N.expiresAt>L);await Promise.all(M.map(async({token:N})=>{let H=await c.get(N);if(!H)return;let z=de(H);if(!z)return;let B=nt(z.session.expiresAt,L);await c.set(N,JSON.stringify({session:z.session,user:k}),Math.floor(B))}))}async function P(k){if(!c)return[];let R=await c.get(`active-sessions-${k}`);return R?de(R)||[]:[]}async function I(k,R){if(!c)return;let L=new Set(R.map((K)=>K.token));for(let{token:K}of R)await c.delete(K);let M=`active-sessions-${k}`,N=await P(k),H=Date.now(),z=N.filter((K)=>K.expiresAt>H&&!L.has(K.token));z.sort((K,W)=>K.expiresAt-W.expiresAt);let B=z.at(-1)?.expiresAt;if(B){await c.set(M,JSON.stringify(z),nt(B,H));return}await c.delete(M)}async function T(k,R){if(!c)return;let L=R??await P(k);await Ue(()=>I(k,L),{onError(M){i.error("Failed to delete committed user sessions from secondary storage",M)}})}async function D(k,R){let L=u.get(k)??Promise.resolve(),M,N=new Promise((z)=>{M=z}),H=L.catch(()=>{}).then(()=>N);u.set(k,H),await L.catch(()=>{});try{return await R()}finally{if(M(),u.get(k)===H)u.delete(k)}}return{createOAuthUser:async(k,R)=>Ht(r,async()=>{let L=await h({createdAt:new Date,updatedAt:new Date,...k,email:k.email?.toLowerCase()},"user",void 0);if(!L)throw new l("BAD_REQUEST",{message:"Failed to create user"});return{user:L,account:await h({...R,userId:L.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(k,R)=>{let L={createdAt:new Date,updatedAt:new Date,...k,email:k.email?.toLowerCase()};if(s.user?.validateUserInfo){let M={...R,action:"create-user"};ss(M);let N;try{N=Yn()}catch(H){throw i.error("Unable to run validateUserInfo: missing endpoint context",H),new l("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await xr(N,{user:L,source:M})}return await h(L,"user",void 0)},createAccount:async(k)=>await h({createdAt:new Date,updatedAt:new Date,...k},"account",void 0),listSessions:async(k,R)=>{if(m)return(await(await we(r)).findMany({model:"session",where:[{field:"userId",value:k},{field:"expiresAt",value:new Date,operator:"gt"}]})).map((L)=>at(n.options,L));if(c){let L=await c.get(`active-sessions-${k}`);if(!L)return[];let M=de(L)||[],N=Date.now(),H=new Set,z=[];for(let{token:B,expiresAt:K}of M){if(K<=N||H.has(B))continue;H.add(B);let W=await c.get(B);if(!W)continue;try{let V=typeof W==="string"?JSON.parse(W):W;if(!V?.session)continue;z.push(at(n.options,{...V.session,expiresAt:new Date(V.session.expiresAt)}))}catch{continue}}return z}return await(await we(r)).findMany({model:"session",where:[{field:"userId",value:k},...R?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(k,R,L,M)=>await(await we(r)).findMany({model:"user",limit:k,offset:R,sortBy:L,where:M}),countTotalUsers:async(k)=>{let R=await(await we(r)).count({model:"user",where:k});if(typeof R==="string")return parseInt(R);return R},deleteUser:async(k)=>{let R=await P(k);if(!c||s.session?.storeSessionInDatabase)await A([{field:"userId",value:k}],"session",void 0);if(await A([{field:"userId",value:k}],"account",void 0),await g([{field:"id",value:k}],"user",void 0)!==null)await T(k,R)},createSession:async(k,R,L,M,N)=>{let H=await(async()=>{let q=Ve();return q?.headers||q?.request?.headers})(),z=s.session?.storeSessionInDatabase,B=N?.deferSecondaryStorageWrites===!0&&m,{id:K,...W}=L||{},V;if(c&&!z){let q=n.generateId({model:"session"});V=q!==!1?q:Lt()}let J=Jc(s),X={...V?{id:V}:{},ipAddress:H?Oi(H,s)||"":"",userAgent:H?.get("user-agent")||"",...W,expiresAt:R?bt(86400,"sec"):bt(f,"sec"),userId:k,token:Lt(32),createdAt:new Date,updatedAt:new Date,...J,...M?W:{}},te=async(q)=>{if(!c)return q;let re=await c.get(`active-sessions-${k}`),ie=[],se=Date.now();if(re)ie=de(re)||[],ie=ie.filter((Ke)=>Ke.expiresAt>se&&Ke.token!==X.token);let ce=[...ie,{token:X.token,expiresAt:X.expiresAt.getTime()}].sort((Ke,vt)=>Ke.expiresAt-vt.expiresAt),$e=nt(ce.at(-1)?.expiresAt??X.expiresAt.getTime(),se);if($e>0)await c.set(`active-sessions-${k}`,JSON.stringify(ce),$e);let St=await(await we(r)).findOne({model:"user",where:[{field:"id",value:k}]}),lt=nt(X.expiresAt,se);if(lt>0)await c.set(X.token,JSON.stringify({session:q,user:St}),lt);return q};return await h(X,"session",c?{fn:async(q)=>{if(!B)return te(q);return await Ue(async()=>{await te(q)},{onError(re){i.error("Failed to mirror committed session to secondary storage",re)}}),q},executeMainFn:z}:void 0)},findSession:async(k)=>{if(c){let N=await c.get(k);if(!N&&(!s.session?.storeSessionInDatabase||n.options.session?.preserveSessionInDatabase))return null;if(N){let H=de(N);if(!H)return null;return{session:at(n.options,{...H.session,expiresAt:new Date(H.session.expiresAt),createdAt:new Date(H.session.createdAt),updatedAt:new Date(H.session.updatedAt)}),user:ke(n.options,{...H.user,createdAt:new Date(H.user.createdAt),updatedAt:new Date(H.user.updatedAt)})}}}let R=await(await we(r)).findOne({model:"session",where:[{value:k,field:"token"}],join:{user:!0}});if(!R)return null;let{user:L,...M}=R;if(!L)return null;return{session:at(n.options,M),user:ke(n.options,L)}},findSessions:async(k,R)=>{let L=[...new Set(k)],M=new Map,N=[];if(c)for(let z of L){let B=await c.get(z);if(B)try{let K=typeof B==="string"?JSON.parse(B):B;if(!K)continue;let W=new Date(K.session.expiresAt);if(R?.onlyActiveSessions&&W<=new Date)continue;let V={session:{...K.session,expiresAt:new Date(K.session.expiresAt)},user:{...K.user,createdAt:new Date(K.user.createdAt),updatedAt:new Date(K.user.updatedAt)}};M.set(z,V)}catch{continue}else N.push(z)}let H=c?N:L;if(H.length>0&&(!c||m)){let z=await(await we(r)).findMany({model:"session",limit:H.length,where:[{field:"token",value:H,operator:"in"},...R?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});for(let{user:B,...K}of z)if(B)M.set(K.token,{session:K,user:B})}return L.flatMap((z)=>{let B=M.get(z);return B?[B]:[]})},updateSession:async(k,R)=>await y(R,[{field:"token",value:k}],"session",c?{async fn(L){let M=await c.get(k);if(!M)return null;let N=de(M);if(!N)return null;let H={...N.session,...L,expiresAt:new Date(L.expiresAt??N.session.expiresAt),createdAt:new Date(N.session.createdAt),updatedAt:new Date(L.updatedAt??N.session.updatedAt)},z=at(n.options,H),B=Date.now(),K=new Date(z.expiresAt).getTime(),W=nt(K,B);if(W>0){await c.set(k,JSON.stringify({session:z,user:N.user}),W);let V=`active-sessions-${z.userId}`,J=await c.get(V),X=(J?de(J)||[]:[]).filter((q)=>q.token!==k&&q.expiresAt>B).concat([{token:k,expiresAt:K}]).sort((q,re)=>q.expiresAt-re.expiresAt),te=X.at(-1)?.expiresAt;if(te&&te>B)await c.set(V,JSON.stringify(X),nt(te,B));else await c.delete(V)}return z},executeMainFn:s.session?.storeSessionInDatabase}:void 0),deleteSession:async(k)=>{if(c){let R=await c.get(k);if(R){let{session:L}=de(R)??{};if(!L){i.error("Session not found in secondary storage");return}let M=L.userId,N=await c.get(`active-sessions-${M}`);if(N){let H=de(N)||[],z=Date.now(),B=H.filter((W)=>W.expiresAt>z&&W.token!==k),K=B.sort((W,V)=>W.expiresAt-V.expiresAt).at(-1)?.expiresAt;if(B.length>0&&K&&K>Date.now())await c.set(`active-sessions-${M}`,JSON.stringify(B),nt(K,z));else await c.delete(`active-sessions-${M}`)}else i.error("Active sessions list not found in secondary storage")}if(await c.delete(k),!s.session?.storeSessionInDatabase)return;if(n.options.session?.preserveSessionInDatabase){await v([{field:"token",value:k}]);return}}await g([{field:"token",value:k}],"session",void 0)},deleteAccounts:async(k)=>{await A([{field:"userId",value:k}],"account",void 0)},deleteAccount:async(k)=>{await g([{field:"id",value:k}],"account",void 0)},deleteUserSessions:async(k)=>{let R=await P(k);if(c){if(!s.session?.storeSessionInDatabase){await T(k,R);return}if(n.options.session?.preserveSessionInDatabase){if(await v([{field:"userId",value:k}])!==null)await T(k,R);return}}if(await A([{field:"userId",value:k}],"session",void 0)!==null)await T(k,R)},deleteSessions:async(k)=>{if(c){if(await Promise.all(k.map((R)=>c.delete(R))),!s.session?.storeSessionInDatabase)return;if(n.options.session?.preserveSessionInDatabase){await v([{field:"token",value:k,operator:"in"}]);return}}await A([{field:"token",value:k,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:k,accountId:R})=>{let L=await(await we(r)).findMany({model:"account",where:[{field:"providerId",value:k},{field:"accountId",value:R}],limit:2,join:{user:!0}});if(L.length>1)throw new S(`Multiple accounts match the same accountId for provider ${JSON.stringify(k)}. Resolve duplicate account identities before continuing.`);let M=L[0];if(!M)return null;let{user:N,...H}=M;return N?{kind:"owned",user:N,account:H}:{kind:"orphaned",account:H}},findUserByEmail:async(k,R)=>{let L=await(await we(r)).findOne({model:"user",where:[{value:k.toLowerCase(),field:"email"}],join:{...R?.includeAccounts?{account:!0}:{}}});if(!L)return null;let{account:M,...N}=L;return{user:N,accounts:M??[]}},findUserById:async(k)=>{if(!k)return null;return await(await we(r)).findOne({model:"user",where:[{field:"id",value:k}]})},linkAccount:async(k)=>await h({createdAt:new Date,updatedAt:new Date,...k},"account",void 0),updateUser:async(k,R)=>{let L=await y({...R,...R.email?{email:R.email.toLowerCase()}:{}},[{field:"id",value:k}],"user",void 0);return await Ue(()=>_(L),{onError(M){i.error("Failed to refresh committed user sessions in secondary storage",M)}}),L},updateUserByEmail:async(k,R)=>{let L=await y({...R,...R.email?{email:R.email.toLowerCase()}:{}},[{field:"email",value:k.toLowerCase()}],"user",void 0);return await Ue(()=>_(L),{onError(M){i.error("Failed to refresh committed user sessions in secondary storage",M)}}),L},updatePassword:async(k,R)=>{await w({password:R},[{field:"userId",value:k},{field:"providerId",value:"credential"},{field:"accountId",value:k}],"account",void 0)},findAccounts:async(k)=>await(await we(r)).findMany({model:"account",where:[{field:"userId",value:k}]}),findCredentialAccount:async(k)=>(await we(r)).findOne({model:"account",where:[{field:"userId",value:k},{field:"providerId",value:"credential"},{field:"accountId",value:k}]}),findAccountByKey:async({providerId:k,accountId:R})=>{let L=await(await we(r)).findMany({model:"account",limit:2,where:[{field:"providerId",value:k},{field:"accountId",value:R}]});if(L.length>1)throw new S(`Multiple accounts match the same accountId for provider ${JSON.stringify(k)}. Resolve duplicate account identities before continuing.`);return L[0]??null},findAccountByUserId:async(k)=>await(await we(r)).findMany({model:"account",where:[{field:"userId",value:k}]}),updateAccount:async(k,R)=>await y(R,[{field:"id",value:k}],"account",void 0),createVerificationValue:async(k)=>{let R=nr(k.identifier,s.verification?.storeIdentifier),L=await rr(k.identifier,R);return await h({createdAt:new Date,updatedAt:new Date,...k,identifier:L},"verification",c?{async fn(M){let N=nt(M.expiresAt);if(N>0)await c.set(`verification:${L}`,JSON.stringify(M),N);return M},executeMainFn:s.verification?.storeInDatabase}:void 0)},findVerificationValue:async(k)=>{let R=nr(k,s.verification?.storeIdentifier),L=await rr(k,R);if(c){let z=await c.get(`verification:${L}`);if(z){let B=de(z);if(B)return B}if(R&&R!=="plain"){let B=await c.get(`verification:${k}`);if(B){let K=de(B);if(K)return K}}if(!s.verification?.storeInDatabase)return null}let M=await we(r);async function N(z){return M.findMany({model:"verification",where:[{field:"identifier",value:z}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let H=await N(L);if(!H.length&&R&&R!=="plain")H=await N(k);if(!s.verification?.disableCleanup)await A([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0);return H[0]||null},deleteVerificationByIdentifier:async(k)=>{let R=await rr(k,nr(k,s.verification?.storeIdentifier));if(c)await c.delete(`verification:${R}`);if(!c||s.verification?.storeInDatabase)await g([{field:"identifier",value:R}],"verification",void 0)},consumeVerificationValue:async(k)=>{let R=nr(k,s.verification?.storeIdentifier),L=await rr(k,R),M=R&&R!=="plain"?[L,k]:[L],N=(z)=>{if(!z)return null;let B=typeof z==="string"?de(z):typeof z==="object"?z:null;if(!B)return null;let K=new Date(B.expiresAt);if(!Number.isFinite(K.getTime()))return null;return{...B,expiresAt:K}},H=null;if(c&&!s.verification?.storeInDatabase){let z=async(B)=>N(await c.getAndDelete(B));for(let B of M){let K=await z(`verification:${B}`);if(!K)continue;await Promise.all(M.filter((W)=>W!==B).map((W)=>c.delete(`verification:${W}`))),H=K;break}}else{let z=async(B)=>D(`verification:${B}`,()=>Ht(r,async()=>{let K=await we(r),W=[{field:"identifier",value:B}],V=(await K.findMany({model:"verification",where:W,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;if(!V)return null;return E("verification",[{field:"id",value:V.id}],async()=>{let J=await K.consumeOne({model:"verification",where:[{field:"id",value:V.id}]});if(!J)return null;return await K.deleteMany({model:"verification",where:W}),J},V)}));for(let B of M)if(H=await z(B),H)break;if(H&&c)await Promise.all(M.map((B)=>c.delete(`verification:${B}`)))}if(!H||H.expiresAt<new Date)return null;return H},reserveVerificationValue:async(k)=>{let R=sy(new Uint8Array(await Er("SHA-256").digest(new TextEncoder().encode("reserve:"+k.identifier))),s),L=nr(k.identifier,s.verification?.storeIdentifier),M=await rr(k.identifier,L);if(c&&!s.verification?.storeInDatabase)throw new S("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await r.create({model:"verification",data:{id:R,identifier:M,value:k.value,expiresAt:k.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(N){if(await r.findOne({model:"verification",where:[{field:"id",value:R}]}))return!1;throw N}if(c){let N=nt(k.expiresAt);if(N>0)await c.set(`verification:${M}`,JSON.stringify({id:R,identifier:M,value:k.value,expiresAt:k.expiresAt}),N)}return!0},updateVerificationByIdentifier:async(k,R)=>{let L=await rr(k,nr(k,s.verification?.storeIdentifier));if(c){let M=await c.get(`verification:${L}`);if(M){let N=de(M);if(N){let H={...N,...R},z=H.expiresAt??N.expiresAt,B=nt(z instanceof Date?z:new Date(z));if(B>0)await c.set(`verification:${L}`,JSON.stringify(H),B);if(!s.verification?.storeInDatabase)return H}}}if(!c||s.verification?.storeInDatabase)return await y(R,[{field:"identifier",value:L}],"verification",void 0);return R},refreshUserSessions:_}};function ls(r){if(r===null||typeof r!=="object")return!1;let n=Object.getPrototypeOf(r);if(n!==null&&n!==Object.prototype&&Object.getPrototypeOf(n)!==null)return!1;if(Symbol.iterator in r)return!1;if(Symbol.toStringTag in r)return Object.prototype.toString.call(r)==="[object Module]";return!0}function fs(r,n,i=".",s){if(!ls(n))return fs(r,{},i,s);let c={...n};for(let u of Object.keys(r)){if(u==="__proto__"||u==="constructor")continue;let f=r[u];if(f===null||f===void 0)continue;if(s&&s(c,u,f,i))continue;if(Array.isArray(f)&&Array.isArray(c[u]))c[u]=[...f,...c[u]];else if(ls(f)&&ls(c[u]))c[u]=fs(f,c[u],(i?`${i}.`:"")+u.toString(),s);else c[u]=f}return c}function so(r){return(...n)=>n.reduce((i,s)=>fs(i,s,"",r),{})}var Wo=so(),mE=so((r,n,i)=>{if(r[n]!==void 0&&typeof i==="function")return r[n]=i(r[n]),!0}),hE=so((r,n,i)=>{if(Array.isArray(r[n])&&typeof i==="function")return r[n]=i(r[n]),!0});var om=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function nm(r){if(r.length>=2&&r.startsWith("[")&&r.endsWith("]"))return r.slice(1,-1);return r}function im(r){if(r.startsWith("[")){let i=r.indexOf("]");if(i===-1)return r;return r.slice(0,i+1)}let n=r.indexOf(":");if(n===-1)return r;if(r.indexOf(":",n+1)!==-1)return r;return r.slice(0,n)}function sm(r){let n=r.indexOf("%");if(n===-1)return r;return r.slice(0,n)}function am(r){return r.replace(/\.+$/,"")}function Fc(r){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r)}function ve(r){let n=r.split(".");return(Number(n[0])<<24|Number(n[1])<<16|Number(n[2])<<8|Number(n[3]))>>>0}function Ce(r,n,i){if(i===0)return!0;let s=i===32?4294967295:-1<<32-i>>>0;return(r&s)===(n&s)}function ao(r){if(r==="0.0.0.0")return"unspecified";if(r==="255.255.255.255")return"broadcast";let n=ve(r);if(Ce(n,ve("127.0.0.0"),8))return"loopback";if(Ce(n,ve("10.0.0.0"),8))return"private";if(Ce(n,ve("172.16.0.0"),12))return"private";if(Ce(n,ve("192.168.0.0"),16))return"private";if(Ce(n,ve("169.254.0.0"),16))return"linkLocal";if(Ce(n,ve("100.64.0.0"),10))return"sharedAddressSpace";if(Ce(n,ve("192.0.2.0"),24))return"documentation";if(Ce(n,ve("198.51.100.0"),24))return"documentation";if(Ce(n,ve("203.0.113.0"),24))return"documentation";if(Ce(n,ve("198.18.0.0"),15))return"benchmarking";if(Ce(n,ve("224.0.0.0"),4))return"multicast";if(Ce(n,ve("0.0.0.0"),8))return"reserved";if(Ce(n,ve("192.0.0.0"),24))return"reserved";if(Ce(n,ve("192.88.99.0"),24))return"reserved";if(Ce(n,ve("240.0.0.0"),4))return"reserved";return"public"}function ps(r,n,i={}){let s=n*5,c=Number.parseInt(r.slice(s,s+4),16),u=Number.parseInt(r.slice(s+5,s+9),16);if(!Number.isFinite(c)||!Number.isFinite(u))return null;let f=(c<<16|u)>>>0;if(i.xor)f=(f^4294967295)>>>0;return`${f>>>24&255}.${f>>>16&255}.${f>>>8&255}.${f&255}`}function cm(r){if(r==="0000:0000:0000:0000:0000:0000:0000:0000")return"unspecified";if(r==="0000:0000:0000:0000:0000:0000:0000:0001")return"loopback";let n=Number.parseInt(r.slice(0,2),16),i=Number.parseInt(r.slice(2,4),16);if(n===255)return"multicast";if(n===254&&(i&192)===128)return"linkLocal";if(n===254&&(i&192)===192)return"reserved";if((n&254)===252)return"private";if(r.startsWith("2001:0db8:"))return"documentation";if(r.startsWith("2001:0002:0000:"))return"benchmarking";if(r.startsWith("2002:")){let s=ps(r,1);if(s&&ao(s)!=="public")return"reserved";return"public"}if(r.startsWith("0064:ff9b:0000:0000:0000:0000:")){let s=ps(r,6);if(s&&ao(s)!=="public")return"reserved";return"reserved"}if(r.startsWith("0064:ff9b:0001:"))return"reserved";if(r.startsWith("2001:0000:")){let s=ps(r,6,{xor:!0});if(s&&ao(s)!=="public")return"reserved";return"reserved"}if(r.startsWith("0100:0000:0000:0000:"))return"reserved";if(r.startsWith("3fff:0"))return"documentation";if(r.startsWith("5f00:"))return"reserved";if(r.startsWith("0000:0000:0000:0000:0000:0000:"))return"reserved";return"public"}function um(r){let n=am(sm(nm(im(r.trim())))).toLowerCase();if(n==="")return{kind:"reserved",literal:"fqdn",canonical:""};if(!yi(n)){if(n==="localhost"||n.endsWith(".localhost"))return{kind:"localhost",literal:"fqdn",canonical:n};if(om.has(n))return{kind:"cloudMetadata",literal:"fqdn",canonical:n};return{kind:"public",literal:"fqdn",canonical:n}}if(Fc(n))return{kind:ao(n),literal:"ipv4",canonical:n};let i=xo(n,{ipv6Subnet:128});if(Fc(i))return{kind:ao(i),literal:"ipv4",canonical:i};return{kind:cm(i),literal:"ipv6",canonical:i}}function ou(r){let n=um(r).kind;return n==="loopback"||n==="localhost"}async function Bf(r){let n=r.options,i=n.plugins||[],s=[],c=[];for(let u of i)if(u.init){let f=u.init(r),m;if(Ci(f))m=await f;else m=f;if(typeof m==="object"){if(m.options){let{databaseHooks:h,trustedOrigins:y,...w}=m.options;if(h)c.push({source:`plugin:${u.id}`,hooks:h});if(y)s.push(y);n=Wo(n,w)}if(m.context)Object.assign(r,m.context)}}if(s.length>0){let u=[...n.trustedOrigins?[n.trustedOrigins]:[],...s],f=u.filter(Array.isArray).flat(),m=u.filter((h)=>typeof h==="function");if(m.length>0)n.trustedOrigins=async(h)=>{let y=await Promise.all(m.map((w)=>w(h)));return[...f,...y.flat()].filter((w)=>typeof w==="string"&&w!=="")};else n.trustedOrigins=f}if(n.databaseHooks)c.push({source:"user",hooks:n.databaseHooks});r.internalAdapter=Di(r.adapter,{options:n,logger:r.logger,hooks:c,generateId:r.generateId}),r.options=n}function Ff(r){let n=[];if(r.advanced?.crossSubDomainCookies?.enabled);return n}async function Yo(r,n){let i=[];if(er(r.baseURL)){let c=r.baseURL.allowedHosts,u=r.baseURL.protocol;for(let f of c)if(!f.includes("://")){if(!u||u==="https"||u==="auto")i.push(`https://${f}`);if(u==="http"||u==="auto"||ou(f))i.push(`http://${f}`)}else i.push(f);if(r.baseURL.fallback)try{i.push(new URL(r.baseURL.fallback).origin)}catch{}}else{let c=_r(typeof r.baseURL==="string"?r.baseURL:void 0,r.basePath,n);if(c)i.push(new URL(c).origin)}if(r.trustedOrigins){if(Array.isArray(r.trustedOrigins))i.push(...r.trustedOrigins);if(typeof r.trustedOrigins==="function"){let c=await r.trustedOrigins(n);i.push(...c)}}let s=ae.BETTER_AUTH_TRUSTED_ORIGINS;if(s)i.push(...s.split(","));return i.filter((c)=>Boolean(c))}function iu(r){if(He(r?.request))return r.request;if(!r?.headers)return;let n=r.headers instanceof Headers?r.headers:new Headers(r.headers);if(!n.has("host")&&!n.has("x-forwarded-host"))return;return n}function Xc(r){return r.advanced?.trustedProxyHeaders??!1}async function el(r,n,i){let s=r.options.baseURL,c=_a(s,r.options.basePath||"/api/auth",n,void 0,i);if(!c)throw new S("Could not resolve base URL from request. Check your allowedHosts config.");let u=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));u.baseURL=c,u.options={...r.options,baseURL:tn(c)||void 0};let f={...u.options,baseURL:s},m=typeof r.options.trustedOrigins==="function"||typeof r.options.account?.accountLinking?.trustedProviders==="function",h;if(m)if(He(n))h=n;else if(n)h=new Request(c,{headers:n});else h=void 0;else h=void 0;if(u.trustedOrigins=await Yo(f,h),u.trustedProviders=await Jo(u.options,h),r.options.advanced?.crossSubDomainCookies?.enabled)u.authCookies=Qc(u.options),u.createAuthCookie=Ko(u.options);return u}async function it(r,n){if(!r)return;for(let i of r){let s=typeof i==="function"?await i():i;if(s[n.field??"id"]===n.value)return s}}async function Jo(r,n){let i=r.account?.accountLinking?.trustedProviders;if(!i)return[];if(Array.isArray(i))return i.filter((s)=>Boolean(s));return(await i(n)??[]).filter((s)=>Boolean(s))}function ir(r,n){if(n.length<r.context.password.config.minPasswordLength)throw r.context.logger.warn("Password is too short"),l.from("BAD_REQUEST",x.PASSWORD_TOO_SHORT)}function Pe(r,n){if(n.length>r.context.password.config.maxPasswordLength)throw r.context.logger.warn("Password is too long"),l.from("BAD_REQUEST",x.PASSWORD_TOO_LONG)}async function su(r,n,i,s){await Ht(r.context.adapter,async()=>{if(await s?.(),r.context.options.emailAndPassword?.revokeSessionsOnPasswordReset)await r.context.internalAdapter.deleteUserSessions(n);if(!await r.context.internalAdapter.findCredentialAccount(n)){await r.context.internalAdapter.createAccount({userId:n,providerId:"credential",accountId:n,password:i});return}await r.context.internalAdapter.updatePassword(n,i)})}async function au(r,n){Pe(r,n.password);let i=await r.context.internalAdapter.findCredentialAccount(n.userId),s=i?.password;if(!i||!s)return!1;return await r.context.password.verify({hash:s,password:n.password})}async function qf(r,n){let i=n.body.password;if(typeof i==="string")Pe(n,i);let s=await n.context.internalAdapter.findCredentialAccount(r),c=s?.password;if(!s||!c||!i){if(i)await n.context.password.hash(i);throw l.from("BAD_REQUEST",x.INVALID_PASSWORD)}if(!await n.context.password.verify({hash:c,password:i}))throw l.from("BAD_REQUEST",x.INVALID_PASSWORD);return!0}function Lr(r,n){let i;try{i=new URL(r).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let s=n.replace(/\/+$/,"");if(s==="")return i;if(i===s)return"/";if(i.startsWith(s+"/"))return i.slice(s.length).replace(/\/+$/,"")||"/";return i}var cu="https://better-auth.invalid";function ct(r,n){let i=r.startsWith("/");if(r.startsWith("//")||r.startsWith("/\\"))throw TypeError("Expected an absolute or root-relative URL");let s=i?new URL(r,cu):new URL(r);if(i&&s.origin!==cu)throw TypeError("Expected an absolute or root-relative URL");let c=n.toString();if(!c)return r;let u=s.search.endsWith("&")?"":"&";return s.search=s.search?`${s.search}${u}${c}`:c,i?s.href.slice(s.origin.length):s.href}function uu(r,n,i){let s=!1;return function(...c){if(!s)(i?.warn??console.warn)(`[Deprecation] ${n}`),s=!0;return r.apply(this,c)}}function du(r){return r.context.skipOriginCheck===!0&&r.context.options.advanced?.disableCSRFCheck===void 0}function ms(r){let n=r.context.skipOriginCheck;if(n===!0)return!0;if(Array.isArray(n)&&r.request)try{let i=new URL(r.context.baseURL).pathname,s=Lr(r.request.url,i);return n.some((c)=>{let u=c.replace(/\/+$/,"");return s===u||s.startsWith(`${u}/`)})}catch{}return!1}var dm=uu(function r(){},"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."),lu=We(async(r)=>{if(r.request?.method==="GET"||r.request?.method==="OPTIONS"||r.request?.method==="HEAD"||!r.request)return;if(await zn(r),ms(r))return;let{body:n,query:i}=r,s=n?.callbackURL||i?.callbackURL,c=n?.redirectTo,u=n?.errorCallbackURL,f=n?.newUserCallbackURL,m=(h,y)=>{if(!h)return;if(typeof h!=="string")throw l.fromStatus("BAD_REQUEST",{message:`Invalid ${y}: expected a string`});if(!r.context.isTrustedOrigin(h,{allowRelativePaths:y!=="origin"})){if(r.context.logger.error(`Invalid ${y}: ${h}`),r.context.logger.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
32
+ `,`Current list of trustedOrigins: ${r.context.trustedOrigins}`),y==="origin")throw l.from("FORBIDDEN",x.INVALID_ORIGIN);if(y==="callbackURL")throw l.from("FORBIDDEN",x.INVALID_CALLBACK_URL);if(y==="redirectURL")throw l.from("FORBIDDEN",x.INVALID_REDIRECT_URL);if(y==="errorCallbackURL")throw l.from("FORBIDDEN",x.INVALID_ERROR_CALLBACK_URL);if(y==="newUserCallbackURL")throw l.from("FORBIDDEN",x.INVALID_NEW_USER_CALLBACK_URL);throw l.fromStatus("FORBIDDEN",{message:`Invalid ${y}`})}};s&&m(s,"callbackURL"),c&&m(c,"redirectURL"),u&&m(u,"errorCallbackURL"),f&&m(f,"newUserCallbackURL")}),Kt=(r)=>We(async(n)=>{if(!n.request)return;if(ms(n))return;let i=r(n),s=(u,f)=>{if(!u)return;if(!n.context.isTrustedOrigin(u,{allowRelativePaths:f!=="origin"})){if(n.context.logger.error(`Invalid ${f}: ${u}`),n.context.logger.info(`If it's a valid URL, please add ${u} to trustedOrigins in your auth config
33
+ `,`Current list of trustedOrigins: ${n.context.trustedOrigins}`),f==="origin")throw l.from("FORBIDDEN",x.INVALID_ORIGIN);if(f==="callbackURL")throw l.from("FORBIDDEN",x.INVALID_CALLBACK_URL);if(f==="redirectURL")throw l.from("FORBIDDEN",x.INVALID_REDIRECT_URL);if(f==="errorCallbackURL")throw l.from("FORBIDDEN",x.INVALID_ERROR_CALLBACK_URL);if(f==="newUserCallbackURL")throw l.from("FORBIDDEN",x.INVALID_NEW_USER_CALLBACK_URL);throw l.fromStatus("FORBIDDEN",{message:`Invalid ${f}`})}},c=Array.isArray(i)?i:[i];for(let u of c)s(u,"callbackURL")});async function zn(r,n=!1){let i=r.request?.headers;if(!i||!r.request)return;let s=i.get("origin"),c=s||i.get("referer")||"",u=i.has("cookie");if(r.context.skipCSRFCheck)return;if(du(r)){r.context.options.advanced?.disableOriginCheck===!0&&dm();return}if(ms(r))return;if(!(n||u))return;let f=s==="null"&&i.get("sec-fetch-site")==="same-origin"?_r(void 0,r.context.options.basePath,r.request,!1,r.context.options.advanced?.trustedProxyHeaders):void 0,m=(f?tn(f):void 0)??c;if(!m||m==="null")throw l.from("FORBIDDEN",x.MISSING_OR_NULL_ORIGIN);let h=Array.isArray(r.context.options.trustedOrigins)?r.context.trustedOrigins:[...r.context.trustedOrigins,...(await r.context.options.trustedOrigins?.(r.request))?.filter((y)=>Boolean(y))||[]];if(!h.some((y)=>Gc(m,y)))throw r.context.logger.error(`Invalid origin: ${m}`),r.context.logger.info(`If it's a valid URL, please add ${m} to trustedOrigins in your auth config
34
+ `,`Current list of trustedOrigins: ${h}`),l.from("FORBIDDEN",x.INVALID_ORIGIN)}var co=We(async(r)=>{if(!r.request)return;await lm(r)});async function lm(r){let n=r.request;if(!n)return;if(r.context.skipCSRFCheck)return;if(du(r))return;let i=n.headers;if(i.has("cookie"))return await zn(r);let s=i.get("Sec-Fetch-Site"),c=i.get("Sec-Fetch-Mode"),u=i.get("Sec-Fetch-Dest");if(Boolean(s&&s.trim()||c&&c.trim()||u&&u.trim())){if(s==="cross-site"&&c==="navigate")throw r.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:s,secFetchMode:c,secFetchDest:u}),l.from("FORBIDDEN",x.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await zn(r,!0)}if(i.get("origin")||i.get("referer"))return await zn(r,!0)}var Wt=new Map,fu=1e5;function fm(){let r=Date.now();for(let[s,c]of Wt)if(r>=c.expiresAt)Wt.delete(s);if(Wt.size<=fu)return;let n=Wt.size-fu,i=0;for(let s of Wt.keys())if(Wt.delete(s),++i>=n)break}function pm(r,n,i){let s=n.window*1000;if(!r)return{next:{key:"",count:1,lastRequest:i},update:!1,allowed:!0,retryAfter:null};if(i-r.lastRequest>=s)return{next:{...r,count:1,lastRequest:i},update:!0,allowed:!0,retryAfter:null};if(r.count>=n.max)return{next:r,update:!0,allowed:!1,retryAfter:mu(r.lastRequest,n.window)};return{next:{...r,count:r.count+1,lastRequest:i},update:!0,allowed:!0,retryAfter:null}}function mm(r){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":r.toString()}})}function mu(r,n){let i=Date.now(),s=n*1000;return Math.ceil((r+s-i)/1000)}function hm(r){let i=r.adapter,s=Math.max(...ym(r)),c=async(m)=>{let h=(await i.findMany({model:"rateLimit",where:[{field:"key",value:m}]}))[0];if(typeof h?.lastRequest==="bigint")h.lastRequest=Number(h.lastRequest);return h},u=async(m,h)=>{if(h.window>s)s=h.window;let y=h.window*1000,w=await c(m),g=Date.now();if(!w)try{return await i.create({model:"rateLimit",data:{key:m,count:1,lastRequest:g}}),{allowed:!0,retryAfter:null}}catch(v){if(!await c(m))throw v;return u(m,h)}if(g-w.lastRequest>=y){if(await i.incrementOne({model:"rateLimit",where:[{field:"key",value:m},{field:"lastRequest",operator:"lte",value:w.lastRequest}],increment:{},set:{count:1,lastRequest:g}}))return await f(g),{allowed:!0,retryAfter:null};return u(m,h)}let A=g-y;if(await i.incrementOne({model:"rateLimit",where:[{field:"key",value:m},{field:"lastRequest",operator:"gt",value:A},{field:"count",operator:"lt",value:h.max}],increment:{count:1},set:{lastRequest:g}}))return{allowed:!0,retryAfter:null};let E=await c(m);if(!E)return u(m,h);if(g-E.lastRequest>=y)return u(m,h);return{allowed:!1,retryAfter:mu(E.lastRequest,h.window)}},f=async(m)=>{let h=m-s*1000;await r.runInBackgroundOrAwait(i.deleteMany({model:"rateLimit",where:[{field:"lastRequest",operator:"lt",value:h}]}).then(()=>{return}).catch((y)=>r.logger.error("Error pruning rate limit rows",y)))};return{consume:u}}function ym(r){let n=[r.rateLimit.window,...yu().map((s)=>s.window)];for(let s of r.options.plugins||[])if(s.rateLimit)n.push(...s.rateLimit.map((c)=>c.window));if(r.rateLimit.customRules){for(let s of Object.values(r.rateLimit.customRules))if(s&&typeof s!=="function")n.push(s.window)}let i=n.filter((s)=>Number.isFinite(s)&&s>0);return i.length>0?i:[r.rateLimit.window]}function wm(r,n){if(r.options.rateLimit?.customStorage)return r.options.rateLimit.customStorage;let i=r.rateLimit.storage;if(i==="secondary-storage"){let s=(u)=>u??r.options.rateLimit?.window??10,c=r.options.secondaryStorage?.increment;if(!c)throw new S("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(u,f)=>{if(await c(u,s(f.window))<=f.max)return{allowed:!0,retryAfter:null};return{allowed:!1,retryAfter:f.window}}}}else if(i==="memory"){let s=(c)=>c??r.options.rateLimit?.window??10;return{async consume(c,u){fm();let f=Date.now(),m=Wt.get(c),h=pm(m&&f<m.expiresAt?m.data:void 0,u,f);if(h.allowed)Wt.set(c,{data:{...h.next,key:c},expiresAt:f+s(u.window)*1000});return{allowed:h.allowed,retryAfter:h.retryAfter}}}}return hm(r)}var pu=!1,gm="no-trusted-ip";async function Am(r,n){let i=new URL(n.baseURL).pathname,s=Lr(r.url,i),c=n.rateLimit.window,u=n.rateLimit.max,f=Oi(r,n.options);if(!f&&n.options.advanced?.ipAddress?.disableIpTracking)return null;if(!f&&!pu)n.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),pu=!0;let m=Aa(f??gm,s),h=yu().find((y)=>y.pathMatcher(s));if(h)c=h.window,u=h.max;for(let y of n.options.plugins||[])if(y.rateLimit){let w=y.rateLimit.find((g)=>g.pathMatcher(s));if(w){c=w.window,u=w.max;break}}if(n.rateLimit.customRules){let y=Object.keys(n.rateLimit.customRules).find((w)=>{if(w.includes("*"))return Jt(w)(s);return w===s});if(y){let w=n.rateLimit.customRules[y],g=typeof w==="function"?await w(r,{window:c,max:u}):w;if(g)c=g.window,u=g.max;if(g===!1)return null}}return{key:m,currentWindow:c,currentMax:u}}async function hu(r,n){if(!n.rateLimit.enabled)return;let i=await Am(r,n);if(!i)return;let{key:s,currentWindow:c,currentMax:u}=i,f=wm(n,{window:c}),m={window:c,max:u},{allowed:h,retryAfter:y}=await f.consume(s,m);if(!h)return mm(y??c)}function yu(){return[{pathMatcher(r){return r.startsWith("/sign-in")||r.startsWith("/sign-up")||r.startsWith("/change-password")||r.startsWith("/change-email")},window:10,max:3},{pathMatcher(r){return r==="/request-password-reset"||r==="/send-verification-email"||r.startsWith("/forget-password")||r==="/email-otp/send-verification-otp"||r==="/email-otp/request-password-reset"},window:60,max:3}]}var{get:JE,set:hs}=Or(()=>null);var{get:wu,set:GE}=Or(()=>null);var{get:ys,set:YE}=Or(()=>!1);var ws=()=>U("/get-session",{method:["GET","POST"],operationId:"getSession",query:Mc,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(r)=>{r.setHeader("cache-control","no-store"),r.setHeader("pragma","no-cache");let n=r.context.options.session?.deferSessionRefresh,i=r.method==="POST";if(i&&!n)throw l.from("METHOD_NOT_ALLOWED",x.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let s=r.context.options.session?.cookieCache?.enabled===!0,c=await r.getSignedCookie(r.context.authCookies.sessionToken.name,r.context.secret);if(!c&&s)return null;let u=On(r,r.context.authCookies.sessionData.name);if(u&&!s){let T=no(r.context.authCookies.sessionData.name,r.context.authCookies.sessionData.attributes,r);T.setCookies(T.clean())}if(!c)return null;let f=s&&!r.query?.disableCookieCache,m=f&&u?await qc(r,u):null;if(f&&u&&!m)Be(r,r.context.authCookies.sessionData);let h=await r.getSignedCookie(r.context.authCookies.dontRememberToken.name,r.context.secret);if(m?.session){let T=m.session,D=T.session.token!==c;if(!D){let k=r.context.options.session?.cookieCache?.version,R="1";if(k){if(typeof k==="string")R=k;else if(typeof k==="function"){let L=k(T.session,T.user);R=L instanceof Promise?await L:L}}D=(T.version||"1")!==R}if(!D){let k=Date.now(),R=new Date(T.session.expiresAt).getTime();D=m.expiresAt<k||!Number.isFinite(R)||R<k}if(D)Be(r,r.context.authCookies.sessionData);else{let k=r.context.sessionConfig.cookieRefreshCache;if(k===!1){r.context.session=T;let z=at(r.context.options,{...T.session,expiresAt:new Date(T.session.expiresAt),createdAt:new Date(T.session.createdAt),updatedAt:new Date(T.session.updatedAt)}),B=ke(r.context.options,{...T.user,createdAt:new Date(T.user.createdAt),updatedAt:new Date(T.user.updatedAt)});return r.json({session:z,user:B})}let R=m.expiresAt-Date.now(),L=k.updateAge*1000,M=await ys();if(R<L&&!M){let z={session:{...T.session},user:T.user,updatedAt:Date.now()};await io(r,z,!1);let B=r.context.authCookies.sessionToken.attributes,K=h?void 0:r.context.sessionConfig.expiresIn;await r.setSignedCookie(r.context.authCookies.sessionToken.name,T.session.token,r.context.secret,{...B,maxAge:K});let W=at(r.context.options,{...z.session,expiresAt:new Date(z.session.expiresAt),createdAt:new Date(z.session.createdAt),updatedAt:new Date(z.session.updatedAt)}),V=ke(r.context.options,{...z.user,createdAt:new Date(z.user.createdAt),updatedAt:new Date(z.user.updatedAt)});return r.context.session={session:W,user:V},r.json({session:W,user:V})}let N=at(r.context.options,{...T.session,expiresAt:new Date(T.session.expiresAt),createdAt:new Date(T.session.createdAt),updatedAt:new Date(T.session.updatedAt)}),H=ke(r.context.options,{...T.user,createdAt:new Date(T.user.createdAt),updatedAt:new Date(T.user.updatedAt)});return r.context.session={session:N,user:H},r.json({session:N,user:H})}}let y=await r.context.internalAdapter.findSession(c);if(r.context.session=y,!y||y.session.expiresAt<new Date){if(dr(r),y){if(!n||i)await r.context.internalAdapter.deleteSession(y.session.token)}return r.json(null)}if(h||r.query?.disableRefresh){let T=at(r.context.options,y.session),D=ke(r.context.options,y.user);return r.json({session:T,user:D})}let w=r.context.sessionConfig.expiresIn,g=r.context.sessionConfig.updateAge,A=y.session.expiresAt.valueOf()-w*1000+g*1000<=Date.now(),E=r.query?.disableRefresh||r.context.options.session?.disableSessionRefresh,v=await ys(),_=A&&!E&&!v;if(n&&!i){await io(r,y,!!h);let T=at(r.context.options,y.session),D=ke(r.context.options,y.user);return r.json({session:T,user:D,needsRefresh:_})}if(_){let T=await r.context.internalAdapter.updateSession(y.session.token,{expiresAt:bt(r.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!T)throw dr(r),l.from("UNAUTHORIZED",x.FAILED_TO_GET_SESSION);let D=r.context.sessionConfig.expiresIn;await Le(r,{session:T,user:y.user},!1,{maxAge:D});let k=at(r.context.options,T),R=ke(r.context.options,y.user);return r.json({session:k,user:R})}await io(r,y,!!h);let P=at(r.context.options,y.session),I=ke(r.context.options,y.user);return r.json({session:P,user:I})}catch(s){if(Oe(s))throw s;throw r.context.logger.error("INTERNAL_SERVER_ERROR",s),l.from("INTERNAL_SERVER_ERROR",x.FAILED_TO_GET_SESSION)}}),qt=(r)=>Kc(r.context.options),Ye=async(r,n)=>{if(r.context.session)return r.context.session;let i=await ws()({...r,method:"GET",asResponse:!1,headers:r.headers,returnHeaders:!0,returnStatus:!1,query:{...n,...r.query,disableCookieCache:n?.disableCookieCache||r.query?.disableCookieCache,disableRefresh:n?.disableRefresh||r.query?.disableRefresh}}).catch(()=>null);if(!i)return r.context.session=null,null;if(i.headers)i.headers.forEach((s,c)=>{let u=c.toLowerCase();if(u==="cache-control"||u==="pragma")return;if(u==="set-cookie")r.responseHeaders.append(c,s);else r.responseHeaders.set(c,s)});return r.context.session=i.response,i.response},gu=async(r)=>{if(!qt(r))return Ye(r);return r.context.session=null,Ye(r,{disableCookieCache:!0})},_t=We(async(r)=>{let n=await Ye(r);if(!n?.session)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:n}}),Qe=We(async(r)=>{let n=await gu(r);if(!n?.session)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:n}}),bm=We(async(r)=>{let n=await Ye(r);if(!n?.session&&(r.request||r.headers))throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:n}}),Ds=We(async(r)=>{let n=await Ye(r);if(!n?.session)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(r.context.sessionConfig.freshAge!==0){let i=new Date(n.session.createdAt).getTime(),s=r.context.sessionConfig.freshAge*1000;if(Date.now()-i>=s)throw l.from("FORBIDDEN",x.SESSION_NOT_FRESH)}return{session:n}}),Au=()=>U("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[Ds],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(r)=>{try{let n=(await r.context.internalAdapter.listSessions(r.context.session.user.id,{onlyActiveSessions:!0})).filter((i)=>i.expiresAt>new Date);return r.json(n.map((i)=>at(r.context.options,i)))}catch(n){throw r.context.logger.error(n),r.error("INTERNAL_SERVER_ERROR")}}),bu=U("/revoke-session",{method:"POST",body:t({token:e().meta({description:"The token to revoke"})}),use:[Qe],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(r)=>{let n=r.body.token;if((await r.context.internalAdapter.findSession(n))?.session.userId===r.context.session.user.id)try{await r.context.internalAdapter.deleteSession(n)}catch(i){throw r.context.logger.error(i&&typeof i==="object"&&"name"in i?i.name:"",i),l.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return r.json({status:!0})}),Eu=U("/revoke-sessions",{method:"POST",use:[Qe],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(r)=>{try{await r.context.internalAdapter.deleteUserSessions(r.context.session.user.id)}catch(n){throw r.context.logger.error(n&&typeof n==="object"&&"name"in n?n.name:"",n),l.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return r.json({status:!0})}),ku=U("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[Qe],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(r)=>{let n=r.context.session;if(!n.user)throw l.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let i=(await r.context.internalAdapter.listSessions(n.user.id)).filter((s)=>s.expiresAt>new Date).filter((s)=>s.token!==r.context.session.session.token);return await Promise.all(i.map((s)=>r.context.internalAdapter.deleteSession(s.token))),r.json({status:!0})});function $n(r){return r}async function gs(r,n,i){let s={tokens:n,profile:i},c=r.accountSubject,u=await c(s),f=String(u);if(typeof u==="number"&&!Number.isFinite(u)||f.trim().length===0||f==="undefined"||f==="null")throw new S("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:r.id,accountId:f}}async function jn(r,n,i){try{return await gs(r,n,i)}catch{throw l.from("UNAUTHORIZED",x.FAILED_TO_GET_USER_INFO)}}var Ae={NO_CODE:"no_code",PROVIDER_NOT_FOUND:"oauth_provider_not_found",ISSUER_MISSING:"issuer_missing",ISSUER_MISMATCH:"issuer_mismatch",INVALID_CODE:"invalid_code",NONCE_BINDING_MISSING:"nonce_binding_missing",UNABLE_TO_GET_USER_INFO:"unable_to_get_user_info",NO_CALLBACK_URL:"no_callback_url",UNABLE_TO_LINK_ACCOUNT:"unable_to_link_account",EMAIL_DOES_NOT_MATCH:"email_does_not_match",ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:"account_already_linked_to_different_user",EMAIL_NOT_FOUND:"email_not_found",EMAIL_NOT_VERIFIED:"email_not_verified"},Em="https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email";function lo(r,n,i,s){let c=new URLSearchParams({error:i});if(s)c.set("error_description",s);let u=ct(n,c);throw r.redirect(u)}function Dr(r,n){return`${n?.source==="generic"?`Generic OAuth provider "${r}"`:`Provider "${r}"`} did not return an email${n?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See ${Em}`}var Vt=li("a-z","0-9","A-Z","-_");/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function As(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Hn=(r)=>r?`"${r}" `:"";function Bn(r,n=""){if(typeof r!=="boolean")throw TypeError(Hn(n)+"expected boolean, got type="+typeof r);return r}function kt(r,n=""){if(typeof r!=="number")throw TypeError(Hn(n)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw RangeError(Hn(n)+"expected integer >= 0, got "+r);return r}function le(r,n,i=""){if(As(r)&&(n===void 0||r.length===n))return r;if(n!==void 0)kt(n,"length");let s=As(r),c=n!==void 0?` of length ${n}`:"",u=s?`length=${r.length}`:`type=${typeof r}`,f=Hn(i)+"expected Uint8Array"+c+", got "+u;if(!s)throw TypeError(f);throw RangeError(f)}var Su=(r,n)=>{if(r===null||typeof r!=="object"||Array.isArray(r))throw TypeError(n==="object"?"expected valid options object":`"${n}" expected object, got type=${typeof r}`)};function ks(r,n=!0){if(r.destroyed)throw Error("hash was destroyed");if(n&&r.finished)throw Error("digest() was already called")}function Tu(r,n){le(r,void 0,"output");let i=n.outputLen;if(!(r.length>=i))throw RangeError('"output" expected length >= '+i)}function ut(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ne(...r){for(let n=0;n<r.length;n++)r[n].fill(0)}function km(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var Me=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Sm(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function vm(r){for(let n=0;n<r.length;n++)r[n]=Sm(r[n]);return r}var ze=Me?(r)=>r:vm,Ru=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Tm=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));function Iu(r){if(le(r),Ru)return r.toHex();let n="";for(let i=0;i<r.length;i++)n+=Tm[r[i]];return n}function vu(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function _u(r){if(typeof r!=="string")throw TypeError("hex string expected, got "+typeof r);if(Ru)try{return Uint8Array.fromHex(r)}catch(c){if(c instanceof SyntaxError)throw RangeError(c.message);throw c}let n=r.length,i=n/2;if(n%2)throw RangeError("hex string expected, got unpadded hex of length "+n);let s=new Uint8Array(i);for(let c=0,u=0;c<i;c++,u+=2){let f=vu(r.charCodeAt(u)),m=vu(r.charCodeAt(u+1));if(f===void 0||m===void 0){let h=r[u]+r[u+1];throw RangeError('hex string expected, got non-hex character "'+h+'" at index '+u)}s[c]=f*16+m}return s}function Uu(r){if(typeof r!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Cu(r,n){if(!r.byteLength||!n.byteLength)return!1;return r.buffer===n.buffer&&r.byteOffset<n.byteOffset+n.byteLength&&n.byteOffset<r.byteOffset+r.byteLength}function xu(r,n){if(Cu(r,n)&&r.byteOffset<n.byteOffset)throw Error("complex overlap of input and output is not supported")}function Rm(...r){let n=0;for(let s=0;s<r.length;s++){let c=r[s];le(c),n+=c.length}let i=new Uint8Array(n);for(let s=0,c=0;s<r.length;s++){let u=r[s];i.set(u,c),c+=u.length}return i}function Ou(r,n){return Su(r,"defaults"),Su(n,"opts"),Object.assign(r,n)}function Lu(r,n){if(r=le(r),n=le(n),r.length!==n.length)return!1;let i=0;for(let s=0;s<r.length;s++)i|=r[s]^n[s];return i===0}function Du(r,n,i){let s=n,c=i||(()=>[]),u=(m,h)=>s(h,...c(m)).update(m).digest(),f=s(new Uint8Array(r),...c(new Uint8Array(0)));return u.outputLen=f.outputLen,u.blockLen=f.blockLen,u.create=(m,...h)=>s(m,...h),u}var Pu=(r,n)=>{function i(s,...c){if(le(s,void 0,"key"),r.nonceLength!==void 0){let g=c[0];le(g,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let u=r.tagLength,f=r.nonceLength!==void 0?1:0;if(!r.withAAD){for(let g=f;g<c.length;g++)if(As(c[g]))throw Error("AAD not supported")}if(r.withAAD&&c[f]!==void 0)le(c[f],void 0,"AAD");let m=n(s,...c),h=(g,A)=>{if(A!==void 0){if(g!==2)throw Error("cipher output not supported");le(A,void 0,"output")}},y=!1;return{encrypt(g,A){if(y)throw Error("cannot encrypt() twice with same key + nonce");return y=!0,le(g,void 0,"data"),h(m.encrypt.length,A),m.encrypt(g,A)},decrypt(g,A){if(le(g,void 0,"data"),u&&g.length<u)throw Error('"ciphertext" expected length >= tagLength='+u);return h(m.decrypt.length,A),m.decrypt(g,A)}}}return Object.assign(i,r),i};function yo(r,n,i=!0){if(n===void 0)return new Uint8Array(r);if(le(n,r,"output"),i&&!wo(n))throw Error("invalid output, must be aligned");return n}function Nu(r,n,i){kt(r),kt(n),Bn(i);let s=new Uint8Array(16),c=km(s);return c.setBigUint64(0,BigInt(n),i),c.setBigUint64(8,BigInt(r),i),s}function wo(r){return r.byteOffset%4===0}function Pr(r){return Uint8Array.from(le(r))}function zu(r=32){kt(r,"bytesLength");let n=typeof globalThis==="object"?globalThis.crypto:null;if(typeof n?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(r>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${r}`);return n.getRandomValues(new Uint8Array(r))}function Ss(r,n=zu){if(typeof r!=="function")throw TypeError('"fn" expected cipher constructor, got type='+typeof r);if(typeof n!=="function")throw TypeError('"randomBytes_" expected function, got type='+typeof n);let{nonceLength:i}=r;kt(i,"fn.nonceLength");let s=(u,f,m)=>{let h=Rm(u,f);if(!Cu(m,f))f.fill(0);return h},c=(u,...f)=>({encrypt(m){le(m,void 0,"data");let h=n(i),y=r(u,h,...f).encrypt(m);if(y instanceof Promise)return y.then((w)=>s(h,w,m));return s(h,y,m)},decrypt(m){le(m,void 0,"data");let h=m.subarray(0,i),y=m.subarray(i);return r(u,h,...f).decrypt(y)}});if("blockSize"in r)c.blockSize=r.blockSize;if("tagLength"in r)c.tagLength=r.tagLength;if("withAAD"in r)c.withAAD=r.withAAD;return c}var ju=(r)=>Uint8Array.from(r.split(""),(n)=>n.charCodeAt(0)),Im=(()=>ze(ut(ju("expand 16-byte k"))))(),_m=(()=>ze(ut(ju("expand 32-byte k"))))();function oe(r,n){return r<<n|r>>>32-n}var go=64,Um=16,Ts=(()=>4294967295)(),$u=Uint32Array.of();function Cm(r,n,i,s,c,u,f,m){let h=c.length,y=new Uint8Array(go),w=ut(y),g=Me&&wo(c)&&wo(u),A=g?ut(c):$u,E=g?ut(u):$u;if(!Me){for(let v=0;v<h;f++){if(r(n,i,s,w,f,m),ze(w),f>=Ts)throw Error("arx: counter overflow");let _=Math.min(go,h-v);for(let P=0,I;P<_;P++)I=v+P,u[I]=c[I]^y[P];v+=_}return}for(let v=0;v<h;f++){if(r(n,i,s,w,f,m),f>=Ts)throw Error("arx: counter overflow");let _=Math.min(go,h-v);if(g&&_===go){let P=v/4;if(v%4!==0)throw Error("arx: invalid block position");for(let I=0,T;I<Um;I++)T=P+I,E[T]=A[T]^w[I];v+=go;continue}for(let P=0,I;P<_;P++)I=v+P,u[I]=c[I]^y[P];v+=_}}function Hu(r,n){let{allowShortKeys:i,extendNonceFn:s,counterLength:c,counterRight:u,rounds:f}=Ou({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},n);if(typeof r!=="function")throw Error("core must be a function");return kt(c),kt(f),Bn(u),Bn(i),(m,h,y,w,g=0)=>{le(m,void 0,"key"),le(h,void 0,"nonce"),le(y,void 0,"data");let A=y.length,E=w!==void 0;if(w=yo(A,w,!1),E)xu(y,w);if(kt(g),g<0||g>=Ts)throw Error("arx: counter overflow");let v=[],_=m.length,P,I;if(_===32)v.push(P=Pr(m)),I=_m;else if(_===16&&i)P=new Uint8Array(32),P.set(m),P.set(m,16),I=Im,v.push(P);else throw le(m,32,"arx key"),Error("invalid key size");if(!Me||!wo(h))v.push(h=Pr(h));let T=ut(P);if(s){if(h.length!==24)throw Error("arx: extended nonce must be 24 bytes");let R=h.subarray(0,16);if(Me)s(I,T,ut(R),T);else{let L=ze(Uint32Array.from(I));s(L,T,ut(R),T),Ne(L),ze(T)}h=h.subarray(16)}else if(!Me)ze(T);let D=16-c;if(D!==h.length)throw Error(`arx: nonce must be ${D} or 16 bytes`);if(D!==12){let R=new Uint8Array(12);R.set(h,u?0:12-h.length),h=R,v.push(h)}let k=ze(ut(h));try{return Cm(r,I,T,k,y,w,g,f),w}finally{Ne(...v)}}}function Se(r,n){return r[n++]&255|(r[n++]&255)<<8}class Bu{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(r){r=Pr(le(r,32,"key"));let n=Se(r,0),i=Se(r,2),s=Se(r,4),c=Se(r,6),u=Se(r,8),f=Se(r,10),m=Se(r,12),h=Se(r,14);this.r[0]=n&8191,this.r[1]=(n>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|c<<9)&8191,this.r[4]=(c>>>4|u<<12)&255,this.r[5]=u>>>1&8190,this.r[6]=(u>>>14|f<<2)&8191,this.r[7]=(f>>>11|m<<5)&8065,this.r[8]=(m>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let y=0;y<8;y++)this.pad[y]=Se(r,16+2*y)}process(r,n,i=!1){let s=i?0:2048,{h:c,r:u}=this,f=u[0],m=u[1],h=u[2],y=u[3],w=u[4],g=u[5],A=u[6],E=u[7],v=u[8],_=u[9],P=Se(r,n+0),I=Se(r,n+2),T=Se(r,n+4),D=Se(r,n+6),k=Se(r,n+8),R=Se(r,n+10),L=Se(r,n+12),M=Se(r,n+14),N=c[0]+(P&8191),H=c[1]+((P>>>13|I<<3)&8191),z=c[2]+((I>>>10|T<<6)&8191),B=c[3]+((T>>>7|D<<9)&8191),K=c[4]+((D>>>4|k<<12)&8191),W=c[5]+(k>>>1&8191),V=c[6]+((k>>>14|R<<2)&8191),J=c[7]+((R>>>11|L<<5)&8191),X=c[8]+((L>>>8|M<<8)&8191),te=c[9]+(M>>>5|s),q=0,re=q+N*f+H*(5*_)+z*(5*v)+B*(5*E)+K*(5*A);q=re>>>13,re&=8191,re+=W*(5*g)+V*(5*w)+J*(5*y)+X*(5*h)+te*(5*m),q+=re>>>13,re&=8191;let ie=q+N*m+H*f+z*(5*_)+B*(5*v)+K*(5*E);q=ie>>>13,ie&=8191,ie+=W*(5*A)+V*(5*g)+J*(5*w)+X*(5*y)+te*(5*h),q+=ie>>>13,ie&=8191;let se=q+N*h+H*m+z*f+B*(5*_)+K*(5*v);q=se>>>13,se&=8191,se+=W*(5*E)+V*(5*A)+J*(5*g)+X*(5*w)+te*(5*y),q+=se>>>13,se&=8191;let ce=q+N*y+H*h+z*m+B*f+K*(5*_);q=ce>>>13,ce&=8191,ce+=W*(5*v)+V*(5*E)+J*(5*A)+X*(5*g)+te*(5*w),q+=ce>>>13,ce&=8191;let $e=q+N*w+H*y+z*h+B*m+K*f;q=$e>>>13,$e&=8191,$e+=W*(5*_)+V*(5*v)+J*(5*E)+X*(5*A)+te*(5*g),q+=$e>>>13,$e&=8191;let St=q+N*g+H*w+z*y+B*h+K*m;q=St>>>13,St&=8191,St+=W*f+V*(5*_)+J*(5*v)+X*(5*E)+te*(5*A),q+=St>>>13,St&=8191;let lt=q+N*A+H*g+z*w+B*y+K*h;q=lt>>>13,lt&=8191,lt+=W*m+V*f+J*(5*_)+X*(5*v)+te*(5*E),q+=lt>>>13,lt&=8191;let Ke=q+N*E+H*A+z*g+B*w+K*y;q=Ke>>>13,Ke&=8191,Ke+=W*h+V*m+J*f+X*(5*_)+te*(5*v),q+=Ke>>>13,Ke&=8191;let vt=q+N*v+H*E+z*A+B*g+K*w;q=vt>>>13,vt&=8191,vt+=W*y+V*h+J*m+X*f+te*(5*_),q+=vt>>>13,vt&=8191;let lr=q+N*_+H*v+z*E+B*A+K*g;q=lr>>>13,lr&=8191,lr+=W*w+V*y+J*h+X*m+te*f,q+=lr>>>13,lr&=8191,q=(q<<2)+q|0,q=q+re|0,re=q&8191,q=q>>>13,ie+=q,c[0]=re,c[1]=ie,c[2]=se,c[3]=ce,c[4]=$e,c[5]=St,c[6]=lt,c[7]=Ke,c[8]=vt,c[9]=lr}finalize(){let{h:r,pad:n}=this,i=new Uint16Array(10),s=r[1]>>>13;r[1]&=8191;for(let f=2;f<10;f++)r[f]+=s,s=r[f]>>>13,r[f]&=8191;r[0]+=s*5,s=r[0]>>>13,r[0]&=8191,r[1]+=s,s=r[1]>>>13,r[1]&=8191,r[2]+=s,i[0]=r[0]+5,s=i[0]>>>13,i[0]&=8191;for(let f=1;f<10;f++)i[f]=r[f]+s,s=i[f]>>>13,i[f]&=8191;i[9]-=8192;let c=(s^1)-1;for(let f=0;f<10;f++)i[f]&=c;c=~c;for(let f=0;f<10;f++)r[f]=r[f]&c|i[f];r[0]=(r[0]|r[1]<<13)&65535,r[1]=(r[1]>>>3|r[2]<<10)&65535,r[2]=(r[2]>>>6|r[3]<<7)&65535,r[3]=(r[3]>>>9|r[4]<<4)&65535,r[4]=(r[4]>>>12|r[5]<<1|r[6]<<14)&65535,r[5]=(r[6]>>>2|r[7]<<11)&65535,r[6]=(r[7]>>>5|r[8]<<8)&65535,r[7]=(r[8]>>>8|r[9]<<5)&65535;let u=r[0]+n[0];r[0]=u&65535;for(let f=1;f<8;f++)u=(r[f]+n[f]|0)+(u>>>16)|0,r[f]=u&65535;Ne(i)}update(r){ks(this),le(r),r=Pr(r);let{buffer:n,blockLen:i}=this,s=r.length;for(let c=0;c<s;){let u=Math.min(i-this.pos,s-c);if(u===i){for(;i<=s-c;c+=i)this.process(r,c);continue}if(n.set(r.subarray(c,c+u),this.pos),this.pos+=u,c+=u,this.pos===i)this.process(n,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,Ne(this.h,this.r,this.buffer,this.pad)}digestInto(r){ks(this),Tu(r,this),this.finished=!0;let{buffer:n,h:i}=this,{pos:s}=this;if(s){n[s++]=1;for(;s<16;s++)n[s]=0;this.process(n,0,!0)}this.finalize();let c=0;for(let u=0;u<8;u++)r[c++]=i[u]>>>0,r[c++]=i[u]>>>8}digest(){let{buffer:r,outputLen:n}=this;this.digestInto(r);let i=r.slice(0,n);return this.destroy(),i}}var Mu=Du(32,(r)=>new Bu(r));function Vu(r,n,i,s,c,u=20){let f=r[0],m=r[1],h=r[2],y=r[3],w=n[0],g=n[1],A=n[2],E=n[3],v=n[4],_=n[5],P=n[6],I=n[7],T=c,D=i[0],k=i[1],R=i[2],L=f,M=m,N=h,H=y,z=w,B=g,K=A,W=E,V=v,J=_,X=P,te=I,q=T,re=D,ie=k,se=R;for(let $e=0;$e<u;$e+=2)L=L+z|0,q=oe(q^L,16),V=V+q|0,z=oe(z^V,12),L=L+z|0,q=oe(q^L,8),V=V+q|0,z=oe(z^V,7),M=M+B|0,re=oe(re^M,16),J=J+re|0,B=oe(B^J,12),M=M+B|0,re=oe(re^M,8),J=J+re|0,B=oe(B^J,7),N=N+K|0,ie=oe(ie^N,16),X=X+ie|0,K=oe(K^X,12),N=N+K|0,ie=oe(ie^N,8),X=X+ie|0,K=oe(K^X,7),H=H+W|0,se=oe(se^H,16),te=te+se|0,W=oe(W^te,12),H=H+W|0,se=oe(se^H,8),te=te+se|0,W=oe(W^te,7),L=L+B|0,se=oe(se^L,16),X=X+se|0,B=oe(B^X,12),L=L+B|0,se=oe(se^L,8),X=X+se|0,B=oe(B^X,7),M=M+K|0,q=oe(q^M,16),te=te+q|0,K=oe(K^te,12),M=M+K|0,q=oe(q^M,8),te=te+q|0,K=oe(K^te,7),N=N+W|0,re=oe(re^N,16),V=V+re|0,W=oe(W^V,12),N=N+W|0,re=oe(re^N,8),V=V+re|0,W=oe(W^V,7),H=H+z|0,ie=oe(ie^H,16),J=J+ie|0,z=oe(z^J,12),H=H+z|0,ie=oe(ie^H,8),J=J+ie|0,z=oe(z^J,7);let ce=0;s[ce++]=f+L|0,s[ce++]=m+M|0,s[ce++]=h+N|0,s[ce++]=y+H|0,s[ce++]=w+z|0,s[ce++]=g+B|0,s[ce++]=A+K|0,s[ce++]=E+W|0,s[ce++]=v+V|0,s[ce++]=_+J|0,s[ce++]=P+X|0,s[ce++]=I+te|0,s[ce++]=T+q|0,s[ce++]=D+re|0,s[ce++]=k+ie|0,s[ce++]=R+se|0}function xm(r,n,i,s){let c=Me?r:ze(r.slice(0,4)),u=Me?n:ze(n.slice(0,8)),f=Me?i:ze(i.slice(0,4)),m=new Uint32Array(16);Vu(c,u,f.subarray(1),m,f[0]);let h=0;if(s[h++]=m[0]-c[0]|0,s[h++]=m[1]-c[1]|0,s[h++]=m[2]-c[2]|0,s[h++]=m[3]-c[3]|0,s[h++]=m[12]-f[0]|0,s[h++]=m[13]-f[1]|0,s[h++]=m[14]-f[2]|0,s[h++]=m[15]-f[3]|0,ze(s),!Me)Ne(c,u,f);Ne(m)}var Om=Hu(Vu,{counterRight:!1,counterLength:8,extendNonceFn:xm,allowShortKeys:!1});var Lm=new Uint8Array(16),Ku=(r,n)=>{r.update(n);let i=n.length%16;if(i)r.update(Lm.subarray(i))},Dm=new Uint8Array(32);function Wu(r,n,i,s,c){if(c!==void 0)le(c,void 0,"AAD");let u=r(n,i,Dm),f=Nu(s.length,c?c.length:0,!0),m=Mu.create(u);if(c)Ku(m,c);Ku(m,s),m.update(f);let h=m.digest();return Ne(u,f),h}var Pm=(r)=>(n,i,s)=>({encrypt(u,f){let m=u.length;f=yo(m+16,f,!1),f.set(u);let h=f.subarray(0,-16);r(n,i,h,h,1);let y=Wu(r,n,i,h,s);return f.set(y,m),Ne(y),f},decrypt(u,f){f=yo(u.length-16,f,!1);let m=u.subarray(0,-16),h=u.subarray(-16),y=Wu(r,n,i,m,s);if(!Lu(h,y))throw Ne(y),Error("invalid tag");return f.set(u.subarray(0,-16)),r(n,i,f,f,1),Ne(y),f}});var Qo=Pu({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},Pm(Om));var Fu="$ba$";function Nm(r){if(!r.startsWith(Fu))return null;let n=4,i=r.indexOf("$",n);if(i===-1)return null;let s=parseInt(r.slice(n,i),10);if(!Number.isInteger(s)||s<0)return null;return{version:s,ciphertext:r.slice(i+1)}}function zm(r,n){return`${Fu}${r}$${n}`}async function qu(r,n){let i=await Er("SHA-256").digest(r),s=Uu(n);return Iu(Ss(Qo)(new Uint8Array(i)).encrypt(s))}async function Rs(r,n){let i=await Er("SHA-256").digest(r),s=_u(n),c=Ss(Qo)(new Uint8Array(i));return new TextDecoder().decode(c.decrypt(s))}var Mn=async({key:r,data:n})=>{if(typeof r==="string")return qu(r,n);let i=r.keys.get(r.currentVersion);if(!i)throw Error(`Secret version ${r.currentVersion} not found in keys`);let s=await qu(i,n);return zm(r.currentVersion,s)},Kn=async({key:r,data:n})=>{if(typeof r==="string")return Rs(r,n);let i=Nm(n);if(i){let s=r.keys.get(i.version);if(!s)throw Error(`Secret version ${i.version} not found in keys (key may have been retired)`);return Rs(s,i.ciphertext)}if(r.legacySecret)return Rs(r.legacySecret,n);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")};function $m(r){if(r.startsWith("$ba$"))return!0;return r.length%2===0&&/^[0-9a-f]+$/i.test(r)}function Wn(r,n){if(!r)return r;if(n.options.account?.encryptOAuthTokens){if(!$m(r))return r;return Kn({key:n.secretConfig,data:r})}return r}function ye(r,n){if(n.options.account?.encryptOAuthTokens&&r)return Mn({key:n.secretConfig,data:r});return r}function sr(r){if(!r.callbackPath)return`/callback/${r.id}`;return r.callbackPath.startsWith("/")?r.callbackPath:`/${r.callbackPath}`}function Ft(r){if(!r)return;try{return r.clone()}catch{return new Request(r.url,{cache:r.cache,credentials:r.credentials,headers:r.headers,integrity:r.integrity,keepalive:r.keepalive,method:r.method,mode:r.mode,redirect:r.redirect,referrer:r.referrer,referrerPolicy:r.referrerPolicy,signal:r.signal})}}async function Te(r,n,i,s=3600,c){return await Tn({email:n.toLowerCase(),updateTo:i?.toLowerCase(),...c},r,s)}async function Is(r,n){if(!r.context.options.emailVerification?.sendVerificationEmail)throw r.context.logger.error("Verification email isn't enabled."),l.from("BAD_REQUEST",x.VERIFICATION_EMAIL_NOT_ENABLED);let i=await Te(r.context.secret,n.email,void 0,r.context.options.emailVerification?.expiresIn),s=r.body.callbackURL?encodeURIComponent(r.body.callbackURL):encodeURIComponent("/"),c=`${r.context.baseURL}/verify-email?token=${i}&callbackURL=${s}`;await r.context.options.emailVerification.sendVerificationEmail({user:n,url:c,token:i},r.request)}var Ju=U("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:t({email:je().meta({description:"The email to send the verification email to"}),callbackURL:e().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(r)=>{if(!r.context.options.emailVerification?.sendVerificationEmail)throw r.context.logger.error("Verification email isn't enabled."),l.from("BAD_REQUEST",x.VERIFICATION_EMAIL_NOT_ENABLED);let{email:n}=r.body,i=await Ye(r);if(!i){let c=Date.now(),u=await r.context.internalAdapter.findUserByEmail(n),f;if(!u||u.user.emailVerified)await Te(r.context.secret,n,void 0,r.context.options.emailVerification?.expiresIn);else try{await Is(r,u.user)}catch(h){f=h}let m=500-(Date.now()-c);if(m>0)await new Promise((h)=>setTimeout(h,m));if(f)throw f;return r.json({status:!0})}if(i?.user.email.toLowerCase()!==n.toLowerCase())throw l.from("BAD_REQUEST",x.EMAIL_MISMATCH);if(i?.user.emailVerified)throw l.from("BAD_REQUEST",x.EMAIL_ALREADY_VERIFIED);return await Is(r,i.user),r.json({status:!0})}),Gu=U("/verify-email",{method:"GET",operationId:"verifyEmail",query:t({token:e().meta({description:"The token to verify the email"}),callbackURL:e().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[Kt((r)=>r.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(r)=>{function n(m){if(r.query.callbackURL){let h=new URLSearchParams({error:m.code}),y=ct(r.query.callbackURL,h);throw r.redirect(y)}throw l.from("UNAUTHORIZED",m)}let{token:i}=r.query,s;try{s=await Mt(i,new TextEncoder().encode(r.context.secret),{algorithms:["HS256"]})}catch(m){if(m instanceof yr)return n(x.TOKEN_EXPIRED);return n(x.INVALID_TOKEN)}let c=t({email:je(),updateTo:e().optional(),requestType:e().optional()}).parse(s.payload),u=await r.context.internalAdapter.findUserByEmail(c.email);if(!u)return n(x.USER_NOT_FOUND);if(c.updateTo){let m=await Ye(r);if(m&&m.user.email!==c.email)return n(x.INVALID_USER);switch(c.requestType){case"change-email-confirmation":{let h=await Te(r.context.secret,c.email,c.updateTo,r.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),y=r.query.callbackURL?encodeURIComponent(r.query.callbackURL):encodeURIComponent("/"),w=`${r.context.baseURL}/verify-email?token=${h}&callbackURL=${y}`;if(r.context.options.emailVerification?.sendVerificationEmail)await r.context.runInBackgroundOrAwait(r.context.options.emailVerification.sendVerificationEmail({user:{...u.user,email:c.updateTo},url:w,token:h},Ft(r.request)));if(r.query.callbackURL)throw r.redirect(r.query.callbackURL);return r.json({status:!0})}case"change-email-verification":{let h=m;if(!h){let w=await r.context.internalAdapter.createSession(u.user.id);if(!w)throw l.from("INTERNAL_SERVER_ERROR",x.FAILED_TO_CREATE_SESSION);h={session:w,user:u.user}}let y=await r.context.internalAdapter.updateUserByEmail(c.email,{email:c.updateTo,emailVerified:!0});if(r.context.options.emailVerification?.afterEmailVerification)await r.context.options.emailVerification.afterEmailVerification(y,r.request);if(await Le(r,{session:h.session,user:{...h.user,email:c.updateTo,emailVerified:!0}}),r.query.callbackURL)throw r.redirect(r.query.callbackURL);return r.json({status:!0,user:ke(r.context.options,y)})}default:{let h=m;if(!h){let A=await r.context.internalAdapter.createSession(u.user.id);if(!A)throw l.from("INTERNAL_SERVER_ERROR",x.FAILED_TO_CREATE_SESSION);h={session:A,user:u.user}}let y=await r.context.internalAdapter.updateUserByEmail(c.email,{email:c.updateTo,emailVerified:!1}),w=await Te(r.context.secret,c.updateTo),g=r.query.callbackURL?encodeURIComponent(r.query.callbackURL):encodeURIComponent("/");if(r.context.options.emailVerification?.sendVerificationEmail)await r.context.runInBackgroundOrAwait(r.context.options.emailVerification.sendVerificationEmail({user:y,url:`${r.context.baseURL}/verify-email?token=${w}&callbackURL=${g}`,token:w},Ft(r.request)));if(await Le(r,{session:h.session,user:{...h.user,email:c.updateTo,emailVerified:!1}}),r.query.callbackURL)throw r.redirect(r.query.callbackURL);return r.json({status:!0,user:ke(r.context.options,y)})}}}if(u.user.emailVerified){if(r.query.callbackURL)throw r.redirect(r.query.callbackURL);return r.json({status:!0,user:null})}if(r.context.options.emailVerification?.beforeEmailVerification)await r.context.options.emailVerification.beforeEmailVerification(u.user,r.request);let f=await r.context.internalAdapter.updateUserByEmail(c.email,{emailVerified:!0});if(r.context.options.emailVerification?.afterEmailVerification)await r.context.options.emailVerification.afterEmailVerification(f,r.request);if(r.context.options.emailVerification?.autoSignInAfterVerification){let m=await Ye(r);if(!m||m.user.email!==c.email){let h=await r.context.internalAdapter.createSession(u.user.id);if(!h)throw l.from("INTERNAL_SERVER_ERROR",x.FAILED_TO_CREATE_SESSION);await Le(r,{session:h,user:{...u.user,emailVerified:!0}})}else await Le(r,{session:m.session,user:{...m.user,emailVerified:!0}})}if(r.query.callbackURL)throw r.redirect(r.query.callbackURL);return r.json({status:!0,user:null})});function Us(r){if(Array.isArray(r))return r.map((n)=>typeof n==="string"?n.trim():"").filter(Boolean);if(typeof r==="string")return r.trim().split(/\s+/).filter(Boolean);return[]}function Ao(r){let n=(i)=>new Date(new Date().getTime()+i*1000);return{tokenType:r.token_type,accessToken:r.access_token,refreshToken:r.refresh_token,accessTokenExpiresAt:r.expires_in?n(r.expires_in):void 0,refreshTokenExpiresAt:r.refresh_token_expires_in?n(r.refresh_token_expires_in):void 0,scopes:Us(r.scope),idToken:r.id_token,raw:r}}function Cs(r,n){let i=r?r.split(",").map((c)=>c.trim()).filter(Boolean):[],s=(n??[]).map((c)=>c.trim()).filter(Boolean);return[...new Set([...i,...s])].join(",")}function Re(r){let n=Array.isArray(r)?r[0]:r;return typeof n==="string"&&n.length>0?n:void 0}async function xs(r){let n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return xt.encode(new Uint8Array(i),{padding:!1})}var Os=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],ar=new Set(Os);async function G({id:r,options:n,authorizationEndpoint:i,state:s,codeVerifier:c,scopes:u,claims:f,redirectURI:m,duration:h,prompt:y,accessType:w,responseType:g,display:A,loginHint:E,nonce:v,hd:_,responseMode:P,additionalParams:I,scopeJoiner:T}){n=typeof n==="function"?await n():n;let D=new URL(n.authorizationEndpoint||i);D.searchParams.set("response_type",g||"code");let k=Re(n.clientId);if(!k)throw Error("OAuth provider requires clientId");if(D.searchParams.set("client_id",k),D.searchParams.set("state",s),u?.length)D.searchParams.set("scope",u.join(T||" "));if(D.searchParams.set("redirect_uri",n.redirectURI||m),h&&D.searchParams.set("duration",h),A&&D.searchParams.set("display",A),E&&D.searchParams.set("login_hint",E),v&&D.searchParams.set("nonce",v),y&&D.searchParams.set("prompt",y),_&&D.searchParams.set("hd",_),w&&D.searchParams.set("access_type",w),P&&D.searchParams.set("response_mode",P),c){let R=await xs(c);D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("code_challenge",R)}if(f){let R=f.reduce((L,M)=>(L[M]=null,L),{});D.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...R}}))}if(I)for(let[R,L]of Object.entries(I)){if(ar.has(R))continue;D.searchParams.set(R,L)}return D}var bo=j(e(),e()).refine((r)=>!Object.keys(r).some((n)=>ar.has(n)),{message:`additionalParams cannot include reserved OAuth parameters: ${Os.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional();function Qu(r){return new URLSearchParams({v:r}).toString().slice(2)}function Zu(r,n){let i=`${Qu(r)}:${Qu(n)}`;return`Basic ${Dt.encode(i)}`}var jm="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";async function Yu({getClientAssertion:r,context:n}){return{client_assertion:await r(n),client_assertion_type:jm}}var Hm=class extends Error{constructor(r,n,i){super(n||r.toString(),{cause:i});this.status=r,this.statusText=n,this.error=i,Error.captureStackTrace(this,this.constructor)}},Bm=async(r,n)=>{let i=n||{},s={onRequest:[n===null||n===void 0?void 0:n.onRequest],onResponse:[n===null||n===void 0?void 0:n.onResponse],onSuccess:[n===null||n===void 0?void 0:n.onSuccess],onError:[n===null||n===void 0?void 0:n.onError],onRetry:[n===null||n===void 0?void 0:n.onRetry]};if(!n||!(n===null||n===void 0?void 0:n.plugins))return{url:r,options:i,hooks:s};for(let w of(n===null||n===void 0?void 0:n.plugins)||[]){var c,u,f,m,h;if(w.init){var y;let g=await((y=w.init)===null||y===void 0?void 0:y.call(w,r.toString(),i));i=g.options||i,r=g.url}s.onRequest.push((c=w.hooks)===null||c===void 0?void 0:c.onRequest),s.onResponse.push((u=w.hooks)===null||u===void 0?void 0:u.onResponse),s.onSuccess.push((f=w.hooks)===null||f===void 0?void 0:f.onSuccess),s.onError.push((m=w.hooks)===null||m===void 0?void 0:m.onError),s.onRetry.push((h=w.hooks)===null||h===void 0?void 0:h.onRetry)}return{url:r,options:i,hooks:s}},Xu=class{constructor(r){this.options=r}shouldAttemptRetry(r,n){if(this.options.shouldRetry)return Promise.resolve(r<this.options.attempts&&this.options.shouldRetry(n));return Promise.resolve(r<this.options.attempts)}getDelay(){return this.options.delay}},Mm=class{constructor(r){this.options=r}shouldAttemptRetry(r,n){if(this.options.shouldRetry)return Promise.resolve(r<this.options.attempts&&this.options.shouldRetry(n));return Promise.resolve(r<this.options.attempts)}getDelay(r){return Math.min(this.options.maxDelay,this.options.baseDelay*2**r)}};function Km(r){if(typeof r==="number")return new Xu({type:"linear",attempts:r,delay:1000});switch(r.type){case"linear":return new Xu(r);case"exponential":return new Mm(r);default:throw Error("Invalid retry strategy")}}var Wm=["get","post","put","patch","delete"];function od(r){if(!r.startsWith("@"))return{method:void 0,path:r};let n=r.indexOf("/"),i=r.slice(1,n===-1?void 0:n);if(!Wm.includes(i))return{method:void 0,path:r};return{method:i,path:n===-1?r:r.slice(n+1)}}var Vm=(r)=>r==="."||r==="..",qm=(r)=>r.split(":").map((n)=>encodeURIComponent(n)).join(":");function Fm(r,n){let i=n.get(r);if(i===void 0)return qm(r);if(Vm(i))throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(i)}function Jm(r,n){let{baseURL:i,params:s,query:c}=n||{query:{},params:{},baseURL:""},u=r.startsWith("http")?r.split("/").slice(0,3).join("/"):i||"",{path:f}=od(r);if(f!==r)r=`/${f}`;if(!u.endsWith("/"))u+="/";let[m,h]=r.replace(u,"").split("?"),y=new URLSearchParams(h);for(let[A,E]of Object.entries(c||{})){if(E==null)continue;let v;if(typeof E==="string")v=E;else if(Array.isArray(E)){for(let _ of E)y.append(A,_);continue}else v=JSON.stringify(E);y.set(A,v)}let w=new Map;if(s)if(Array.isArray(s)){let A=m.split("/").filter((E)=>E.startsWith(":"));for(let[E,v]of A.entries()){let _=s[E];w.set(v,String(_))}}else for(let[A,E]of Object.entries(s))w.set(`:${A}`,String(E));m=m.split("/").map((A)=>Fm(A,w)).join("/"),m=m.replace(/^\/+/,"");let g=y.toString();if(g=g.length>0?`?${g}`.replace(/\+/g,"%20"):"",!u.startsWith("http"))return`${u}${m}${g}`;return new URL(`${m}${g}`,u)}var Gm=async(r)=>{let n={},i=async(s)=>typeof s==="function"?await s():s;if(r===null||r===void 0?void 0:r.auth){if(r.auth.type==="Bearer"){let s=await i(r.auth.token);if(!s)return n;n.authorization=`Bearer ${s}`}else if(r.auth.type==="Basic"){let[s,c]=await Promise.all([i(r.auth.username),i(r.auth.password)]);if(!s||!c)return n;n.authorization=`Basic ${btoa(`${s}:${c}`)}`}else if(r.auth.type==="Custom"){let[s,c]=await Promise.all([i(r.auth.prefix),i(r.auth.value)]);if(!c)return n;n.authorization=`${s!==null&&s!==void 0?s:""} ${c}`}}return n},Qm=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Zm(r){let n=r.headers.get("content-type"),i=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!n)return"json";let s=n.split(";").shift()||"";if(Qm.test(s))return"json";if(i.has(s)||s.startsWith("text/"))return"text";return"blob"}function Ym(r){try{return JSON.parse(r),!0}catch(n){return!1}}function nd(r){if(r===void 0)return!1;let n=typeof r;if(n==="string"||n==="number"||n==="boolean"||n===null)return!0;if(n!=="object")return!1;if(Array.isArray(r))return!0;if(r.buffer)return!1;return r.constructor&&r.constructor.name==="Object"||typeof r.toJSON==="function"}function ed(r){try{return JSON.parse(r)}catch(n){return r}}function td(r){return typeof r==="function"}function Xm(r){if(r===null||r===void 0?void 0:r.customFetchImpl)return r.customFetchImpl;if(typeof globalThis<"u"&&td(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&td(window.fetch))return window.fetch;throw Error("No fetch implementation found")}function eh(...r){let n={};for(let i of r){if(!i)continue;if(i instanceof Headers)i.forEach((s,c)=>{n[c]=s});else{let s=Array.isArray(i)?i:Object.entries(i);for(let[c,u]of s)if(u!==null&&u!==void 0)n[c]=u}}return n}async function th(r){let n=new Headers(eh(r===null||r===void 0?void 0:r.headers,await Gm(r)));if(!n.has("content-type")){let i=rh(r===null||r===void 0?void 0:r.body);if(i)n.set("content-type",i)}return n}function rh(r){if(nd(r))return"application/json";return null}function oh(r){let n=r.get("content-type");return n?n.split(";")[0].trim().toLowerCase():null}function nh(r,n){let{body:i}=r;if(!i)return null;if(!nd(i))return i;if(typeof i==="string")return i;if(oh(n)==="application/x-www-form-urlencoded")return new URLSearchParams(i).toString();return JSON.stringify(i)}function ih(r,n){if(n===null||n===void 0?void 0:n.method)return n.method.toUpperCase();let{method:i}=od(r);if(i)return i.toUpperCase();return(n===null||n===void 0?void 0:n.body)?"POST":"GET"}function sh(r,n){let i;if(!(r===null||r===void 0?void 0:r.signal)&&(r===null||r===void 0?void 0:r.timeout))i=setTimeout(()=>n===null||n===void 0?void 0:n.abort(),r===null||r===void 0?void 0:r.timeout);return{abortTimeout:i,clearTimeout:()=>{if(i)clearTimeout(i)}}}var ah=class r extends Error{constructor(n,i){super(i||JSON.stringify(n,null,2));this.issues=n,Object.setPrototypeOf(this,r.prototype)}};async function ch(r,n){let i=await r["~standard"].validate(n);if(i.issues)throw new ah(i.issues);return i.value}function Eo(r){return Eo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Eo(r)}function uh(r,n){if(Eo(r)!="object"||!r)return r;var i=r[Symbol.toPrimitive];if(i!==void 0){var s=i.call(r,n||"default");if(Eo(s)!="object")return s;throw TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(r)}function dh(r){var n=uh(r,"string");return Eo(n)=="symbol"?n:n+""}function lh(r,n,i){return(n=dh(n))in r?Object.defineProperty(r,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[n]=i,r}function rd(r,n){var i=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);n&&(s=s.filter(function(c){return Object.getOwnPropertyDescriptor(r,c).enumerable})),i.push.apply(i,s)}return i}function De(r){for(var n=1;n<arguments.length;n++){var i=arguments[n]!=null?arguments[n]:{};n%2?rd(Object(i),!0).forEach(function(s){lh(r,s,i[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):rd(Object(i)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(i,s))})}return r}var C=async(r,n)=>{var i,s,c;let{hooks:u,url:f,options:m}=await Bm(r,n),h=Xm(m),y=new AbortController,w=(i=m.signal)!==null&&i!==void 0?i:y.signal,g=Jm(f,m),A=await th(m),E=nh(m,A),v=ih(f,m),_=De(De({},m),{},{url:g,headers:A,body:E,method:v,signal:w});for(let W of u.onRequest)if(W){let V=await W(_);if(typeof V==="object"&&V!==null)Object.assign(_,V)}if("pipeTo"in _&&typeof _.pipeTo==="function"||typeof(n===null||n===void 0||(s=n.body)===null||s===void 0?void 0:s.pipe)==="function"){if(!("duplex"in _))_.duplex="half"}let{clearTimeout:P}=sh(m,y),I=await h(_.url,_);P();let T={response:I,request:_};for(let W of u.onResponse)if(W){var D;let V=await W(De(De({},T),{},{response:(n===null||n===void 0||(D=n.hookOptions)===null||D===void 0?void 0:D.cloneResponse)?I.clone():I}));if(V instanceof Response)I=V;else if(typeof V==="object"&&V!==null)I=V.response}if(I.ok){if(_.method==="HEAD")return{data:"",error:null};let W=Zm(I),V={data:null,response:I,request:_};if(W==="json"||W==="text"){var k;let J=await I.text();V.data=await((k=_.jsonParser)!==null&&k!==void 0?k:ed)(J)}else V.data=await I[W]();if(_===null||_===void 0?void 0:_.output){if(_.output&&!_.disableValidation)V.data=await ch(_.output,V.data)}for(let J of u.onSuccess)if(J){var R;await J(De(De({},V),{},{response:(n===null||n===void 0||(R=n.hookOptions)===null||R===void 0?void 0:R.cloneResponse)?I.clone():I}))}if(n===null||n===void 0?void 0:n.throw)return V.data;return{data:V.data,error:null}}let L=(c=n===null||n===void 0?void 0:n.jsonParser)!==null&&c!==void 0?c:ed,M=await I.text(),N=Ym(M),H=N?await L(M):null,z={response:I,responseText:M,request:_,error:De(De({},H),{},{status:I.status,statusText:I.statusText})};for(let W of u.onError)if(W){var B;await W(De(De({},z),{},{response:(n===null||n===void 0||(B=n.hookOptions)===null||B===void 0?void 0:B.cloneResponse)?I.clone():I}))}if(n===null||n===void 0?void 0:n.retry){var K;let W=Km(n.retry),V=(K=n.retryAttempt)!==null&&K!==void 0?K:0;if(await W.shouldAttemptRetry(V,I)){for(let X of u.onRetry)if(X)await X(T);let J=W.getDelay(V);return await new Promise((X)=>setTimeout(X,J)),await C(r,De(De({},n),{},{retryAttempt:V+1}))}}if(n===null||n===void 0?void 0:n.throw)throw new Hm(I.status,I.statusText,N?H:M);return{data:null,error:De(De({},H),{},{status:I.status,statusText:I.statusText})}};var fh=new Set([301,302,303,307,308]);function ph(r){return r.type==="opaqueredirect"||fh.has(r.status)}function id(r){return new S(`The OAuth endpoint "${r}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}var sd={redirect:"manual"};async function Vn(r,n){let i=!1,s=n?.onError,c=await C(r,{...n,...sd,async onError(u){if(ph(u.response))i=!0;await s?.(u)}}).catch((u)=>{if(i)throw id(r);throw u});if(i)throw id(r);return c}function mh(r,n){if(n==="basic")return{method:"client_secret_basic"};if(r.clientSecret)return{method:"client_secret_post"};return{method:"none"}}function Ls(r,n,i){if(n.clientSecret||i.has("client_secret"))throw Error(`${r} token endpoint authentication cannot be combined with clientSecret`)}function qn(r,n){if(n)r.set("client_id",n)}function cd(r,n){if(!n.clientSecret)throw Error(`${r} token endpoint authentication requires clientSecret`)}function Jn(r,n){if(!n)throw Error(`${r} token endpoint authentication requires clientId`)}function hh({body:r,options:n,clientId:i,requireClientSecret:s}){if(s)cd("client_secret_post",n);if(n.clientSecret)Jn("client_secret_post",i),qn(r,i),r.set("client_secret",n.clientSecret)}function yh({headers:r,options:n,clientId:i,body:s}){if(s.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");cd("client_secret_basic",n),Jn("client_secret_basic",i),r.authorization=Zu(i,n.clientSecret)}function ad(r){if(r.has("client_assertion")!==r.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function Gn({body:r,headers:n,options:i,tokenEndpoint:s,grantType:c,tokenEndpointAuth:u,authentication:f}){ad(r);let m=Re(i.clientId);if(r.has("client_assertion")){if(u)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");Ls("private_key_jwt",i,r),qn(r,m);return}let h=u??mh(i,f);if(h.method==="custom"){await h.customizeRequest({body:r,headers:n,options:i,tokenEndpoint:s,grantType:c}),ad(r);return}if(h.method==="private_key_jwt"){if(Ls(h.method,i,r),Jn(h.method,m),!s)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let y=await Yu({getClientAssertion:h.getClientAssertion,context:{clientId:m,tokenEndpoint:s,grantType:c}});qn(r,m);for(let[w,g]of Object.entries(y))r.set(w,g);return}if(h.method==="none"){if(Ls(h.method,i,r),c==="client_credentials")throw Error("none token endpoint authentication cannot be used with client_credentials grant");Jn(h.method,m),qn(r,m);return}if(h.method==="client_secret_basic"){yh({headers:n,options:i,clientId:m,body:r});return}hh({body:r,options:i,clientId:m,requireClientSecret:u?.method==="client_secret_post"})}var wh=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function gh({refreshToken:r,options:n,authentication:i,tokenEndpointAuth:s,tokenEndpoint:c,extraParams:u,resource:f}){n=typeof n==="function"?await n():n;let m=bh({refreshToken:r,options:n,extraParams:u,resource:f});return await Gn({body:m.body,headers:m.headers,options:n,tokenEndpoint:c??"",grantType:"refresh_token",tokenEndpointAuth:s,authentication:i}),m}function Ah(r,n){if(!n)return;for(let[i,s]of Object.entries(n)){if(wh.has(i))continue;r.set(i,s)}}function bh({refreshToken:r,options:n,extraParams:i,resource:s}){let c=new URLSearchParams,u={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(c.set("grant_type","refresh_token"),c.set("refresh_token",r),s)if(typeof s==="string")c.append("resource",s);else for(let f of s)c.append("resource",f);if(i)Ah(c,i);return{body:c,headers:u}}async function Q({refreshToken:r,options:n,tokenEndpoint:i,authentication:s,tokenEndpointAuth:c,extraParams:u,resource:f}){let{body:m,headers:h}=await gh({refreshToken:r,options:n,authentication:s,tokenEndpointAuth:c,tokenEndpoint:i,extraParams:u,resource:f}),{data:y,error:w}=await Vn(i,{method:"POST",body:m,headers:h});if(w)throw w;let g={accessToken:y.access_token,refreshToken:y.refresh_token,tokenType:y.token_type,scopes:Us(y.scope),idToken:y.id_token};if(y.expires_in)g.accessTokenExpiresAt=new Date(new Date().getTime()+y.expires_in*1000);if(y.refresh_token_expires_in)g.refreshTokenExpiresAt=new Date(new Date().getTime()+y.refresh_token_expires_in*1000);return g}async function Ps({code:r,codeVerifier:n,redirectURI:i,options:s,authentication:c,tokenEndpointAuth:u,tokenEndpoint:f,deviceId:m,headers:h,additionalParams:y={},resource:w}){s=typeof s==="function"?await s():s;let g=Eh({code:r,codeVerifier:n,redirectURI:i,options:s,deviceId:m,headers:h,additionalParams:y,resource:w});return await Gn({body:g.body,headers:g.headers,options:s,tokenEndpoint:f??"",grantType:"authorization_code",tokenEndpointAuth:u,authentication:c}),g}function Eh({code:r,codeVerifier:n,redirectURI:i,options:s,deviceId:c,headers:u,additionalParams:f={},resource:m}){let h=new URLSearchParams,y={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...u};if(h.set("grant_type","authorization_code"),h.set("code",r),n&&h.set("code_verifier",n),s.clientKey&&h.set("client_key",s.clientKey),c&&h.set("device_id",c),h.set("redirect_uri",s.redirectURI||i),m)if(typeof m==="string")h.append("resource",m);else for(let w of m)h.append("resource",w);for(let[w,g]of Object.entries(f))if(!h.has(w))h.append(w,g);return{body:h,headers:y}}async function Z({code:r,codeVerifier:n,redirectURI:i,options:s,tokenEndpoint:c,authentication:u,tokenEndpointAuth:f,deviceId:m,headers:h,additionalParams:y={},resource:w}){let{body:g,headers:A}=await Ps({code:r,codeVerifier:n,redirectURI:i,options:s,authentication:u,tokenEndpointAuth:f,tokenEndpoint:c,deviceId:m,headers:h,additionalParams:y,resource:w}),{data:E,error:v}=await Vn(c,{method:"POST",body:g,headers:A});if(v)throw v;return Ao(E)}async function kh(r){let n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map((s)=>s.toString(16).padStart(2,"0")).join("")}async function Sh(r,n,i="exact"){if(typeof r!=="string")return!1;if(r===n)return!0;if(i==="exact-or-sha256")return r===await kh(n);return!1}function ko(r){let n=r.options??{};if(n.disableIdTokenSignIn)return!1;return Boolean(r.idToken||n.verifyIdToken)}async function So(r,n,i,s){let c=r.options??{};if(c.disableIdTokenSignIn)return!1;try{if(c.verifyIdToken)return await c.verifyIdToken(n,i,s);let u=r.idToken;if(!u)return!1;if("verify"in u)return await u.verify(n,i,s);if(n.split(".").length!==3)return u.allowOpaqueToken===!0;let{alg:f}=Ur(n),{payload:m}=await Mt(n,u.jwks,{issuer:u.issuer,audience:u.audience,algorithms:u.algorithms??(f?[f]:void 0),maxTokenAge:u.maxTokenAge,clockTolerance:30});if(i&&!await Sh(m.nonce,i,u.nonceComparison))return!1;if(u.verifyClaims&&!u.verifyClaims(m))return!1;return!0}catch{return!1}}function vo(r,n){return{linked:!1,error:{code:r,message:n}}}async function dd(r,{link:n,userInfo:i,account:s,profile:c,scopes:u}){try{await xr(r,{user:{...i,id:n.userId,email:i.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:s.providerId,profile:c}}})}catch(m){if(!Oe(m)||!m.body?.code)throw m;return vo(m.body.code,m.body.message)}if(!r.context.trustedProviders.includes(s.providerId)&&!i.emailVerified||r.context.options.account?.accountLinking?.enabled===!1)return r.context.logger.error("Unable to link account - untrusted provider"),vo(Ae.UNABLE_TO_LINK_ACCOUNT);if(i.email?.toLowerCase()!==n.email.toLowerCase()&&r.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return vo(Ae.EMAIL_DOES_NOT_MATCH);let f=await r.context.internalAdapter.findAccountByKey(s);if(f){if(f.userId.toString()!==n.userId.toString())return vo(Ae.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let m=Cs(f.scope,u),h=Object.fromEntries(Object.entries({providerId:s.providerId,accessToken:await ye(s.accessToken,r.context),refreshToken:await ye(s.refreshToken,r.context),idToken:s.idToken,accessTokenExpiresAt:s.accessTokenExpiresAt,refreshTokenExpiresAt:s.refreshTokenExpiresAt,scope:m||void 0}).filter(([y,w])=>w!==void 0));await r.context.internalAdapter.updateAccount(f.id,h)}else if(!await r.context.internalAdapter.createAccount({userId:n.userId,...s,accessToken:await ye(s.accessToken,r.context),refreshToken:await ye(s.refreshToken,r.context),scope:u?.join(",")??s.scope}))return vo(Ae.UNABLE_TO_LINK_ACCOUNT);return await To(r,n.userId,i),{linked:!0}}async function Qn(r,n){let{userInfo:i,account:s,callbackURL:c,disableSignUp:u,overrideUserInfo:f}=n,m=n.source??{method:"oauth",oauth:{providerId:s.providerId}},h=!!n.selectedUser||n.requireExactAccountBinding===!0,y=null,w=await r.context.internalAdapter.findAccountOwnerByKey({providerId:s.providerId,accountId:s.accountId}).catch((P)=>{r.context.logger.error(`Better auth was unable to query your database.
35
+ Error: `,P),lo(r,r.context.options.onAPIError?.errorURL||`${r.context.baseURL}/error`,"internal_server_error")});if(w?.kind==="orphaned")return r.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let g=await(async()=>{if(w?.kind==="owned"){if(n.selectedUser&&w.user.id!==n.selectedUser.userId)throw new l("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:w.user,linkedAccount:w.account,accounts:[w.account]}}if(n.selectedUser){let I=await r.context.internalAdapter.findUserById(n.selectedUser.userId);if(!I)throw new l("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:I,linkedAccount:null,accounts:[]}}let P=await r.context.internalAdapter.findUserByEmail(i.email.toLowerCase(),{includeAccounts:!0});if(!P)return null;return{user:P.user,linkedAccount:null,accounts:P.accounts}})().catch((P)=>{if(Oe(P))throw P;r.context.logger.error(`Better auth was unable to query your database.
36
+ Error: `,P),lo(r,r.context.options.onAPIError?.errorURL||`${r.context.baseURL}/error`,"internal_server_error")}),A=g?.user,E=!A;if(g){let P=g.linkedAccount??g.accounts.find((I)=>I.providerId===s.providerId&&I.accountId===s.accountId);if(!P){let I=r.context.options.account?.accountLinking,T=n.isTrustedProvider||n.trustProviderByName!==!1&&r.context.trustedProviders.includes(s.providerId),D=I?.requireLocalEmailVerified??!0;if(!n.selectedUser&&(!T&&!i.emailVerified||D&&!g.user.emailVerified||I?.enabled===!1||I?.disableImplicitLinking===!0)){if(ai())r.context.logger.warn(`User already exist but account isn't linked to ${s.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`);return{error:"account not linked",data:null}}try{let{id:k,...R}=i;await xr(r,{user:{...R,id:g.user.id,email:i.email.toLowerCase()},source:{...m,action:"link-account"}});let L=await r.context.internalAdapter.linkAccount({providerId:s.providerId,accountId:s.accountId,userId:g.user.id,accessToken:await ye(s.accessToken,r.context),refreshToken:await ye(s.refreshToken,r.context),idToken:s.idToken,accessTokenExpiresAt:s.accessTokenExpiresAt,refreshTokenExpiresAt:s.refreshTokenExpiresAt,scope:s.scope});if(!L)return{error:"unable to link account",data:null};if(h&&(L.accountId!==s.accountId||L.providerId!==s.providerId||L.userId!==g.user.id))throw new l("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(r.context.options.account?.storeAccountCookie)if(n.deferNonDatabaseWrites)y=L;else await Et(r,L)}catch(k){if(Oe(k))throw k;return r.context.logger.error("Unable to link account",k),{error:"unable to link account",data:null}}if(!n.selectedUser&&i.emailVerified&&!g.user.emailVerified&&i.email.toLowerCase()===g.user.email)await r.context.internalAdapter.updateUser(g.user.id,{emailVerified:!0});if(!n.selectedUser)A=await To(r,g.user.id,i)??A}else{let{id:I,...T}=i;await xr(r,{user:{...T,id:g.user.id,email:i.email.toLowerCase()},source:{...m,action:"sign-in"}});let D=r.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:s.providerId,idToken:s.idToken,accessToken:await ye(s.accessToken,r.context),refreshToken:await ye(s.refreshToken,r.context),accessTokenExpiresAt:s.accessTokenExpiresAt,refreshTokenExpiresAt:s.refreshTokenExpiresAt}).filter(([k,R])=>R!==void 0)):{};if(r.context.options.account?.storeAccountCookie){let k={...P,...D};if(n.deferNonDatabaseWrites)y=k;else await Et(r,k)}if(Object.keys(D).length>0){let k=await r.context.internalAdapter.updateAccount(P.id,D);if(!k)return{error:"unable to update account",data:null};if(h&&(k.accountId!==s.accountId||k.providerId!==s.providerId||k.userId!==g.user.id))throw new l("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(n.deferNonDatabaseWrites&&y)y=k}if(!n.selectedUser&&i.emailVerified&&!g.user.emailVerified&&i.email.toLowerCase()===g.user.email)await r.context.internalAdapter.updateUser(g.user.id,{emailVerified:!0})}if(n.selectedUser?n.selectedUser.profile==="update":f){let{id:I,email:T,emailVerified:D,name:k,image:R,...L}=i,M=$i(r.context.options,L,"update"),N=await r.context.internalAdapter.updateUser(g.user.id,{name:k,image:R,...M,email:i.email.toLowerCase(),emailVerified:i.email.toLowerCase()===g.user.email?g.user.emailVerified||i.emailVerified:i.emailVerified});if(N==null)r.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session.");if(n.selectedUser&&N&&N.id!==n.selectedUser.userId)throw new l("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});A=N??A}}else{if(u)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:P,email:I,emailVerified:T,name:D,image:k,...R}=i,L=$i(r.context.options,R,"create"),M={accessToken:await ye(s.accessToken,r.context),refreshToken:await ye(s.refreshToken,r.context),idToken:s.idToken,accessTokenExpiresAt:s.accessTokenExpiresAt,refreshTokenExpiresAt:s.refreshTokenExpiresAt,scope:s.scope,providerId:s.providerId,accountId:s.accountId},{createdUser:N,createdAccount:H}=await Ht(r.context.adapter,async()=>{let z=await r.context.internalAdapter.createUser({name:D,image:k,...L,email:i.email.toLowerCase(),emailVerified:i.emailVerified},m);return{createdUser:z,createdAccount:await r.context.internalAdapter.createAccount({...M,userId:z.id})}});if(h&&(H.accountId!==s.accountId||H.providerId!==s.providerId||H.userId!==N.id))throw new l("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(A=N,r.context.options.account?.storeAccountCookie)if(n.deferNonDatabaseWrites)y=H;else await Et(r,H)}catch(P){if(Oe(P))throw P;return r.context.logger.error("Unable to create OAuth user",P),{error:"unable to create user",data:null,isRegister:!1}}}if(!A)return{error:"unable to create user",data:null,isRegister:!1};let v=r.context.socialProviders.find((P)=>P.id===s.providerId)?.options?.requireEmailVerification;if(E&&!A.emailVerified&&(r.context.options.emailVerification?.sendOnSignUp??v))await ud(r,A,c,n.deferNonDatabaseWrites);if(v&&!A.emailVerified){if(!E&&r.context.options.emailVerification?.sendOnSignIn)await ud(r,A,c,n.deferNonDatabaseWrites);return{error:Ae.EMAIL_NOT_VERIFIED,data:null,isRegister:E}}let _=await r.context.internalAdapter.createSession(A.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:n.deferNonDatabaseWrites===!0});if(!_)return{error:"unable to create session",data:null,isRegister:!1};if(h&&_.userId!==(n.selectedUser?.userId??A.id))throw new l("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:_,user:A},error:null,isRegister:E,accountCookie:y}}async function ud(r,n,i,s){let c=r.context.options.emailVerification?.sendVerificationEmail;if(!c)return;let u=async()=>{try{let f=await Te(r.context.secret,n.email,void 0,r.context.options.emailVerification?.expiresIn),m=`${r.context.baseURL}/verify-email?token=${f}&callbackURL=${encodeURIComponent(i||"/")}`;await r.context.runInBackgroundOrAwait(c({user:n,url:m,token:f},r.request))}catch(f){r.context.logger.error("Failed to send OAuth verification email",f)}};if(s)await Ue(u);else await u()}async function To(r,n,i){if(r.context.options.account?.accountLinking?.updateUserInfoOnLink!==!0)return;try{let{email:s,emailVerified:c,name:u,image:f,...m}=i,h=$i(r.context.options,m,"update");return await r.context.internalAdapter.updateUser(n,{name:u,image:f,...h})}catch(s){r.context.logger.warn("Could not update user info on account link",s);return}}var vh=bd("better-auth:oauth-encryption:v1");function Ns(r,n){return ty(Po(No,bd(r),vh,bd(`better-auth:${n}:v1`),32))}function zs(r,n){if(typeof r==="string")return Ns(r,n);return{keys:new Map(Array.from(r.keys,([i,s])=>[i,Ns(s,n)])),currentVersion:r.currentVersion,...r.legacySecret&&{legacySecret:Ns(r.legacySecret,n)}}}var $s=Fn({callbackURL:e(),codeVerifier:e(),errorURL:e().optional(),newUserURL:e().optional(),expiresAt:b(),oauthState:e().optional(),link:t({email:e(),userId:bs()}).optional(),requestSignUp:o().optional(),idTokenNonce:e().optional(),serverContext:j(e(),ne()).optional()}),Hs=(r)=>`auth-state:${r}`,QS=new Set(Object.keys($s.shape)),Ze=class extends S{code;details;errorURL;constructor(r,n){super(r,n);this.code=n.code,this.details=n.details,this.errorURL=n.errorURL}};async function ld(r,n,i){let s=Vt(32);if(r.context.oauthConfig.storeStateStrategy==="cookie"){let f={...n,oauthState:s},m=await Mn({key:zs(r.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(f)}),h=r.context.createAuthCookie(i?.cookieName??"oauth_state",{maxAge:600});return r.setCookie(h.name,m,h.attributes),{state:s,codeVerifier:n.codeVerifier}}let c=r.context.createAuthCookie(i?.cookieName??"state",{maxAge:300});await r.setSignedCookie(c.name,s,r.context.secret,c.attributes);let u=new Date;if(u.setMinutes(u.getMinutes()+10),!await r.context.internalAdapter.createVerificationValue({value:JSON.stringify({...n,oauthState:s}),identifier:Hs(s),expiresAt:u}))throw new Ze("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:s,codeVerifier:n.codeVerifier}}async function pd(r,n,i){if(!n)throw new Ze("State not found in OAuth callback",{code:"state_not_found"});let s=r.context.oauthConfig.storeStateStrategy,c;if(s==="cookie"){let u=r.context.createAuthCookie(i?.cookieName??"oauth_state"),f=r.getCookie(u.name);if(!f)throw new Ze("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:n}});try{let m=await Kn({key:zs(r.context.secretConfig,"oauth-state-cookie"),data:f});c=$s.parse(JSON.parse(m))}catch(m){throw new Ze("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:n},cause:m})}if(!c.oauthState||c.oauthState!==n)throw new Ze("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:n},errorURL:c.errorURL});Be(r,u)}else{let u=await r.context.internalAdapter.findVerificationValue(Hs(n));if(!u)throw new Ze("State mismatch: verification not found",{code:"state_mismatch",details:{state:n}});if(c=$s.parse(JSON.parse(u.value)),c.oauthState!==void 0&&c.oauthState!==n)throw new Ze("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:n},errorURL:c.errorURL});let f=r.context.createAuthCookie(i?.cookieName??"state"),m=await r.getSignedCookie(f.name,r.context.secret);if(!(i?.skipStateCookieCheck??r.context.oauthConfig.skipStateCookieCheck)&&(!m||m!==n))throw new Ze("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:n},errorURL:c.errorURL});Be(r,f),await r.context.internalAdapter.deleteVerificationByIdentifier(Hs(n))}if(c.expiresAt<Date.now())throw new Ze("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:c.expiresAt},errorURL:c.errorURL});return c}function Nr(r){return r.requiresIdTokenNonce?Vt(32):void 0}async function zr(r,n){let i=r.body?.callbackURL||r.context.options.baseURL;if(!i)throw l.from("BAD_REQUEST",x.CALLBACK_URL_REQUIRED);let s=n?.codeVerifier??Vt(128),c=await wu(),u=c&&Object.keys(c).length?c:void 0,f={...n?.additionalData?n.additionalData:{},callbackURL:i,codeVerifier:s,errorURL:r.body?.errorCallbackURL,newUserURL:r.body?.newUserCallbackURL,link:n?.link,serverContext:u,expiresAt:Date.now()+600000,requestSignUp:r.body?.requestSignUp,idTokenNonce:n?.idTokenNonce};await hs(f);try{return ld(r,f)}catch(m){throw r.context.logger.error("Failed to create verification",m),new l("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:m})}}async function hd(r){let n=r.query.state||r.body?.state,i=r.context.options.onAPIError?.errorURL||`${r.context.baseURL}/error`,s;try{s=await pd(r,n)}catch(c){r.context.logger.error("Failed to parse state",c);let u="internal_server_error",f=i;if(c instanceof Ze)u=c.code==="state_security_mismatch"?"state_mismatch":c.code,f=c.errorURL||i;lo(r,f,u)}if(!s.errorURL)s.errorURL=i;if(s)await hs(s);return s}var yd=(r)=>({id:"apple",name:"Apple",accountSubject:({profile:i})=>i.sub,async createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u,codeVerifier:f}){if(!Re(r.clientId)||!r.clientSecret)throw O.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");let m=r.disableDefaultScope?[]:["email","name"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return await G({id:"apple",options:r,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:m,state:i,redirectURI:c,codeVerifier:f,responseMode:"form_post",responseType:"code id_token",additionalParams:u})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://appleid.apple.com/auth/token"}),idToken:{jwks:(i)=>gd(i.kid),issuer:"https://appleid.apple.com",audience:r.audience&&r.audience.length?r.audience:r.appBundleIdentifier?r.appBundleIdentifier:r.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:r,tokenEndpoint:"https://appleid.apple.com/auth/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);if(!i.idToken)return null;let s=ge(i.idToken);if(!s)return null;let c;if(i.user?.name)c=`${i.user.name.firstName||""} ${i.user.name.lastName||""}`.trim();else c=s.name||"";let u=typeof s.email_verified==="boolean"?s.email_verified:s.email_verified==="true",f={...s,name:c},m=await r.mapProfileToUser?.(f);return{user:{name:f.name,emailVerified:u,email:s.email,...m},data:f}},options:r}),gd=async(r)=>{let{data:n}=await C("https://appleid.apple.com/auth/keys");if(!n?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let i=n.keys.find((s)=>s.kid===r);if(!i)throw Error(`JWK with kid ${r} not found`);return await At(i,i.alg)};var Ad=(r)=>({id:"atlassian",name:"Atlassian",accountSubject:({profile:i})=>i.account_id,async createAuthorizationURL({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f}){if(!r.clientId||!r.clientSecret)throw O.error("Client Id and Secret are required for Atlassian"),new S("CLIENT_ID_AND_SECRET_REQUIRED");if(!c)throw new S("codeVerifier is required for Atlassian");let m=r.disableDefaultScope?[]:["read:jira-user","offline_access"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"atlassian",options:r,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:m,state:i,codeVerifier:c,redirectURI:u,additionalParams:{...f??{},audience:"api.atlassian.com"},prompt:r.prompt})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);if(!i.accessToken)return null;try{let{data:s}=await C("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${i.accessToken}`}});if(!s)return null;let c=await r.mapProfileToUser?.(s);return{user:{name:s.name,email:s.email,image:s.picture,emailVerified:!1,...c},data:s}}catch(s){return O.error("Failed to fetch user info from Atlassian:",s),null}},options:r});var Th="https://dash.cloudflare.com/oauth2/auth",Ed="https://dash.cloudflare.com/oauth2/token",Rh="https://api.cloudflare.com/client/v4/user",kd=(r)=>{let n=r.clientSecret?"client_secret_basic":"none";return{method:r.tokenEndpointAuthMethod??n}},vd=(r)=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:i,codeVerifier:s,redirectURI:c}){let u=r.disableDefaultScope?[]:["user-details.read"];if(r.scope?.length)u.push(...r.scope);if(i?.length)u.push(...i);return G({id:"cloudflare",options:r,authorizationEndpoint:Th,scopes:u.length?[...new Set(u)]:void 0,state:n,codeVerifier:s,redirectURI:c})},validateAuthorizationCode:async({code:n,codeVerifier:i,redirectURI:s})=>Z({code:n,codeVerifier:i,redirectURI:s,options:r,tokenEndpoint:Ed,tokenEndpointAuth:kd(r)}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>Q({refreshToken:n,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:Ed,tokenEndpointAuth:kd(r)}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let{data:i,error:s}=await C(Rh,{headers:{authorization:`Bearer ${n.accessToken}`}});if(s||!i?.success||!i.result)return O.error("Failed to fetch user info from Cloudflare:",s??i?.errors),null;let c=i.result,u=[c.first_name,c.last_name].filter(Boolean).join(" ")||c.email,f=await r.mapProfileToUser?.(c);return{user:{name:u,email:c.email,emailVerified:!1,...f},data:c}},options:r});var Td=(r)=>{if(!r.domain||!r.region||!r.userPoolId)throw O.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new S("DOMAIN_AND_REGION_REQUIRED");let n=r.domain.replace(/^https?:\/\//,""),i=`https://${n}/oauth2/authorize`,s=`https://${n}/oauth2/token`,c=`https://${n}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:u})=>u.sub,async createAuthorizationURL({state:u,scopes:f,codeVerifier:m,redirectURI:h,additionalParams:y}){if(!Re(r.clientId))throw O.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");if(r.requireClientSecret&&!r.clientSecret)throw O.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new S("CLIENT_SECRET_REQUIRED");let w=r.disableDefaultScope?[]:["openid","profile","email"];if(r.scope)w.push(...r.scope);if(f)w.push(...f);let g=await G({id:"cognito",options:{...r},authorizationEndpoint:i,scopes:w,state:u,codeVerifier:m,redirectURI:h,prompt:r.prompt,additionalParams:{...r.identityProvider?{identity_provider:r.identityProvider}:{},...y??{}}}),A=g.searchParams.get("scope");if(A){g.searchParams.delete("scope");let E=encodeURIComponent(A),v=g.toString(),_=v.includes("?")?"&":"?";return new URL(`${v}${_}scope=${E}`)}return g},validateAuthorizationCode:async({code:u,codeVerifier:f,redirectURI:m})=>Z({code:u,codeVerifier:f,redirectURI:m,options:r,tokenEndpoint:s}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(u)=>Q({refreshToken:u,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:s}),idToken:{jwks:(u)=>Rd(u.kid,r.region,r.userPoolId),issuer:`https://cognito-idp.${r.region}.amazonaws.com/${r.userPoolId}`,audience:r.clientId,maxTokenAge:"1h"},async getUserInfo(u){if(r.getUserInfo)return r.getUserInfo(u);if(u.idToken)try{let f=ge(u.idToken);if(!f)return null;let m=f.name||f.given_name||f.username||"",h={...f,name:m},y=await r.mapProfileToUser?.(h);return{user:{name:h.name,email:f.email,image:f.picture,emailVerified:f.email_verified,...y},data:h}}catch(f){O.error("Failed to decode ID token:",f)}if(u.accessToken)try{let{data:f}=await C(c,{headers:{Authorization:`Bearer ${u.accessToken}`}});if(f){let m=await r.mapProfileToUser?.(f);return{user:{name:f.name||f.given_name||f.username||"",email:f.email,image:f.picture,emailVerified:f.email_verified,...m},data:f}}}catch(f){O.error("Failed to fetch user info from Cognito:",f)}return null},options:r}},Rd=async(r,n,i)=>{let s=`https://cognito-idp.${n}.amazonaws.com/${i}/.well-known/jwks.json`;try{let{data:c}=await C(s);if(!c?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let u=c.keys.find((f)=>f.kid===r);if(!u)throw Error(`JWK with kid ${r} not found`);return await At(u,u.alg)}catch(c){throw O.error("Failed to fetch Cognito public key:",c),c}};var Id=(r)=>({id:"discord",name:"Discord",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["identify","email"];if(s)f.push(...s);if(r.scope)f.push(...r.scope);let m=f.includes("bot");return G({id:"discord",options:r,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:f,state:i,redirectURI:c,prompt:r.prompt||"none",additionalParams:{...m&&r.permissions!==void 0?{permissions:String(r.permissions)}:{},...u??{}}})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(c)return null;if(s.avatar===null)s.image_url=`https://cdn.discordapp.com/embed/avatars/${s.discriminator==="0"?Number(BigInt(s.id)>>BigInt(22))%6:parseInt(s.discriminator)%5}.png`;else{let f=s.avatar.startsWith("a_")?"gif":"png";s.image_url=`https://cdn.discordapp.com/avatars/${s.id}/${s.avatar}.${f}`}let u=await r.mapProfileToUser?.(s);return{user:{name:s.global_name||s.username||"",email:s.email,emailVerified:s.verified,image:s.image_url,...u},data:s}},options:r});var _d=(r)=>({id:"dropbox",name:"Dropbox",accountSubject:({profile:i})=>i.account_id,createAuthorizationURL:async({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f})=>{let m=r.disableDefaultScope?[]:["account_info.read"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return await G({id:"dropbox",options:r,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:m,state:i,redirectURI:u,codeVerifier:c,additionalParams:{...r.accessType?{token_access_type:r.accessType}:{},...f??{}}})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>await Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await r.mapProfileToUser?.(s);return{user:{name:s.name?.display_name,email:s.email,emailVerified:s.email_verified||!1,image:s.profile_photo_url,...u},data:s}},options:r});async function Ih(r,n){let i=Re(n.clientId);if(!i||!n.clientSecret)return null;let s=Array.isArray(n.clientId)?n.clientId:[n.clientId],{data:c,error:u}=await C("https://graph.facebook.com/debug_token",{query:{input_token:r,access_token:`${i}|${n.clientSecret}`}});if(u||!c?.data)return null;let{is_valid:f,app_id:m,user_id:h}=c.data;if(f!==!0||!m||!s.includes(m)||!h)return null;return h}var Ud=(r)=>({id:"facebook",name:"Facebook",accountSubject:({profile:n})=>("sub"in n)?n.sub:n.id,async createAuthorizationURL({state:n,scopes:i,redirectURI:s,loginHint:c,additionalParams:u}){if(!Re(r.clientId)||!r.clientSecret)throw O.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");let f=r.disableDefaultScope?[]:["email","public_profile"];if(r.scope)f.push(...r.scope);if(i)f.push(...i);return await G({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:f,state:n,redirectURI:s,loginHint:c,additionalParams:{...r.configId?{config_id:r.configId}:{},...u??{}}})},validateAuthorizationCode:async({code:n,redirectURI:i})=>Z({code:n,redirectURI:i,options:r,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:rs(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:r.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>Q({refreshToken:n,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);if(n.idToken&&n.idToken.split(".").length===3){let m=ge(n.idToken),h=await r.mapProfileToUser?.(m);return{user:{name:m.name,email:m.email,image:m.picture,emailVerified:!1,...h},data:m}}let i=n.accessToken;if(!i)return null;let s=await Ih(i,r);if(!s)return null;let{data:c,error:u}=await C("https://graph.facebook.com/me?fields="+["id","name","email","picture",...r?.fields||[]].join(","),{auth:{type:"Bearer",token:i}});if(u)return null;if(c.id!==s)return null;let f=await r.mapProfileToUser?.(c);return{user:{name:c.name,email:c.email,image:c.picture.data.url,emailVerified:c.email_verified??!1,...f},data:c}},options:r});var Cd=(r)=>({id:"figma",name:"Figma",accountSubject:({profile:i})=>i.id,async createAuthorizationURL({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f}){if(!r.clientId||!r.clientSecret)throw O.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");if(!c)throw new S("codeVerifier is required for Figma");let m=r.disableDefaultScope?[]:["current_user:read"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return await G({id:"figma",options:r,authorizationEndpoint:"https://www.figma.com/oauth",scopes:m,state:i,codeVerifier:c,redirectURI:u,additionalParams:f})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);try{let{data:s}=await C("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${i.accessToken}`}});if(!s)return O.error("Failed to fetch user from Figma"),null;let c=await r.mapProfileToUser?.(s);return{user:{name:s.handle,email:s.email,image:s.img_url,emailVerified:!1,...c},data:s}}catch(s){return O.error("Failed to fetch user info from Figma:",s),null}},options:r});var xd=(r)=>({id:"github",name:"GitHub",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,loginHint:c,codeVerifier:u,redirectURI:f,additionalParams:m}){let h=r.disableDefaultScope?[]:["read:user","user:email"];if(r.scope)h.push(...r.scope);if(s)h.push(...s);return G({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:h,state:i,codeVerifier:u,redirectURI:f,loginHint:c,prompt:r.prompt,additionalParams:m})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>{let{body:u,headers:f}=await Ps({code:i,codeVerifier:s,redirectURI:c,options:r}),{data:m,error:h}=await C("https://github.com/login/oauth/access_token",{method:"POST",body:u,headers:f});if(h)return O.error("GitHub OAuth token exchange failed:",h),null;if("error"in m)return O.error("GitHub OAuth token exchange failed:",m),null;return Ao(m)},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://github.com/login/oauth/access_token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${i.accessToken}`}});if(c)return null;let{data:u}=await C("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});if(!s.email&&u)s.email=(u.find((h)=>h.primary)??u[0])?.email;let f=u?.find((h)=>h.email===s.email)?.verified??!1,m=await r.mapProfileToUser?.(s);return{user:{name:s.name||s.login||"",email:s.email,image:s.avatar_url,emailVerified:f,...m},data:s}},options:r});var Bs=(r="")=>r.split("://").map((n)=>n.replace(/\/{2,}/g,"/")).join("://"),_h=(r)=>{let n=r||"https://gitlab.com";return{authorizationEndpoint:Bs(`${n}/oauth/authorize`),tokenEndpoint:Bs(`${n}/oauth/token`),userinfoEndpoint:Bs(`${n}/api/v4/user`)}},Od=(r)=>{let{authorizationEndpoint:n,tokenEndpoint:i,userinfoEndpoint:s}=_h(r.issuer),c="gitlab";return{id:"gitlab",name:"Gitlab",accountSubject:({profile:u})=>u.id,createAuthorizationURL:async({state:u,scopes:f,codeVerifier:m,loginHint:h,redirectURI:y,additionalParams:w})=>{let g=r.disableDefaultScope?[]:["read_user"];if(r.scope)g.push(...r.scope);if(f)g.push(...f);return await G({id:"gitlab",options:r,authorizationEndpoint:n,scopes:g,state:u,redirectURI:y,codeVerifier:m,loginHint:h,additionalParams:w})},validateAuthorizationCode:async({code:u,redirectURI:f,codeVerifier:m})=>Z({code:u,redirectURI:f,options:r,codeVerifier:m,tokenEndpoint:i}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(u)=>Q({refreshToken:u,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:i}),async getUserInfo(u){if(r.getUserInfo)return r.getUserInfo(u);let{data:f,error:m}=await C(s,{headers:{authorization:`Bearer ${u.accessToken}`}});if(m||f.state!=="active"||f.locked)return null;let h=await r.mapProfileToUser?.(f);return{user:{name:f.name??f.username??"",email:f.email,image:f.avatar_url,emailVerified:f.email_verified??!1,...h},data:f}},options:r}};var Uh="1h",Ch="RS256";var Ms=(r,n)=>{if(!r)return!0;if(typeof n!=="string"||!n)return!1;if(r==="*")return!0;return n===r},Ld=(r)=>({id:"google",name:"Google",accountSubject:({profile:n})=>n.sub,async createAuthorizationURL({state:n,scopes:i,codeVerifier:s,redirectURI:c,loginHint:u,display:f,additionalParams:m}){if(!Re(r.clientId)||!r.clientSecret)throw O.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");if(!s)throw new S("codeVerifier is required for Google");let h=r.disableDefaultScope?[]:["email","profile","openid"];if(r.scope)h.push(...r.scope);if(i)h.push(...i);return await G({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:h,state:n,codeVerifier:s,redirectURI:c,prompt:r.prompt,accessType:r.accessType,display:f||r.display,loginHint:u,hd:r.hd,additionalParams:{...r.includeGrantedScopes===!1?{}:{include_granted_scopes:"true"},...m??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:i,redirectURI:s})=>Z({code:n,codeVerifier:i,redirectURI:s,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>Q({refreshToken:n,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:(n)=>Dd(n.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:r.clientId,maxTokenAge:Uh,verifyClaims:r.hd?(n)=>Ms(r.hd,n.hd):void 0},async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);if(!n.idToken)return null;let i=ge(n.idToken);if(!Ms(r.hd,i.hd))return O.error(`Google sign-in rejected: id token hosted domain (hd) "${i.hd??"<missing>"}" does not satisfy the configured "hd" option "${r.hd}".`),null;let s=await r.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...s},data:i}},options:r}),Dd=async(r)=>{let[n]=await xh(r);if(!n)throw Error(`JWK with kid ${r} not found`);return n},xh=async(r)=>{let{data:n}=await C("https://www.googleapis.com/oauth2/v3/certs");if(!n?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let i=r?n.keys.filter((s)=>s.kid===r):n.keys;if(!i.length)throw Error(`JWK with kid ${r} not found`);return Promise.all(i.map((s)=>At(s,Ch)))};var Pd=(r)=>({id:"huggingface",name:"Hugging Face",accountSubject:({profile:i})=>i.sub,createAuthorizationURL({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:["openid","profile","email"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"huggingface",options:r,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:m,state:i,codeVerifier:c,redirectURI:u,additionalParams:f})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://huggingface.co/oauth/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://huggingface.co/oauth/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await r.mapProfileToUser?.(s);return{user:{name:s.name||s.preferred_username||"",email:s.email,image:s.picture,emailVerified:s.email_verified??!1,...u},data:s}},options:r});var Nd=(r)=>({id:"kakao",name:"Kakao",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];if(r.scope)f.push(...r.scope);if(s)f.push(...s);return G({id:"kakao",options:r,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:f,state:i,redirectURI:c,additionalParams:u})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${i.accessToken}`}});if(c||!s)return null;let u=await r.mapProfileToUser?.(s),f=s.kakao_account||{},m=f.profile||{};return{user:{name:m.nickname||f.name||"",email:f.email,image:m.profile_image_url||m.thumbnail_image_url,emailVerified:!!f.is_email_valid&&!!f.is_email_verified,...u},data:s}},options:r});var zd=(r)=>({id:"kick",name:"Kick",accountSubject:({profile:n})=>n.user_id,createAuthorizationURL({state:n,scopes:i,redirectURI:s,codeVerifier:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["user:read"];if(r.scope)f.push(...r.scope);if(i)f.push(...i);return G({id:"kick",redirectURI:s,options:r,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:f,codeVerifier:c,state:n,additionalParams:u})},async validateAuthorizationCode({code:n,redirectURI:i,codeVerifier:s}){return Z({code:n,redirectURI:i,options:r,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:s})},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>Q({refreshToken:n,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let{data:i,error:s}=await C("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(s)return null;let c=i.data[0],u=await r.mapProfileToUser?.(c);return{user:{name:c.name,email:c.email,image:c.profile_picture,emailVerified:!1,...u},data:c}},options:r});var $d=(r)=>({id:"line",name:"LINE",accountSubject:({profile:u})=>u.sub,async createAuthorizationURL({state:u,scopes:f,codeVerifier:m,redirectURI:h,loginHint:y,additionalParams:w}){let g=r.disableDefaultScope?[]:["openid","profile","email"];if(r.scope)g.push(...r.scope);if(f)g.push(...f);return await G({id:"line",options:r,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:g,state:u,codeVerifier:m,redirectURI:h,loginHint:y,additionalParams:w})},validateAuthorizationCode:async({code:u,codeVerifier:f,redirectURI:m})=>Z({code:u,codeVerifier:f,redirectURI:m,options:r,tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(u)=>Q({refreshToken:u,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),idToken:{verify:async(u,f)=>{let m=new URLSearchParams;if(m.set("id_token",u),m.set("client_id",r.clientId),f)m.set("nonce",f);let{data:h,error:y}=await C("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:m});if(y||!h)return!1;if(h.aud!==r.clientId)return!1;if(h.nonce&&h.nonce!==f)return!1;return!0}},async getUserInfo(u){if(r.getUserInfo)return r.getUserInfo(u);let f=null;if(u.idToken)try{f=ge(u.idToken)}catch{}if(!f){let{data:h}=await C("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${u.accessToken}`}});f=h||null}if(!f)return null;let m=await r.mapProfileToUser?.(f);return{user:{name:f.name||"",email:f.email,image:f.picture,emailVerified:!1,...m},data:f}},options:r});var jd=(r)=>({id:"linear",name:"Linear",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,loginHint:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:["read"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"linear",options:r,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:m,state:i,redirectURI:u,loginHint:c,additionalParams:f})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://api.linear.app/oauth/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://api.linear.app/oauth/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.accessToken}`},body:JSON.stringify({query:`
37
+ query {
38
+ viewer {
39
+ id
40
+ name
41
+ email
42
+ avatarUrl
43
+ active
44
+ createdAt
45
+ updatedAt
46
+ }
47
+ }
48
+ `})});if(c||!s?.data?.viewer)return null;let u=s.data.viewer,f=await r.mapProfileToUser?.(u);return{user:{name:s.data.viewer.name,email:s.data.viewer.email,image:s.data.viewer.avatarUrl,emailVerified:!1,...f},data:u}},options:r});var Hd=(r)=>({id:"linkedin",name:"Linkedin",accountSubject:({profile:s})=>s.sub,createAuthorizationURL:async({state:s,scopes:c,redirectURI:u,loginHint:f,additionalParams:m})=>{let h=r.disableDefaultScope?[]:["profile","email","openid"];if(r.scope)h.push(...r.scope);if(c)h.push(...c);return await G({id:"linkedin",options:r,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:h,state:s,loginHint:f,redirectURI:u,additionalParams:m})},validateAuthorizationCode:async({code:s,redirectURI:c})=>await Z({code:s,redirectURI:c,options:r,tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(s)=>Q({refreshToken:s,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),async getUserInfo(s){if(r.getUserInfo)return r.getUserInfo(s);let{data:c,error:u}=await C("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${s.accessToken}`}});if(u)return null;let f=await r.mapProfileToUser?.(c);return{user:{name:c.name,email:c.email,emailVerified:c.email_verified??!1,image:c.picture,...f},data:c}},options:r});var Bd="9188040d-6c67-4c5b-b112-36a304b66dad",Md=(r)=>{let n=r.tenantId||"common",i=r.authority||"https://login.microsoftonline.com";while(i.endsWith("/"))i=i.slice(0,-1);let s=`${i}/${n}/oauth2/v2.0/authorize`,c=`${i}/${n}/oauth2/v2.0/token`;if(r.clientSecret&&r.clientAssertion)throw new S("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let u=r.clientAssertion?{method:"private_key_jwt",getClientAssertion:r.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:f})=>f.oid,createAuthorizationURL(f){if(!Re(r.clientId))throw O.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");let m=r.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(r.scope)m.push(...r.scope);if(f.scopes)m.push(...f.scopes);return G({id:"microsoft",options:r,authorizationEndpoint:s,state:f.state,codeVerifier:f.codeVerifier,scopes:m,redirectURI:f.redirectURI,prompt:r.prompt,loginHint:f.loginHint,additionalParams:f.additionalParams})},validateAuthorizationCode({code:f,codeVerifier:m,redirectURI:h}){return Z({code:f,codeVerifier:m,redirectURI:h,options:r,tokenEndpoint:c,tokenEndpointAuth:u})},idToken:{jwks:(f)=>Kd(f.kid,n,i),algorithms:["RS256"],audience:r.clientId,maxTokenAge:"1h",issuer:n!=="common"&&n!=="organizations"&&n!=="consumers"?`${i}/${n}/v2.0`:void 0,verifyClaims:(f)=>{let m=f.tid;if(typeof m!=="string"||f.iss!==`${i}/${m}/v2.0`)return!1;if(n==="organizations"&&m===Bd)return!1;if(n==="consumers"&&m!==Bd)return!1;return!0}},async getUserInfo(f){if(r.getUserInfo)return r.getUserInfo(f);if(!f.idToken)return null;let m=ge(f.idToken);if(typeof m.oid!=="string"||m.oid.trim().length===0)return O.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let h=r.profilePhotoSize||48;if(!r.disableProfilePhoto&&f.accessToken)await C(`https://graph.microsoft.com/v1.0/me/photos/${h}x${h}/$value`,{headers:{Authorization:`Bearer ${f.accessToken}`},async onResponse(g){if(!g.response.ok)return;try{let A=await g.response.clone().arrayBuffer();m.picture=`data:image/jpeg;base64, ${Dt.encode(A)}`}catch(A){O.error(A&&typeof A==="object"&&"name"in A?A.name:"",A)}}});let y=await r.mapProfileToUser?.(m),w=m.email_verified!==void 0?m.email_verified:m.email&&(m.verified_primary_email?.includes(m.email)||m.verified_secondary_email?.includes(m.email))?!0:!1;return{user:{name:m.name,email:m.email,image:m.picture,emailVerified:w,...y},data:m}},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(f)=>{let m=r.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(r.scope)m.push(...r.scope);return Q({refreshToken:f,options:{clientId:r.clientId,clientSecret:r.clientSecret},extraParams:{scope:m.join(" ")},tokenEndpoint:c,tokenEndpointAuth:u})},options:r}},Kd=async(r,n,i)=>{let{data:s}=await C(`${i}/${n}/discovery/v2.0/keys`);if(!s?.keys)throw new l("BAD_REQUEST",{message:"Keys not found"});let c=s.keys.find((u)=>u.kid===r);if(!c)throw Error(`JWK with kid ${r} not found`);return await At(c,c.alg??"RS256")};var Wd=(r)=>({id:"naver",name:"Naver",accountSubject:({profile:i})=>i.response.id,createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["profile","email"];if(r.scope)f.push(...r.scope);if(s)f.push(...s);return G({id:"naver",options:r,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:f,state:i,redirectURI:c,additionalParams:u})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${i.accessToken}`}});if(c||!s||s.resultcode!=="00")return null;let u=await r.mapProfileToUser?.(s),f=s.response||{};return{user:{name:f.name||f.nickname||"",email:f.email,image:f.profile_image,emailVerified:!1,...u},data:s}},options:r});var Vd=(r)=>({id:"notion",name:"Notion",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,loginHint:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:[];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"notion",options:r,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:m,state:i,redirectURI:u,loginHint:c,additionalParams:{...f??{},owner:"user"}})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://api.notion.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://api.notion.com/v1/oauth/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${i.accessToken}`,"Notion-Version":"2022-06-28"}});if(c||!s)return null;let u=s.bot?.owner?.user;if(!u)return null;let f=await r.mapProfileToUser?.(u);return{user:{name:u.name||"",email:u.person?.email||null,image:u.avatar_url,emailVerified:!1,...f},data:u}},options:r});var qd=(r)=>{let n=r.issuer||"https://idp.paybin.io",i=`${n}/oauth2/authorize`,s=`${n}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:c})=>c.sub,async createAuthorizationURL({state:c,scopes:u,codeVerifier:f,redirectURI:m,loginHint:h,additionalParams:y}){if(!r.clientId||!r.clientSecret)throw O.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");if(!f)throw new S("codeVerifier is required for Paybin");let w=r.disableDefaultScope?[]:["openid","email","profile"];if(r.scope)w.push(...r.scope);if(u)w.push(...u);return await G({id:"paybin",options:r,authorizationEndpoint:i,scopes:w,state:c,codeVerifier:f,redirectURI:m,prompt:r.prompt,loginHint:h,additionalParams:y})},validateAuthorizationCode:async({code:c,codeVerifier:u,redirectURI:f})=>Z({code:c,codeVerifier:u,redirectURI:f,options:r,tokenEndpoint:s}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(c)=>Q({refreshToken:c,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:s}),async getUserInfo(c){if(r.getUserInfo)return r.getUserInfo(c);if(!c.idToken)return null;let u=ge(c.idToken),f=await r.mapProfileToUser?.(u);return{user:{name:u.name||u.preferred_username||"",email:u.email,image:u.picture,emailVerified:u.email_verified||!1,...f},data:u}},options:r}};var Fd=(r)=>{let n=(r.environment||"sandbox")==="sandbox",i=n?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",s=n?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",c=n?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",u={clientId:r.clientId,clientSecret:r.clientSecret},f={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:m})=>m.user_id,async createAuthorizationURL({state:m,codeVerifier:h,redirectURI:y,additionalParams:w}){if(!r.clientId||!r.clientSecret)throw O.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");return await G({id:"paypal",options:r,authorizationEndpoint:i,scopes:[],state:m,codeVerifier:h,redirectURI:y,prompt:r.prompt,additionalParams:w})},validateAuthorizationCode:async({code:m,codeVerifier:h,redirectURI:y})=>{try{return await Z({code:m,codeVerifier:h,redirectURI:r.redirectURI||y,options:u,tokenEndpoint:s,tokenEndpointAuth:f})}catch(w){throw O.error("PayPal token exchange failed:",w),new S("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(m)=>{try{return await Q({refreshToken:m,options:u,tokenEndpoint:s,tokenEndpointAuth:f})}catch(h){throw O.error("PayPal token refresh failed:",h),new S("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(m){if(r.getUserInfo)return r.getUserInfo(m);if(!m.accessToken)return O.error("Access token is required to fetch PayPal user info"),null;try{let h=await C(`${c}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${m.accessToken}`,Accept:"application/json"}});if(!h.data)return O.error("Failed to fetch user info from PayPal"),null;let y=h.data;if(m.idToken){let g;try{g=ge(m.idToken).sub}catch(E){return O.error("Failed to decode PayPal ID token:",E),null}let A=y.sub??y.user_id;if(!g||A!==g)return O.error("PayPal user info subject does not match ID token subject"),null}let w=await r.mapProfileToUser?.(y);return{user:{name:y.name,email:y.email,image:y.picture,emailVerified:y.email_verified,...w},data:y}}catch(h){return O.error("Failed to fetch user info from PayPal:",h),null}},options:r}};var Jd=(r)=>({id:"polar",name:"Polar",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:["openid","profile","email"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"polar",options:r,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:m,state:i,codeVerifier:c,redirectURI:u,prompt:r.prompt,additionalParams:f})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await r.mapProfileToUser?.(s);return{user:{name:s.public_name||s.username||"",email:s.email,image:s.avatar_url,emailVerified:s.email_verified??!1,...u},data:s}},options:r});var Oh="https://backboard.railway.com/oauth/auth",Gd="https://backboard.railway.com/oauth/token",Lh="https://backboard.railway.com/oauth/me",Qd=(r)=>({id:"railway",name:"Railway",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:i,codeVerifier:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["openid","email","profile"];if(r.scope)f.push(...r.scope);if(i)f.push(...i);return G({id:"railway",options:r,authorizationEndpoint:Oh,scopes:f,state:n,codeVerifier:s,redirectURI:c,additionalParams:u})},validateAuthorizationCode:async({code:n,codeVerifier:i,redirectURI:s})=>Z({code:n,codeVerifier:i,redirectURI:s,options:r,tokenEndpoint:Gd,authentication:"basic"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>Q({refreshToken:n,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:Gd,authentication:"basic"}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let{data:i,error:s}=await C(Lh,{headers:{authorization:`Bearer ${n.accessToken}`}});if(s||!i)return null;let c=await r.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture,emailVerified:!1,...c},data:i}},options:r});var Dh="placeholder.invalid";function dt({identifier:r,namespace:n}){let i=je().safeParse(`${r}@${n}.${Dh}`);if(!i.success)throw TypeError("Invalid placeholder email");return i.data}var Yd=(r)=>{let i={clientId:r.clientId,clientSecret:r.clientSecret},s={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:c})=>c.id,createAuthorizationURL({state:c,scopes:u,redirectURI:f,additionalParams:m}){let h=r.disableDefaultScope?[]:["identity"];if(r.scope)h.push(...r.scope);if(u)h.push(...u);return G({id:"reddit",options:r,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:h,state:c,redirectURI:f,duration:r.duration,additionalParams:m})},validateAuthorizationCode:async({code:c,redirectURI:u})=>Z({code:c,redirectURI:r.redirectURI||u,options:i,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:s,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(c)=>Q({refreshToken:c,options:i,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:s}),async getUserInfo(c){if(r.getUserInfo)return r.getUserInfo(c);let{data:u,error:f}=await C("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${c.accessToken}`,"User-Agent":"better-auth"}});if(f)return null;let m=await r.mapProfileToUser?.(u),h=m?.email||dt({identifier:u.id,namespace:"reddit"});return{user:{name:u.name,image:u.icon_img?.split("?")[0],...m,email:h,emailVerified:m?.emailVerified??!1},data:u}},options:r}};var rl=(r)=>({id:"roblox",name:"Roblox",accountSubject:({profile:i})=>i.sub,createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["openid","profile"];if(r.scope)f.push(...r.scope);if(s)f.push(...s);return G({id:"roblox",options:r,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:f,state:i,redirectURI:c,prompt:r.prompt||"select_account consent",additionalParams:u})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:r.redirectURI||s,options:r,tokenEndpoint:"https://apis.roblox.com/oauth/v1/token",authentication:"post"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://apis.roblox.com/oauth/v1/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await r.mapProfileToUser?.(s);return{user:{name:s.nickname||s.preferred_username||"",image:s.picture,email:dt({identifier:s.sub,namespace:"roblox"}),emailVerified:!1,...u},data:{...s}}},options:r});var ol=(r)=>{let n=(r.environment??"production")==="sandbox",i=r.loginUrl?`https://${r.loginUrl}/services/oauth2/authorize`:n?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",s=r.loginUrl?`https://${r.loginUrl}/services/oauth2/token`:n?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",c=r.loginUrl?`https://${r.loginUrl}/services/oauth2/userinfo`:n?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",accountSubject:({profile:u})=>u.user_id,async createAuthorizationURL({state:u,scopes:f,codeVerifier:m,redirectURI:h,additionalParams:y}){if(!r.clientId||!r.clientSecret)throw O.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new S("CLIENT_ID_AND_SECRET_REQUIRED");if(!m)throw new S("codeVerifier is required for Salesforce");let w=r.disableDefaultScope?[]:["openid","email","profile"];if(r.scope)w.push(...r.scope);if(f)w.push(...f);return G({id:"salesforce",options:r,authorizationEndpoint:i,scopes:w,state:u,codeVerifier:m,redirectURI:r.redirectURI||h,additionalParams:y})},validateAuthorizationCode:async({code:u,codeVerifier:f,redirectURI:m})=>Z({code:u,codeVerifier:f,redirectURI:r.redirectURI||m,options:r,tokenEndpoint:s}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(u)=>Q({refreshToken:u,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:s}),async getUserInfo(u){if(r.getUserInfo)return r.getUserInfo(u);try{let{data:f}=await C(c,{headers:{Authorization:`Bearer ${u.accessToken}`}});if(!f)return O.error("Failed to fetch user info from Salesforce"),null;let m=await r.mapProfileToUser?.(f);return{user:{name:f.name,email:f.email,image:f.photos?.picture||f.photos?.thumbnail,emailVerified:f.email_verified??!1,...m},data:f}}catch(f){return O.error("Failed to fetch user info from Salesforce:",f),null}},options:r}};var nl=(r)=>({id:"slack",name:"Slack",accountSubject:({profile:i})=>i["https://slack.com/user_id"],createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["openid","profile","email"];if(s)f.push(...s);if(r.scope)f.push(...r.scope);return G({id:"slack",options:r,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:f,state:i,redirectURI:c,additionalParams:u})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://slack.com/api/openid.connect.token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://slack.com/api/openid.connect.token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await r.mapProfileToUser?.(s);return{user:{name:s.name||"",email:s.email,emailVerified:s.email_verified,image:s.picture||s["https://slack.com/user_image_512"],...u},data:s}},options:r});var il=(r)=>({id:"spotify",name:"Spotify",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:["user-read-email"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:m,state:i,codeVerifier:c,redirectURI:u,additionalParams:f})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,redirectURI:c,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await r.mapProfileToUser?.(s);return{user:{name:s.display_name,email:s.email,image:s.images[0]?.url,emailVerified:!1,...u},data:s}},options:r});var sl=(r)=>{let i={method:"custom",customizeRequest({body:s}){s.set("client_key",r.clientKey),s.set("client_secret",r.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:s})=>s.data.user.open_id,createAuthorizationURL({state:s,scopes:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:["user.info.profile"];if(r.scope)m.push(...r.scope);if(c)m.push(...c);let h=new URL("https://www.tiktok.com/v2/auth/authorize");if(h.searchParams.set("scope",m.join(",")),h.searchParams.set("response_type","code"),h.searchParams.set("client_key",r.clientKey),h.searchParams.set("redirect_uri",r.redirectURI||u),h.searchParams.set("state",s),f)for(let[y,w]of Object.entries(f)){if(ar.has(y))continue;if(y==="client_key")continue;h.searchParams.set(y,w)}return h},validateAuthorizationCode:async({code:s,codeVerifier:c,redirectURI:u})=>Z({code:s,codeVerifier:c,redirectURI:r.redirectURI||u,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:i}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(s)=>Q({refreshToken:s,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:i}),async getUserInfo(s){if(r.getUserInfo)return r.getUserInfo(s);let{data:c,error:u}=await C(`https://open.tiktokapis.com/v2/user/info/?fields=${["open_id","avatar_large_url","display_name","username"].join(",")}`,{headers:{authorization:`Bearer ${s.accessToken}`}});if(u)return null;return{user:{email:c.data.user.email||dt({identifier:c.data.user.open_id,namespace:"tiktok"}),name:c.data.user.display_name||c.data.user.username||"",image:c.data.user.avatar_large_url,emailVerified:!1},data:c}},options:r}};var al=(r)=>({id:"twitch",name:"Twitch",accountSubject:({profile:i})=>i.sub,createAuthorizationURL({state:i,scopes:s,redirectURI:c,additionalParams:u}){let f=r.disableDefaultScope?[]:["user:read:email","openid"];if(r.scope)f.push(...r.scope);if(s)f.push(...s);return G({id:"twitch",redirectURI:c,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:f,state:i,claims:r.claims||["email","email_verified","preferred_username","picture"],additionalParams:u})},validateAuthorizationCode:async({code:i,redirectURI:s})=>Z({code:i,redirectURI:s,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let s=i.idToken;if(!s)return O.error("No idToken found in token"),null;let c=ge(s),u=await r.mapProfileToUser?.(c);return{user:{name:c.preferred_username,email:c.email,image:c.picture,emailVerified:c.email_verified,...u},data:c}},options:r});var cl=(r)=>({id:"twitter",name:"Twitter",accountSubject:({profile:i})=>i.data.id,createAuthorizationURL(i){let s=r.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];if(r.scope)s.push(...r.scope);if(i.scopes)s.push(...i.scopes);return G({id:"twitter",options:r,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:s,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI,additionalParams:i.additionalParams})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c})=>Z({code:i,codeVerifier:s,authentication:"basic",redirectURI:c,options:r,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},authentication:"basic",tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);let{data:s,error:c}=await C("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(c)return null;let{data:u,error:f}=await C("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}}),m=!1;if(!f&&u?.data?.confirmed_email)s.data.email=u.data.confirmed_email,m=!0;let h=await r.mapProfileToUser?.(s);return{user:{name:s.data.name,email:s.data.email||dt({identifier:s.data.id,namespace:"twitter"}),image:s.data.profile_image_url,emailVerified:m,...h},data:s}},options:r});var ul=(r)=>({id:"vercel",name:"Vercel",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:i,codeVerifier:s,redirectURI:c,additionalParams:u}){if(!s)throw new S("codeVerifier is required for Vercel");let f=void 0;if(r.scope!==void 0||i!==void 0){if(f=[],r.scope)f.push(...r.scope);if(i)f.push(...i)}return G({id:"vercel",options:r,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:f,state:n,codeVerifier:s,redirectURI:c,additionalParams:u})},validateAuthorizationCode:async({code:n,codeVerifier:i,redirectURI:s})=>Z({code:n,codeVerifier:i,redirectURI:s,options:r,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let{data:i,error:s}=await C("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(s||!i)return null;let c=await r.mapProfileToUser?.(i);return{user:{name:i.name??i.preferred_username??"",email:i.email,image:i.picture,emailVerified:i.email_verified??!1,...c},data:i}},options:r});var dl=(r)=>({id:"vk",name:"VK",accountSubject:({profile:i})=>i.user.user_id,async createAuthorizationURL({state:i,scopes:s,codeVerifier:c,redirectURI:u,additionalParams:f}){let m=r.disableDefaultScope?[]:["email","phone"];if(r.scope)m.push(...r.scope);if(s)m.push(...s);return G({id:"vk",options:r,authorizationEndpoint:"https://id.vk.com/authorize",scopes:m,state:i,redirectURI:u,codeVerifier:c,additionalParams:f})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:c,deviceId:u})=>Z({code:i,codeVerifier:s,redirectURI:r.redirectURI||c,options:r,deviceId:u,tokenEndpoint:"https://id.vk.com/oauth2/auth"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://id.vk.com/oauth2/auth"}),async getUserInfo(i){if(r.getUserInfo)return r.getUserInfo(i);if(!i.accessToken)return null;let{data:s,error:c}=await C("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({access_token:i.accessToken,client_id:r.clientId}).toString()});if(c)return null;let u=await r.mapProfileToUser?.(s);if(!s.user.email&&!u?.email)return null;return{user:{first_name:s.user.first_name,last_name:s.user.last_name,email:s.user.email,image:s.user.avatar,emailVerified:!1,birthday:s.user.birthday,sex:s.user.sex,name:`${s.user.first_name} ${s.user.last_name}`,...u},data:s}},options:r});var ll=(r)=>({id:"wechat",name:"WeChat",accountSubject:({profile:n})=>n.unionid||n.openid,createAuthorizationURL({state:n,scopes:i,redirectURI:s,additionalParams:c}){let u=r.disableDefaultScope?[]:["snsapi_login"];r.scope&&u.push(...r.scope),i&&u.push(...i);let f=new URL("https://open.weixin.qq.com/connect/qrconnect");if(f.searchParams.set("scope",u.join(",")),f.searchParams.set("response_type","code"),f.searchParams.set("appid",r.clientId),f.searchParams.set("redirect_uri",r.redirectURI||s),f.searchParams.set("state",n),f.searchParams.set("lang",r.lang||"cn"),c)for(let[m,h]of Object.entries(c)){if(ar.has(m))continue;if(m==="appid")continue;f.searchParams.set(m,h)}return f.hash="wechat_redirect",f},validateAuthorizationCode:async({code:n})=>{let{data:i,error:s}=await C("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:r.clientId,secret:r.clientSecret,code:n,grant_type:"authorization_code"}).toString(),{method:"GET"});if(s||!i||i.errcode)throw Error(`Failed to validate authorization code: ${i?.errmsg||s?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:i.access_token,refreshToken:i.refresh_token,accessTokenExpiresAt:new Date(Date.now()+i.expires_in*1000),scopes:i.scope.split(","),openid:i.openid,unionid:i.unionid}},refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>{let{data:i,error:s}=await C("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:r.clientId,grant_type:"refresh_token",refresh_token:n}).toString(),{method:"GET"});if(s||!i||i.errcode)throw Error(`Failed to refresh access token: ${i?.errmsg||s?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:i.access_token,refreshToken:i.refresh_token,accessTokenExpiresAt:new Date(Date.now()+i.expires_in*1000),scopes:i.scope.split(",")}},async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let i=n.openid;if(!i)return null;let{data:s,error:c}=await C("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:n.accessToken||"",openid:i,lang:"zh_CN"}).toString(),{method:"GET"});if(c||!s||s.errcode)return null;let u=await r.mapProfileToUser?.(s),f=s.unionid||s.openid||i;return{user:{name:s.nickname,email:s.email||dt({identifier:f,namespace:"wechat"}),image:s.headimgurl,emailVerified:!1,...u},data:s}},options:r});var fl=(r)=>{let n={pkce:!0,...r};return{id:"zoom",name:"Zoom",accountSubject:({profile:i})=>i.id,createAuthorizationURL:async({state:i,redirectURI:s,codeVerifier:c,additionalParams:u})=>G({id:"zoom",options:n,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:i,redirectURI:s,codeVerifier:n.pkce?c:void 0,additionalParams:u}),validateAuthorizationCode:async({code:i,redirectURI:s,codeVerifier:c})=>Z({code:i,redirectURI:n.redirectURI||s,codeVerifier:c,options:n,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:n.refreshAccessToken?n.refreshAccessToken:async(i)=>Q({refreshToken:i,options:{clientId:n.clientId,clientKey:n.clientKey,clientSecret:n.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(i){if(n.getUserInfo)return n.getUserInfo(i);let{data:s,error:c}=await C("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(c)return null;let u=await n.mapProfileToUser?.(s);return{user:{name:s.display_name,image:s.pic_url,email:s.email,emailVerified:Boolean(s.verified),...u},data:{...s}}}}};var ru={apple:yd,atlassian:Ad,cloudflare:vd,cognito:Td,discord:Id,facebook:Ud,figma:Cd,github:xd,microsoft:Md,google:Ld,huggingface:Pd,slack:nl,spotify:il,twitch:al,twitter:cl,dropbox:_d,kick:zd,linear:jd,linkedin:Hd,gitlab:Od,tiktok:sl,reddit:Yd,roblox:rl,salesforce:ol,vk:dl,zoom:fl,notion:Vd,kakao:Nd,naver:Wd,line:$d,paybin:qd,paypal:Fd,polar:Jd,railway:Qd,vercel:ul,wechat:ll},Ph=Object.keys(ru),Zn=d(Ph).or(e());function pl(r){if(!r)return[];return r.split(",").map((n)=>n.trim()).filter(Boolean)}var ml=U("/list-accounts",{method:"GET",use:[_t],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(r)=>{let n=r.context.session,i=await r.context.internalAdapter.findAccounts(n.user.id);return r.json(i.map((s)=>{let{scope:c,...u}=Wc(r.context.options,s);return{...u,scopes:pl(c)}}))}),hl=U("/link-social",{method:"POST",requireHeaders:!0,body:t({callbackURL:e().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Zn,idToken:t({token:e(),nonce:e().optional(),accessToken:e().optional(),refreshToken:e().optional()}).optional(),requestSignUp:o().optional(),scopes:a(e()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:e().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:o().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:e().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:bo,additionalData:j(e(),st()).optional()}),use:[_t],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(r)=>{let n=r.context.session,i=await it(r.context.socialProviders,{value:r.body.provider});if(!i)throw r.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:r.body.provider}),l.from("NOT_FOUND",x.PROVIDER_NOT_FOUND);if(r.body.idToken){if(!ko(i))throw r.context.logger.error("Provider does not support id token verification",{provider:r.body.provider}),l.from("NOT_FOUND",x.ID_TOKEN_NOT_SUPPORTED);let{token:f,nonce:m}=r.body.idToken;if(!await So(i,f,m,r))throw r.context.logger.warn("Invalid id token",{provider:r.body.provider}),l.from("UNAUTHORIZED",x.INVALID_TOKEN);let h=await i.getUserInfo({idToken:f,accessToken:r.body.idToken.accessToken,refreshToken:r.body.idToken.refreshToken});if(!h||!h?.user)throw r.context.logger.error("Failed to get user info",{provider:r.body.provider}),l.from("UNAUTHORIZED",x.FAILED_TO_GET_USER_INFO);if(!h.user.email)throw r.context.logger.error(Dr(r.body.provider,{source:"id_token"}),{provider:r.body.provider}),l.from("UNAUTHORIZED",x.USER_EMAIL_NOT_FOUND);let y=await jn(i,{idToken:f,accessToken:r.body.idToken.accessToken,refreshToken:r.body.idToken.refreshToken},h.data),w=await r.context.internalAdapter.findAccountByKey(y);if(w?.userId===n.user.id){let g=Object.fromEntries(Object.entries({providerId:i.id,accessToken:await ye(r.body.idToken.accessToken,r.context),idToken:f,refreshToken:await ye(r.body.idToken.refreshToken,r.context)}).filter(([A,E])=>E!==void 0));return await r.context.internalAdapter.updateAccount(w.id,g),await To(r,n.user.id,h.user),r.json({url:"",status:!0,redirect:!1})}if(w)throw l.from("CONFLICT",x.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!r.context.trustedProviders.includes(i.id)&&!h.user.emailVerified||r.context.options.account?.accountLinking?.enabled===!1)throw l.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(h.user.email?.toLowerCase()!==n.user.email.toLowerCase()&&r.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw l.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await r.context.internalAdapter.createAccount({userId:n.user.id,...y,accessToken:await ye(r.body.idToken.accessToken,r.context),idToken:f,refreshToken:await ye(r.body.idToken.refreshToken,r.context)})}catch{throw l.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await To(r,n.user.id,h.user),r.json({url:"",status:!0,redirect:!1})}let s=Nr(i),c=await zr(r,{link:{userId:n.user.id,email:n.user.email},additionalData:r.body.additionalData,idTokenNonce:s}),u=await i.createAuthorizationURL({state:c.state,codeVerifier:c.codeVerifier,idTokenNonce:s,redirectURI:`${r.context.baseURL}${sr(i)}`,scopes:r.body.scopes,loginHint:r.body.loginHint,additionalParams:r.body.additionalParams});if(!r.body.disableRedirect)r.setHeader("Location",u.toString());return r.json({url:u.toString(),redirect:!r.body.disableRedirect})}),yl=U("/unlink-account",{method:"POST",body:t({accountId:e().meta({description:"The Better Auth account ID to unlink"})}),use:[Ds],metadata:{openapi:{description:"Unlink an account",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(r)=>{let{accountId:n}=r.body,i=await r.context.internalAdapter.findAccounts(r.context.session.user.id);if(i.length===1&&!r.context.options.account?.accountLinking?.allowUnlinkingAll)throw l.from("BAD_REQUEST",x.FAILED_TO_UNLINK_LAST_ACCOUNT);let s=i.find((c)=>c.id===n);if(!s)throw l.from("BAD_REQUEST",x.ACCOUNT_NOT_FOUND);return await r.context.internalAdapter.deleteAccount(s.id),r.json({status:!0})});async function Ks(r,n){let i=await Ye(r,{disableCookieCache:qt(r)});if(!i&&(r.request||r.headers))throw r.error("UNAUTHORIZED");let s=i?.user?.id||n;if(!s)throw l.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return s}var Ws=ee([br({accountId:e().meta({description:"The Better Auth account ID"}),userId:e().meta({description:"The user ID associated with the account"}).optional()}),br({useAccountCookie:p(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:e().meta({description:"The user ID associated with the account"}).optional()})]);function wl(r,n,{resolvedUserId:i,selection:s}){return(!Do(r.context.options)||n.userId===i)&&("accountId"in s?n.id===s.accountId:!0)}async function Vs(r,{resolvedUserId:n,selection:i}){if("accountId"in i){let s=(await r.context.internalAdapter.findAccounts(n)).find((c)=>c.id===i.accountId);if(s)return{account:s,accountCookie:null}}else if(r.context.options.account?.storeAccountCookie){let s=await Pn(r);if(s&&wl(r,s,{resolvedUserId:n,selection:i}))return{account:s,accountCookie:s}}throw l.from("BAD_REQUEST",x.ACCOUNT_NOT_FOUND)}async function gl(r,{resolvedUserId:n,selection:i,account:s}){let c=s??(await Vs(r,{resolvedUserId:n,selection:i})).account;if(!wl(r,c,{resolvedUserId:n,selection:i}))throw l.from("BAD_REQUEST",x.ACCOUNT_NOT_FOUND);let u=await it(r.context.socialProviders,{value:c.providerId});if(!u)throw l.from("BAD_REQUEST",{message:`Provider ${c.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let f=null,m=c.accessTokenExpiresAt&&new Date(c.accessTokenExpiresAt).getTime()-Date.now()<5000;if(c.refreshToken&&m&&u.refreshAccessToken){let y=await Wn(c.refreshToken,r.context);f=await u.refreshAccessToken(y,r);let w={accessToken:await ye(f?.accessToken,r.context),accessTokenExpiresAt:f?.accessTokenExpiresAt,refreshToken:f?.refreshToken?await ye(f.refreshToken,r.context):c.refreshToken,refreshTokenExpiresAt:f?.refreshTokenExpiresAt??c.refreshTokenExpiresAt,idToken:f?.idToken||c.idToken},g=null;if(c.id)g=await r.context.internalAdapter.updateAccount(c.id,w);if(r.context.options.account?.storeAccountCookie)await Et(r,{...c,...g??w})}let h=(()=>{if(f?.accessTokenExpiresAt){if(typeof f.accessTokenExpiresAt==="string")return new Date(f.accessTokenExpiresAt);return f.accessTokenExpiresAt}if(c.accessTokenExpiresAt){if(typeof c.accessTokenExpiresAt==="string")return new Date(c.accessTokenExpiresAt);return c.accessTokenExpiresAt}})();return{accessToken:f?.accessToken??await Wn(c.accessToken??"",r.context),accessTokenExpiresAt:h,scopes:pl(c.scope),idToken:f?.idToken??c.idToken??void 0}}catch(f){throw l.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}var Al=U("/get-access-token",{method:"POST",body:Ws,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(r)=>{let{userId:n}=r.body,i=await gl(r,{resolvedUserId:await Ks(r,n),selection:r.body});return r.json(i)}),bl=U("/refresh-token",{method:"POST",body:Ws,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(r)=>{let{userId:n}=r.body,{account:i,accountCookie:s}=await Vs(r,{resolvedUserId:await Ks(r,n),selection:r.body}),c=await it(r.context.socialProviders,{value:i.providerId});if(!c)throw l.from("BAD_REQUEST",{message:`Provider ${i.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!c.refreshAccessToken)throw l.from("BAD_REQUEST",{message:`Provider ${i.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let u=i.refreshToken??void 0;if(!u)throw l.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let f=await Wn(u,r.context),m=await c.refreshAccessToken(f,r),h=m.refreshToken?await ye(m.refreshToken,r.context):u,y=m.refreshTokenExpiresAt??i.refreshTokenExpiresAt,w={accessToken:await ye(m.accessToken,r.context),refreshToken:h,accessTokenExpiresAt:m.accessTokenExpiresAt,refreshTokenExpiresAt:y,idToken:m.idToken||i.idToken},g=null;if(i.id)g=await r.context.internalAdapter.updateAccount(i.id,w);if(s?.id===i.id&&r.context.options.account?.storeAccountCookie)await Et(r,{...s,...g??w});let A=g?.scope??i.scope;return r.json({accessToken:m.accessToken,refreshToken:m.refreshToken??f,accessTokenExpiresAt:m.accessTokenExpiresAt,refreshTokenExpiresAt:y,scope:A,idToken:m.idToken||i.idToken,providerId:i.providerId,accountId:i.id})}catch(f){throw l.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),El=U("/account-info",{method:"GET",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:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:Ws},async(r)=>{let{userId:n}=r.query,i=await Ks(r,n),{account:s}=await Vs(r,{resolvedUserId:i,selection:r.query}),c=await it(r.context.socialProviders,{value:s.providerId});if(!c)throw l.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let u=await gl(r,{resolvedUserId:i,selection:r.query,account:s});if(!u.accessToken)throw l.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let f=await c.getUserInfo({...u,accessToken:u.accessToken});if(!f)throw l.from("UNAUTHORIZED",x.FAILED_TO_GET_USER_INFO);return r.json({...f,account:{id:s.id,providerId:s.providerId,accountId:s.accountId}})});var cr=t({code:e().optional(),error:e().optional(),device_id:e().optional(),error_description:e().optional(),state:e().optional(),user:e().optional(),iss:e().optional()}),kl=U("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:cr.optional(),query:cr.optional(),metadata:{...En,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async(r)=>{let n,i=r.context.options.onAPIError?.errorURL||`${r.context.baseURL}/error`;if(r.method==="POST"){let J=r.body?cr.parse(r.body):{},X=r.query?cr.parse(r.query):{},te=cr.parse({...J,...X}),q=new URLSearchParams;for(let[ie,se]of Object.entries(te))if(se!==void 0&&se!==null)q.set(ie,String(se));let re=`${r.context.baseURL}/callback/${r.params.id}?${q.toString()}`;throw r.redirect(re)}try{if(r.method==="GET")n=cr.parse(r.query);else if(r.method==="POST")n=cr.parse(r.body);else throw Error("Unsupported method")}catch(J){r.context.logger.error("INVALID_CALLBACK_REQUEST",J);let X=ct(i,new URLSearchParams({error:"invalid_callback_request"}));throw r.redirect(X)}let{code:s,error:c,state:u,error_description:f,device_id:m,user:h,iss:y}=n;if(u===void 0&&s){let J=await it(r.context.socialProviders,{value:r.params.id});if(J?.allowIdpInitiated){let X=Nr(J),{state:te,codeVerifier:q}=await zr(r,{idTokenNonce:X}),re=await J.createAuthorizationURL({state:te,codeVerifier:q,idTokenNonce:X,redirectURI:`${r.context.baseURL}${sr(J)}`});throw r.redirect(re.toString())}}if(!u){r.context.logger.error("State not found",c);let J=ct(i,new URLSearchParams({error:"state_not_found"}));throw r.redirect(J)}let{codeVerifier:w,callbackURL:g,link:A,errorURL:E,newUserURL:v,requestSignUp:_,idTokenNonce:P}=await hd(r);function I(J,X){let te=E??i,q=new URLSearchParams({error:J});if(X)q.set("error_description",X);let re=ct(te,q);throw r.redirect(re)}if(c)I(c,f);if(!s)throw r.context.logger.warn("Code not found"),I(Ae.NO_CODE);let T=await it(r.context.socialProviders,{value:r.params.id});if(!T)throw r.context.logger.warn("OAuth provider not found",{providerId:r.params.id}),I(Ae.PROVIDER_NOT_FOUND);if(y&&T.issuer&&y!==T.issuer)throw r.context.logger.error("OAuth issuer mismatch",{expected:T.issuer,received:y}),I(Ae.ISSUER_MISMATCH);if(T.requiresIdTokenNonce&&!P)throw r.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:T.id}),I(Ae.NONCE_BINDING_MISSING);let D;try{D=await T.validateAuthorizationCode({code:s,codeVerifier:w,deviceId:m,redirectURI:`${r.context.baseURL}${sr(T)}`})}catch(J){throw r.context.logger.error("",J),I(Ae.INVALID_CODE)}if(!D)throw I(Ae.INVALID_CODE);let k=h?de(h):null,R=await T.getUserInfo({...D,...P?{expectedIdTokenNonce:P}:{},user:k??void 0});if(!R?.user)return r.context.logger.error("Unable to get user info"),I(Ae.UNABLE_TO_GET_USER_INFO);let L=R.user,M=$n(R.data),N;try{N=await gs(T,D,R.data)}catch(J){return r.context.logger.error("Unable to derive provider account identity",{providerId:T.id,error:J}),I(Ae.UNABLE_TO_GET_USER_INFO)}let{accountId:H}=N;if(!g)throw r.context.logger.error("No callback URL found"),I(Ae.NO_CALLBACK_URL);let z={...N,...D,scope:D.scopes?.join(",")};if(A){let J=await dd(r,{link:A,userInfo:L,account:z,profile:M,scopes:D.scopes});if(!J.linked)return I(J.error.code,J.error.message);throw r.redirect(g)}if(!L.email)return r.context.logger.error(Dr(T.id)),I(Ae.EMAIL_NOT_FOUND);let B;try{B=await Qn(r,{userInfo:{...L,id:H,email:L.email,name:L.name||""},account:z,callbackURL:g,disableSignUp:T.disableImplicitSignUp&&!_||T.options?.disableSignUp,overrideUserInfo:T.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:T.id,profile:M}}})}catch(J){if(Oe(J)&&J.body?.code)I(J.body.code,J.body.message);throw J}if(B.error)return r.context.logger.error(B.error.split(" ").join("_")),I(B.error.split(" ").join("_"));let{session:K,user:W}=B.data;await Le(r,{session:K,user:W});let V;try{V=(B.isRegister?v||g:g).toString()}catch{V=B.isRegister?v||g:g}throw r.redirect(V)});function Sl(r){return r.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;")}var Nh=(r,n="Unknown",i=null)=>{let s=r.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
49
+ <html lang="en">
50
+ <head>
51
+ <meta charset="UTF-8" />
52
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
53
+ <title>Error</title>
54
+ <style>
55
+ * {
56
+ box-sizing: border-box;
57
+ }
58
+ body {
59
+ font-family: ${s?.font?.defaultFamily||"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"};
60
+ background: ${s?.colors?.background||"var(--background)"};
61
+ color: var(--foreground);
62
+ margin: 0;
63
+ }
64
+ :root,
65
+ :host {
66
+ --spacing: 0.25rem;
67
+ --container-md: 28rem;
68
+ --text-sm: ${s?.size?.textSm||"0.875rem"};
69
+ --text-sm--line-height: calc(1.25 / 0.875);
70
+ --text-2xl: ${s?.size?.text2xl||"1.5rem"};
71
+ --text-2xl--line-height: calc(2 / 1.5);
72
+ --text-4xl: ${s?.size?.text4xl||"2.25rem"};
73
+ --text-4xl--line-height: calc(2.5 / 2.25);
74
+ --text-6xl: ${s?.size?.text6xl||"3rem"};
75
+ --text-6xl--line-height: 1;
76
+ --font-weight-medium: 500;
77
+ --font-weight-semibold: 600;
78
+ --font-weight-bold: 700;
79
+ --default-transition-duration: 150ms;
80
+ --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
81
+ --radius: ${s?.size?.radiusSm||"0.625rem"};
82
+ --default-mono-font-family: ${s?.font?.monoFamily||"var(--font-geist-mono)"};
83
+ --primary: ${s?.colors?.primary||"black"};
84
+ --primary-foreground: ${s?.colors?.primaryForeground||"white"};
85
+ --background: ${s?.colors?.background||"white"};
86
+ --foreground: ${s?.colors?.foreground||"oklch(0.271 0 0)"};
87
+ --border: ${s?.colors?.border||"oklch(0.89 0 0)"};
88
+ --destructive: ${s?.colors?.destructive||"oklch(0.55 0.15 25.723)"};
89
+ --muted-foreground: ${s?.colors?.mutedForeground||"oklch(0.545 0 0)"};
90
+ --corner-border: ${s?.colors?.cornerBorder||"#404040"};
91
+ }
92
+
93
+ button, .btn {
94
+ cursor: pointer;
95
+ background: none;
96
+ border: none;
97
+ color: inherit;
98
+ font: inherit;
99
+ transition: all var(--default-transition-duration)
100
+ var(--default-transition-timing-function);
101
+ }
102
+ button:hover, .btn:hover {
103
+ opacity: 0.8;
104
+ }
105
+
106
+ @media (prefers-color-scheme: dark) {
107
+ :root,
108
+ :host {
109
+ --primary: ${s?.colors?.primary||"white"};
110
+ --primary-foreground: ${s?.colors?.primaryForeground||"black"};
111
+ --background: ${s?.colors?.background||"oklch(0.15 0 0)"};
112
+ --foreground: ${s?.colors?.foreground||"oklch(0.98 0 0)"};
113
+ --border: ${s?.colors?.border||"oklch(0.27 0 0)"};
114
+ --destructive: ${s?.colors?.destructive||"oklch(0.65 0.15 25.723)"};
115
+ --muted-foreground: ${s?.colors?.mutedForeground||"oklch(0.65 0 0)"};
116
+ --corner-border: ${s?.colors?.cornerBorder||"#a0a0a0"};
117
+ }
118
+ }
119
+ @media (max-width: 640px) {
120
+ :root, :host {
121
+ --text-6xl: 2.5rem;
122
+ --text-2xl: 1.25rem;
123
+ --text-sm: 0.8125rem;
124
+ }
125
+ }
126
+ @media (max-width: 480px) {
127
+ :root, :host {
128
+ --text-6xl: 2rem;
129
+ --text-2xl: 1.125rem;
130
+ }
131
+ }
132
+ </style>
133
+ </head>
134
+ <body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
135
+ <div
136
+ style="
137
+ display: flex;
138
+ flex-direction: column;
139
+ align-items: center;
140
+ justify-content: center;
141
+ gap: 1.5rem;
142
+ position: relative;
143
+ width: 100%;
144
+ min-height: 100vh;
145
+ padding: 1rem;
146
+ "
147
+ >
148
+ ${s?.disableBackgroundGrid?"":`
149
+ <div
150
+ style="
151
+ position: absolute;
152
+ inset: 0;
153
+ background-image: linear-gradient(to right, ${s?.colors?.gridColor||"var(--border)"} 1px, transparent 1px),
154
+ linear-gradient(to bottom, ${s?.colors?.gridColor||"var(--border)"} 1px, transparent 1px);
155
+ background-size: 40px 40px;
156
+ opacity: 0.6;
157
+ pointer-events: none;
158
+ width: 100vw;
159
+ height: 100vh;
160
+ "
161
+ ></div>
162
+ <div
163
+ style="
164
+ position: absolute;
165
+ inset: 0;
166
+ display: flex;
167
+ align-items: center;
168
+ justify-content: center;
169
+ background: ${s?.colors?.background||"var(--background)"};
170
+ mask-image: radial-gradient(ellipse at center, transparent 20%, black);
171
+ -webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
172
+ pointer-events: none;
173
+ "
174
+ ></div>
175
+ `}
176
+
177
+ <div
178
+ style="
179
+ position: relative;
180
+ z-index: 10;
181
+ border: 2px solid var(--border);
182
+ background: ${s?.colors?.cardBackground||"var(--background)"};
183
+ padding: 1.5rem;
184
+ max-width: 42rem;
185
+ width: 100%;
186
+ "
187
+ >
188
+ ${s?.disableCornerDecorations?"":`
189
+ <!-- Corner decorations -->
190
+ <div
191
+ style="
192
+ position: absolute;
193
+ top: -2px;
194
+ left: -2px;
195
+ width: 2rem;
196
+ height: 2rem;
197
+ border-top: 4px solid var(--corner-border);
198
+ border-left: 4px solid var(--corner-border);
199
+ "
200
+ ></div>
201
+ <div
202
+ style="
203
+ position: absolute;
204
+ top: -2px;
205
+ right: -2px;
206
+ width: 2rem;
207
+ height: 2rem;
208
+ border-top: 4px solid var(--corner-border);
209
+ border-right: 4px solid var(--corner-border);
210
+ "
211
+ ></div>
212
+
213
+ <div
214
+ style="
215
+ position: absolute;
216
+ bottom: -2px;
217
+ left: -2px;
218
+ width: 2rem;
219
+ height: 2rem;
220
+ border-bottom: 4px solid var(--corner-border);
221
+ border-left: 4px solid var(--corner-border);
222
+ "
223
+ ></div>
224
+ <div
225
+ style="
226
+ position: absolute;
227
+ bottom: -2px;
228
+ right: -2px;
229
+ width: 2rem;
230
+ height: 2rem;
231
+ border-bottom: 4px solid var(--corner-border);
232
+ border-right: 4px solid var(--corner-border);
233
+ "
234
+ ></div>`}
235
+
236
+ <div style="text-align: center; margin-bottom: 1.5rem;">
237
+ <div style="margin-bottom: 1.5rem;">
238
+ <div
239
+ style="
240
+ display: inline-block;
241
+ border: 2px solid ${s?.disableTitleBorder?"transparent":s?.colors?.titleBorder||"var(--destructive)"};
242
+ padding: 0.375rem 1rem;
243
+ "
244
+ >
245
+ <h1
246
+ style="
247
+ font-size: var(--text-6xl);
248
+ font-weight: var(--font-weight-semibold);
249
+ color: ${s?.colors?.titleColor||"var(--foreground)"};
250
+ letter-spacing: -0.02em;
251
+ margin: 0;
252
+ "
253
+ >
254
+ ERROR
255
+ </h1>
256
+ </div>
257
+ <div
258
+ style="
259
+ height: 2px;
260
+ background-color: var(--border);
261
+ width: calc(100% + 3rem);
262
+ margin-left: -1.5rem;
263
+ margin-top: 1.5rem;
264
+ "
265
+ ></div>
266
+ </div>
267
+
268
+ <h2
269
+ style="
270
+ font-size: var(--text-2xl);
271
+ font-weight: var(--font-weight-semibold);
272
+ color: var(--foreground);
273
+ margin: 0 0 1rem;
274
+ "
275
+ >
276
+ Something went wrong
277
+ </h2>
278
+
279
+ <div
280
+ style="
281
+ display: inline-flex;
282
+ align-items: center;
283
+ gap: 0.5rem;
284
+ border: 2px solid var(--border);
285
+ background-color: var(--muted);
286
+ padding: 0.375rem 0.75rem;
287
+ margin: 0 0 1rem;
288
+ flex-wrap: wrap;
289
+ justify-content: center;
290
+ "
291
+ >
292
+ <span
293
+ style="
294
+ font-size: 0.75rem;
295
+ color: var(--muted-foreground);
296
+ font-weight: var(--font-weight-semibold);
297
+ "
298
+ >
299
+ CODE:
300
+ </span>
301
+ <span
302
+ style="
303
+ font-size: var(--text-sm);
304
+ font-family: var(--default-mono-font-family, monospace);
305
+ color: var(--foreground);
306
+ word-break: break-all;
307
+ "
308
+ >
309
+ ${Sl(n)}
310
+ </span>
311
+ </div>
312
+
313
+ <p
314
+ style="
315
+ color: var(--muted-foreground);
316
+ max-width: 28rem;
317
+ margin: 0 auto;
318
+ font-size: var(--text-sm);
319
+ line-height: 1.5;
320
+ text-wrap: pretty;
321
+ "
322
+ >
323
+ ${!i?`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(n)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`:i}
324
+ </p>
325
+ </div>
326
+
327
+ <div
328
+ style="
329
+ display: flex;
330
+ gap: 0.75rem;
331
+ margin-top: 1.5rem;
332
+ justify-content: center;
333
+ flex-wrap: wrap;
334
+ "
335
+ >
336
+ <a
337
+ href="/"
338
+ style="
339
+ text-decoration: none;
340
+ "
341
+ >
342
+ <div
343
+ style="
344
+ border: 2px solid var(--border);
345
+ background: var(--primary);
346
+ color: var(--primary-foreground);
347
+ padding: 0.5rem 1rem;
348
+ border-radius: 0;
349
+ white-space: nowrap;
350
+ "
351
+ class="btn"
352
+ >
353
+ Go Home
354
+ </div>
355
+ </a>
356
+ <a
357
+ href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(n)}?askai=${encodeURIComponent(`What does the error code ${n} mean?`)}"
358
+ target="_blank"
359
+ rel="noopener noreferrer"
360
+ style="
361
+ text-decoration: none;
362
+ "
363
+ >
364
+ <div
365
+ style="
366
+ border: 2px solid var(--border);
367
+ background: transparent;
368
+ color: var(--foreground);
369
+ padding: 0.5rem 1rem;
370
+ border-radius: 0;
371
+ white-space: nowrap;
372
+ "
373
+ class="btn"
374
+ >
375
+ Ask AI
376
+ </div>
377
+ </a>
378
+ </div>
379
+ </div>
380
+ </div>
381
+ </body>
382
+ </html>`},vl=U("/error",{method:"GET",metadata:{...En,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(r)=>{let n=new URL(r.request?.url||""),i=n.searchParams.get("error")||"UNKNOWN",s=n.searchParams.get("error_description")||null,c=/^[\'A-Za-z0-9_-]+$/.test(i||"")?i:"UNKNOWN",u=s?Sl(s):null,f=new URLSearchParams;if(f.set("error",c),s)f.set("error_description",s);let m=r.context.options,h=m.onAPIError?.errorURL;if(h){let y=ct(h,f);return new Response(null,{status:302,headers:{Location:y}})}if(Ln&&!m.onAPIError?.customizeDefaultErrorPage)return new Response(null,{status:302,headers:{Location:`/?${f.toString()}`}});return new Response(Nh(r.context.options,c,u),{headers:{"Content-Type":"text/html"}})});var Tl=U("/ok",{method:"GET",metadata:{...En,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(r)=>r.json({ok:!0}));function Rl(r,n,i){let s=n?new URL(n,r.baseURL):new URL(`${r.baseURL}/error`);if(i)Object.entries(i).forEach(([c,u])=>s.searchParams.set(c,u));return s.href}function zh(r,n,i){let s=new URL(n,r.baseURL);if(i)Object.entries(i).forEach(([c,u])=>s.searchParams.set(c,u));return s.href}var Il=U("/request-password-reset",{method:"POST",body:t({email:je().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:e().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:[Kt((r)=>r.body.redirectTo)]},async(r)=>{if(!r.context.options.emailAndPassword?.sendResetPassword)throw r.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),l.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:n,redirectTo:i}=r.body,s=await r.context.internalAdapter.findUserByEmail(n,{includeAccounts:!0});if(!s)return Lt(24),await r.context.internalAdapter.findVerificationValue("dummy-verification-token"),r.context.logger.warn("Reset Password: User not found"),r.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let c=bt(r.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),u=Lt(24);await r.context.internalAdapter.createVerificationValue({value:s.user.id,identifier:`reset-password:${u}`,expiresAt:c});let f=i?encodeURIComponent(i):"",m=`${r.context.baseURL}/reset-password/${u}?callbackURL=${f}`;return await r.context.runInBackgroundOrAwait(r.context.options.emailAndPassword.sendResetPassword({user:s.user,url:m,token:u},r.request)),r.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),_l=U("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:t({callbackURL:e().meta({description:"The URL to redirect the user to reset their password"})}),use:[Kt((r)=>r.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(r)=>{let{token:n}=r.params,{callbackURL:i}=r.query;if(!n||!i)throw r.redirect(Rl(r.context,i,{error:"INVALID_TOKEN"}));let s=await r.context.internalAdapter.findVerificationValue(`reset-password:${n}`);if(!s||s.expiresAt<new Date)throw r.redirect(Rl(r.context,i,{error:"INVALID_TOKEN"}));throw r.redirect(zh(r.context,i,{token:n}))}),Ul=U("/reset-password",{method:"POST",operationId:"resetPassword",query:t({token:e().optional()}).optional(),body:t({newPassword:e().meta({description:"The new password to set"}),token:e().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(r)=>{let n=r.body.token||r.query?.token;if(!n)throw l.from("BAD_REQUEST",x.INVALID_TOKEN);let{newPassword:i}=r.body;ir(r,i),Pe(r,i);let s=`reset-password:${n}`,c=await r.context.internalAdapter.findVerificationValue(s);if(!c||c.expiresAt<new Date)throw l.from("BAD_REQUEST",x.INVALID_TOKEN);let u=c.value,f=await r.context.internalAdapter.findUserById(u);if(!f)throw l.from("BAD_REQUEST",x.USER_NOT_FOUND);if(await su(r,u,await r.context.password.hash(i),async()=>{if(!await r.context.internalAdapter.consumeVerificationValue(s))throw l.from("BAD_REQUEST",x.INVALID_TOKEN)}),r.context.options.emailAndPassword?.onPasswordReset)await r.context.options.emailAndPassword.onPasswordReset({user:f},r.request);return r.json({status:!0})}),Cl=U("/verify-password",{method:"POST",body:t({password:e().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:[Qe]},async(r)=>{let{password:n}=r.body,i=r.context.session;if(!await au(r,{password:n,userId:i.user.id}))throw l.from("BAD_REQUEST",x.INVALID_PASSWORD);return r.json({status:!0})});var $h=t({callbackURL:e().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:e().optional(),errorCallbackURL:e().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:Zn,disableRedirect:o().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:ho(t({token:e().meta({description:"ID token from the provider"}),nonce:e().meta({description:"Nonce used to generate the token"}).optional(),accessToken:e().meta({description:"Access token from the provider"}).optional(),refreshToken:e().meta({description:"Refresh token from the provider"}).optional(),expiresAt:b().meta({description:"Expiry date of the token"}).optional(),user:t({name:t({firstName:e().optional(),lastName:e().optional()}).optional(),email:e().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:a(e()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:o().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:e().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:bo,additionalData:j(e(),st()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),xl=()=>U("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:$h,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(r)=>{let n=await it(r.context.socialProviders,{value:r.body.provider});if(!n)throw r.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:r.body.provider}),l.from("NOT_FOUND",x.PROVIDER_NOT_FOUND);if(r.body.idToken){if(!ko(n))throw r.context.logger.error("Provider does not support id token verification",{provider:r.body.provider}),l.from("NOT_FOUND",x.ID_TOKEN_NOT_SUPPORTED);let{token:f,nonce:m}=r.body.idToken;if(!await So(n,f,m,r))throw r.context.logger.warn("Invalid id token",{provider:r.body.provider}),l.from("UNAUTHORIZED",x.INVALID_TOKEN);let h={idToken:f,accessToken:r.body.idToken.accessToken,refreshToken:r.body.idToken.refreshToken,user:r.body.idToken.user},y=await n.getUserInfo(h);if(!y||!y?.user)throw r.context.logger.error("Failed to get user info",{provider:r.body.provider}),l.from("UNAUTHORIZED",x.FAILED_TO_GET_USER_INFO);if(!y.user.email)throw r.context.logger.error(Dr(r.body.provider,{source:"id_token"}),{provider:r.body.provider}),l.from("UNAUTHORIZED",x.USER_EMAIL_NOT_FOUND);let w=await jn(n,h,y.data),g=$n(y.data),A=await Qn(r,{userInfo:{...y.user,email:y.user.email,id:w.accountId,name:y.user.name||"",image:y.user.image,emailVerified:y.user.emailVerified||!1},account:{...w,accessToken:r.body.idToken.accessToken,idToken:f},callbackURL:r.body.callbackURL,disableSignUp:n.disableImplicitSignUp&&!r.body.requestSignUp||n.options?.disableSignUp||n.disableSignUp,source:{method:"oauth",oauth:{providerId:n.id,profile:g}}});if(A.error){if(A.error===Ae.EMAIL_NOT_VERIFIED)throw l.from("FORBIDDEN",x.EMAIL_NOT_VERIFIED);throw l.from("UNAUTHORIZED",{message:A.error,code:"OAUTH_LINK_ERROR"})}return await Le(r,A.data),r.json({redirect:!1,token:A.data.session.token,url:void 0,user:ke(r.context.options,A.data.user)})}let i=Nr(n),{codeVerifier:s,state:c}=await zr(r,{additionalData:r.body.additionalData,idTokenNonce:i}),u=await n.createAuthorizationURL({state:c,codeVerifier:s,idTokenNonce:i,redirectURI:`${r.context.baseURL}${sr(n)}`,scopes:r.body.scopes,loginHint:r.body.loginHint,additionalParams:r.body.additionalParams});if(!r.body.disableRedirect)r.setHeader("Location",u.toString());return r.json({url:u.toString(),redirect:!r.body.disableRedirect})}),Ol=()=>U("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[co],cloneRequest:!0,body:t({email:e().meta({description:"Email of the user"}),password:e().meta({description:"Password of the user"}),callbackURL:e().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:o().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(r)=>{if(!r.context.options?.emailAndPassword?.enabled)throw r.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!"),l.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:n,password:i}=r.body;if(!je().safeParse(n).success)throw l.from("BAD_REQUEST",x.INVALID_EMAIL);Pe(r,i);let s=await r.context.internalAdapter.findUserByEmail(n.toLowerCase(),{includeAccounts:!0}),c=s?.accounts.find((h)=>h.providerId==="credential"&&h.accountId===s.user.id);if(!s||!c)throw await r.context.password.hash(i),r.context.logger.warn("User not found"),l.from("UNAUTHORIZED",x.INVALID_EMAIL_OR_PASSWORD);let u=s.user,f=c.password;if(!f)throw await r.context.password.hash(i),r.context.logger.warn("Password not found"),l.from("UNAUTHORIZED",x.INVALID_EMAIL_OR_PASSWORD);if(!await r.context.password.verify({hash:f,password:i}))throw r.context.logger.warn("Invalid password"),l.from("UNAUTHORIZED",x.INVALID_EMAIL_OR_PASSWORD);if(r.context.options?.emailAndPassword?.requireEmailVerification&&!u.emailVerified){if(!r.context.options?.emailVerification?.sendVerificationEmail)throw l.from("FORBIDDEN",x.EMAIL_NOT_VERIFIED);if(r.context.options?.emailVerification?.sendOnSignIn){let h=await Te(r.context.secret,u.email,void 0,r.context.options.emailVerification?.expiresIn),y=r.body.callbackURL?encodeURIComponent(r.body.callbackURL):encodeURIComponent("/"),w=`${r.context.baseURL}/verify-email?token=${h}&callbackURL=${y}`;await r.context.runInBackgroundOrAwait(r.context.options.emailVerification.sendVerificationEmail({user:u,url:w,token:h},Ft(r.request)))}throw l.from("FORBIDDEN",x.EMAIL_NOT_VERIFIED)}let m=await r.context.internalAdapter.createSession(u.id,r.body.rememberMe===!1);if(!m)throw r.context.logger.error("Failed to create session"),l.from("UNAUTHORIZED",x.FAILED_TO_CREATE_SESSION);if(await Le(r,{session:m,user:u},r.body.rememberMe===!1),r.body.callbackURL)r.setHeader("Location",r.body.callbackURL);return r.json({redirect:!!r.body.callbackURL,token:m.token,url:r.body.callbackURL,user:ke(r.context.options,u)})});var jh=t({callbackURL:e().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:o().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:e().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),Ll=(r)=>({success:!0,url:r?.url,redirect:r?.redirect}),Dl=U("/sign-out",{method:"POST",body:jh,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"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async(r)=>{let n=await r.getSignedCookie(r.context.authCookies.sessionToken.name,r.context.secret),i=null;if(n)try{i=await r.context.internalAdapter.findSession(n)}catch(c){r.context.logger.error("Failed to read session from database",c)}if(n)try{await r.context.internalAdapter.deleteSession(n)}catch(c){r.context.logger.error("Failed to delete session from database",c)}dr(r);let s=await(async()=>{try{if(!i)return null;let c=await r.context.internalAdapter.findAccounts(i.user.id),u=new Map(r.context.socialProviders.map((y)=>[y.id,y])),f=c.filter((y)=>Boolean(u.get(y.providerId)?.createEndSessionURL)).sort((y,w)=>w.updatedAt.getTime()-y.updatedAt.getTime());if(f.length===0)return null;let m=new Set,h=r.body?.callbackURL?new URL(r.body.callbackURL,r.context.baseURL).toString():void 0;for(let y of f){if(m.has(y.providerId))continue;m.add(y.providerId);let w=u.get(y.providerId);try{let g=await w?.createEndSessionURL?.({idToken:y.idToken,postLogoutRedirectURI:h,state:r.body?.state});if(g)return g.toString()}catch(g){r.context.logger.error(`Failed to create logout URL for provider "${y.providerId}"`,g)}}return null}catch(c){return r.context.logger.error("Failed to create provider logout URL",c),null}})();if(s){let c=!r.body?.disableRedirect;if(c)r.setHeader("Location",s);return r.json(Ll({url:s,redirect:c}))}return r.json(Ll())});var Hh=t({name:e(),email:je(),password:e().nonempty(),image:e().optional(),callbackURL:e().optional(),rememberMe:o().optional()}).and(j(e(),st())),Pl=()=>U("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[co],body:Hh,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(r)=>Ht(r.context.adapter,async()=>{if(!r.context.options.emailAndPassword?.enabled||r.context.options.emailAndPassword?.disableSignUp)throw l.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let n=r.body,{name:i,email:s,password:c,image:u,callbackURL:f,rememberMe:m,...h}=n;if(!je().safeParse(s).success)throw l.from("BAD_REQUEST",x.INVALID_EMAIL);if(!c||typeof c!=="string")throw l.from("BAD_REQUEST",x.INVALID_PASSWORD);ir(r,c),Pe(r,c);let y=r.context.options.emailAndPassword.requireEmailVerification||r.context.options.emailAndPassword.autoSignIn===!1,w=r.context.options.emailAndPassword.autoSignIn===!1||y,g=Mi(r.context.options,h,"create"),A=s.toLowerCase(),E=()=>{let T=new Date,D=r.context.generateId({model:"user"})||Lt(),k={name:i,email:A,emailVerified:!1,image:u??null,createdAt:T,updatedAt:T},R=r.context.options.emailAndPassword?.customSyntheticUser,L;if(R){let M=Object.keys(r.context.options.user?.additionalFields??{}),N={};for(let z of M)if(z in g)N[z]=g[z];let H=R({coreFields:k,additionalFields:N,id:D});L=zo(r.context.options,H)}else L=zo(r.context.options,{...k,...g,id:D});return r.json({token:null,user:ke(r.context.options,L)})},v=await r.context.internalAdapter.findUserByEmail(A);if(v?.user){if(r.context.logger.info(`Sign-up attempt for existing email: ${s}`),y){if(await r.context.password.hash(c),r.context.options.emailAndPassword?.onExistingUserSignUp)await r.context.runInBackgroundOrAwait(r.context.options.emailAndPassword.onExistingUserSignUp({user:v.user},Ft(r.request)));return E()}throw l.from("UNPROCESSABLE_ENTITY",x.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let _=await r.context.password.hash(c),P;try{if(P=await r.context.internalAdapter.createUser({email:A,name:i,image:u,...g,emailVerified:!1},{method:"email-password"}),!P)throw l.from("BAD_REQUEST",x.FAILED_TO_CREATE_USER)}catch(T){if(Oe(T)){if(T.statusCode===403&&y)return E();throw T}if(ai())r.context.logger.error("Failed to create user",T);throw r.context.logger?.error("Failed to create user",T),l.from("UNPROCESSABLE_ENTITY",x.FAILED_TO_CREATE_USER)}if(!P)throw l.from("UNPROCESSABLE_ENTITY",x.FAILED_TO_CREATE_USER);if(await r.context.internalAdapter.linkAccount({userId:P.id,providerId:"credential",accountId:P.id,password:_}),r.context.options.emailVerification?.sendOnSignUp??r.context.options.emailAndPassword.requireEmailVerification){let T=await Te(r.context.secret,P.email,void 0,r.context.options.emailVerification?.expiresIn),D=n.callbackURL?encodeURIComponent(n.callbackURL):encodeURIComponent("/"),k=`${r.context.baseURL}/verify-email?token=${T}&callbackURL=${D}`;if(r.context.options.emailVerification?.sendVerificationEmail)await r.context.runInBackgroundOrAwait(r.context.options.emailVerification.sendVerificationEmail({user:P,url:k,token:T},Ft(r.request)))}if(w)return r.json({token:null,user:ke(r.context.options,P)});let I=await r.context.internalAdapter.createSession(P.id,m===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!I)throw l.from("BAD_REQUEST",x.FAILED_TO_CREATE_SESSION);return await Le(r,{session:I,user:P},m===!1),r.json({token:I.token,user:ke(r.context.options,P)})}));var Bh=j(e().meta({description:"Field name must be a string"}),st()),Nl=()=>U("/update-session",{method:"POST",operationId:"updateSession",body:Bh,use:[_t],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(r)=>{let n=r.body;if(typeof n!=="object"||Array.isArray(n))throw l.from("BAD_REQUEST",x.BODY_MUST_BE_AN_OBJECT);let i=r.context.session,s=Yc(r.context.options,n,"update");if(Object.keys(s).length===0)throw l.fromStatus("BAD_REQUEST",{message:"No fields to update"});let c=await r.context.internalAdapter.updateSession(i.session.token,{...s,updatedAt:new Date});if(!c&&qt(r))throw dr(r),l.from("UNAUTHORIZED",x.FAILED_TO_GET_SESSION);let u=c??{...i.session,...s,updatedAt:new Date};return await Le(r,{session:u,user:i.user}),r.json({session:at(r.context.options,u)})});var Mh=j(e().meta({description:"Field name must be a string"}),st()),zl=()=>U("/update-user",{method:"POST",operationId:"updateUser",body:Mh,use:[_t],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(r)=>{let n=r.body;if(typeof n!=="object"||Array.isArray(n))throw l.from("BAD_REQUEST",x.BODY_MUST_BE_AN_OBJECT);if(n.email)throw l.from("BAD_REQUEST",x.EMAIL_CAN_NOT_BE_UPDATED);let{name:i,image:s,...c}=n,u=r.context.session,f=Mi(r.context.options,c,"update");if(s===void 0&&i===void 0&&Object.keys(f).length===0)throw l.fromStatus("BAD_REQUEST",{message:"No fields to update"});let m=await r.context.internalAdapter.updateUser(u.user.id,{name:i,image:s,...f})??{...u.user,...i!==void 0&&{name:i},...s!==void 0&&{image:s},...f};return await Le(r,{session:u.session,user:m}),r.json({status:!0})}),$l=U("/change-password",{method:"POST",operationId:"changePassword",body:t({newPassword:e().meta({description:"The new password to set"}),currentPassword:e().meta({description:"The current password is required"}),revokeOtherSessions:o().meta({description:"Must be a boolean value"}).optional()}),use:[Qe],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(r)=>{let{newPassword:n,currentPassword:i,revokeOtherSessions:s}=r.body,c=r.context.session;ir(r,n),Pe(r,n),Pe(r,i);let u=await r.context.internalAdapter.findCredentialAccount(c.user.id);if(!u||!u.password)throw l.from("BAD_REQUEST",x.CREDENTIAL_ACCOUNT_NOT_FOUND);let f=await r.context.password.hash(n);if(!await r.context.password.verify({hash:u.password,password:i}))throw l.from("BAD_REQUEST",x.INVALID_PASSWORD);let m=await Ht(r.context.adapter,async()=>{if(s)await r.context.internalAdapter.deleteUserSessions(c.user.id);if(await r.context.internalAdapter.updateAccount(u.id,{password:f}),!s)return null;let y=await r.context.internalAdapter.createSession(c.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!y)throw l.from("INTERNAL_SERVER_ERROR",x.FAILED_TO_GET_SESSION);return y}),h=null;if(m)await Le(r,{session:m,user:c.user}),h=m.token;return r.json({token:h,user:ke(r.context.options,c.user)})}),jl=U.serverOnly({method:"POST",body:t({newPassword:e().meta({description:"The new password to set is required"})}),use:[Qe]},async(r)=>{let{newPassword:n}=r.body,i=r.context.session;ir(r,n),Pe(r,n);let s=await r.context.internalAdapter.findCredentialAccount(i.user.id),c=await r.context.password.hash(n);if(!s)return await r.context.internalAdapter.linkAccount({userId:i.user.id,providerId:"credential",accountId:i.user.id,password:c}),r.json({status:!0});if(!s.password)return await r.context.internalAdapter.updateAccount(s.id,{password:c}),r.json({status:!0});throw l.from("BAD_REQUEST",x.PASSWORD_ALREADY_SET)}),Hl=U("/delete-user",{method:"POST",use:[Qe],body:t({callbackURL:e().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:e().meta({description:"The password of the user is required to delete the user"}).optional(),token:e().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(r)=>{if(!r.context.options.user?.deleteUser?.enabled)throw r.context.logger.error("Delete user is disabled. Enable it in the options"),l.fromStatus("NOT_FOUND");let n=r.context.session;if(r.body.password){Pe(r,r.body.password);let c=await r.context.internalAdapter.findCredentialAccount(n.user.id);if(!c||!c.password)throw l.from("BAD_REQUEST",x.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await r.context.password.verify({hash:c.password,password:r.body.password}))throw l.from("BAD_REQUEST",x.INVALID_PASSWORD)}if(r.body.token)return await qs({...r,query:{token:r.body.token}}),r.json({success:!0,message:"User deleted"});if(r.context.options.user.deleteUser?.sendDeleteAccountVerification){let c=Vt(32,"0-9","a-z");await r.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`delete-account-${c}`,expiresAt:new Date(Date.now()+(r.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1000)});let u=`${r.context.baseURL}/delete-user/callback?token=${c}&callbackURL=${encodeURIComponent(r.body.callbackURL||"/")}`;return await r.context.runInBackgroundOrAwait(r.context.options.user.deleteUser.sendDeleteAccountVerification({user:n.user,url:u,token:c},r.request)),r.json({success:!0,message:"Verification email sent"})}if(!r.body.password&&r.context.sessionConfig.freshAge!==0){let c=new Date(n.session.createdAt).getTime(),u=r.context.sessionConfig.freshAge*1000;if(Date.now()-c>=u)throw l.from("BAD_REQUEST",x.SESSION_EXPIRED)}let i=r.context.options.user.deleteUser?.beforeDelete;if(i)await i(n.user,r.request);await r.context.internalAdapter.deleteUser(n.user.id),await r.context.internalAdapter.deleteUserSessions(n.user.id),dr(r);let s=r.context.options.user.deleteUser?.afterDelete;if(s)await s(n.user,r.request);return r.json({success:!0,message:"User deleted"})}),qs=U("/delete-user/callback",{method:"GET",query:t({token:e().meta({description:"The token to verify the deletion request"}),callbackURL:e().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[Kt((r)=>r.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(r)=>{if(!r.context.options.user?.deleteUser?.enabled)throw r.context.logger.error("Delete user is disabled. Enable it in the options"),l.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let n=await Ye(r,{disableCookieCache:qt(r)});if(!n)throw l.from("NOT_FOUND",x.FAILED_TO_GET_USER_INFO);let i=await r.context.internalAdapter.consumeVerificationValue(`delete-account-${r.query.token}`);if(!i||i.value!==n.user.id)throw l.from("NOT_FOUND",x.INVALID_TOKEN);let s=r.context.options.user.deleteUser?.beforeDelete;if(s)await s(n.user,r.request);await r.context.internalAdapter.deleteUser(n.user.id),await r.context.internalAdapter.deleteUserSessions(n.user.id),await r.context.internalAdapter.deleteAccounts(n.user.id),dr(r);let c=r.context.options.user.deleteUser?.afterDelete;if(c)await c(n.user,r.request);if(r.query.callbackURL)throw r.redirect(r.query.callbackURL||"/");return r.json({success:!0,message:"User deleted"})}),Bl=U("/change-email",{method:"POST",body:t({newEmail:je().meta({description:"The new email address to set must be a valid email address"}),callbackURL:e().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[Qe],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(r)=>{if(!r.context.options.user?.changeEmail?.enabled)throw r.context.logger.error("Change email is disabled."),l.from("BAD_REQUEST",x.CHANGE_EMAIL_DISABLED);let n=r.body.newEmail.toLowerCase();if(n===r.context.session.user.email)throw r.context.logger.warn("Email is the same"),l.fromStatus("BAD_REQUEST",{message:"Email is the same"});let i=r.context.session.user.emailVerified!==!0&&r.context.options.user.changeEmail.updateEmailWithoutVerification,s=r.context.options.emailVerification?.sendVerificationEmail,c=s&&r.context.session.user.emailVerified&&r.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!i&&!c&&!s)throw r.context.logger.error("Verification email isn't enabled."),l.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await r.context.internalAdapter.findUserByEmail(n))return await Te(r.context.secret,r.context.session.user.email,n,r.context.options.emailVerification?.expiresIn),r.context.logger.info("Change email attempt for existing email"),r.json({status:!0});if(i){if(await r.context.internalAdapter.updateUser(r.context.session.user.id,{email:n}),await Le(r,{session:r.context.session.session,user:{...r.context.session.user,email:n}}),s){let m=await Te(r.context.secret,n,void 0,r.context.options.emailVerification?.expiresIn),h=`${r.context.baseURL}/verify-email?token=${m}&callbackURL=${encodeURIComponent(r.body.callbackURL||"/")}`;await r.context.runInBackgroundOrAwait(s({user:{...r.context.session.user,email:n},url:h,token:m},r.request))}return r.json({status:!0})}if(c){let m=await Te(r.context.secret,r.context.session.user.email,n,r.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),h=`${r.context.baseURL}/verify-email?token=${m}&callbackURL=${encodeURIComponent(r.body.callbackURL||"/")}`;return await r.context.runInBackgroundOrAwait(c({user:r.context.session.user,newEmail:n,url:h,token:m},r.request)),r.json({status:!0})}if(!s)throw r.context.logger.error("Verification email isn't enabled."),l.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let u=await Te(r.context.secret,r.context.session.user.email,n,r.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),f=`${r.context.baseURL}/verify-email?token=${u}&callbackURL=${encodeURIComponent(r.body.callbackURL||"/")}`;return await r.context.runInBackgroundOrAwait(s({user:{...r.context.session.user,email:n},url:f,token:u},r.request)),r.json({status:!0})});var Ml=so((r,n,i)=>{if(Array.isArray(r[n])&&Array.isArray(i))return r[n]=i,!0}),ur=new WeakMap;function Fs(r,n){let i=r.options;return i?.operationId??i?.metadata?.openapi?.operationId??n??r.path??"/:virtual"}function Kl(r,n){if(!n)return;n.forEach((i,s)=>{if(!r.responseHeaders)r.responseHeaders=new Headers({[s]:i});else if(s.toLowerCase()==="set-cookie")r.responseHeaders.append(s,i);else r.responseHeaders.set(s,i)})}function Wl(r){let n=r[vs],i=r.headers&&r.headers!==n?new Headers(r.headers):null;if(!n&&!i)return null;let s=new Headers;return n?.forEach((c,u)=>{s.append(u,c)}),i?.forEach((c,u)=>{if(u.toLowerCase()==="set-cookie")s.append(u,c);else s.set(u,c)}),s}async function Kh(r,n,i,s){let c=or(r.context.options),u={};for(let f of n){let m=!1;try{m=f.matcher(r)}catch(A){let E=ur.get(f.handler)??"unknown";throw r.context.logger.error(`An error occurred during ${E} hook matcher execution:`,A),new l("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!m)continue;let h=ur.get(f.handler)??"unknown",y=i.path??"/:virtual",w=await c(`hook before ${y} ${h}`,{[Xe]:"before",[F.ATTR_HTTP_ROUTE]:y,[et]:h,[fo]:s},()=>f.handler({...r,returnHeaders:!0})).catch((A)=>{if(Oe(A)&&uo(r.context.logger.level,"debug"))A.stack=A.errorStack;throw A});Kl(r.context,w?.headers);let g=w?.response;if(g&&typeof g==="object"){if("context"in g&&typeof g.context==="object"){let{headers:A,...E}=g.context;if(A instanceof Headers)if(u.headers)A.forEach((v,_)=>{u.headers?.set(_,v)});else u.headers=A;u=Ml(E,u);continue}return g}}return{context:u}}async function Wh(r,n,i,s){let c=or(r.context.options);for(let u of n){if(!u.matcher(r))continue;let f=ur.get(u.handler)??"unknown",m=i.path??"/:virtual",h=await c(`hook after ${m} ${f}`,{[Xe]:"after",[F.ATTR_HTTP_ROUTE]:m,[et]:f,[fo]:s},()=>u.handler(r)).catch((y)=>{if(Oe(y)){if(uo(r.context.logger.level,"debug"))y.stack=y.errorStack;return{response:y,headers:Wl(y)}}throw y});if(Kl(r.context,h.headers),h.response!==void 0)r.context.returned=h.response}return{response:r.context.returned,headers:r.context.responseHeaders}}function Vh(r){let n=r.options.plugins||[],i=[],s=[],c=r.options.hooks?.before;if(c)ur.set(c,"user"),i.push({matcher:()=>!0,handler:c});let u=r.options.hooks?.after;if(u)ur.set(u,"user"),s.push({matcher:()=>!0,handler:u});let f=n.flatMap((h)=>(h.hooks?.before??[]).map((y)=>(ur.set(y.handler,`plugin:${h.id}`),y))),m=n.flatMap((h)=>(h.hooks?.after??[]).map((y)=>(ur.set(y.handler,`plugin:${h.id}`),y)));if(f.length)i.push(...f);if(m.length)s.push(...m);return{beforeHooks:i,afterHooks:s}}async function Vl(r,n){let i=or(n.context.options),s=n.operationId??Fs(r),c=r.path??"/:virtual",u=r.options?.method,f=Array.isArray(u)?u[0]:u,m=n.method??n.request?.method??f??"?",h=n.asResponse??He(n.request),y={...n,context:{...n.context,returned:void 0,responseHeaders:void 0,session:n.context.session??null},path:r.path,headers:n.headers?new Headers(n.headers):void 0};return i(`${m} ${c}`,{[F.ATTR_HTTP_ROUTE]:c,[fo]:s},async()=>pr(y,async()=>{let{beforeHooks:w,afterHooks:g}=Vh(y.context),A=await Kh(y,w,r,s);if("context"in A&&A.context&&typeof A.context==="object"){let{headers:_,...P}=A.context;if(_){if(!y.headers)y.headers=new Headers;let I=y.headers;_.forEach((T,D)=>{I.set(D,T)})}y=Ml(P,y)}else if(A){let _=y.context.responseHeaders;return h?Fe(A,{headers:_}):n.returnHeaders?{headers:_,response:A}:A}y.asResponse=!1,y.returnHeaders=!0,y.returnStatus=!0;let E=await pr(y,()=>i(`handler ${c}`,{[F.ATTR_HTTP_ROUTE]:c,[fo]:s},()=>r(y))).catch((_)=>{if(Oe(_))return{response:_,status:_.statusCode,headers:Wl(_)};throw _});if(E instanceof Response)return E;y.context.returned=E.response,y.context.responseHeaders=E.headers??void 0;let v=await Wh(y,g,r,s);if(v.response!==void 0)E.response=v.response;if(E.headers=v.headers??E.headers,Oe(E.response)&&uo(y.context.logger.level,"debug"))E.response.stack=E.response.errorStack;if(Oe(E.response)&&!h){if(E.headers)Object.defineProperty(E.response,vs,{enumerable:!1,configurable:!0,writable:!1,value:E.headers});throw E.response}return h?Fe(E.response,{headers:E.headers??void 0,status:E.status}):n.returnHeaders?n.returnStatus?{headers:E.headers,response:E.response,status:E.status}:{headers:E.headers,response:E.response}:n.returnStatus?{response:E.response,status:E.status}:E.response}))}async function qh(r,n){if(r.baseURL)return r;let i=iu(n),s=r.options.baseURL,c=er(s)&&Boolean(s.fallback);if(i===void 0&&!c)throw new l("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 el(r,i,Xc(r.options))}catch(u){if(u instanceof S)throw new l("INTERNAL_SERVER_ERROR",{message:u.message});throw u}}function ql(r,n){let i={};for(let[s,c]of Object.entries(r))i[s]=async(u)=>{let f=Fs(c,s),m=async()=>{let h=await n,y=h.checkSchema?.();if(y)await y;let w=er(h.options.baseURL)?await qh(h,u):h;return Vl(c,{...u,context:w,operationId:f,asResponse:u?.asResponse??He(u?.request)})};if(await us())return m();return ds(new WeakMap,m)},i[s].path=c.path,i[s].options=c.options;return i}function Hf(r,n){let i=new Map;r.plugins?.forEach((c)=>{if(c.endpoints){for(let[u,f]of Object.entries(c.endpoints))if(f&&"path"in f&&typeof f.path==="string"){let m=f.path,h=[];if(f.options&&"method"in f.options){if(Array.isArray(f.options.method))h=f.options.method;else if(typeof f.options.method==="string")h=[f.options.method]}if(h.length===0)h=["*"];if(!i.has(m))i.set(m,[]);i.get(m).push({pluginId:c.id,endpointKey:u,methods:h})}}});let s=[];for(let[c,u]of i.entries())if(u.length>1){let f=new Map,m=!1;for(let h of u)for(let y of h.methods){if(!f.has(y))f.set(y,[]);if(f.get(y).push(h.pluginId),f.get(y).length>1)m=!0;if(y==="*"&&u.length>1)m=!0;else if(y!=="*"&&f.has("*"))m=!0}if(m){let h=[...new Set(u.map((w)=>w.pluginId))],y=[];for(let[w,g]of f.entries())if(g.length>1||w==="*"&&u.length>1||w!=="*"&&f.has("*"))y.push(w);s.push({path:c,plugins:h,conflictingMethods:y})}}if(s.length>0){let c=s.map((u)=>` - "${u.path}" [${u.conflictingMethods.join(", ")}] used by plugins: ${u.plugins.join(", ")}`).join(`
383
+ `);n.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
384
+ ${c}
385
+
386
+ To resolve this, you can:
387
+ 1. Use only one of the conflicting plugins
388
+ 2. Configure the plugins to use different paths (if supported)
389
+ 3. Ensure plugins use different HTTP methods for the same path
390
+ `)}}function nu(r,n){let i=or(n),s=n.plugins?.reduce((u,f)=>({...u,...f.endpoints}),{})??{},c=n.plugins?.map((u)=>u.middlewares?.map((f)=>{let m=async(h)=>{let y=await r;return i(`middleware ${f.path} ${u.id}`,{[Xe]:"middleware",[F.ATTR_HTTP_ROUTE]:f.path,[et]:`plugin:${u.id}`},()=>f.middleware({...h,context:{...y,...h.context}}))};return m.options=f.middleware.options,{path:f.path,middleware:m}})).filter((u)=>u!==void 0).flat()||[];return{api:ql({signInSocial:xl(),callbackOAuth:kl,getSession:ws(),signOut:Dl,signUpEmail:Pl(),signInEmail:Ol(),resetPassword:Ul,verifyPassword:Cl,verifyEmail:Gu,sendVerificationEmail:Ju,changeEmail:Bl,changePassword:$l,setPassword:jl,updateSession:Nl(),updateUser:zl(),deleteUser:Hl,requestPasswordReset:Il,requestPasswordResetCallback:_l,listSessions:Au(),revokeSession:bu,revokeSessions:Eu,revokeOtherSessions:ku,linkSocialAccount:hl,listUserAccounts:ml,deleteUserCallback:qs,unlinkAccount:yl,refreshToken:bl,getAccessToken:Al,accountInfo:El,...s,ok:Tl,error:vl},r),middlewares:c}}var Vf=(r,n)=>{let i=or(n),{api:s,middlewares:c}=nu(r,n),u=new URL(r.baseURL).pathname;return mi(s,{routerContext:r,openapi:{disabled:!0},basePath:u,routerMiddleware:[{path:"/**",middleware:lu},...c],allowedMediaTypes:["application/json"],skipTrailingSlashes:n.advanced?.skipTrailingSlashes??!1,async onRequest(f){let m=r.options.disabledPaths||[],h=Lr(f.url,u);if(m.includes(h))return new Response("Not Found",{status:404});let y=r.checkSchema?.();if(y)await y;let w=f,g=await hu(w,r);if(g)return g;for(let A of r.options.plugins||[])if(A.onRequest){let E=await i(`onRequest ${A.id}`,{[Xe]:"onRequest",[et]:`plugin:${A.id}`},()=>A.onRequest(w,r));if(E&&"response"in E)return E.response;if(E&&"request"in E)w=E.request}return w},async onResponse(f,m){for(let h of r.options.plugins||[])if(h.onResponse){let y=await i(`onResponse ${h.id}`,{[Xe]:"onResponse",[et]:`plugin:${h.id}`,[F.ATTR_HTTP_RESPONSE_STATUS_CODE]:f.status},()=>h.onResponse(f,r));if(y)return y.response}return f},async onError(f){if(Oe(f)&&f.status==="FOUND")return;if(n.onAPIError?.throw)throw f;if(n.onAPIError?.onError){try{await n.onAPIError.onError(f,r)}catch(y){r.logger.error("onAPIError.onError threw",y)}return}let m=n.logger?.level,h=m==="error"||m==="warn"||m==="debug"?O:void 0;if(n.logger?.disabled!==!0){if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"){if(f.message.includes("no column")||f.message.includes("column")||f.message.includes("relation")||f.message.includes("table")||f.message.includes("does not exist")){r.logger?.error(f.message);return}}if(Oe(f)){if(f.status==="INTERNAL_SERVER_ERROR")r.logger.error(f.status,f);h?.error(f.message)}else r.logger?.error(f&&typeof f==="object"&&"name"in f?f.name:"",f)}}})};function Fh(r){return{success:!1,error:`You are not allowed to access resource: ${r}`}}function Jh(r){return{success:!1,error:`unauthorized to access resource "${r}"`}}function Fl(r){return r==="OR"?"OR":"AND"}function Jl(r){return Array.isArray(r)}function Gh(r){if(Jl(r))return{actions:r,connector:"AND"};if(!r||typeof r!=="object")throw new S("Invalid access control request");let{actions:n,connector:i}=r;if(!Jl(n))return{actions:[],connector:Fl(i)};return{actions:n,connector:Fl(i)}}function Gl(r,n){return typeof n==="string"&&r.includes(n)}function Qh(r,{actions:n,connector:i}){if(n.length===0)return!1;if(i==="OR")return n.some((s)=>Gl(r,s));return n.every((s)=>Gl(r,s))}function tl(r){return{authorize(n,i="AND"){let s=!1;for(let[c,u]of Object.entries(n)){let f=r[c];if(!f){if(i==="AND")return Fh(c);continue}let m=Qh(f,Gh(u));if(m)s=!0;if(m&&i==="OR")return{success:!0};if(!m&&i==="AND")return Jh(c)}if(s)return{success:!0};return{success:!1,error:"Not authorized"}},statements:r}}function zf(r){return{newRole(n){return tl(n)},statements:r}}
391
+ export{Ni,x,Vo,Oe,We,U,Df,Oi,Er,En,Zd,_r,tn,er,Gc,Kc,Ci,ke,zo,at,Wc,js,Mi,$i,Lf,Uf,Yc,Jc,ji,Xd,eu,Go,Ko,Qc,Le,dr,we,tu,Ht,Zc,Di,Wo,Bf,Ff,Yo,Xc,el,Jo,qf,Ye,_t,Ds,Vt,Qo,C,ru,Hf,nu,Vf,tl,zf};