gemi 0.121.0 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (324) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/App.d.ts +9 -0
  4. package/dist/app/App.d.ts.map +1 -1
  5. package/dist/app/index.js +1 -1
  6. package/dist/auth/AuthController.d.ts +14 -0
  7. package/dist/auth/AuthController.d.ts.map +1 -1
  8. package/dist/auth/config.d.ts +16 -0
  9. package/dist/auth/config.d.ts.map +1 -1
  10. package/dist/auth/connections/ConnectionManager.d.ts +24 -8
  11. package/dist/auth/connections/ConnectionManager.d.ts.map +1 -1
  12. package/dist/auth/connections/ConnectionStore.d.ts.map +1 -1
  13. package/dist/auth/connections/ConnectionsController.d.ts.map +1 -1
  14. package/dist/auth/connections/InstagramConnectionProvider.d.ts +80 -0
  15. package/dist/auth/connections/InstagramConnectionProvider.d.ts.map +1 -0
  16. package/dist/auth/connections/OAuthConnectionProvider.d.ts +71 -1
  17. package/dist/auth/connections/OAuthConnectionProvider.d.ts.map +1 -1
  18. package/dist/auth/connections/errors.d.ts +1 -1
  19. package/dist/auth/connections/errors.d.ts.map +1 -1
  20. package/dist/auth/oauth/InstagramOAuthProvider.d.ts +46 -0
  21. package/dist/auth/oauth/InstagramOAuthProvider.d.ts.map +1 -0
  22. package/dist/auth/oauth/OAuthProvider.d.ts +13 -0
  23. package/dist/auth/oauth/OAuthProvider.d.ts.map +1 -1
  24. package/dist/auth/oauth/instagram.d.ts +114 -0
  25. package/dist/auth/oauth/instagram.d.ts.map +1 -0
  26. package/dist/auth/oauth/metaSignedRequest.d.ts +43 -0
  27. package/dist/auth/oauth/metaSignedRequest.d.ts.map +1 -0
  28. package/dist/auth/types.d.ts +2 -1
  29. package/dist/auth/types.d.ts.map +1 -1
  30. package/dist/bin/gemi.js +4 -1
  31. package/dist/bin/gemi.js.map +3 -3
  32. package/dist/bun/plugin.js +1 -1
  33. package/dist/bun/preload.js +1 -1
  34. package/dist/{chunk-dwedx1jb.js → chunk-08fcqny0.js} +3 -3
  35. package/dist/{chunk-dwedx1jb.js.map → chunk-08fcqny0.js.map} +1 -1
  36. package/dist/{chunk-vx7hvyvq.js → chunk-0qmc7snf.js} +2 -2
  37. package/dist/{chunk-vx7hvyvq.js.map → chunk-0qmc7snf.js.map} +1 -1
  38. package/dist/{chunk-qy8c0gzr.js → chunk-0tc0j3pf.js} +2 -2
  39. package/dist/{chunk-qy8c0gzr.js.map → chunk-0tc0j3pf.js.map} +1 -1
  40. package/dist/{chunk-meg8rtr6.js → chunk-1f1sb3w7.js} +2 -2
  41. package/dist/{chunk-meg8rtr6.js.map → chunk-1f1sb3w7.js.map} +1 -1
  42. package/dist/{chunk-d5f1m3d2.js → chunk-1kdga1b2.js} +2 -2
  43. package/dist/{chunk-d5f1m3d2.js.map → chunk-1kdga1b2.js.map} +1 -1
  44. package/dist/{chunk-48gmyaxc.js → chunk-2amj1eyp.js} +2 -2
  45. package/dist/{chunk-48gmyaxc.js.map → chunk-2amj1eyp.js.map} +1 -1
  46. package/dist/chunk-2vc72qez.js +9 -0
  47. package/dist/chunk-2vc72qez.js.map +10 -0
  48. package/dist/{chunk-9xyxbxgk.js → chunk-30xxc6r7.js} +2 -2
  49. package/dist/{chunk-9xyxbxgk.js.map → chunk-30xxc6r7.js.map} +1 -1
  50. package/dist/chunk-39dx7xrz.js +10 -0
  51. package/dist/{chunk-f8xvjx6m.js.map → chunk-39dx7xrz.js.map} +8 -4
  52. package/dist/{chunk-dhbgrv58.js → chunk-4qpypa3h.js} +1 -1
  53. package/dist/{chunk-wqe47c0j.js → chunk-52xkw2bs.js} +2 -2
  54. package/dist/{chunk-wqe47c0j.js.map → chunk-52xkw2bs.js.map} +1 -1
  55. package/dist/{chunk-3gsv1vv1.js → chunk-53hc0ah1.js} +2 -2
  56. package/dist/{chunk-3gsv1vv1.js.map → chunk-53hc0ah1.js.map} +1 -1
  57. package/dist/{chunk-qsz9241c.js → chunk-58ffbwdc.js} +2 -2
  58. package/dist/{chunk-qsz9241c.js.map → chunk-58ffbwdc.js.map} +1 -1
  59. package/dist/{chunk-0ejjgzwc.js → chunk-5a4qbtez.js} +2 -2
  60. package/dist/{chunk-0ejjgzwc.js.map → chunk-5a4qbtez.js.map} +1 -1
  61. package/dist/{chunk-7mmw0jr2.js → chunk-675kzd7z.js} +2 -2
  62. package/dist/{chunk-7mmw0jr2.js.map → chunk-675kzd7z.js.map} +1 -1
  63. package/dist/{chunk-dedqr5wb.js → chunk-6gjvqtcp.js} +2 -2
  64. package/dist/{chunk-dedqr5wb.js.map → chunk-6gjvqtcp.js.map} +1 -1
  65. package/dist/{chunk-6yhpprzs.js → chunk-6pxavyh3.js} +2 -2
  66. package/dist/{chunk-6yhpprzs.js.map → chunk-6pxavyh3.js.map} +1 -1
  67. package/dist/{chunk-h43jp8ws.js → chunk-73v34hw8.js} +2 -2
  68. package/dist/{chunk-h43jp8ws.js.map → chunk-73v34hw8.js.map} +1 -1
  69. package/dist/{chunk-wjkh2gem.js → chunk-8x73yyfs.js} +1 -1
  70. package/dist/{chunk-yds7zwc3.js → chunk-96a1459v.js} +2 -2
  71. package/dist/{chunk-yds7zwc3.js.map → chunk-96a1459v.js.map} +1 -1
  72. package/dist/{chunk-d2c3947c.js → chunk-9a9ef0f1.js} +2 -2
  73. package/dist/{chunk-d2c3947c.js.map → chunk-9a9ef0f1.js.map} +1 -1
  74. package/dist/{chunk-ep0baa9g.js → chunk-9p7eq7bz.js} +2 -2
  75. package/dist/{chunk-ep0baa9g.js.map → chunk-9p7eq7bz.js.map} +1 -1
  76. package/dist/chunk-9t08wbkd.js +58 -0
  77. package/dist/{chunk-rhmxpjce.js.map → chunk-9t08wbkd.js.map} +3 -3
  78. package/dist/{chunk-pn2x59ge.js → chunk-aafanq8n.js} +3 -3
  79. package/dist/{chunk-pn2x59ge.js.map → chunk-aafanq8n.js.map} +1 -1
  80. package/dist/{chunk-tewhms9w.js → chunk-ay8nat73.js} +2 -2
  81. package/dist/{chunk-tewhms9w.js.map → chunk-ay8nat73.js.map} +1 -1
  82. package/dist/{chunk-fpc7bfa9.js → chunk-bk2aheea.js} +2 -2
  83. package/dist/{chunk-fpc7bfa9.js.map → chunk-bk2aheea.js.map} +1 -1
  84. package/dist/{chunk-mr94nfp1.js → chunk-d0wr9jk4.js} +3 -3
  85. package/dist/{chunk-mr94nfp1.js.map → chunk-d0wr9jk4.js.map} +1 -1
  86. package/dist/chunk-d3ywmeb7.js +4 -0
  87. package/dist/chunk-d3ywmeb7.js.map +10 -0
  88. package/dist/{chunk-zefs2b6h.js → chunk-de7hxe73.js} +2 -2
  89. package/dist/{chunk-zefs2b6h.js.map → chunk-de7hxe73.js.map} +1 -1
  90. package/dist/{chunk-er8acmch.js → chunk-dmj6ysym.js} +2 -2
  91. package/dist/{chunk-er8acmch.js.map → chunk-dmj6ysym.js.map} +1 -1
  92. package/dist/chunk-ebx5hnqn.js +71 -0
  93. package/dist/chunk-ebx5hnqn.js.map +13 -0
  94. package/dist/chunk-eevna943.js +5 -0
  95. package/dist/chunk-eevna943.js.map +10 -0
  96. package/dist/{chunk-9rr5h818.js → chunk-enta97jb.js} +3 -3
  97. package/dist/{chunk-9rr5h818.js.map → chunk-enta97jb.js.map} +1 -1
  98. package/dist/{chunk-s5k3yq6t.js → chunk-f1thqe6j.js} +2 -2
  99. package/dist/{chunk-s5k3yq6t.js.map → chunk-f1thqe6j.js.map} +1 -1
  100. package/dist/{chunk-zrcd9hxr.js → chunk-fsy344zb.js} +2 -2
  101. package/dist/{chunk-zrcd9hxr.js.map → chunk-fsy344zb.js.map} +1 -1
  102. package/dist/{chunk-gemzbw7f.js → chunk-fxxbwyce.js} +2 -2
  103. package/dist/{chunk-gemzbw7f.js.map → chunk-fxxbwyce.js.map} +1 -1
  104. package/dist/{chunk-1wnnkde0.js → chunk-fyk07w01.js} +3 -3
  105. package/dist/{chunk-1wnnkde0.js.map → chunk-fyk07w01.js.map} +1 -1
  106. package/dist/chunk-gvp6brdt.js +57 -0
  107. package/dist/{chunk-baz7ne68.js.map → chunk-gvp6brdt.js.map} +23 -13
  108. package/dist/{chunk-7g649j8h.js → chunk-gwnmgkq5.js} +2 -2
  109. package/dist/{chunk-7g649j8h.js.map → chunk-gwnmgkq5.js.map} +1 -1
  110. package/dist/{chunk-51w5ktv2.js → chunk-h76mddt3.js} +2 -2
  111. package/dist/{chunk-51w5ktv2.js.map → chunk-h76mddt3.js.map} +1 -1
  112. package/dist/{chunk-nz8z8jr1.js → chunk-hnrzm5pf.js} +3 -3
  113. package/dist/{chunk-nz8z8jr1.js.map → chunk-hnrzm5pf.js.map} +1 -1
  114. package/dist/{chunk-3wnghdsx.js → chunk-hs88b8gt.js} +2 -2
  115. package/dist/{chunk-3wnghdsx.js.map → chunk-hs88b8gt.js.map} +1 -1
  116. package/dist/{chunk-0k02tza1.js → chunk-j0cnsgjq.js} +1 -1
  117. package/dist/{chunk-pemhmjzp.js → chunk-j8vc3bze.js} +3 -3
  118. package/dist/{chunk-pemhmjzp.js.map → chunk-j8vc3bze.js.map} +1 -1
  119. package/dist/{chunk-471htqmz.js → chunk-k17wx7gz.js} +2 -2
  120. package/dist/{chunk-471htqmz.js.map → chunk-k17wx7gz.js.map} +1 -1
  121. package/dist/{chunk-m83zm86m.js → chunk-kc924zjz.js} +2 -2
  122. package/dist/{chunk-m83zm86m.js.map → chunk-kc924zjz.js.map} +1 -1
  123. package/dist/{chunk-5nj94s66.js → chunk-kdjhgtp9.js} +4 -4
  124. package/dist/{chunk-5nj94s66.js.map → chunk-kdjhgtp9.js.map} +1 -1
  125. package/dist/{chunk-32n8t8x6.js → chunk-kvas36p6.js} +2 -2
  126. package/dist/{chunk-32n8t8x6.js.map → chunk-kvas36p6.js.map} +1 -1
  127. package/dist/{chunk-4fx8p02c.js → chunk-kzstewtm.js} +2 -2
  128. package/dist/{chunk-4fx8p02c.js.map → chunk-kzstewtm.js.map} +1 -1
  129. package/dist/{chunk-gc2dz11k.js → chunk-mxbtcaed.js} +2 -2
  130. package/dist/{chunk-gc2dz11k.js.map → chunk-mxbtcaed.js.map} +1 -1
  131. package/dist/{chunk-cca0grq3.js → chunk-n1a2zj5z.js} +2 -2
  132. package/dist/{chunk-cca0grq3.js.map → chunk-n1a2zj5z.js.map} +1 -1
  133. package/dist/{chunk-0yj0s1pn.js → chunk-nf608sb1.js} +2 -2
  134. package/dist/{chunk-0yj0s1pn.js.map → chunk-nf608sb1.js.map} +1 -1
  135. package/dist/{chunk-19dpzp4y.js → chunk-nvngb4ed.js} +3 -3
  136. package/dist/{chunk-19dpzp4y.js.map → chunk-nvngb4ed.js.map} +1 -1
  137. package/dist/{chunk-cskqet01.js → chunk-pfm9ngch.js} +2 -2
  138. package/dist/{chunk-cskqet01.js.map → chunk-pfm9ngch.js.map} +1 -1
  139. package/dist/{chunk-fenc5tpv.js → chunk-q1e3q01h.js} +2 -2
  140. package/dist/{chunk-fenc5tpv.js.map → chunk-q1e3q01h.js.map} +1 -1
  141. package/dist/{chunk-2c0s0561.js → chunk-qen6587t.js} +2 -2
  142. package/dist/{chunk-2c0s0561.js.map → chunk-qen6587t.js.map} +1 -1
  143. package/dist/{chunk-r01aqf0q.js → chunk-r5tadf14.js} +2 -2
  144. package/dist/{chunk-r01aqf0q.js.map → chunk-r5tadf14.js.map} +1 -1
  145. package/dist/{chunk-cvr5624r.js → chunk-rjm1kj8n.js} +1 -1
  146. package/dist/{chunk-jaa6xkeh.js → chunk-rjtmgbay.js} +2 -2
  147. package/dist/{chunk-jaa6xkeh.js.map → chunk-rjtmgbay.js.map} +1 -1
  148. package/dist/{chunk-rhvc1axc.js → chunk-rkgsvsrj.js} +2 -2
  149. package/dist/{chunk-rhvc1axc.js.map → chunk-rkgsvsrj.js.map} +1 -1
  150. package/dist/{chunk-m53fgf20.js → chunk-s5jxc63j.js} +3 -3
  151. package/dist/{chunk-m53fgf20.js.map → chunk-s5jxc63j.js.map} +1 -1
  152. package/dist/{chunk-5tdxbwzg.js → chunk-sxa70wgn.js} +3 -3
  153. package/dist/{chunk-5tdxbwzg.js.map → chunk-sxa70wgn.js.map} +1 -1
  154. package/dist/chunk-tazvfppr.js +5 -0
  155. package/dist/{chunk-htgmy3x7.js.map → chunk-tazvfppr.js.map} +1 -1
  156. package/dist/{chunk-gy81nd9a.js → chunk-vd6zn8c4.js} +2 -2
  157. package/dist/{chunk-gy81nd9a.js.map → chunk-vd6zn8c4.js.map} +1 -1
  158. package/dist/chunk-vpgbn494.js +24 -0
  159. package/dist/{chunk-03fez0pt.js.map → chunk-vpgbn494.js.map} +3 -3
  160. package/dist/{chunk-7ftj43vp.js → chunk-vwnd4jb5.js} +2 -2
  161. package/dist/{chunk-7ftj43vp.js.map → chunk-vwnd4jb5.js.map} +1 -1
  162. package/dist/{chunk-c0v61fp5.js → chunk-w0jfqnw9.js} +2 -2
  163. package/dist/{chunk-c0v61fp5.js.map → chunk-w0jfqnw9.js.map} +1 -1
  164. package/dist/{chunk-65beps2q.js → chunk-w61sphn5.js} +3 -3
  165. package/dist/{chunk-65beps2q.js.map → chunk-w61sphn5.js.map} +1 -1
  166. package/dist/{chunk-zg6hmc48.js → chunk-wqharhrp.js} +1 -1
  167. package/dist/{chunk-sx340k85.js → chunk-x0jahbqj.js} +2 -2
  168. package/dist/{chunk-sx340k85.js.map → chunk-x0jahbqj.js.map} +1 -1
  169. package/dist/{chunk-y6wt5b6t.js → chunk-xhmtph39.js} +1 -1
  170. package/dist/{chunk-c7qs1xp3.js → chunk-y67evsdy.js} +2 -2
  171. package/dist/{chunk-c7qs1xp3.js.map → chunk-y67evsdy.js.map} +1 -1
  172. package/dist/{chunk-krk7mcgm.js → chunk-ycsrpf47.js} +3 -3
  173. package/dist/{chunk-krk7mcgm.js.map → chunk-ycsrpf47.js.map} +1 -1
  174. package/dist/{chunk-9d2d08qm.js → chunk-ywgvxx35.js} +2 -2
  175. package/dist/{chunk-9d2d08qm.js.map → chunk-ywgvxx35.js.map} +1 -1
  176. package/dist/{chunk-4acpw92g.js → chunk-z23h4s1a.js} +3 -3
  177. package/dist/{chunk-4acpw92g.js.map → chunk-z23h4s1a.js.map} +1 -1
  178. package/dist/{chunk-tk135gmj.js → chunk-zjej5vqh.js} +3 -3
  179. package/dist/{chunk-tk135gmj.js.map → chunk-zjej5vqh.js.map} +1 -1
  180. package/dist/chunks/{ThemeProvider-BLI4zpLu.js → ThemeProvider-CgK2mmVV.js} +576 -2
  181. package/dist/chunks/ThemeProvider-CgK2mmVV.js.map +1 -0
  182. package/dist/client/auth/useEmailCode.d.ts.map +1 -1
  183. package/dist/client/auth/useSignIn.d.ts.map +1 -1
  184. package/dist/client/auth/useSignOut.d.ts.map +1 -1
  185. package/dist/client/index.d.ts +5 -1
  186. package/dist/client/index.d.ts.map +1 -1
  187. package/dist/client/index.js +216 -8
  188. package/dist/client/index.js.map +1 -1
  189. package/dist/client/init.d.ts +8 -0
  190. package/dist/client/init.d.ts.map +1 -1
  191. package/dist/client/realtime/FakeSocket.d.ts +47 -0
  192. package/dist/client/realtime/FakeSocket.d.ts.map +1 -0
  193. package/dist/client/realtime/RealtimeClient.d.ts +162 -0
  194. package/dist/client/realtime/RealtimeClient.d.ts.map +1 -0
  195. package/dist/client/realtime/RealtimeContext.d.ts +8 -0
  196. package/dist/client/realtime/RealtimeContext.d.ts.map +1 -0
  197. package/dist/client/realtime/useChannelSubscription.d.ts +32 -0
  198. package/dist/client/realtime/useChannelSubscription.d.ts.map +1 -0
  199. package/dist/client/rpc.d.ts +11 -0
  200. package/dist/client/rpc.d.ts.map +1 -1
  201. package/dist/client/useChannel.d.ts +87 -0
  202. package/dist/client/useChannel.d.ts.map +1 -0
  203. package/dist/client/useMutation.d.ts.map +1 -1
  204. package/dist/client/useQuery.d.ts +13 -0
  205. package/dist/client/useQuery.d.ts.map +1 -1
  206. package/dist/config/index.js +1 -1
  207. package/dist/console/run.js +2 -2
  208. package/dist/console/run.js.map +1 -1
  209. package/dist/container/index.js +2 -2
  210. package/dist/container/index.js.map +1 -1
  211. package/dist/database/index.js +2 -2
  212. package/dist/database/index.js.map +1 -1
  213. package/dist/email/index.js +2 -2
  214. package/dist/email/index.js.map +1 -1
  215. package/dist/facades/Broadcast.d.ts +68 -0
  216. package/dist/facades/Broadcast.d.ts.map +1 -0
  217. package/dist/facades/Connections.d.ts +12 -5
  218. package/dist/facades/Connections.d.ts.map +1 -1
  219. package/dist/facades/index.d.ts +1 -0
  220. package/dist/facades/index.d.ts.map +1 -1
  221. package/dist/facades/index.js +2 -2
  222. package/dist/facades/index.js.map +1 -1
  223. package/dist/foundation/index.js +2 -2
  224. package/dist/foundation/index.js.map +1 -1
  225. package/dist/gemi.d.ts +19 -6
  226. package/dist/http/ChannelRouter.d.ts +171 -0
  227. package/dist/http/ChannelRouter.d.ts.map +1 -0
  228. package/dist/http/index.d.ts +1 -0
  229. package/dist/http/index.d.ts.map +1 -1
  230. package/dist/http/index.js +2 -2
  231. package/dist/http/index.js.map +1 -1
  232. package/dist/i18n/dictionaryRuntime.js +2 -2
  233. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  234. package/dist/i18n/index.js +2 -2
  235. package/dist/i18n/index.js.map +1 -1
  236. package/dist/kernel/Kernel.d.ts +6 -0
  237. package/dist/kernel/Kernel.d.ts.map +1 -1
  238. package/dist/kernel/index.js +3 -3
  239. package/dist/kernel/index.js.map +5 -6
  240. package/dist/kernel/providers.d.ts +2 -2
  241. package/dist/kernel/providers.d.ts.map +1 -1
  242. package/dist/orm/context.d.ts.map +1 -1
  243. package/dist/orm/index.js +2 -2
  244. package/dist/orm/index.js.map +1 -1
  245. package/dist/server/Server.d.ts.map +1 -1
  246. package/dist/server/httpDev.d.ts +1 -2
  247. package/dist/server/httpDev.d.ts.map +1 -1
  248. package/dist/server/httpProd.d.ts +1 -1
  249. package/dist/server/httpProd.d.ts.map +1 -1
  250. package/dist/server/index.js +2 -2
  251. package/dist/server/index.js.map +3 -3
  252. package/dist/server/shutdown.d.ts +9 -0
  253. package/dist/server/shutdown.d.ts.map +1 -1
  254. package/dist/services/broadcast/BroadcastDriver.d.ts +73 -0
  255. package/dist/services/broadcast/BroadcastDriver.d.ts.map +1 -0
  256. package/dist/services/broadcast/BroadcastEvent.d.ts +67 -0
  257. package/dist/services/broadcast/BroadcastEvent.d.ts.map +1 -0
  258. package/dist/services/broadcast/BroadcastManager.d.ts +148 -0
  259. package/dist/services/broadcast/BroadcastManager.d.ts.map +1 -0
  260. package/dist/services/broadcast/BroadcastServiceProvider.d.ts +16 -0
  261. package/dist/services/broadcast/BroadcastServiceProvider.d.ts.map +1 -0
  262. package/dist/services/broadcast/FakeBroadcastManager.d.ts +45 -0
  263. package/dist/services/broadcast/FakeBroadcastManager.d.ts.map +1 -0
  264. package/dist/services/broadcast/MemoryBroadcastDriver.d.ts +23 -0
  265. package/dist/services/broadcast/MemoryBroadcastDriver.d.ts.map +1 -0
  266. package/dist/services/broadcast/SocketHub.d.ts +192 -0
  267. package/dist/services/broadcast/SocketHub.d.ts.map +1 -0
  268. package/dist/services/broadcast/brand.d.ts +16 -0
  269. package/dist/services/broadcast/brand.d.ts.map +1 -0
  270. package/dist/services/broadcast/channels.d.ts +77 -0
  271. package/dist/services/broadcast/channels.d.ts.map +1 -0
  272. package/dist/services/broadcast/config.d.ts +93 -0
  273. package/dist/services/broadcast/config.d.ts.map +1 -0
  274. package/dist/services/broadcast/protocol.d.ts +123 -0
  275. package/dist/services/broadcast/protocol.d.ts.map +1 -0
  276. package/dist/services/broadcast/socketTag.d.ts +17 -0
  277. package/dist/services/broadcast/socketTag.d.ts.map +1 -0
  278. package/dist/services/broadcast/types.d.ts +27 -0
  279. package/dist/services/broadcast/types.d.ts.map +1 -0
  280. package/dist/services/broadcast/wire.d.ts +35 -0
  281. package/dist/services/broadcast/wire.d.ts.map +1 -0
  282. package/dist/services/events/EventManager.d.ts +6 -0
  283. package/dist/services/events/EventManager.d.ts.map +1 -1
  284. package/dist/services/index.d.ts +18 -1
  285. package/dist/services/index.d.ts.map +1 -1
  286. package/dist/services/index.js +15 -15
  287. package/dist/services/index.js.map +8 -3
  288. package/dist/services/queue/work.js +2 -2
  289. package/dist/services/queue/work.js.map +1 -1
  290. package/dist/services/router/config.d.ts +7 -0
  291. package/dist/services/router/config.d.ts.map +1 -1
  292. package/dist/stats/route-table.js +1 -1
  293. package/dist/support/index.js +2 -2
  294. package/dist/support/index.js.map +1 -1
  295. package/dist/testing/Page.d.ts +8 -0
  296. package/dist/testing/Page.d.ts.map +1 -1
  297. package/dist/testing/index.d.ts +2 -0
  298. package/dist/testing/index.d.ts.map +1 -1
  299. package/dist/testing/index.js +174 -8
  300. package/dist/testing/index.js.map +1 -1
  301. package/dist/vitest/index.js +1 -1
  302. package/package.json +1 -1
  303. package/skills/gemi-react-best-practices/SKILL.md +3 -1
  304. package/skills/gemi-react-best-practices/rules/query-live-over-polling.md +56 -0
  305. package/dist/chunk-03fez0pt.js +0 -24
  306. package/dist/chunk-2n3pgfnb.js +0 -5
  307. package/dist/chunk-2n3pgfnb.js.map +0 -10
  308. package/dist/chunk-baz7ne68.js +0 -57
  309. package/dist/chunk-f8xvjx6m.js +0 -10
  310. package/dist/chunk-htgmy3x7.js +0 -5
  311. package/dist/chunk-krtybgz1.js +0 -4
  312. package/dist/chunk-krtybgz1.js.map +0 -10
  313. package/dist/chunk-pspthd52.js +0 -71
  314. package/dist/chunk-pspthd52.js.map +0 -13
  315. package/dist/chunk-rhmxpjce.js +0 -58
  316. package/dist/chunk-s07v65x6.js +0 -9
  317. package/dist/chunk-s07v65x6.js.map +0 -10
  318. package/dist/chunks/ThemeProvider-BLI4zpLu.js.map +0 -1
  319. /package/dist/{chunk-dhbgrv58.js.map → chunk-4qpypa3h.js.map} +0 -0
  320. /package/dist/{chunk-wjkh2gem.js.map → chunk-8x73yyfs.js.map} +0 -0
  321. /package/dist/{chunk-0k02tza1.js.map → chunk-j0cnsgjq.js.map} +0 -0
  322. /package/dist/{chunk-cvr5624r.js.map → chunk-rjm1kj8n.js.map} +0 -0
  323. /package/dist/{chunk-zg6hmc48.js.map → chunk-wqharhrp.js.map} +0 -0
  324. /package/dist/{chunk-y6wt5b6t.js.map → chunk-xhmtph39.js.map} +0 -0
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../auth/connections/ConnectionStore.ts", "../auth/connections/errors.ts", "../auth/connections/OAuthConnectionProvider.ts", "../auth/connections/ConnectionManager.ts"],
4
+ "sourcesContent": [
5
+ "import type { SQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport type { Encrypter } from \"../../services/encryption/Encrypter\";\nimport type { OAuthTokenSet } from \"./OAuthConnectionProvider\";\n\n/** One stored connection, tokens decrypted. Lives only inside the framework. */\nexport interface ConnectionRecord {\n id: string;\n userId: string;\n provider: string;\n providerAccountId: string | null;\n scopes: string[];\n accessToken: string;\n refreshToken: string | null;\n tokenType: string | null;\n expiresAt: Date | null;\n needsReconnect: boolean;\n /** Bumped on every token change: the compare-and-swap that serialises refreshes. */\n revision: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Where connections are kept. `DatabaseConnectionStore` in an app, `MemoryConnectionStore` in tests. */\nexport interface ConnectionStore {\n find(userId: string, provider: string): Promise<ConnectionRecord | null>;\n list(userId: string): Promise<ConnectionRecord[]>;\n /** Stores a fresh grant, replacing any connection the user had to this provider. */\n save(userId: string, provider: string, tokens: OAuthTokenSet): Promise<ConnectionRecord>;\n /**\n * Replaces the tokens of the connection at `revision`, or resolves `null`\n * when it has moved on (another request refreshed it first) or is gone.\n */\n updateTokens(id: string, revision: number, tokens: OAuthTokenSet): Promise<ConnectionRecord | null>;\n markNeedsReconnect(id: string): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\nexport class MemoryConnectionStore implements ConnectionStore {\n private readonly rows = new Map<string, ConnectionRecord>();\n\n async find(userId: string, provider: string) {\n for (const row of this.rows.values()) {\n if (row.userId === userId && row.provider === provider) return { ...row };\n }\n return null;\n }\n\n async list(userId: string) {\n return [...this.rows.values()].filter((row) => row.userId === userId).map((row) => ({ ...row }));\n }\n\n async save(userId: string, provider: string, tokens: OAuthTokenSet) {\n const existing = await this.find(userId, provider);\n const now = new Date();\n const row: ConnectionRecord = {\n id: existing?.id ?? Bun.randomUUIDv7(),\n userId,\n provider,\n ...fromTokens(tokens),\n needsReconnect: false,\n revision: (existing?.revision ?? 0) + 1,\n createdAt: existing?.createdAt ?? now,\n updatedAt: now,\n };\n this.rows.set(row.id, row);\n return { ...row };\n }\n\n async updateTokens(id: string, revision: number, tokens: OAuthTokenSet) {\n const row = this.rows.get(id);\n if (!row || row.revision !== revision) return null;\n // As the database store's COALESCE: a refresh that does not name the\n // account keeps the one the connection has.\n const fresh = fromTokens(tokens);\n fresh.providerAccountId ??= row.providerAccountId;\n const next = { ...row, ...fresh, needsReconnect: false, revision: revision + 1, updatedAt: new Date() };\n this.rows.set(id, next);\n return { ...next };\n }\n\n async markNeedsReconnect(id: string) {\n const row = this.rows.get(id);\n if (row) this.rows.set(id, { ...row, needsReconnect: true, updatedAt: new Date() });\n }\n\n async delete(id: string) {\n this.rows.delete(id);\n }\n}\n\nexport interface DatabaseConnectionStoreOptions {\n /** Default `gemi_oauth_connections`. A plain identifier: it is spliced into every statement. */\n table?: string;\n}\n\n/**\n * Connections in a table of the app's database, tokens encrypted with the\n * app's `Encrypter` (the keys in `app/config/encryption.ts`). Raw SQL, like\n * the queue's and the locks' tables, for SQLite, Postgres and MySQL 8 /\n * MariaDB: the table is not an ORM model, so no ORM read can return a token.\n */\nexport class DatabaseConnectionStore implements ConnectionStore {\n readonly table: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\">,\n private readonly encrypter: () => Encrypter,\n options: DatabaseConnectionStoreOptions = {},\n ) {\n const table = options.table ?? \"gemi_oauth_connections\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(`The connections table name \"${table}\" is not a plain identifier.`);\n }\n this.table = table;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n }\n\n /** Creates the table if it does not exist: the DDL Prisma makes for the model in the docs. */\n async createTable(): Promise<void> {\n for (const statement of createConnectionTableStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n\n async find(userId: string, provider: string) {\n const q = this.sql;\n const rows = (await q`\n SELECT * FROM ${this.name(q)} WHERE user_id = ${userId} AND provider = ${provider}\n `) as RawRow[];\n return rows[0] ? this.decode(rows[0]) : null;\n }\n\n async list(userId: string) {\n const q = this.sql;\n const rows = (await q`\n SELECT * FROM ${this.name(q)} WHERE user_id = ${userId} ORDER BY provider\n `) as RawRow[];\n return rows.map((row) => this.decode(row));\n }\n\n async save(userId: string, provider: string, tokens: OAuthTokenSet) {\n const q = this.sql;\n const values = this.encode(tokens);\n const now = Date.now();\n\n const update = async () =>\n affected(\n await q`\n UPDATE ${this.name(q)}\n SET provider_account_id = ${values.providerAccountId}, scopes = ${values.scopes},\n access_token = ${values.accessToken}, refresh_token = ${values.refreshToken},\n token_type = ${values.tokenType}, expires_at = ${values.expiresAt},\n needs_reconnect = 0, revision = revision + 1, updated_at = ${now}\n WHERE user_id = ${userId} AND provider = ${provider}\n `,\n );\n\n if ((await update()) === 0) {\n try {\n await q`\n INSERT INTO ${this.name(q)} (id, user_id, provider, provider_account_id, scopes,\n access_token, refresh_token, token_type, expires_at, needs_reconnect, revision,\n created_at, updated_at)\n VALUES (${Bun.randomUUIDv7()}, ${userId}, ${provider}, ${values.providerAccountId},\n ${values.scopes}, ${values.accessToken}, ${values.refreshToken}, ${values.tokenType},\n ${values.expiresAt}, 0, 1, ${now}, ${now})\n `;\n } catch (error) {\n // A concurrent callback for the same user and provider inserted first.\n if ((await update()) === 0) throw error;\n }\n }\n\n const saved = await this.find(userId, provider);\n if (!saved) throw new Error(\"The OAuth connection vanished while it was being saved.\");\n return saved;\n }\n\n async updateTokens(id: string, revision: number, tokens: OAuthTokenSet) {\n const q = this.sql;\n const values = this.encode(tokens);\n const result = await q`\n UPDATE ${this.name(q)}\n SET provider_account_id = COALESCE(${values.providerAccountId}, provider_account_id),\n scopes = ${values.scopes}, access_token = ${values.accessToken},\n refresh_token = ${values.refreshToken}, token_type = ${values.tokenType},\n expires_at = ${values.expiresAt}, needs_reconnect = 0, revision = revision + 1,\n updated_at = ${Date.now()}\n WHERE id = ${id} AND revision = ${revision}\n `;\n if (affected(result) === 0) return null;\n const rows = (await q`SELECT * FROM ${this.name(q)} WHERE id = ${id}`) as RawRow[];\n return rows[0] ? this.decode(rows[0]) : null;\n }\n\n async markNeedsReconnect(id: string) {\n const q = this.sql;\n await q`UPDATE ${this.name(q)} SET needs_reconnect = 1, updated_at = ${Date.now()} WHERE id = ${id}`;\n }\n\n async delete(id: string) {\n const q = this.sql;\n await q`DELETE FROM ${this.name(q)} WHERE id = ${id}`;\n }\n\n /**\n * Re-encrypts every token still under an older key. Run by\n * `gemi run encryption:rotate`; a token refreshed in the meantime is\n * already current and is skipped by the revision check.\n */\n async rotateEncryption(options: { dryRun?: boolean } = {}): Promise<{ scanned: number; rotated: number }> {\n const q = this.sql;\n const encrypter = this.encrypter();\n const rows = (await q`\n SELECT id, access_token, refresh_token, revision FROM ${this.name(q)} ORDER BY id\n `) as RawRow[];\n let rotated = 0;\n for (const row of rows) {\n const stale = (value: string | null) => typeof value === \"string\" && encrypter.needsReencryption(value);\n if (!stale(row.access_token) && !stale(row.refresh_token)) continue;\n rotated += 1;\n if (options.dryRun) continue;\n const reseal = (value: string | null) => (value === null ? null : encrypter.encrypt(encrypter.decrypt(value)));\n await q`\n UPDATE ${this.name(q)}\n SET access_token = ${reseal(row.access_token)}, refresh_token = ${reseal(row.refresh_token)},\n revision = revision + 1\n WHERE id = ${row.id} AND revision = ${Number(row.revision)}\n `;\n }\n return { scanned: rows.length, rotated };\n }\n\n private encode(tokens: OAuthTokenSet) {\n const encrypter = this.encrypter();\n return {\n providerAccountId: tokens.providerAccountId,\n scopes: tokens.scopes.join(\" \"),\n accessToken: encrypter.encrypt(tokens.accessToken),\n refreshToken: tokens.refreshToken === null ? null : encrypter.encrypt(tokens.refreshToken),\n tokenType: tokens.tokenType,\n expiresAt: tokens.expiresAt === null ? null : tokens.expiresAt.getTime(),\n };\n }\n\n private decode(row: RawRow): ConnectionRecord {\n const encrypter = this.encrypter();\n return {\n id: String(row.id),\n userId: String(row.user_id),\n provider: String(row.provider),\n providerAccountId: row.provider_account_id === null ? null : String(row.provider_account_id),\n scopes: String(row.scopes ?? \"\").split(\" \").filter(Boolean),\n accessToken: encrypter.decrypt(String(row.access_token)),\n refreshToken: row.refresh_token === null ? null : encrypter.decrypt(String(row.refresh_token)),\n tokenType: row.token_type === null ? null : String(row.token_type),\n expiresAt: row.expires_at === null ? null : new Date(Number(row.expires_at)),\n needsReconnect: Number(row.needs_reconnect) === 1,\n revision: Number(row.revision),\n createdAt: new Date(Number(row.created_at)),\n updatedAt: new Date(Number(row.updated_at)),\n };\n }\n\n private get mysql() {\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n }\n\n private name(q: SQL) {\n return q.unsafe(this.mysql ? `\\`${this.table}\\`` : `\"${this.table}\"`);\n }\n}\n\ninterface RawRow {\n id: unknown;\n user_id: unknown;\n provider: unknown;\n provider_account_id: unknown;\n scopes: unknown;\n access_token: string;\n refresh_token: string | null;\n token_type: unknown;\n expires_at: unknown;\n needs_reconnect: unknown;\n revision: unknown;\n created_at: unknown;\n updated_at: unknown;\n}\n\nfunction fromTokens(tokens: OAuthTokenSet) {\n return {\n providerAccountId: tokens.providerAccountId,\n scopes: [...tokens.scopes],\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n tokenType: tokens.tokenType,\n expiresAt: tokens.expiresAt,\n };\n}\n\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/** The connections table, as Prisma generates it for the model in the docs, with `IF NOT EXISTS`. */\nexport function createConnectionTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`user_id\\` VARCHAR(191) NOT NULL,\n \\`provider\\` VARCHAR(191) NOT NULL,\n \\`provider_account_id\\` VARCHAR(191) NULL,\n \\`scopes\\` TEXT NOT NULL,\n \\`access_token\\` TEXT NOT NULL,\n \\`refresh_token\\` TEXT NULL,\n \\`token_type\\` VARCHAR(191) NULL,\n \\`expires_at\\` BIGINT NULL,\n \\`needs_reconnect\\` INTEGER NOT NULL DEFAULT 0,\n \\`revision\\` BIGINT NOT NULL DEFAULT 0,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n UNIQUE INDEX \\`${table}_user_id_provider_key\\`(\\`user_id\\`, \\`provider\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"user_id\" TEXT NOT NULL,\n \"provider\" TEXT NOT NULL,\n \"provider_account_id\" TEXT,\n \"scopes\" TEXT NOT NULL,\n \"access_token\" TEXT NOT NULL,\n \"refresh_token\" TEXT,\n \"token_type\" TEXT,\n \"expires_at\" BIGINT,\n \"needs_reconnect\" INTEGER NOT NULL DEFAULT 0,\n \"revision\" BIGINT NOT NULL DEFAULT 0,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL${constraint}\n)`,\n `CREATE UNIQUE INDEX IF NOT EXISTS \"${table}_user_id_provider_key\" ON \"${table}\"(\"user_id\", \"provider\")`,\n ];\n}\n",
6
+ "/**\n * Why an OAuth connection operation failed. Never carries a token or a token\n * endpoint's body; `providerError` is the provider's RFC 6749 error code at\n * most (`invalid_grant`).\n */\nexport type OAuthConnectionErrorCode =\n | \"unknown_provider\"\n | \"exchange_failed\"\n | \"refresh_failed\"\n | \"reconnect_required\"\n | \"revoke_failed\"\n | \"revoke_unsupported\"\n | \"forbidden_url\"\n | \"missing_account_id\";\n\nexport class OAuthConnectionError extends Error {\n readonly status?: number;\n readonly providerError?: string;\n\n constructor(\n readonly code: OAuthConnectionErrorCode,\n message: string,\n options: { cause?: unknown; status?: number; providerError?: string } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = \"OAuthConnectionError\";\n this.status = options.status;\n this.providerError = options.providerError;\n }\n}\n\n/**\n * The connection's tokens no longer work and refreshing them failed, so the\n * user has to connect the account again (send them to\n * `/auth/connections/<provider>`). The connection is marked, so every later\n * call fails the same way without asking the provider again, until it is\n * reconnected.\n */\nexport class OAuthReconnectRequiredError extends OAuthConnectionError {\n constructor(\n readonly provider: string,\n options: { cause?: unknown; status?: number; providerError?: string } = {},\n ) {\n super(\n \"reconnect_required\",\n `The ${provider} connection needs to be reconnected: its tokens were refused and could not be refreshed.`,\n options,\n );\n this.name = \"OAuthReconnectRequiredError\";\n }\n}\n",
7
+ "import { OAuthConnectionError } from \"./errors\";\n\nexport interface OAuthConnectionProviderConfig {\n /** The provider's authorization endpoint: `https://www.figma.com/oauth`. */\n authorizeUrl: string;\n /** The token endpoint, for the code exchange (and refreshes, unless `refreshUrl` says otherwise). */\n tokenUrl: string;\n /**\n * Where refresh tokens are spent, for a provider with a refresh endpoint of\n * its own: Figma refreshes at `https://api.figma.com/v1/oauth/refresh`.\n * Default `tokenUrl`.\n */\n refreshUrl?: string;\n /**\n * The `grant_type` sent with a refresh. Default `\"refresh_token\"` (RFC 6749\n * §6). `false` leaves it out, for a refresh endpoint that documents only\n * `refresh_token` (Figma's).\n */\n refreshGrantType?: string | false;\n /**\n * The RFC 7009 revocation endpoint. Without one, `revoke()` is refused and\n * `disconnect()` (which forgets the tokens locally) is the way to remove a\n * connection.\n */\n revokeUrl?: string;\n clientId: string;\n clientSecret: string;\n /** The scopes to request. */\n scopes: string[];\n /** How `scopes` are joined on the authorization URL. Default `\" \"` (RFC 6749). */\n scopeSeparator?: string;\n /**\n * How the client authenticates to the token, refresh and revocation endpoints:\n * `\"body\"` sends `client_id` and `client_secret` as form fields (what most\n * providers document), `\"basic\"` sends them as HTTP Basic credentials.\n * Default `\"body\"`.\n */\n clientAuth?: \"body\" | \"basic\";\n /** Send a PKCE challenge (S256). Default `true`; turn off only for a provider that rejects it. */\n pkce?: boolean;\n /**\n * Extra query parameters for the authorization URL, such as\n * `{ access_type: \"offline\", prompt: \"consent\" }` for Google. They cannot\n * replace `state`, the PKCE challenge, `redirect_uri`, `client_id` or `scope`.\n */\n authorizationParams?: Record<string, string>;\n /**\n * The callback URL registered with the provider. Default\n * `${HOST_NAME}/auth/connections/<name>/callback` (the request's origin when\n * `HOST_NAME` is unset).\n */\n redirectUri?: string;\n /**\n * Where the provider's API lives: `https://api.figma.com`. Required:\n * `connection.fetch` takes paths relative to it and **refuses any other\n * origin**, so the user's token only ever goes to the provider's API host,\n * even for a URL that came from user input.\n */\n apiBaseUrl: string;\n /** Refresh this many seconds before the access token expires. Default 60. */\n refreshLeewaySeconds?: number;\n /**\n * How a connection is refreshed, for a provider that does not spend a\n * refresh token at a token endpoint. Instagram, for one, renews the\n * long-lived access token itself (`ig_refresh_token`) and issues no refresh\n * token. Unset, a refresh spends the refresh token at `refreshUrl`, and a\n * connection without one has to be reconnected once its token expires.\n *\n * Resolve the new tokens, or `null` when there is nothing to refresh yet\n * (the current token is kept, and nothing is marked). Throw\n * `OAuthConnectionError` with the HTTP `status` for a refusal: a 4xx (other\n * than `invalid_client`) marks the connection `needs_reconnect`, anything\n * else leaves it alone.\n */\n refreshStrategy?: ConnectionRefreshStrategy;\n /**\n * Lets a user connect more than one account at this provider (several\n * Instagram accounts to post to). Connections are then told apart by\n * `providerAccountId`, which the exchange must supply; connecting an\n * account again replaces only that account's connection. Default `false`:\n * one connection per user, and connecting again replaces it.\n */\n multiple?: boolean;\n /**\n * How `connection.fetch` sends the token: `\"header\"` (the default) as\n * `Authorization: Bearer`, `\"query\"` as an `access_token` query parameter,\n * for an API that documents only that (Instagram's Graph API). Either way\n * the token goes only to `apiBaseUrl`'s origin.\n */\n tokenPlacement?: \"header\" | \"query\";\n /**\n * Whether an API response says the access token itself was refused, which\n * makes `connection.fetch` refresh and retry once. Default: the status is\n * 401. Instagram also answers a dead token with a 400 whose error `code` is\n * 190. Read `response.clone()`, never the response itself: it is handed\n * back to the caller when this answers `false`. Clone only once the status\n * says it could be a refusal, so a large success body is not buffered twice.\n */\n isTokenRejected?: (response: Response) => boolean | Promise<boolean>;\n}\n\n/**\n * Why a connection is being refreshed: its token is about to expire, the API\n * refused it, or the app called `connection.refresh()`.\n */\nexport type ConnectionRefreshReason = \"expiring\" | \"rejected\" | \"requested\";\n\n/** What a `refreshStrategy` is handed: the connection's current grant. */\nexport interface ConnectionRefreshContext {\n accessToken: string;\n refreshToken: string | null;\n scopes: string[];\n expiresAt: Date | null;\n /** When the current access token was stored (the last connect or refresh). */\n issuedAt: Date;\n providerAccountId: string | null;\n /**\n * Why: `\"rejected\"` when the API just refused the token, so a strategy that\n * would otherwise wait (`null`) should treat the grant as gone.\n */\n reason: ConnectionRefreshReason;\n}\n\n/** See `OAuthConnectionProviderConfig.refreshStrategy`. */\nexport type ConnectionRefreshStrategy = (\n context: ConnectionRefreshContext,\n) => Promise<OAuthTokenSet | null>;\n\n/** What a token endpoint answered, normalised. */\nexport interface OAuthTokenSet {\n accessToken: string;\n refreshToken: string | null;\n tokenType: string | null;\n /** Absent when the provider did not say (`expires_in` missing). */\n expiresAt: Date | null;\n /** The scopes granted, when the provider says; otherwise the ones requested. */\n scopes: string[];\n /**\n * The provider's id for the account, when the token response carries one\n * (Figma's `user_id_string`; `user_id` or `account_id` otherwise).\n */\n providerAccountId: string | null;\n /**\n * What the provider said about the account at connect time (Instagram's\n * username and picture, say), handed to `onConnected` and not stored.\n */\n profile?: Record<string, unknown>;\n}\n\n/**\n * A provider an app can connect a user's account to, to call its API on the\n * user's behalf — as opposed to `OAuthProvider`, which signs the user in.\n * Configured under `auth.connections`:\n *\n * ```ts\n * connections: {\n * figma: new OAuthConnectionProvider({\n * authorizeUrl: \"https://www.figma.com/oauth\",\n * tokenUrl: \"https://api.figma.com/v1/oauth/token\",\n * refreshUrl: \"https://api.figma.com/v1/oauth/refresh\",\n * refreshGrantType: false,\n * clientAuth: \"basic\",\n * clientId: process.env.FIGMA_CLIENT_ID!,\n * clientSecret: process.env.FIGMA_CLIENT_SECRET!,\n * scopes: [\"file_content:read\"],\n * apiBaseUrl: \"https://api.figma.com\",\n * }),\n * }\n * ```\n */\nexport class OAuthConnectionProvider {\n readonly config: Required<\n Omit<OAuthConnectionProviderConfig, \"revokeUrl\" | \"redirectUri\" | \"refreshUrl\" | \"refreshStrategy\" | \"isTokenRejected\">\n > &\n Pick<\n OAuthConnectionProviderConfig,\n \"revokeUrl\" | \"redirectUri\" | \"refreshUrl\" | \"refreshStrategy\" | \"isTokenRejected\"\n >;\n\n constructor(config: OAuthConnectionProviderConfig) {\n for (const key of [\"authorizeUrl\", \"tokenUrl\"] as const) {\n assertHttpUrl(key, config[key]);\n }\n for (const key of [\"refreshUrl\", \"revokeUrl\"] as const) {\n if (config[key] !== undefined) assertHttpUrl(key, config[key]);\n }\n // Required (not just recommended): it is what keeps `connection.fetch`\n // from sending the user's token anywhere but the provider's API host. A\n // missing one (`process.env.X` unset, or plain JS) fails the boot, when\n // the auth config is loaded, rather than the first `fetch`.\n if (config.apiBaseUrl === undefined || config.apiBaseUrl === null || config.apiBaseUrl === \"\") {\n throw new Error(\n \"OAuthConnectionProvider: apiBaseUrl is required. Set it to the provider's API origin \" +\n '(e.g. apiBaseUrl: \"https://api.figma.com\"); connection.fetch only sends the token there.',\n );\n }\n assertHttpUrl(\"apiBaseUrl\", config.apiBaseUrl);\n this.config = {\n scopeSeparator: \" \",\n clientAuth: \"body\",\n pkce: true,\n authorizationParams: {},\n refreshLeewaySeconds: 60,\n multiple: false,\n tokenPlacement: \"header\",\n ...config,\n refreshGrantType: config.refreshGrantType ?? \"refresh_token\",\n };\n }\n\n /**\n * Whether `response` refuses the access token itself: `isTokenRejected`\n * when configured, else a 401.\n */\n async isTokenRejected(response: Response): Promise<boolean> {\n const check = this.config.isTokenRejected;\n if (!check) return response.status === 401;\n return await check(response);\n }\n\n /** The URL to send the browser to. */\n authorizationUrl(args: { state: string; codeChallenge: string; redirectUri: string }): string {\n const url = new URL(this.config.authorizeUrl);\n const params: Record<string, string> = {\n ...this.config.authorizationParams,\n response_type: \"code\",\n client_id: this.config.clientId,\n redirect_uri: args.redirectUri,\n scope: this.config.scopes.join(this.config.scopeSeparator),\n state: args.state,\n };\n if (this.config.pkce) {\n params.code_challenge = args.codeChallenge;\n params.code_challenge_method = \"S256\";\n }\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n return url.toString();\n }\n\n /** Exchanges an authorization code for tokens. */\n exchangeCode(args: { code: string; codeVerifier: string; redirectUri: string }): Promise<OAuthTokenSet> {\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: args.code,\n redirect_uri: args.redirectUri,\n });\n if (this.config.pkce) body.set(\"code_verifier\", args.codeVerifier);\n return this.tokenRequest(this.config.tokenUrl, body, {\n scopes: this.config.scopes,\n refreshToken: null,\n phase: \"exchange\",\n });\n }\n\n /**\n * Spends `refreshToken` for a new access token at `refreshUrl` (default\n * `tokenUrl`). A provider that does not rotate refresh tokens (Figma)\n * answers without one, and the old one is kept.\n */\n refresh(refreshToken: string, scopes: string[]): Promise<OAuthTokenSet> {\n const body = new URLSearchParams();\n const grantType = this.config.refreshGrantType;\n if (grantType !== false && grantType !== \"\") body.set(\"grant_type\", grantType);\n body.set(\"refresh_token\", refreshToken);\n return this.tokenRequest(this.config.refreshUrl ?? this.config.tokenUrl, body, {\n scopes,\n refreshToken,\n phase: \"refresh\",\n });\n }\n\n /** Revokes `token` at the provider (RFC 7009). */\n async revoke(token: string, hint: \"refresh_token\" | \"access_token\"): Promise<void> {\n if (!this.config.revokeUrl) {\n throw new OAuthConnectionError(\n \"revoke_unsupported\",\n \"This provider has no revokeUrl configured. Use disconnect() to forget the tokens locally.\",\n );\n }\n const body = new URLSearchParams({ token, token_type_hint: hint });\n let response: Response;\n try {\n response = await fetch(this.config.revokeUrl, this.post(body));\n } catch (cause) {\n throw new OAuthConnectionError(\"revoke_failed\", \"The revocation request failed.\", { cause });\n }\n // RFC 7009: 200 whether or not the token was still valid.\n if (!response.ok) {\n throw new OAuthConnectionError(\n \"revoke_failed\",\n `The provider refused the revocation (HTTP ${response.status}).`,\n { status: response.status },\n );\n }\n }\n\n private post(body: URLSearchParams): RequestInit {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n // GitHub answers form-encoded unless asked for JSON.\n Accept: \"application/json\",\n };\n if (this.config.clientAuth === \"basic\") {\n const credentials = `${encodeURIComponent(this.config.clientId)}:${encodeURIComponent(this.config.clientSecret)}`;\n headers.Authorization = `Basic ${Buffer.from(credentials).toString(\"base64\")}`;\n } else {\n body.set(\"client_id\", this.config.clientId);\n body.set(\"client_secret\", this.config.clientSecret);\n }\n return { method: \"POST\", headers, body: body.toString(), redirect: \"error\" };\n }\n\n private async tokenRequest(\n endpoint: string,\n body: URLSearchParams,\n previous: { scopes: string[]; refreshToken: string | null; phase: \"exchange\" | \"refresh\" },\n ): Promise<OAuthTokenSet> {\n const failure = previous.phase === \"exchange\" ? \"exchange_failed\" : \"refresh_failed\";\n let response: Response;\n try {\n response = await fetch(endpoint, this.post(body));\n } catch (cause) {\n throw new OAuthConnectionError(failure, \"The token request failed.\", { cause });\n }\n\n const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n if (!response.ok || typeof payload.access_token !== \"string\" || payload.access_token === \"\") {\n // Only the provider's error code, never the body: it can echo the grant.\n const code = typeof payload.error === \"string\" && /^[a-z0-9_]{1,64}$/.test(payload.error) ? payload.error : undefined;\n throw new OAuthConnectionError(\n failure,\n `The token endpoint refused the ${previous.phase === \"exchange\" ? \"code\" : \"refresh token\"} ` +\n `(HTTP ${response.status}${code ? `, ${code}` : \"\"}).`,\n { status: response.status, providerError: code },\n );\n }\n\n const expiresIn = Number(payload.expires_in);\n const scope = typeof payload.scope === \"string\" ? payload.scope : undefined;\n // Figma's `user_id_string` before its deprecated numeric `user_id`, which\n // JSON parsing has already rounded: Figma's ids do not fit a double.\n const accountId = payload.user_id_string ?? payload.user_id ?? payload.account_id;\n return {\n accessToken: payload.access_token,\n refreshToken:\n typeof payload.refresh_token === \"string\" && payload.refresh_token !== \"\"\n ? payload.refresh_token\n : previous.refreshToken,\n tokenType: typeof payload.token_type === \"string\" ? payload.token_type : null,\n expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? new Date(Date.now() + expiresIn * 1000) : null,\n scopes: scope !== undefined ? scope.split(/[\\s,]+/).filter(Boolean) : previous.scopes,\n providerAccountId:\n typeof accountId === \"string\" || typeof accountId === \"number\" ? String(accountId) : null,\n };\n }\n}\n\nfunction assertHttpUrl(key: string, value: unknown): void {\n let url: URL | undefined;\n try {\n url = new URL(String(value));\n } catch {\n url = undefined;\n }\n if (!url || (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname)))) {\n throw new Error(\n `OAuthConnectionProvider: ${key} must be an https URL (http only for localhost), got ${JSON.stringify(value)}.`,\n );\n }\n}\n\nexport function isLoopback(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n",
8
+ "import { DatabaseManager } from \"../../database/DatabaseManager\";\nimport { app } from \"../../foundation/app\";\nimport { currentEncrypter } from \"../../orm/encryption\";\nimport { LockManager } from \"../../services/lock/LockManager\";\nimport {\n type ConnectionRecord,\n type ConnectionStore,\n DatabaseConnectionStore,\n MemoryConnectionStore,\n} from \"./ConnectionStore\";\nimport { OAuthConnectionError, OAuthReconnectRequiredError } from \"./errors\";\nimport {\n type ConnectionRefreshReason,\n type OAuthConnectionProvider,\n type OAuthTokenSet,\n isLoopback,\n} from \"./OAuthConnectionProvider\";\n\n/** A user, as far as a connection is concerned: anything with an `id`. */\nexport type ConnectionOwner = { id: string | number } | string | number;\n\n/** See `ProviderConnection.status`. */\nexport type ConnectionStatus = \"connected\" | \"needs_reconnect\";\n\n/** What `Connections.fake` answers an API request with. */\nexport type FakeConnectionHandler = (request: Request) => Response | Promise<Response>;\n\nexport interface ConnectionManagerOptions {\n providers: Record<string, OAuthConnectionProvider>;\n /** Default: a `DatabaseConnectionStore` on the default database connection. */\n store?: ConnectionStore | (() => ConnectionStore);\n}\n\n/**\n * The OAuth connections a user has made, and the one place their tokens are\n * read, refreshed and spent. Reached through the `Connections` facade.\n */\nexport class ConnectionManager {\n static token = \"auth.connections\";\n\n private resolvedStore: ConnectionStore | undefined;\n private readonly refreshing = new Map<string, Promise<ConnectionRecord>>();\n private fakes: Map<string, FakeConnectionHandler> | undefined;\n private fakeStore: MemoryConnectionStore | undefined;\n readonly fakeRequests: Request[] = [];\n\n constructor(private readonly options: ConnectionManagerOptions) {\n for (const [name, provider] of Object.entries(options.providers)) {\n if (!provider.config.multiple) continue;\n // A multiple-account provider's connections are stored under\n // `<name>:<account id>`, which must not be read as another provider's.\n const clash = Object.keys(options.providers).find((other) => other.startsWith(`${name}${ACCOUNT_SEPARATOR}`));\n if (name.includes(ACCOUNT_SEPARATOR) || clash) {\n throw new Error(\n `auth.connections: \"${clash ?? name}\" cannot be used alongside the multiple-account provider \"${name}\" ` +\n `(\"${ACCOUNT_SEPARATOR}\" separates a provider from an account id in the store).`,\n );\n }\n }\n }\n\n get providers(): Record<string, OAuthConnectionProvider> {\n return this.options.providers;\n }\n\n /** The store connections are kept in. */\n get store(): ConnectionStore {\n if (this.fakeStore) return this.fakeStore;\n if (!this.resolvedStore) {\n const configured = this.options.store;\n this.resolvedStore =\n typeof configured === \"function\"\n ? configured()\n : (configured ??\n new DatabaseConnectionStore(app(DatabaseManager).connection(), () => currentEncrypter()));\n }\n return this.resolvedStore;\n }\n\n provider(name: string): OAuthConnectionProvider {\n const provider = this.options.providers[name];\n if (!provider) {\n const known = Object.keys(this.options.providers);\n throw new OAuthConnectionError(\n \"unknown_provider\",\n `No OAuth connection provider \"${name}\" in auth.connections` +\n (known.length > 0 ? ` (configured: ${known.join(\", \")}).` : \" (none are configured).\"),\n );\n }\n return provider;\n }\n\n /**\n * The user's connection to `provider`, or `null` when they have not\n * connected it. With `accountId`, only the connection to that account\n * (`providerAccountId`). For a provider with `multiple: true` and no\n * `accountId`, the account added most recently; use `list(user,\n * provider)` for all of them.\n */\n async for(user: ConnectionOwner, provider: string, accountId?: string): Promise<ProviderConnection | null> {\n const config = this.provider(provider);\n const userId = ownerId(user);\n if (!config.config.multiple) {\n const record = await this.store.find(userId, provider);\n if (!record || (accountId !== undefined && record.providerAccountId !== accountId)) return null;\n return new ProviderConnection(this, record);\n }\n if (accountId !== undefined) {\n const record =\n (await this.store.find(userId, storeKey(provider, accountId))) ??\n // Stored before the provider was switched to `multiple`.\n (await this.store.find(userId, provider));\n return record && record.providerAccountId === accountId ? new ProviderConnection(this, record) : null;\n }\n const [latest] = (await this.list(user, provider)).sort(\n (a, b) => b.connectedAt.getTime() - a.connectedAt.getTime(),\n );\n return latest ?? null;\n }\n\n /** Every connection the user has, or only those to `provider`. */\n async list(user: ConnectionOwner, provider?: string): Promise<ProviderConnection[]> {\n if (provider !== undefined) this.provider(provider);\n const records = await this.store.list(ownerId(user));\n return records\n .filter((record) => {\n const name = this.providerName(record.provider);\n return name !== null && (provider === undefined || name === provider);\n })\n .map((record) => new ProviderConnection(this, record));\n }\n\n /**\n * Stores tokens for the user, replacing any earlier connection to the same\n * provider — or, for a provider with `multiple: true`, to the same account\n * (`providerAccountId`, required there). The connect callback calls this;\n * call it yourself for tokens obtained some other way.\n */\n async save(\n user: ConnectionOwner,\n provider: string,\n tokens: Partial<OAuthTokenSet> & { accessToken: string },\n ): Promise<ProviderConnection> {\n const config = this.provider(provider);\n const userId = ownerId(user);\n const { profile: _profile, ...grant } = tokens;\n const set: OAuthTokenSet = {\n refreshToken: null,\n tokenType: null,\n expiresAt: null,\n providerAccountId: null,\n scopes: config.config.scopes,\n ...grant,\n };\n if (!config.config.multiple) {\n return new ProviderConnection(this, await this.store.save(userId, provider, set));\n }\n\n const accountId = set.providerAccountId;\n if (typeof accountId !== \"string\" || accountId === \"\") {\n throw new OAuthConnectionError(\n \"missing_account_id\",\n `\"${provider}\" allows several accounts per user, so a connection needs the provider's account id ` +\n \"(providerAccountId), and the token exchange did not supply one.\",\n );\n }\n const record = await this.store.save(userId, storeKey(provider, accountId), set);\n // The same account, stored before the provider was switched to `multiple`.\n const legacy = await this.store.find(userId, provider);\n if (legacy && legacy.providerAccountId === accountId) await this.store.delete(legacy.id);\n return new ProviderConnection(this, record);\n }\n\n /**\n * The configured provider a stored connection belongs to: the store key\n * itself, or `<name>` of a multiple-account provider's `<name>:<account id>`.\n * `null` for a provider no longer configured.\n *\n * @internal\n */\n providerName(key: string): string | null {\n const providers = this.options.providers;\n if (Object.hasOwn(providers, key)) return key;\n const at = key.indexOf(ACCOUNT_SEPARATOR);\n if (at <= 0) return null;\n const name = key.slice(0, at);\n return Object.hasOwn(providers, name) && providers[name].config.multiple ? name : null;\n }\n\n // --- testing ---------------------------------------------------------------\n\n /**\n * Fakes every provider's API: connections live in memory, `fetch` answers\n * through `handlers[provider]` (recorded in `fakeRequests`), and nothing\n * reaches a token or revocation endpoint. Returns `this` so a test can\n * `save` a connection to start from.\n */\n fake(handlers: Record<string, FakeConnectionHandler> = {}): this {\n this.fakes = new Map(Object.entries(handlers));\n this.fakeStore = new MemoryConnectionStore();\n this.fakeRequests.length = 0;\n return this;\n }\n\n /** Undoes `fake`. */\n restore(): void {\n this.fakes = undefined;\n this.fakeStore = undefined;\n this.fakeRequests.length = 0;\n }\n\n get faked(): boolean {\n return this.fakes !== undefined;\n }\n\n // --- internals, for ProviderConnection ---------------------------------------\n\n /** @internal */\n async send(provider: string, request: Request): Promise<Response> {\n if (!this.fakes) return fetch(request);\n this.fakeRequests.push(request.clone());\n const handler = this.fakes.get(provider);\n if (!handler) {\n throw new Error(`Connections.fake() has no handler for \"${provider}\". Pass one: Connections.fake({ ${provider}: (req) => ... }).`);\n }\n return handler(request);\n }\n\n /**\n * A record whose access token is not the one at `staleRevision`: refreshed\n * by this call, or by whoever refreshed it first. Serialised per connection\n * in this process (concurrent callers share one refresh) and, through the\n * app's lock store, across processes — a rotating refresh token must be\n * spent exactly once.\n *\n * @internal\n */\n refresh(record: ConnectionRecord, reason: ConnectionRefreshReason = \"requested\"): Promise<ConnectionRecord> {\n const inFlight = this.refreshing.get(record.id);\n if (inFlight) return inFlight;\n const task = this.withLock(record.id, () => this.refreshOnce(record, reason)).finally(() =>\n this.refreshing.delete(record.id),\n );\n this.refreshing.set(record.id, task);\n return task;\n }\n\n private async refreshOnce(seen: ConnectionRecord, reason: ConnectionRefreshReason): Promise<ConnectionRecord> {\n // Re-read under the lock: another process may have refreshed already.\n const name = this.providerName(seen.provider) ?? seen.provider;\n const current = await this.store.find(seen.userId, seen.provider);\n if (!current || current.id !== seen.id) {\n throw new OAuthReconnectRequiredError(name);\n }\n if (current.revision !== seen.revision && !current.needsReconnect) return current;\n if (current.needsReconnect) throw new OAuthReconnectRequiredError(name);\n\n const provider = this.provider(name);\n if (this.faked) return current;\n const strategy = provider.config.refreshStrategy;\n if (!strategy && current.refreshToken === null) {\n await this.store.markNeedsReconnect(current.id);\n throw new OAuthReconnectRequiredError(name);\n }\n\n let tokens: OAuthTokenSet | null;\n try {\n tokens = strategy\n ? await strategy({\n accessToken: current.accessToken,\n refreshToken: current.refreshToken,\n scopes: [...current.scopes],\n expiresAt: current.expiresAt,\n issuedAt: current.updatedAt,\n reason,\n providerAccountId: current.providerAccountId,\n })\n : await provider.refresh(current.refreshToken as string, current.scopes);\n } catch (error) {\n // A refusal from the token endpoint is final: the grant is gone. A\n // network error or a 5xx is not, and leaves the connection alone. Nor\n // is `invalid_client`: the app's own credentials (or `clientAuth`) are\n // wrong, reconnecting would fail the same way, and marking would make\n // every user reconnect once the config is fixed.\n if (\n error instanceof OAuthConnectionError &&\n error.status !== undefined &&\n error.status >= 400 &&\n error.status < 500 &&\n error.providerError !== \"invalid_client\"\n ) {\n await this.store.markNeedsReconnect(current.id);\n throw new OAuthReconnectRequiredError(name, {\n cause: error,\n status: error.status,\n providerError: error.providerError,\n });\n }\n throw error;\n }\n // The strategy has nothing to refresh yet: keep the current token.\n if (tokens === null) return current;\n\n const updated = await this.store.updateTokens(current.id, current.revision, tokens);\n if (updated) return updated;\n // Someone else wrote first (only possible without a shared lock store).\n const winner = await this.store.find(current.userId, current.provider);\n if (!winner) throw new OAuthReconnectRequiredError(name);\n return winner;\n }\n\n private async withLock<T>(id: string, fn: () => Promise<T>): Promise<T> {\n const application = app();\n if (this.faked || !application.bound(LockManager)) return fn();\n const result = await application\n .make(LockManager)\n .run(`gemi:oauth-connection:${id}`, { ttl: 30_000, wait: 20_000 }, () => fn());\n if (!result.acquired) {\n throw new OAuthConnectionError(\n \"refresh_failed\",\n \"Timed out waiting for another refresh of this connection to finish.\",\n );\n }\n return result.value as T;\n }\n}\n\n/**\n * One user's connection to one provider. Never exposes a token as a property,\n * and serialises (`toJSON`, `console.log`) without them.\n */\nexport class ProviderConnection {\n constructor(\n private readonly manager: ConnectionManager,\n private record: ConnectionRecord,\n ) {}\n\n /** The provider's name under `auth.connections`. */\n get provider(): string {\n return this.manager.providerName(this.record.provider) ?? this.record.provider;\n }\n get userId(): string {\n return this.record.userId;\n }\n get providerAccountId(): string | null {\n return this.record.providerAccountId;\n }\n /** The scopes the provider granted. */\n get scopes(): readonly string[] {\n return this.record.scopes;\n }\n get expiresAt(): Date | null {\n return this.record.expiresAt;\n }\n /** A refresh was refused: the user has to connect again. */\n get needsReconnect(): boolean {\n return this.record.needsReconnect;\n }\n get connectedAt(): Date {\n return this.record.createdAt;\n }\n\n /**\n * What to show the user: `\"needs_reconnect\"` when a refresh was refused, or\n * when the access token has expired and there is no refresh token to renew\n * it; `\"connected\"` otherwise. Read without calling the provider.\n */\n get status(): ConnectionStatus {\n if (this.record.needsReconnect) return \"needs_reconnect\";\n const expiresAt = this.record.expiresAt?.getTime();\n if (this.record.refreshToken === null && expiresAt !== undefined && expiresAt <= Date.now()) {\n return \"needs_reconnect\";\n }\n return \"connected\";\n }\n\n /** Whether every one of `scopes` was granted. */\n hasScopes(...scopes: string[]): boolean {\n return scopes.every((scope) => this.record.scopes.includes(scope));\n }\n\n /**\n * `fetch`, as the user: adds `Authorization: Bearer <token>`, refreshes the\n * token first when it is about to expire, and after a 401 refreshes and\n * retries once. A refresh the provider refuses marks the connection and\n * throws `OAuthReconnectRequiredError`.\n *\n * A path is resolved against the provider's `apiBaseUrl`, and a URL on any\n * other origin is refused (`OAuthConnectionError`,\n * `forbidden_url`), so the token only ever goes to the provider. Redirects\n * are followed by hand: the token is dropped on one that leaves the origin.\n * A streamed request body cannot be sent twice, so a 401 for one is\n * returned rather than retried.\n */\n async fetch(input: string | URL, init: RequestInit = {}): Promise<Response> {\n const url = this.resolveUrl(input);\n const record = await this.current();\n const first = await this.send(url, init, record.accessToken);\n // Retry only a refusal of the token itself, not one from where a redirect\n // led after the token was dropped.\n if (!first.authorized || init.body instanceof ReadableStream) return first.response;\n const provider = this.manager.provider(this.provider);\n if (!(await provider.isTokenRejected(first.response))) return first.response;\n\n await first.response.body?.cancel().catch(() => {});\n const refreshed = await this.refreshFrom(record, \"rejected\");\n return (await this.send(url, init, refreshed.accessToken)).response;\n }\n\n /**\n * A valid access token, refreshed first if it is about to expire — for an\n * SDK that wants the token itself. Prefer `fetch`, which also retries a 401.\n */\n async accessToken(): Promise<string> {\n return (await this.current()).accessToken;\n }\n\n /** Refreshes now, whatever the expiry says. */\n async refresh(): Promise<void> {\n await this.refreshFrom(this.record);\n }\n\n /**\n * Revokes the grant at the provider (the refresh token when there is one,\n * which ends the whole grant, else the access token) and deletes the\n * connection. If the provider refuses, nothing is deleted and\n * `OAuthConnectionError` (`revoke_failed`) is thrown — call `disconnect()`\n * to forget the tokens anyway. A provider without a `revokeUrl` throws\n * `revoke_unsupported`; use `disconnect()`.\n */\n async revoke(): Promise<void> {\n if (!this.manager.faked) {\n const provider = this.manager.provider(this.provider);\n if (this.record.refreshToken !== null) {\n await provider.revoke(this.record.refreshToken, \"refresh_token\");\n } else {\n await provider.revoke(this.record.accessToken, \"access_token\");\n }\n }\n await this.manager.store.delete(this.record.id);\n }\n\n /** Forgets the tokens locally without telling the provider. */\n async disconnect(): Promise<void> {\n await this.manager.store.delete(this.record.id);\n }\n\n toJSON() {\n return {\n provider: this.provider,\n providerAccountId: this.providerAccountId,\n scopes: [...this.scopes],\n expiresAt: this.expiresAt,\n needsReconnect: this.needsReconnect,\n status: this.status,\n connectedAt: this.connectedAt,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return { ProviderConnection: this.toJSON() };\n }\n\n private async current(): Promise<ConnectionRecord> {\n if (this.record.needsReconnect) throw new OAuthReconnectRequiredError(this.provider);\n const leeway = this.manager.provider(this.provider).config.refreshLeewaySeconds * 1000;\n const expiresAt = this.record.expiresAt?.getTime();\n if (expiresAt !== undefined && expiresAt - Date.now() <= leeway) {\n return this.refreshFrom(this.record, \"expiring\");\n }\n return this.record;\n }\n\n private async refreshFrom(\n record: ConnectionRecord,\n reason: ConnectionRefreshReason = \"requested\",\n ): Promise<ConnectionRecord> {\n try {\n this.record = await this.manager.refresh(record, reason);\n } catch (error) {\n if (error instanceof OAuthReconnectRequiredError) {\n this.record = { ...this.record, needsReconnect: true };\n }\n throw error;\n }\n return this.record;\n }\n\n private resolveUrl(input: string | URL): URL {\n const base = this.manager.provider(this.provider).config.apiBaseUrl;\n let url: URL;\n try {\n url = new URL(String(input), base);\n } catch {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch was given ${JSON.stringify(String(input))}, which is not a URL.`,\n );\n }\n if (url.origin !== new URL(base).origin) {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch only sends the ${this.provider} token to ${new URL(base).origin} ` +\n `(apiBaseUrl), not to ${url.origin}.`,\n );\n }\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname))) {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch only sends a token over https, not to ${url.origin}.`,\n );\n }\n return url;\n }\n\n private async send(url: URL, init: RequestInit, token: string): Promise<{ response: Response; authorized: boolean }> {\n let target = url;\n let method = (init.method ?? \"GET\").toUpperCase();\n let body = init.body;\n let authorized = true;\n\n // Followed by hand (unless the caller asked for \"manual\" or \"error\"), so\n // the token never follows a redirect to another origin.\n if (init.redirect === \"manual\" || init.redirect === \"error\") {\n const response = await this.manager.send(this.provider, this.request(target, init, method, body, token));\n return { response, authorized };\n }\n\n for (let hop = 0; ; hop++) {\n const request = this.request(target, { ...init, redirect: \"manual\" }, method, body, authorized ? token : null);\n const response = await this.manager.send(this.provider, request);\n const location = response.headers.get(\"location\");\n if (!REDIRECTS.has(response.status) || location === null || hop >= 5) return { response, authorized };\n\n await response.body?.cancel().catch(() => {});\n const next = new URL(location, target);\n if (next.origin !== target.origin) authorized = false;\n if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === \"POST\")) {\n method = \"GET\";\n body = undefined;\n }\n target = next;\n }\n }\n\n private request(url: URL, init: RequestInit, method: string, body: RequestInit[\"body\"], token: string | null): Request {\n const headers = new Headers(init.headers);\n const target = new URL(url);\n const placement = this.manager.provider(this.provider).config.tokenPlacement;\n if (token === null) {\n headers.delete(\"authorization\");\n } else if (placement === \"query\") {\n // Where the provider documents it (Instagram's Graph API). Only ever on\n // `apiBaseUrl`'s origin: a redirect elsewhere is sent with `token` null.\n target.searchParams.set(\"access_token\", token);\n } else {\n headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return new Request(target, { ...init, method, body, headers });\n }\n}\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Between a multiple-account provider's name and the account id, in the store's `provider` column. */\nconst ACCOUNT_SEPARATOR = \":\";\n\nfunction storeKey(provider: string, accountId: string): string {\n return `${provider}${ACCOUNT_SEPARATOR}${accountId}`;\n}\n\nfunction ownerId(user: ConnectionOwner): string {\n const id = typeof user === \"object\" && user !== null ? user.id : user;\n if (id === undefined || id === null || id === \"\") {\n throw new TypeError(\"An OAuth connection belongs to a user: pass the user (or its id).\");\n }\n return String(id);\n}\n"
9
+ ],
10
+ "mappings": ";sLAwCO,AAAM,LAAiD,LAC3C,KAAO,IAAI,SAEtB,KAAI,CAAC,EAAgB,EAAkB,CAC3C,QAAW,KAAO,KAAK,KAAK,OAAO,EACjC,GAAI,EAAI,SAAW,GAAU,EAAI,WAAa,EAAU,MAAO,IAAK,CAAI,EAE1E,OAAO,UAGH,KAAI,CAAC,EAAgB,CACzB,MAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,EAAE,OAAO,CAAC,IAAQ,EAAI,SAAW,CAAM,EAAE,IAAI,CAAC,KAAS,IAAK,CAAI,EAAE,OAG3F,KAAI,CAAC,EAAgB,EAAkB,EAAuB,CAClE,IAAM,EAAW,MAAM,KAAK,KAAK,EAAQ,CAAQ,EAC3C,EAAM,IAAI,KACV,EAAwB,CAC5B,GAAI,GAAU,IAAM,IAAI,aAAa,EACrC,SACA,cACG,EAAW,CAAM,EACpB,eAAgB,GAChB,UAAW,GAAU,UAAY,GAAK,EACtC,UAAW,GAAU,WAAa,EAClC,UAAW,CACb,EAEA,OADA,KAAK,KAAK,IAAI,EAAI,GAAI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ACjE,GAAI,IAAO,QAAa,IAAO,MAAQ,IAAO,GAC5C,MAAU,UAAU,mEAAmE,EAEzF,OAAO,OAAO,CAAE",
11
+ "debugId": "95CC3A366C2DD52264756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{constants as M}from"os";var Y=Symbol.for("gemi.server.shutdown");function Q(){let j=globalThis;return j[Y]??={shuttingDown:!1,drained:!1},j[Y]}function R(){return Q().shuttingDown}function f(){Q().shuttingDown=!0}function x(){Q().drained=!0}function W(j=process.env){let z={timeoutMs:U(j.GEMI_SHUTDOWN_TIMEOUT,20),delayMs:U(j.GEMI_SHUTDOWN_DELAY,0),providerTimeoutMs:U(j.GEMI_SHUTDOWN_PROVIDER_TIMEOUT,5)};if(z.delayMs>0&&z.delayMs>=z.timeoutMs)console.warn(`[gemi] GEMI_SHUTDOWN_DELAY (${z.delayMs/1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${z.timeoutMs/1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`);return z}function U(j,z){let B=j===void 0||j.trim()===""?NaN:Number(j);if(Number.isFinite(B)&&B>=0)return B*1000;if(j!==void 0)console.warn(`[gemi] Ignoring shutdown setting "${j}": expected a number of seconds.`);return z*1000}async function E(j){let{server:z,settings:B}=j,J=Date.now()+B.timeoutMs;f(),console.log(`[gemi] Shutting down: draining in-flight requests (up to ${B.timeoutMs/1000}s).`);let H=!0;if(z){if(B.delayMs>0)await _(Math.min(B.delayMs,J-Date.now()));let O=z.stop(),V=Promise.resolve();try{V=Promise.resolve(j.closeSockets?.()).catch(()=>{})}catch(F){console.error("[gemi] Closing the broadcast sockets failed:",F)}let X=J-Date.now(),$=j.closeSockets?Promise.race([O,Promise.all([V,y(z)])]):O;if(H=X>0?await G($,X):z.pendingRequests===0,!H)console.error(`[gemi] Shutdown grace period elapsed with ${z.pendingRequests} request(s) still in flight; abandoning them.`),z.stop(!0).catch(()=>{})}x();let P=await j.shutdownProviders({timeoutMs:B.providerTimeoutMs}),K=H&&P.failed.length===0&&P.timedOut.length===0;return console.log(`[gemi] Shutdown ${K?"complete":"finished with errors"}.`),K?0:1}function y(j){return new Promise((z)=>{let B=()=>{if(j.pendingRequests===0){z();return}setTimeout(B,50).unref?.()};B()})}async function G(j,z){if(z<=0)return!1;let B,J=await Promise.race([j.then(()=>!0,()=>!0),new Promise((H)=>{B=setTimeout(()=>H(!1),z)})]);return clearTimeout(B),J}function _(j){return new Promise((z)=>setTimeout(z,Math.max(0,j)))}function q(j){if(!R())return j;try{return j.headers.set("Connection","close"),j}catch{let z=new Response(j.body,j);return z.headers.set("Connection","close"),z}}function N(j){return async(z,B)=>{if(Q().drained)return new Response("Service Unavailable",{status:503,headers:{Connection:"close"}});return q(await j(z,B))}}var Z=Symbol.for("gemi.server.signalsInstalled"),w=1000;function D(j,z={}){let B=globalThis;if(B[Z])return;B[Z]=!0;let J=z.repeatWindowMs??w,H,P=(K)=>{if(H!==void 0){if(Date.now()-H<J)return;console.error(`[gemi] ${K} received again; exiting without waiting for the drain.`),process.exit(128+M.signals[K])}H=Date.now(),console.log(`[gemi] ${K} received.`),j().then((O)=>process.exit(O),(O)=>{console.error("[gemi] Shutdown failed:",O),process.exit(1)})};process.on("SIGTERM",P),process.on("SIGINT",P)}
3
+ export{R as wj,f as xj,W as yj,E as zj,N as Aj,D as Bj};
4
+
5
+ //# debugId=99E7524D418555E864756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../server/shutdown.ts"],
4
+ "sourcesContent": [
5
+ "import { constants } from \"node:os\";\nimport type { ShutdownReport } from \"../foundation/Application\";\nimport type { Instrumentation } from \"./types\";\n\n// On `globalThis` under a registry symbol rather than in a module variable, so\n// the flag an app's health route reads is the one the server set even when two\n// copies of this module are loaded — the built CLI bundles its own gemi (see\n// `app/App.ts`), and `bun --hot` re-evaluates every module on a reload.\nconst STATE = Symbol.for(\"gemi.server.shutdown\");\n\ntype ShutdownState = { shuttingDown: boolean; drained: boolean };\n\nfunction state(): ShutdownState {\n const global = globalThis as { [STATE]?: ShutdownState };\n global[STATE] ??= { shuttingDown: false, drained: false };\n return global[STATE];\n}\n\n/**\n * True from the moment this server process has been told to stop — before it\n * stops accepting connections — until it exits.\n *\n * gemi has no health endpoint of its own, so taking an instance out of a load\n * balancer is the app's health route's job: answer it with a `503` while this\n * is true, and the platform's probe pulls the instance while the in-flight\n * requests are still draining. Every response sent in that window also carries\n * `Connection: close`, so a client that honours it opens its next request on a\n * new connection — one the load balancer can route elsewhere — instead of\n * reusing this one.\n */\nexport function isShuttingDown(): boolean {\n return state().shuttingDown;\n}\n\nexport function markShuttingDown() {\n state().shuttingDown = true;\n}\n\n/**\n * The request drain is over and the providers' `shutdown()` may be running:\n * from here on a request must not reach the app. See `serveForShutdown`.\n */\nexport function markDrained() {\n state().drained = true;\n}\n\n/** Test seam: a fresh process starts false, and so should each test. */\nexport function resetShuttingDown() {\n state().shuttingDown = false;\n state().drained = false;\n}\n\nexport type ShutdownSettings = {\n /**\n * From the signal to the end of the request drain, in milliseconds — the\n * delay below included. Requests still in flight when it runs out are\n * abandoned. `GEMI_SHUTDOWN_TIMEOUT`, in seconds; default 20. `0` means\n * \"close the listener and do not wait\": a shutdown with nothing in flight is\n * still a clean one.\n */\n timeoutMs: number;\n /**\n * How long to keep accepting new requests after `isShuttingDown()` turns\n * true, in milliseconds, so a health probe can see the `503` and the load\n * balancer stop routing here before the listener closes.\n * `GEMI_SHUTDOWN_DELAY`, in seconds; default 0.\n */\n delayMs: number;\n /**\n * The shared deadline for every provider's `shutdown()`, in milliseconds,\n * after the drain. `GEMI_SHUTDOWN_PROVIDER_TIMEOUT`, in seconds; default 5.\n * `0` skips the hooks — deliberately, so it is not reported as a failure.\n */\n providerTimeoutMs: number;\n};\n\n/**\n * 20s to drain plus 5s for providers is 25s: under the 30s that Kubernetes,\n * Azure Container Apps and ECS give by default between `SIGTERM` and `SIGKILL`,\n * with 5s left for the `gemi start` relay, the process exit and clock skew\n * between the platform's timer and ours. A platform with a shorter window\n * (Cloud Run's 10s, Fly's 5s) needs these lowered, not the other way round —\n * a drain that outlives the grace period ends in the same `SIGKILL` as no drain.\n *\n * The delay defaults to 0 because it only helps where a probe is watching, and\n * otherwise every shutdown would pay it for nothing.\n */\nexport function shutdownSettings(\n env: Record<string, string | undefined> = process.env,\n): ShutdownSettings {\n const settings = {\n timeoutMs: seconds(env.GEMI_SHUTDOWN_TIMEOUT, 20),\n delayMs: seconds(env.GEMI_SHUTDOWN_DELAY, 0),\n providerTimeoutMs: seconds(env.GEMI_SHUTDOWN_PROVIDER_TIMEOUT, 5),\n };\n // Warned, not clamped: the delay is sized to a probe, the timeout to the\n // platform's grace period, and which one is wrong only the operator knows.\n // Left alone, every shutdown spends the whole timeout in the delay and then\n // abandons whatever is in flight without draining it.\n if (settings.delayMs > 0 && settings.delayMs >= settings.timeoutMs) {\n console.warn(\n `[gemi] GEMI_SHUTDOWN_DELAY (${settings.delayMs / 1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${settings.timeoutMs / 1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`,\n );\n }\n return settings;\n}\n\nfunction seconds(value: string | undefined, fallback: number): number {\n const parsed = value === undefined || value.trim() === \"\" ? NaN : Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1000;\n if (value !== undefined) {\n console.warn(`[gemi] Ignoring shutdown setting \"${value}\": expected a number of seconds.`);\n }\n return fallback * 1000;\n}\n\n/** The part of `Bun.Server` a drain needs. */\nexport type Stoppable = {\n stop(closeActiveConnections?: boolean): Promise<void>;\n readonly pendingRequests: number;\n};\n\n/**\n * The shutdown sequence, in its order:\n *\n * 1. `isShuttingDown()` turns true — first, so the health route answers `503`\n * and responses carry `Connection: close` while the listener is still open.\n * 2. After `delayMs`, the listener closes (`server.stop()` without force):\n * new connections are refused, while every request in flight — a streamed\n * response included, to its last chunk — runs to completion.\n * Broadcast sockets are told `bye` and closed (`closeSockets`): a graceful\n * stop waits for open WebSockets, which never close on their own.\n * 3. That completion is awaited until `timeoutMs` from the start.\n * 4. From here a request is refused with a `503` before it reaches the app\n * (`serveForShutdown`), and every provider's `shutdown()` runs, reverse\n * order, `providerTimeoutMs`.\n *\n * Resolves with the exit code: 0 when every step finished in time, 1 when the\n * drain was cut short or a provider failed or overran.\n *\n * Two things `stop()` does not do, both measured on Bun 1.3.14, and both why\n * the process exit that follows is what actually ends the server:\n *\n * - It does not close a kept-alive connection. One that is idle when the\n * listener closes stays open, and a request sent down it afterwards is\n * served. That is what the `Connection: close` on every response in the\n * window is for: a client (or a proxy in front) that honours it opens its\n * next request on a new connection, which the closed listener refuses. A\n * client that does not honour it is what step 4's `503` is for — Bun does\n * not close the socket after a `Connection: close` response either (#566).\n * - `stop(true)` issued after a graceful `stop()` does not cut the remaining\n * requests off; it waits for the same ones. It is still called when the\n * drain times out, for a Bun that does, but nothing here depends on it. Nor\n * does it close an idle kept-alive connection. Only a `stop(true)` issued\n * *first* does that, and it cuts off the requests in flight with it, which\n * is the drain given up — so the idle ones are refused, not closed.\n */\nexport async function drain(params: {\n server: Stoppable | undefined;\n /**\n * Says `bye` to the broadcast sockets and closes them, right after the\n * listener closes, and resolves once they are closed or cut. A graceful\n * `stop()` waits for open WebSockets, which otherwise never close on their\n * own.\n */\n closeSockets?: () => void | Promise<void>;\n shutdownProviders: (options: { timeoutMs: number }) => Promise<ShutdownReport>;\n settings: ShutdownSettings;\n}): Promise<number> {\n const { server, settings } = params;\n const deadline = Date.now() + settings.timeoutMs;\n\n markShuttingDown();\n console.log(\n `[gemi] Shutting down: draining in-flight requests (up to ${settings.timeoutMs / 1000}s).`,\n );\n\n let drained = true;\n if (server) {\n if (settings.delayMs > 0) {\n await sleep(Math.min(settings.delayMs, deadline - Date.now()));\n }\n const stopped = server.stop();\n let socketsClosed: Promise<unknown> = Promise.resolve();\n try {\n socketsClosed = Promise.resolve(params.closeSockets?.()).catch(() => {});\n } catch (error) {\n console.error(\"[gemi] Closing the broadcast sockets failed:\", error);\n }\n // No time left to wait — a `GEMI_SHUTDOWN_TIMEOUT` of 0, or a delay that\n // spent all of it — is \"do not wait for what is in flight\", and that is\n // only a failure when something *is* in flight. Reading it as one made\n // every clean shutdown log an abandonment and exit 1 for the operator who\n // zeroed the budget to fit a 5s grace period, with nothing to abandon.\n const remaining = deadline - Date.now();\n // With broadcast sockets, the stop's own promise has been seen to stay\n // pending for good after every request finished and every socket was\n // closed or terminated (Bun 1.4.2 on a loaded Linux CI runner, with its\n // `pendingWebSockets` stuck above 0). So the drain also ends on its real\n // condition: no request in flight, and the hub's sockets closed or cut.\n const done = params.closeSockets\n ? Promise.race([stopped, Promise.all([socketsClosed, noRequestInFlight(server)])])\n : stopped;\n drained =\n remaining > 0 ? await settlesWithin(done, remaining) : server.pendingRequests === 0;\n if (!drained) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${server.pendingRequests} request(s) still in flight; abandoning them.`,\n );\n void server.stop(true).catch(() => {});\n }\n }\n\n // Whether or not the drain finished: a request that arrives now, down a\n // kept-alive connection the listener's close left open, would run against\n // providers that are being shut down underneath it.\n markDrained();\n const report = await params.shutdownProviders({ timeoutMs: settings.providerTimeoutMs });\n const clean = drained && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n}\n\n/**\n * Resolves once `server` has no request in flight. A streamed response counts\n * until its last chunk (measured on Bun 1.4, macOS and Linux).\n */\nfunction noRequestInFlight(server: Stoppable): Promise<void> {\n return new Promise((resolve) => {\n const check = () => {\n if (server.pendingRequests === 0) {\n resolve();\n return;\n }\n const timer = setTimeout(check, 50);\n (timer as { unref?: () => void }).unref?.();\n };\n check();\n });\n}\n\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n // `drain` decides for itself what a budget that is already spent means, so\n // this is only a guard: a race against `setTimeout(0)` is a coin toss, and\n // \"did not settle within no time at all\" is the honest answer to it.\n if (ms <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n promise.then(\n () => true,\n () => true,\n ),\n new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n }),\n ]);\n clearTimeout(timer);\n return result;\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\n/**\n * `Connection: close` on a response sent while shutting down, so the client's\n * next request opens a connection — which the load balancer can send elsewhere\n * — instead of reusing this one.\n *\n * The spec makes some responses' headers immutable (a `Response.redirect`, a\n * proxied `fetch`), and setting one throws. Bun 1.3.14 lets both be set, so\n * the copy is for a Bun that follows the spec — a throw here would turn every\n * such response in the drain window into a 500.\n */\nexport function closeConnectionWhileShuttingDown(res: Response): Response {\n if (!isShuttingDown()) return res;\n try {\n res.headers.set(\"Connection\", \"close\");\n return res;\n } catch {\n const copy = new Response(res.body, res);\n copy.headers.set(\"Connection\", \"close\");\n return copy;\n }\n}\n\n/**\n * What every response goes through while this process serves: the app's\n * instrumentation, with the two changes a shutdown makes to it.\n *\n * - While the requests in flight drain, a response carries `Connection: close`\n * (`closeConnectionWhileShuttingDown`).\n * - Once they have drained, a request is answered `503` with\n * `Connection: close` and reaches neither the app nor its instrumentation.\n * The listener is closed by then, so only a kept-alive connection can still\n * deliver one, and `server.stop()` leaves those open. Serving it would run a\n * handler against providers whose `shutdown()` is closing the pool, the\n * queue or the cache it uses — until the process exits. The instrumentation\n * is skipped too because it is app code, and a tracer or error reporter is\n * exactly what a provider flushes and closes at this point.\n */\nexport function serveForShutdown(instrumentation: Instrumentation): Instrumentation {\n return async (req, next) => {\n if (state().drained) {\n return new Response(\"Service Unavailable\", {\n status: 503,\n headers: { Connection: \"close\" },\n });\n }\n return closeConnectionWhileShuttingDown(await instrumentation(req, next));\n };\n}\n\n// Installed once per process, not once per `Server`: a listener per instance\n// would each start a shutdown of its own, and read the other's signal as the\n// second one.\nconst SIGNALS_INSTALLED = Symbol.for(\"gemi.server.signalsInstalled\");\n\n/**\n * A repeat of the first signal inside this window is the same shutdown\n * delivered twice, not an operator asking to skip the drain. One shutdown\n * routinely arrives more than once, milliseconds apart: Ctrl+C on\n * `bun run start` reaches the server directly (the whole foreground group is\n * signalled), and again through `gemi start`'s relay — twice over, since\n * `bun run` forwards it to `gemi start` too. systemd's default\n * `KillMode=control-group` and `tini -g` do the same to every process in the\n * group. A person pressing Ctrl+C again is well outside a second.\n */\nconst REPEAT_WINDOW_MS = 1000;\n\n/**\n * `SIGTERM` or `SIGINT` runs `stop` and exits with the code it resolves with.\n * Another signal of either kind, more than `repeatWindowMs` after the first,\n * exits at once with `128 + n` — an operator pressing Ctrl+C again does not\n * want to wait out the grace period. Without a listener the first signal would\n * do that too: the default action for both is to terminate the process on the\n * spot.\n */\nexport function installShutdownSignals(\n stop: () => Promise<number>,\n options: { repeatWindowMs?: number } = {},\n) {\n const global = globalThis as { [SIGNALS_INSTALLED]?: boolean };\n if (global[SIGNALS_INSTALLED]) return;\n global[SIGNALS_INSTALLED] = true;\n\n const repeatWindowMs = options.repeatWindowMs ?? REPEAT_WINDOW_MS;\n let receivedAt: number | undefined;\n const onSignal = (signal: \"SIGTERM\" | \"SIGINT\") => {\n if (receivedAt !== undefined) {\n if (Date.now() - receivedAt < repeatWindowMs) return;\n console.error(`[gemi] ${signal} received again; exiting without waiting for the drain.`);\n process.exit(128 + constants.signals[signal]);\n }\n receivedAt = Date.now();\n console.log(`[gemi] ${signal} received.`);\n stop().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"[gemi] Shutdown failed:\", error);\n process.exit(1);\n },\n );\n };\n process.on(\"SIGTERM\", onSignal);\n process.on(\"SIGINT\", onSignal);\n}\n"
6
+ ],
7
+ "mappings": ";AAAA,oBAAS,WAQT,IAAM,EAAQ,OAAO,IAAI,sBAAsB,EAI/C,SAAS,CAAK,EAAkB,CAC9B,IAAM,EAAS,WAEf,OADA,EAAO,K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as A,ej as $,fj as D}from"./chunk-d5f1m3d2.js";class j extends Error{code;constructor(q,z=1){super(q);this.code=z;this.name="CommandFailed"}}class J{static commandName="unset";static description="";static args=[];static options=[];run(q){}}function p(q){return q}function C(){return{commands:[],commandsDir:"app/commands"}}var I=Symbol.for("gemi.console.builder");function k(q){if(q.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(q)||/\s/.test(q))throw Error(`Invalid command name ${JSON.stringify(q)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
2
+ import{Ac as R}from"./chunk-675kzd7z.js";import{Gc as E,Ic as Q,Rc as S}from"./chunk-08fcqny0.js";import{nj as K}from"./chunk-hnrzm5pf.js";import{Dj as A,Ej as $,Fj as D}from"./chunk-1kdga1b2.js";class j extends Error{code;constructor(q,z=1){super(q);this.code=z;this.name="CommandFailed"}}class J{static commandName="unset";static description="";static args=[];static options=[];run(q){}}function p(q){return q}function C(){return{commands:[],commandsDir:"app/commands"}}var I=Symbol.for("gemi.console.builder");function k(q){if(q.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(q)||/\s/.test(q))throw Error(`Invalid command name ${JSON.stringify(q)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
3
3
 
4
4
  defineCommand("mail:send")
5
5
  .arg("user", { required: true })
@@ -14,6 +14,6 @@ import{vc as R}from"./chunk-7mmw0jr2.js";import{Bc as E,Dc as Q,Mc as S}from"./c
14
14
  static event = UserRegistered;
15
15
 
16
16
  If this is an abstract base its subclasses extend, move it out of the `+"listeners directory \u2014 the walk excludes gemi's `Listener` and "+"nothing else, so a base sitting beside its subclasses is registered and run like one of them.")}function v(q){for(let z of q){if(Object.getOwnPropertyDescriptor(z,"name")?.writable)continue;console.warn(`Event listener ${z.name} does not declare \`static name\`, so it is registered under its class name, which a production build renames. Nothing reads that name across a build boundary while the `+"listener is sync, which is why this is a warning \u2014 but adding "+`\`queued = true\` to it is refused at boot for the same reason, because the queue's key is that string. Add: static name = "${z.name}";`)}}function u(q){let z=new Set;for(let{event:F}of q){if(z.has(F))continue;if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;z.add(F),console.warn(`Event ${F.name} does not declare \`static name\`, so it is dispatched under its class name. A production build minifies the code that dispatches it and renames the class, while discovery reads `+"the listener's copy from source and does not \u2014 so the dispatch would "+`reach no listener in production and nowhere else. Add: static name = "${F.name}";`)}}
17
- export{j as fc,J as gc,p as hc,C as ic,c as jc,o as kc,T as lc,i as mc,B as nc,U as oc,W as pc,Sq as qc,Zq as rc,_q as sc,Iq as tc,Uq as uc};
17
+ export{j as kc,J as lc,p as mc,C as nc,c as oc,o as pc,T as qc,i as rc,B as sc,U as tc,W as uc,Sq as vc,Zq as wc,_q as xc,Iq as yc,Uq as zc};
18
18
 
19
- //# debugId=42C133D67C469DDF64756E2164756E21
19
+ //# debugId=69C570A5A44A083A64756E2164756E21
@@ -12,6 +12,6 @@
12
12
  "import { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nimport {\n discoverClasses,\n DiscoveryError,\n projectRoot,\n} from \"../support/discover\";\nimport { Command, type CommandClass } from \"../console/Command\";\nimport { commandConfigDefaults } from \"../console/config\";\nimport { isUnfinishedBuilder } from \"../console/builder\";\nimport { CronJob } from \"./cron/CronJob\";\nimport { scheduleConfigDefaults } from \"./cron/config\";\nimport { eventConfigDefaults } from \"./events/config\";\nimport type { EventClass } from \"./events/Event\";\nimport { Listener, type ListenerClass } from \"./events/Listener\";\nimport { Job } from \"./queue/Job\";\nimport { queueConfigDefaults } from \"./queue/config\";\nimport { Workflow, type WorkflowClass } from \"./queue/workflow/Workflow\";\n\n/**\n * Reading an application's jobs off the filesystem, for the two subsystems that\n * were asking every app to write its job list twice.\n *\n * Both functions here are the same call to `discoverClasses` with a different\n * base class, which is deliberate: one walk, one set of skip rules, one answer\n * to \"what does this app have\". They are exported from `gemi/services` rather\n * than kept private to the providers because the list stopped being something\n * an app could import — a test that used to walk the exported `jobs` array\n * needs somewhere to ask the same question, and so does a script.\n *\n * What the providers add on top of these is the decision of *whether* to ask,\n * which is the config's to make and not this file's.\n */\n\n/**\n * A directory the app named, resolved the way the app meant it.\n *\n * Relative paths hang off the project root rather than `process.cwd()` at the\n * moment of the call, because a config slice saying `app/jobs` means the app's\n * `app/jobs` and not whatever directory somebody happened to launch a script\n * from. Absolute paths are taken as given, which is what makes these callable\n * from a test that has no project around it.\n */\nfunction resolveDir(dir: string): string {\n return isAbsolute(dir) ? dir : join(projectRoot(), dir);\n}\n\n/**\n * Says something when the directory is missing *and so is the tree it lives in*.\n *\n * A missing directory has two readings and they want opposite responses. An app\n * that has never written a cron job has no `app/cron`, and warning about that on\n * every boot for the rest of its life is noise — the answer \"you have no cron\n * jobs\" is correct and uninteresting. But a deploy that ships `dist/` and\n * `node_modules/` without the source has no `app/cron` *and no `app/`*, and\n * there discovery quietly returns nothing while the app very much does have\n * jobs: the exact silence #322 and #323 exist to remove, reintroduced one layer\n * down and in production only.\n *\n * The parent directory is what tells them apart. If neither the directory nor\n * the one above it is there, the tree this was pointed into is not there\n * either, and that is worth a sentence.\n */\nfunction warnIfSourceIsMissing(\n resolved: string,\n subject: string,\n slice: string,\n) {\n if (existsSync(resolved) || existsSync(dirname(resolved))) return;\n\n console.warn(\n `No ${subject} were discovered: neither ${resolved} nor the directory ` +\n `above it exists, so this process cannot see the application's source. ` +\n `If this is a deploy that ships only the build output, list the classes ` +\n `explicitly in app/config/${slice}.ts so they travel with it.`,\n );\n}\n\n/**\n * The `Job` subclasses under `dir`, defaulting to the config slice's `app/jobs`.\n *\n * This is what a `queue` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array:\n * every job this application would register, in the order it would register\n * them.\n *\n * Every file underneath is imported, so calling this runs the app's job modules\n * — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverJobs(\n dir: string = queueConfigDefaults().jobsDir,\n): Promise<Array<new () => Job>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"queue jobs\", \"queue\");\n const jobs = await discoverClasses(resolved, Job);\n warnIfNameWillNotSurviveTheBuild(jobs);\n return jobs;\n}\n\n/**\n * The `Workflow` subclasses under `dir`, defaulting to the queue slice's\n * `app/workflows`: what a `queue` slice with no `workflows` key resolves to.\n * A missing directory is no workflows, said nothing about unless the tree\n * above it is missing too.\n */\nexport async function discoverWorkflows(\n dir: string = queueConfigDefaults().workflowsDir,\n): Promise<WorkflowClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"workflows\", \"queue\");\n const workflows = (await discoverClasses(resolved, Workflow)) as WorkflowClass[];\n for (const workflow of workflows) {\n if (Object.getOwnPropertyDescriptor(workflow, \"name\")?.writable) continue;\n console.warn(\n `Workflow ${workflow.name} does not declare \\`static name\\`. A workflow ` +\n `is stored under its name, and a production build renames the class. ` +\n `Add: static name = \"${workflow.name}\";`,\n );\n }\n return workflows;\n}\n\n/**\n * Says something about a discovered job that never declared `static name`.\n *\n * This is the one hazard discovery introduces rather than removes, and it is\n * production-only. `gemi build` minifies the server entry, and app code\n * reachable from it — a controller, and every job class that controller\n * imports to dispatch — is bundled and minified with it. Minification renames\n * the class binding, and a class's implicit `.name` is that binding: a\n * `TestJob` in the bundle reports `\"D\"`. Discovery, meanwhile, imports\n * `app/jobs/TestJob.ts` from source at runtime, where it is still `\"TestJob\"`.\n * The queue is keyed by that name, so the two halves stop agreeing and the\n * dispatch is dropped — in production, and only there.\n *\n * A declared `static name = \"TestJob\"` is a string literal, which survives\n * minification intact, and the two halves agree again. `docs/jobs-and-queues.md`\n * has always called it required; before discovery an app could get away without\n * it, because the explicit `jobs` array was bundled too and both sides were\n * wrong in the same way.\n *\n * The check is exact rather than a guess: a `static name = \"...\"` class field\n * defines a *writable* own property, while the implicit class name is\n * non-writable. Cron is unaffected — `CronJob.name` is an instance field\n * holding a string literal, not the class binding.\n */\nfunction warnIfNameWillNotSurviveTheBuild(jobs: Array<new () => Job>) {\n for (const job of jobs) {\n if (Object.getOwnPropertyDescriptor(job, \"name\")?.writable) continue;\n\n console.warn(\n `Queued job ${job.name} does not declare \\`static name\\`, so it is ` +\n `registered under its class name. A production build minifies the ` +\n `class that dispatches it and renames it, while discovery reads this ` +\n `file from source and does not — so the dispatch would be dropped in ` +\n `production and nowhere else. Add: static name = \"${job.name}\";`,\n );\n }\n}\n\n/**\n * The `CronJob` subclasses under `dir`, defaulting to the config slice's\n * `app/cron`.\n *\n * This is what a `schedule` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array —\n * though after boot `app(Scheduler).jobs` is the better one, because it is what\n * the scheduler actually took rather than what this would find if asked again.\n *\n * Every file underneath is imported, so calling this runs the app's cron\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCronJobs(\n dir: string = scheduleConfigDefaults().jobsDir,\n): Promise<Array<new () => CronJob>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"cron jobs\", \"schedule\");\n return await discoverClasses(resolved, CronJob);\n}\n\n/**\n * The `Command` subclasses under `dir`, defaulting to the config slice's\n * `app/commands`.\n *\n * This is what a `commands`-less `command` slice resolves to, and what\n * `gemi run` lists. Unlike the two above it is not called during boot — a\n * command registry has one consumer, and importing every file under\n * `app/commands` into every server process would be a cost paid on every start\n * for code no request reaches.\n *\n * Every file underneath is imported, so calling this runs the app's command\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCommands(\n dir: string = commandConfigDefaults().commandsDir,\n): Promise<CommandClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"commands\", \"command\");\n\n const unfinished: string[] = [];\n\n const commands = await discoverClasses(\n resolved,\n Command,\n [],\n (value, file) => {\n if (isUnfinishedBuilder(value)) unfinished.push(file);\n },\n );\n\n refuseUnfinishedBuilders(unfinished);\n\n return commands as CommandClass[];\n}\n\n/**\n * Stops the walk for a builder chain that was never finished.\n *\n * This is the one silence the builder introduces, and it is the exact shape\n * #322 and #323 exist to remove. `defineCommand(...).arg(...)` without a\n * trailing `.handle(...)` is a plain object rather than a class, so\n * `discoverClasses` discards it along with every constant and helper a command\n * file happens to export — and the command disappears from `gemi run` with\n * nothing raised. The author sees a listing containing every command except the\n * one they just wrote.\n *\n * A throw rather than a warning, because there is no reading of an unfinished\n * builder under which the author meant it: the chain builds a description of a\n * command and then discards it.\n *\n * \"Unfinished\" is decided by `.handle()` clearing the brand, not by the export\n * still being a builder object. Those differ for the natural way to share\n * declarations —\n *\n * export const base = defineCommand(\"reindex\").option(\"verbose\", …);\n * export default base.handle(async () => {});\n *\n * — where `base` is a builder that *did* produce a command. Keying off the shape\n * alone made that file abort the whole of `gemi run`, taking every other command\n * in the project down with it, under a message that was untrue for it.\n */\nfunction refuseUnfinishedBuilders(files: string[]): void {\n if (files.length === 0) return;\n\n const subject =\n files.length === 1\n ? `${files[0]} exports a command builder that never called \\`.handle()\\``\n : `${files.length} files export a command builder that never called ` +\n `\\`.handle()\\`:\\n ${files.join(\"\\n \")}`;\n\n throw new DiscoveryError(\n `${subject}, so there is no command to run. \\`.handle()\\` is what turns ` +\n `the chain into a command — finish it:\\n\\n` +\n ` export default defineCommand(\"my-command\")\\n` +\n ` .handle(async ({ line }) => { line(\"hello\") })`,\n );\n}\n\n/**\n * The `Listener` subclasses under `dir`, defaulting to the config slice's\n * `app/listeners`.\n *\n * This is what an `events` config slice with no `listeners` key resolves to.\n * Call it directly to ask what an application would register: every listener,\n * in the order it would register them.\n *\n * Only listeners are walked. Event classes are never discovered — each is\n * imported by the listener that binds to it and by the code that dispatches it,\n * so there is nothing a walk over them would find that is not already in the\n * module graph.\n *\n * **Known residual, matching jobs and cron.** `discoverClasses` excludes the\n * `base` it is handed and not intermediates, so an abstract listener base\n * written in `listenersDir` and extended by its siblings is discovered and\n * registered alongside them — constructed, with its `handle` called, on every\n * dispatch of whatever event it declares. Keep shared bases outside the\n * directory.\n *\n * Every file underneath is imported, so calling this runs the app's listener\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n *\n * @throws DiscoveryError if a discovered listener declares no `static event`.\n */\nexport async function discoverListeners(\n dir: string = eventConfigDefaults().listenersDir,\n): Promise<ListenerClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"event listeners\", \"events\");\n\n const listeners = (await discoverClasses(\n resolved,\n Listener,\n )) as ListenerClass[];\n\n refuseListenersWithNoEvent(listeners);\n warnIfListenerNameWillNotSurviveTheBuild(listeners);\n warnIfEventNameWillNotSurviveTheBuild(listeners);\n\n return listeners;\n}\n\n/**\n * Stops the walk for a listener that binds to nothing.\n *\n * `static event` is declared as required on the base and the compiler still\n * cannot see it missing: every subclass inherits the declaration whether or not\n * it assigns to one, so `typeof SomeListener` type-checks either way. What the\n * author gets instead is a file that is imported, registered under no name, and\n * never called — the silence this whole module is arranged against.\n *\n * A throw rather than a warning, because there is no reading of a listener with\n * no event under which the author meant it. The usual cause is the residual\n * above: an abstract base sharing a gate between two listeners, sitting in\n * `listenersDir` where the walk finds it. Moving it out is the fix, and the\n * message says so — the alternative, excluding it by some guess about\n * abstractness, is how a discovery pass ends up quietly covering less than the\n * directory holds.\n */\nfunction refuseListenersWithNoEvent(listeners: ListenerClass[]): void {\n const orphans = listeners.filter((listener) => !listener.event);\n if (orphans.length === 0) return;\n\n throw new DiscoveryError(\n `${orphans\n .map((listener) => listener.name)\n .join(\", \")} declare no \\`static event\\`, so there is no event name to ` +\n `register them under and their \\`handle\\` would never run. Every ` +\n `listener binds to exactly one event:\\n\\n` +\n ` static event = UserRegistered;\\n\\n` +\n `If this is an abstract base its subclasses extend, move it out of the ` +\n `listeners directory — the walk excludes gemi's \\`Listener\\` and ` +\n `nothing else, so a base sitting beside its subclasses is registered ` +\n `and run like one of them.`,\n );\n}\n\n/**\n * Says something about a discovered listener that never declared `static name`.\n *\n * The hazard is `warnIfNameWillNotSurviveTheBuild`'s, one subsystem over: a\n * `static name = \"...\"` class field defines a *writable* own property while the\n * implicit class binding does not, and a minifier renames the binding while\n * leaving the string literal alone. The two spellings are indistinguishable by\n * value — both read `\"SendWelcomeEmail\"` in development — so the descriptor is\n * the only thing that tells them apart, and the difference only becomes visible\n * in a production build.\n *\n * A warning rather than a refusal, because a *sync* listener's name has no\n * second half to disagree with: every reader of it comes from this same\n * source-side walk, so a minified build and this walk cannot produce two\n * different strings for it. A **queued** listener does have one — the name is\n * the queue's key and it crosses a JSON boundary — and that case is refused\n * outright, by `jobForListener`, at the point the listener is registered with\n * the queue rather than here. This walk cannot tell the two apart without\n * constructing every listener it found; the registry constructs them anyway.\n */\nfunction warnIfListenerNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n for (const listener of listeners) {\n if (Object.getOwnPropertyDescriptor(listener, \"name\")?.writable) continue;\n\n console.warn(\n `Event listener ${listener.name} does not declare \\`static name\\`, so ` +\n `it is registered under its class name, which a production build ` +\n `renames. Nothing reads that name across a build boundary while the ` +\n `listener is sync, which is why this is a warning — but adding ` +\n `\\`queued = true\\` to it is refused at boot for the same reason, ` +\n `because the queue's key is that string. Add: static name = ` +\n `\"${listener.name}\";`,\n );\n }\n}\n\n/**\n * Says something about the *event* a discovered listener binds to, when that\n * event's name is the implicit class binding.\n *\n * This is the check that matters from the first dispatch, and it is the reason\n * `discoverListeners` reads `static event` at all. The registry is keyed by the\n * event's name; the dispatcher supplies that name from the class it constructs.\n * A production build minifies the server entry and the app code reachable from\n * it — the controller, and the event class it imports in order to dispatch —\n * while discovery imports `app/listeners/*.ts` from source, and those files\n * import `app/events/*.ts` from source too. Two module graphs, two class\n * objects, and an implicit `.name` that reads `\"UserRegistered\"` on one side\n * and `\"D\"` on the other. The dispatch then finds no listeners, which is legal,\n * normal, and completely silent.\n *\n * A declared `static name` is a string literal, which survives minification\n * intact, and the two halves agree again.\n *\n * Checked through the descriptor rather than the string, and not by comparing\n * `event.name` to anything: in development the two spellings produce the same\n * value, so a check on the string would be a tautology that passes forever.\n */\nfunction warnIfEventNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n const warned = new Set<EventClass>();\n\n for (const { event } of listeners) {\n if (warned.has(event)) continue;\n if (Object.getOwnPropertyDescriptor(event, \"name\")?.writable) continue;\n warned.add(event);\n\n console.warn(\n `Event ${event.name} does not declare \\`static name\\`, so it is ` +\n `dispatched under its class name. A production build minifies the ` +\n `code that dispatches it and renames the class, while discovery reads ` +\n `the listener's copy from source and does not — so the dispatch would ` +\n `reach no listener in production and nowhere else. Add: ` +\n `static name = \"${event.name}\";`,\n );\n }\n}\n"
13
13
  ],
14
14
  "mappings": ";sNA4GO,AAAM,IAAsB,DAAM,CAG5B,KAFX,WAAW,CACT,EACS,EAAe,EACxB,CACA,MAAM,CAAO,EAFJ,YAGT,KAAK,KAAO,gBAEhB,CAYO,MAAM,CAAQ,OAKZ,aAAc,cAGd,aAAc,SAGd,MAA0B,CAAC,QAG3B,SAA2B,CAAC,EAWnC,GAAG,CAAC,EAA0B,EAChC,CC1GO,SAAS,CAAmB,CAAC,EAAsC,CACxE,OAAO,EAGF,SAAS,CAAqB,EAA4B,CAC/D,MAAO,CACL,SAAU,CAAC,EACX,YAAa,cACf,ECDK,IAAM,EAA+B,OAAO,IAAI,sBAAsB,EAoF7E,SAAS,CAAgB,CAAC,EAAoB,CAC5C,GAAI,EAAK,KAAK,IAAM,GAClB,MAAU,MAAM,iCAAiC,EAGnD,GAAI,OAAO,KAAK,CAAI,GAAK,KAAK,KAAK,CAAI,EACrC,MAAU,MACR,wBAAwB,KAAK,UAAU,CAAI;AAAA;AAAA;AAAA;AAAA;AAAA,oDAO7C,EAIG,SAAS,CAAa,CAAC,EAAsC,CAClE,EAAiB,CAAI,EAErB,IAAM,EAA0B,CAAC,EAC3B,EAA2B,CAAC,EAC9B,EAAc,GAEZ,EAAU,EACb,GAAgB,EAEjB,QAAQ,CAAC,EAAc,CAErB,OADA,EAAc,EACP,GAGT,GAAG,CAAC,EAAiB,EAAgB,CAAC,EAAG,CAKvC,GAAI,E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BF,eAAsB,EAAiB,CACrC,EAAc,EAAoB,EAAE,aACV,CAC1B,IAAM,EAAW,EAAW,CAAG,EAC/B,EAAsB,EAAU,kBAAmB,QAAQ,EAE3D,IAAM,EAAa,MAAM,EACvB,EACA,CACF,EAMA,OAJA,EAA2B,CAAS,EACpC,EAAyC,CAAS,EAClD,EAAsC,CAAS,EAExC,EAoBT,SAAS,CAA0B,CAAC,EAAkC,CACpE,IAAM,EAAU,EAAU,OAAO,CAAC,IAAa,CAAC,EAAS,KAAK,EAC9D,GAAI,EAAQ,SAAW,EAAG,OAE1B,MAAM,IAAI,EACR,GAAG,EACA,IAAI,CAAC,IAAa,EAAS,IAAI,EAC/B,KAAK,IAAI;AAAA;AAAA;AAAA;AAAA,wEAKV,sEACA,+FAEJ,EAuBF,SAAS,CAAwC,CAAC,EAA4B,CAC5E,QAAW,KAAY,EAAW,CAChC,GAAI,OAAO,yBAAyB,EAAU,MAAM,GAAG,SAAU,SAEjE,QAAQ,KACN,kBAAkB,EAAS,gLAGzB,sEACA,+HAEI,EAAS,QACjB,GA0BJ,SAAS,CAAqC,CAAC,EAA4B,CACzE,IAAM,EAAS,IAAI,IAEnB,QAAa,WAAW,EAAW,CACjC,GAAI,EAAO,IAAI,CAAK,EAAG,SACvB,GAAI,OAAO,yBAAyB,EAAO,MAAM,GAAG,SAAU,SAC9D,EAAO,IAAI,CAAK,EAEhB,QAAQ,KACN,SAAS,EAAM,yLAGb,6EACA,yEACkB,EAAM,QAC5B",
15
- "debugId": "42C133D67C469DDF64756E2164756E21",
15
+ "debugId": "69C570A5A44A083A64756E2164756E21",
16
16
  "names": []
17
17
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{jj as h}from"./chunk-tewhms9w.js";var A=h((f)=>{f.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpAuthLocation||(f.HttpAuthLocation={}));f.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpApiKeyAuthLocation||(f.HttpApiKeyAuthLocation={}));f.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})(f.EndpointURLScheme||(f.EndpointURLScheme={}));f.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(f.AlgorithmId||(f.AlgorithmId={}));var x=(t)=>{let o=[];if(t.sha256!==void 0)o.push({algorithmId:()=>f.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)o.push({algorithmId:()=>f.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){o.push(s)},checksumAlgorithms(){return o}}},d=(t)=>{let o={};return t.checksumAlgorithms().forEach((s)=>{o[s.algorithmId()]=s.checksumConstructor()}),o},a=(t)=>{return x(t)},E=(t)=>{return d(t)};f.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(f.FieldPosition||(f.FieldPosition={}));var m="__smithy_context";f.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(f.IniSectionType||(f.IniSectionType={}));f.RequestHandlerProtocol=void 0;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(f.RequestHandlerProtocol||(f.RequestHandlerProtocol={}));f.SMITHY_CONTEXT_KEY=m;f.getDefaultClientConfiguration=a;f.resolveDefaultRuntimeConfig=E});
2
+ import{Jj as h}from"./chunk-ay8nat73.js";var A=h((f)=>{f.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpAuthLocation||(f.HttpAuthLocation={}));f.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(f.HttpApiKeyAuthLocation||(f.HttpApiKeyAuthLocation={}));f.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})(f.EndpointURLScheme||(f.EndpointURLScheme={}));f.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(f.AlgorithmId||(f.AlgorithmId={}));var x=(t)=>{let o=[];if(t.sha256!==void 0)o.push({algorithmId:()=>f.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)o.push({algorithmId:()=>f.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){o.push(s)},checksumAlgorithms(){return o}}},d=(t)=>{let o={};return t.checksumAlgorithms().forEach((s)=>{o[s.algorithmId()]=s.checksumConstructor()}),o},a=(t)=>{return x(t)},E=(t)=>{return d(t)};f.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(f.FieldPosition||(f.FieldPosition={}));var m="__smithy_context";f.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(f.IniSectionType||(f.IniSectionType={}));f.RequestHandlerProtocol=void 0;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(f.RequestHandlerProtocol||(f.RequestHandlerProtocol={}));f.SMITHY_CONTEXT_KEY=m;f.getDefaultClientConfiguration=a;f.resolveDefaultRuntimeConfig=E});
3
3
  export{A as $};
4
4
 
5
- //# debugId=CCD9CB22556FB75F64756E2164756E21
5
+ //# debugId=47A055F184A93F5564756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "'use strict';\n\nexports.HttpAuthLocation = void 0;\n(function (HttpAuthLocation) {\n HttpAuthLocation[\"HEADER\"] = \"header\";\n HttpAuthLocation[\"QUERY\"] = \"query\";\n})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));\n\nexports.HttpApiKeyAuthLocation = void 0;\n(function (HttpApiKeyAuthLocation) {\n HttpApiKeyAuthLocation[\"HEADER\"] = \"header\";\n HttpApiKeyAuthLocation[\"QUERY\"] = \"query\";\n})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));\n\nexports.EndpointURLScheme = void 0;\n(function (EndpointURLScheme) {\n EndpointURLScheme[\"HTTP\"] = \"http\";\n EndpointURLScheme[\"HTTPS\"] = \"https\";\n})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));\n\nexports.AlgorithmId = void 0;\n(function (AlgorithmId) {\n AlgorithmId[\"MD5\"] = \"md5\";\n AlgorithmId[\"CRC32\"] = \"crc32\";\n AlgorithmId[\"CRC32C\"] = \"crc32c\";\n AlgorithmId[\"SHA1\"] = \"sha1\";\n AlgorithmId[\"SHA256\"] = \"sha256\";\n})(exports.AlgorithmId || (exports.AlgorithmId = {}));\nconst getChecksumConfiguration = (runtimeConfig) => {\n const checksumAlgorithms = [];\n if (runtimeConfig.sha256 !== undefined) {\n checksumAlgorithms.push({\n algorithmId: () => exports.AlgorithmId.SHA256,\n checksumConstructor: () => runtimeConfig.sha256,\n });\n }\n if (runtimeConfig.md5 != undefined) {\n checksumAlgorithms.push({\n algorithmId: () => exports.AlgorithmId.MD5,\n checksumConstructor: () => runtimeConfig.md5,\n });\n }\n return {\n addChecksumAlgorithm(algo) {\n checksumAlgorithms.push(algo);\n },\n checksumAlgorithms() {\n return checksumAlgorithms;\n },\n };\n};\nconst resolveChecksumRuntimeConfig = (clientConfig) => {\n const runtimeConfig = {};\n clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {\n runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();\n });\n return runtimeConfig;\n};\n\nconst getDefaultClientConfiguration = (runtimeConfig) => {\n return getChecksumConfiguration(runtimeConfig);\n};\nconst resolveDefaultRuntimeConfig = (config) => {\n return resolveChecksumRuntimeConfig(config);\n};\n\nexports.FieldPosition = void 0;\n(function (FieldPosition) {\n FieldPosition[FieldPosition[\"HEADER\"] = 0] = \"HEADER\";\n FieldPosition[FieldPosition[\"TRAILER\"] = 1] = \"TRAILER\";\n})(exports.FieldPosition || (exports.FieldPosition = {}));\n\nconst SMITHY_CONTEXT_KEY = \"__smithy_context\";\n\nexports.IniSectionType = void 0;\n(function (IniSectionType) {\n IniSectionType[\"PROFILE\"] = \"profile\";\n IniSectionType[\"SSO_SESSION\"] = \"sso-session\";\n IniSectionType[\"SERVICES\"] = \"services\";\n})(exports.IniSectionType || (exports.IniSectionType = {}));\n\nexports.RequestHandlerProtocol = void 0;\n(function (RequestHandlerProtocol) {\n RequestHandlerProtocol[\"HTTP_0_9\"] = \"http/0.9\";\n RequestHandlerProtocol[\"HTTP_1_0\"] = \"http/1.0\";\n RequestHandlerProtocol[\"TDS_8_0\"] = \"tds/8.0\";\n})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));\n\nexports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY;\nexports.getDefaultClientConfiguration = getDefaultClientConfiguration;\nexports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;\n"
6
6
  ],
7
7
  "mappings": ";uDAEQ,mBAAwB,QAC/B,QAAS,CAAC,EAAkB,CACzB,EAAiB,OAAY,SAC7B,EAAiB,MAAW,UACrB,qBAA6B,mBAAmB,CAAC,EAAE,EAEtD,yBAA8B,QACrC,QAAS,CAAC,EAAwB,CAC/B,EAAuB,OAAY,SACnC,EAAuB,MAAW,UAC3B,2BAAmC,yBAAyB,CAAC,EAAE,EAElE,oBAAyB,QAChC,QAAS,CAAC,EAAmB,CAC1B,EAAkB,KAAU,OAC5B,EAAkB,MAAW,UACtB,sBAA8B,oBAAoB,CAAC,EAAE,EAExD,cAAmB,QAC1B,QAAS,CAAC,EAAa,CACpB,EAAY,IAAS,MACrB,EAAY,MAAW,QACvB,EAAY,OAAY,SACxB,EAAY,KAAU,OACtB,EAAY,OAAY,WACjB,gBAAwB,cAAc,CAAC,EAAE,EACpD,IAAM,EAA2B,CAAC,IAAkB,CAChD,IAAM,EAAqB,CAAC,EAC5B,GAAI,EAAc,SAAW,OACzB,EAAmB,KAAK,CACpB,YAAa,IAAc,cAAY,OACvC,oBAAqB,IAAM,EAAc,MAC7C,CAAC,EAEL,GAAI,EAAc,KAAO,KACrB,EAAmB,KAAK,CACpB,YAAa,IAAc,cAAY,IACvC,oBAAqB,IAAM,EAAc,GAC7C,CAAC,EAEL,MAAO,CACH,oBAAoB,CAAC,EAAM,CACvB,EAAmB,KAAK,CAAI,GAEhC,kBAAkB,EAAG,CACjB,OAAO,EAEf,GAEE,EAA+B,CAAC,IAAiB,CACnD,IAAM,EAAgB,CAAC,EAIvB,OAHA,EAAa,mBAAmB,EAAE,QAAQ,CAAC,IAAsB,CAC7D,EAAc,EAAkB,YAAY,GAAK,EAAkB,oBAAoB,EAC1F,EACM,GAGL,EAAgC,CAAC,IAAkB,CACrD,OAAO,EAAyB,CAAa,GAE3C,EAA8B,CAAC,IAAW,CAC5C,OAAO,EAA6B,CAAM,GAGtC,gBAAqB,QAC5B,QAAS,CAAC,EAAe,CACtB,EAAc,EAAc,OAAY,GAAK,SAC7C,EAAc,EAAc,QAAa,GAAK,YACvC,kBAA0B,gBAAgB,CAAC,EAAE,EAExD,IAAM,EAAqB,mBAEnB,iBAAsB,QAC7B,QAAS,CAAC,EAAgB,CACvB,EAAe,QAAa,UAC5B,EAAe,YAAiB,cAChC,EAAe,SAAc,aACtB,mBAA2B,iBAAiB,CAAC,EAAE,EAElD,yBAA8B,QACrC,QAAS,CAAC,EAAwB,CAC/B,EAAuB,SAAc,WACrC,EAAuB,SAAc,WACrC,EAAuB,QAAa,YAC7B,2BAAmC,yBAAyB,CAAC,EAAE,EAElE,qBAAqB,EACrB,gCAAgC,EAChC,8BAA8B",
8
- "debugId": "CCD9CB22556FB75F64756E2164756E21",
8
+ "debugId": "47A055F184A93F5564756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as re}from"./chunk-s5k3yq6t.js";import{jj as _,mj as a}from"./chunk-tewhms9w.js";var I=_((b)=>{Object.defineProperty(b,"__esModule",{value:!0});b.getHomeDir=void 0;var W=a("os"),V=a("path"),x={},G=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},U=()=>{let{HOME:e,USERPROFILE:t,HOMEPATH:r,HOMEDRIVE:o=`C:${V.sep}`}=process.env;if(e)return e;if(t)return t;if(r)return`${o}${r}`;let i=G();if(!x[i])x[i]=(0,W.homedir)();return x[i]};b.getHomeDir=U});var P=_((j)=>{Object.defineProperty(j,"__esModule",{value:!0});j.getSSOTokenFilepath=void 0;var X=a("crypto"),B=a("path"),J=I(),z=(e)=>{let r=(0,X.createHash)("sha1").update(e).digest("hex");return(0,B.join)((0,J.getHomeDir)(),".aws","sso","cache",`${r}.json`)};j.getSSOTokenFilepath=z});var R=_((C)=>{Object.defineProperty(C,"__esModule",{value:!0});C.getSSOTokenFromFile=C.tokenIntercept=void 0;var Q=a("fs/promises"),Y=P();C.tokenIntercept={};var Z=async(e)=>{if(C.tokenIntercept[e])return C.tokenIntercept[e];let t=(0,Y.getSSOTokenFilepath)(e),r=await(0,Q.readFile)(t,"utf8");return JSON.parse(r)};C.getSSOTokenFromFile=Z});var k=_((L)=>{Object.defineProperty(L,"__esModule",{value:!0});L.readFile=L.fileIntercept=L.filePromises=void 0;var ee=a("fs/promises");L.filePromises={};L.fileIntercept={};var te=(e,t)=>{if(L.fileIntercept[e]!==void 0)return L.fileIntercept[e];if(!L.filePromises[e]||t?.ignoreCache)L.filePromises[e]=(0,ee.readFile)(e,"utf8");return L.filePromises[e]};L.readFile=te});var ye=_((c)=>{var l=I(),O=P(),y=R(),g=a("path"),S=re(),f=k(),q="AWS_PROFILE",$="default",oe=(e)=>e.profile||process.env[q]||$,p=".",ie=(e)=>Object.entries(e).filter(([t])=>{let r=t.indexOf(p);if(r===-1)return!1;return Object.values(S.IniSectionType).includes(t.substring(0,r))}).reduce((t,[r,o])=>{let i=r.indexOf(p),n=r.substring(0,i)===S.IniSectionType.PROFILE?r.substring(i+1):r;return t[n]=o,t},{...e.default&&{default:e.default}}),ne="AWS_CONFIG_FILE",M=()=>process.env[ne]||g.join(l.getHomeDir(),".aws","config"),se="AWS_SHARED_CREDENTIALS_FILE",ce=()=>process.env[se]||g.join(l.getHomeDir(),".aws","credentials"),ae=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,le=["__proto__","profile __proto__"],T=(e)=>{let t={},r,o;for(let i of e.split(/\r?\n/)){let n=i.split(/(^|\s)[;#]/)[0].trim();if(n[0]==="["&&n[n.length-1]==="]"){r=void 0,o=void 0;let s=n.substring(1,n.length-1),u=ae.exec(s);if(u){let[,d,,m]=u;if(Object.values(S.IniSectionType).includes(d))r=[d,m].join(p)}else r=s;if(le.includes(s))throw Error(`Found invalid profile name "${s}"`)}else if(r){let s=n.indexOf("=");if(![0,-1].includes(s)){let[u,d]=[n.substring(0,s).trim(),n.substring(s+1).trim()];if(d==="")o=u;else{if(o&&i.trimStart()===i)o=void 0;t[r]=t[r]||{};let m=o?[o,u].join(p):u;t[r][m]=d}}}}return t},A=()=>({}),K=async(e={})=>{let{filepath:t=ce(),configFilepath:r=M()}=e,o=l.getHomeDir(),i="~/",n=t;if(t.startsWith("~/"))n=g.join(o,t.slice(2));let h=r;if(r.startsWith("~/"))h=g.join(o,r.slice(2));let s=await Promise.all([f.readFile(h,{ignoreCache:e.ignoreCache}).then(T).then(ie).catch(A),f.readFile(n,{ignoreCache:e.ignoreCache}).then(T).catch(A)]);return{configFile:s[0],credentialsFile:s[1]}},pe=(e)=>Object.entries(e).filter(([t])=>t.startsWith(S.IniSectionType.SSO_SESSION+p)).reduce((t,[r,o])=>({...t,[r.substring(r.indexOf(p)+1)]:o}),{}),ue=()=>({}),fe=async(e={})=>f.readFile(e.configFilepath??M()).then(T).then(pe).catch(ue),de=(...e)=>{let t={};for(let r of e)for(let[o,i]of Object.entries(r))if(t[o]!==void 0)Object.assign(t[o],i);else t[o]=i;return t},_e=async(e)=>{let t=await K(e);return de(t.configFile,t.credentialsFile)},Fe={getFileRecord(){return f.fileIntercept},interceptFile(e,t){f.fileIntercept[e]=Promise.resolve(t)},getTokenRecord(){return y.tokenIntercept},interceptToken(e,t){y.tokenIntercept[e]=t}};c.getSSOTokenFromFile=y.getSSOTokenFromFile;c.readFile=f.readFile;c.CONFIG_PREFIX_SEPARATOR=p;c.DEFAULT_PROFILE=$;c.ENV_PROFILE=q;c.externalDataInterceptor=Fe;c.getProfileName=oe;c.loadSharedConfigFiles=K;c.loadSsoSessionData=fe;c.parseKnownFiles=_e;Object.prototype.hasOwnProperty.call(l,"__proto__")&&!Object.prototype.hasOwnProperty.call(c,"__proto__")&&Object.defineProperty(c,"__proto__",{enumerable:!0,value:l.__proto__});Object.keys(l).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(c,e))c[e]=l[e]});Object.prototype.hasOwnProperty.call(O,"__proto__")&&!Object.prototype.hasOwnProperty.call(c,"__proto__")&&Object.defineProperty(c,"__proto__",{enumerable:!0,value:O.__proto__});Object.keys(O).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(c,e))c[e]=O[e]})});
2
+ import{$ as re}from"./chunk-f1thqe6j.js";import{Jj as _,Mj as a}from"./chunk-ay8nat73.js";var I=_((b)=>{Object.defineProperty(b,"__esModule",{value:!0});b.getHomeDir=void 0;var W=a("os"),V=a("path"),x={},G=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},U=()=>{let{HOME:e,USERPROFILE:t,HOMEPATH:r,HOMEDRIVE:o=`C:${V.sep}`}=process.env;if(e)return e;if(t)return t;if(r)return`${o}${r}`;let i=G();if(!x[i])x[i]=(0,W.homedir)();return x[i]};b.getHomeDir=U});var P=_((j)=>{Object.defineProperty(j,"__esModule",{value:!0});j.getSSOTokenFilepath=void 0;var X=a("crypto"),B=a("path"),J=I(),z=(e)=>{let r=(0,X.createHash)("sha1").update(e).digest("hex");return(0,B.join)((0,J.getHomeDir)(),".aws","sso","cache",`${r}.json`)};j.getSSOTokenFilepath=z});var R=_((C)=>{Object.defineProperty(C,"__esModule",{value:!0});C.getSSOTokenFromFile=C.tokenIntercept=void 0;var Q=a("fs/promises"),Y=P();C.tokenIntercept={};var Z=async(e)=>{if(C.tokenIntercept[e])return C.tokenIntercept[e];let t=(0,Y.getSSOTokenFilepath)(e),r=await(0,Q.readFile)(t,"utf8");return JSON.parse(r)};C.getSSOTokenFromFile=Z});var k=_((L)=>{Object.defineProperty(L,"__esModule",{value:!0});L.readFile=L.fileIntercept=L.filePromises=void 0;var ee=a("fs/promises");L.filePromises={};L.fileIntercept={};var te=(e,t)=>{if(L.fileIntercept[e]!==void 0)return L.fileIntercept[e];if(!L.filePromises[e]||t?.ignoreCache)L.filePromises[e]=(0,ee.readFile)(e,"utf8");return L.filePromises[e]};L.readFile=te});var ye=_((c)=>{var l=I(),O=P(),y=R(),g=a("path"),S=re(),f=k(),q="AWS_PROFILE",$="default",oe=(e)=>e.profile||process.env[q]||$,p=".",ie=(e)=>Object.entries(e).filter(([t])=>{let r=t.indexOf(p);if(r===-1)return!1;return Object.values(S.IniSectionType).includes(t.substring(0,r))}).reduce((t,[r,o])=>{let i=r.indexOf(p),n=r.substring(0,i)===S.IniSectionType.PROFILE?r.substring(i+1):r;return t[n]=o,t},{...e.default&&{default:e.default}}),ne="AWS_CONFIG_FILE",M=()=>process.env[ne]||g.join(l.getHomeDir(),".aws","config"),se="AWS_SHARED_CREDENTIALS_FILE",ce=()=>process.env[se]||g.join(l.getHomeDir(),".aws","credentials"),ae=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,le=["__proto__","profile __proto__"],T=(e)=>{let t={},r,o;for(let i of e.split(/\r?\n/)){let n=i.split(/(^|\s)[;#]/)[0].trim();if(n[0]==="["&&n[n.length-1]==="]"){r=void 0,o=void 0;let s=n.substring(1,n.length-1),u=ae.exec(s);if(u){let[,d,,m]=u;if(Object.values(S.IniSectionType).includes(d))r=[d,m].join(p)}else r=s;if(le.includes(s))throw Error(`Found invalid profile name "${s}"`)}else if(r){let s=n.indexOf("=");if(![0,-1].includes(s)){let[u,d]=[n.substring(0,s).trim(),n.substring(s+1).trim()];if(d==="")o=u;else{if(o&&i.trimStart()===i)o=void 0;t[r]=t[r]||{};let m=o?[o,u].join(p):u;t[r][m]=d}}}}return t},A=()=>({}),K=async(e={})=>{let{filepath:t=ce(),configFilepath:r=M()}=e,o=l.getHomeDir(),i="~/",n=t;if(t.startsWith("~/"))n=g.join(o,t.slice(2));let h=r;if(r.startsWith("~/"))h=g.join(o,r.slice(2));let s=await Promise.all([f.readFile(h,{ignoreCache:e.ignoreCache}).then(T).then(ie).catch(A),f.readFile(n,{ignoreCache:e.ignoreCache}).then(T).catch(A)]);return{configFile:s[0],credentialsFile:s[1]}},pe=(e)=>Object.entries(e).filter(([t])=>t.startsWith(S.IniSectionType.SSO_SESSION+p)).reduce((t,[r,o])=>({...t,[r.substring(r.indexOf(p)+1)]:o}),{}),ue=()=>({}),fe=async(e={})=>f.readFile(e.configFilepath??M()).then(T).then(pe).catch(ue),de=(...e)=>{let t={};for(let r of e)for(let[o,i]of Object.entries(r))if(t[o]!==void 0)Object.assign(t[o],i);else t[o]=i;return t},_e=async(e)=>{let t=await K(e);return de(t.configFile,t.credentialsFile)},Fe={getFileRecord(){return f.fileIntercept},interceptFile(e,t){f.fileIntercept[e]=Promise.resolve(t)},getTokenRecord(){return y.tokenIntercept},interceptToken(e,t){y.tokenIntercept[e]=t}};c.getSSOTokenFromFile=y.getSSOTokenFromFile;c.readFile=f.readFile;c.CONFIG_PREFIX_SEPARATOR=p;c.DEFAULT_PROFILE=$;c.ENV_PROFILE=q;c.externalDataInterceptor=Fe;c.getProfileName=oe;c.loadSharedConfigFiles=K;c.loadSsoSessionData=fe;c.parseKnownFiles=_e;Object.prototype.hasOwnProperty.call(l,"__proto__")&&!Object.prototype.hasOwnProperty.call(c,"__proto__")&&Object.defineProperty(c,"__proto__",{enumerable:!0,value:l.__proto__});Object.keys(l).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(c,e))c[e]=l[e]});Object.prototype.hasOwnProperty.call(O,"__proto__")&&!Object.prototype.hasOwnProperty.call(c,"__proto__")&&Object.defineProperty(c,"__proto__",{enumerable:!0,value:O.__proto__});Object.keys(O).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(c,e))c[e]=O[e]})});
3
3
  export{ye as _};
4
4
 
5
- //# debugId=626D5B5E608B0F5764756E2164756E21
5
+ //# debugId=D070A8B0DED21E9364756E2164756E21
@@ -9,6 +9,6 @@
9
9
  "'use strict';\n\nvar getHomeDir = require('./getHomeDir');\nvar getSSOTokenFilepath = require('./getSSOTokenFilepath');\nvar getSSOTokenFromFile = require('./getSSOTokenFromFile');\nvar path = require('path');\nvar types = require('@smithy/types');\nvar readFile = require('./readFile');\n\nconst ENV_PROFILE = \"AWS_PROFILE\";\nconst DEFAULT_PROFILE = \"default\";\nconst getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;\n\nconst CONFIG_PREFIX_SEPARATOR = \".\";\n\nconst getConfigData = (data) => Object.entries(data)\n .filter(([key]) => {\n const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);\n if (indexOfSeparator === -1) {\n return false;\n }\n return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator));\n})\n .reduce((acc, [key, value]) => {\n const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);\n const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;\n acc[updatedKey] = value;\n return acc;\n}, {\n ...(data.default && { default: data.default }),\n});\n\nconst ENV_CONFIG_PATH = \"AWS_CONFIG_FILE\";\nconst getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), \".aws\", \"config\");\n\nconst ENV_CREDENTIALS_PATH = \"AWS_SHARED_CREDENTIALS_FILE\";\nconst getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), \".aws\", \"credentials\");\n\nconst prefixKeyRegex = /^([\\w-]+)\\s([\"'])?([\\w-@\\+\\.%:/]+)\\2$/;\nconst profileNameBlockList = [\"__proto__\", \"profile __proto__\"];\nconst parseIni = (iniData) => {\n const map = {};\n let currentSection;\n let currentSubSection;\n for (const iniLine of iniData.split(/\\r?\\n/)) {\n const trimmedLine = iniLine.split(/(^|\\s)[;#]/)[0].trim();\n const isSection = trimmedLine[0] === \"[\" && trimmedLine[trimmedLine.length - 1] === \"]\";\n if (isSection) {\n currentSection = undefined;\n currentSubSection = undefined;\n const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);\n const matches = prefixKeyRegex.exec(sectionName);\n if (matches) {\n const [, prefix, , name] = matches;\n if (Object.values(types.IniSectionType).includes(prefix)) {\n currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR);\n }\n }\n else {\n currentSection = sectionName;\n }\n if (profileNameBlockList.includes(sectionName)) {\n throw new Error(`Found invalid profile name \"${sectionName}\"`);\n }\n }\n else if (currentSection) {\n const indexOfEqualsSign = trimmedLine.indexOf(\"=\");\n if (![0, -1].includes(indexOfEqualsSign)) {\n const [name, value] = [\n trimmedLine.substring(0, indexOfEqualsSign).trim(),\n trimmedLine.substring(indexOfEqualsSign + 1).trim(),\n ];\n if (value === \"\") {\n currentSubSection = name;\n }\n else {\n if (currentSubSection && iniLine.trimStart() === iniLine) {\n currentSubSection = undefined;\n }\n map[currentSection] = map[currentSection] || {};\n const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;\n map[currentSection][key] = value;\n }\n }\n }\n }\n return map;\n};\n\nconst swallowError$1 = () => ({});\nconst loadSharedConfigFiles = async (init = {}) => {\n const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init;\n const homeDir = getHomeDir.getHomeDir();\n const relativeHomeDirPrefix = \"~/\";\n let resolvedFilepath = filepath;\n if (filepath.startsWith(relativeHomeDirPrefix)) {\n resolvedFilepath = path.join(homeDir, filepath.slice(2));\n }\n let resolvedConfigFilepath = configFilepath;\n if (configFilepath.startsWith(relativeHomeDirPrefix)) {\n resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2));\n }\n const parsedFiles = await Promise.all([\n readFile.readFile(resolvedConfigFilepath, {\n ignoreCache: init.ignoreCache,\n })\n .then(parseIni)\n .then(getConfigData)\n .catch(swallowError$1),\n readFile.readFile(resolvedFilepath, {\n ignoreCache: init.ignoreCache,\n })\n .then(parseIni)\n .catch(swallowError$1),\n ]);\n return {\n configFile: parsedFiles[0],\n credentialsFile: parsedFiles[1],\n };\n};\n\nconst getSsoSessionData = (data) => Object.entries(data)\n .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR))\n .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {});\n\nconst swallowError = () => ({});\nconst loadSsoSessionData = async (init = {}) => readFile.readFile(init.configFilepath ?? getConfigFilepath())\n .then(parseIni)\n .then(getSsoSessionData)\n .catch(swallowError);\n\nconst mergeConfigFiles = (...files) => {\n const merged = {};\n for (const file of files) {\n for (const [key, values] of Object.entries(file)) {\n if (merged[key] !== undefined) {\n Object.assign(merged[key], values);\n }\n else {\n merged[key] = values;\n }\n }\n }\n return merged;\n};\n\nconst parseKnownFiles = async (init) => {\n const parsedFiles = await loadSharedConfigFiles(init);\n return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);\n};\n\nconst externalDataInterceptor = {\n getFileRecord() {\n return readFile.fileIntercept;\n },\n interceptFile(path, contents) {\n readFile.fileIntercept[path] = Promise.resolve(contents);\n },\n getTokenRecord() {\n return getSSOTokenFromFile.tokenIntercept;\n },\n interceptToken(id, contents) {\n getSSOTokenFromFile.tokenIntercept[id] = contents;\n },\n};\n\nexports.getSSOTokenFromFile = getSSOTokenFromFile.getSSOTokenFromFile;\nexports.readFile = readFile.readFile;\nexports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR;\nexports.DEFAULT_PROFILE = DEFAULT_PROFILE;\nexports.ENV_PROFILE = ENV_PROFILE;\nexports.externalDataInterceptor = externalDataInterceptor;\nexports.getProfileName = getProfileName;\nexports.loadSharedConfigFiles = loadSharedConfigFiles;\nexports.loadSsoSessionData = loadSsoSessionData;\nexports.parseKnownFiles = parseKnownFiles;\nObject.prototype.hasOwnProperty.call(getHomeDir, '__proto__') &&\n !Object.prototype.hasOwnProperty.call(exports, '__proto__') &&\n Object.defineProperty(exports, '__proto__', {\n enumerable: true,\n value: getHomeDir['__proto__']\n });\n\nObject.keys(getHomeDir).forEach(function (k) {\n if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = getHomeDir[k];\n});\nObject.prototype.hasOwnProperty.call(getSSOTokenFilepath, '__proto__') &&\n !Object.prototype.hasOwnProperty.call(exports, '__proto__') &&\n Object.defineProperty(exports, '__proto__', {\n enumerable: true,\n value: getSSOTokenFilepath['__proto__']\n });\n\nObject.keys(getSSOTokenFilepath).forEach(function (k) {\n if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = getSSOTokenFilepath[k];\n});\n"
10
10
  ],
11
11
  "mappings": ";8GACA,CAAO,eAAe,EAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EACpD,aAAkB,OAC1B,IAAM,UACA,YACA,EAAe,CAAC,EAChB,EAAqB,IAAM,CAC7B,GAAI,SAAW,QAAQ,QACnB,MAAO,GAAG,QAAQ,QAAQ,IAE9B,MAAO,WAEL,EAAa,IAAM,CACrB,IAAQ,OAAM,cAAa,WAAU,YAAY,KAAK,EAAO,OAAU,QAAQ,IAC/E,GAAI,EACA,OAAO,EACX,GAAI,EACA,OAAO,EACX,GAAI,EACA,MAAO,GAAG,IAAY,IAC1B,IAAM,EAAkB,EAAmB,EAC3C,GAAI,CAAC,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GAAI,IAAM,WAAa,CAAC,OAAO,UAAU,eAAe,KAAK,EAAS,CAAC,EAAG,EAAQ,GAAK,EAAW,GACrG,EACD,OAAO,UAAU,eAAe,KAAK,EAAqB,WAAW,GACjE,CAAC,OAAO,UAAU,eAAe,KAAK,EAAS,WAAW,GAC1D,OAAO,eAAe,EAAS,YAAa,CACxC,WAAY,GACZ,MAAO,EAAoB,SAC/B,CAAC,EAEL,OAAO,KAAK,CAAmB,EAAE,QAAQ,QAAS,CAAC,EAAG,CAClD,GAAI,IAAM,WAAa,CAAC,OAAO,UAAU,eAAe,KAAK,EAAS,CAAC,EAAG,EAAQ,GAAK,EAAoB,GAC9G",
12
- "debugId": "626D5B5E608B0F5764756E2164756E21",
12
+ "debugId": "D070A8B0DED21E9364756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{h as _t}from"./chunk-3gsv1vv1.js";import{A as oo,B as Lt,C as yo,i as er,k as M,l as vo,m as Eo,n as So,p as Gr,q as zr,r as kt,s as Io,t as cr,u as Po,v as xo,w as ar,x as eo,y as ro,z as to}from"./chunk-pn2x59ge.js";import{D as hr,E as mt,G as Qt,K as Ue,O as f}from"./chunk-5tdxbwzg.js";import{P as Oo}from"./chunk-7g649j8h.js";import"./chunk-0ejjgzwc.js";import{X as zt}from"./chunk-3wnghdsx.js";import{Y as gt}from"./chunk-c7qs1xp3.js";import{Z as Ht}from"./chunk-gy81nd9a.js";import"./chunk-zrcd9hxr.js";import"./chunk-s5k3yq6t.js";import"./chunk-32n8t8x6.js";import{la as Zt}from"./chunk-ep0baa9g.js";import{jj as S}from"./chunk-tewhms9w.js";var A=S((oe)=>{Object.defineProperty(oe,"__esModule",{value:!0});oe.resolveHttpAuthSchemeConfig=oe.defaultSSOOIDCHttpAuthSchemeProvider=oe.defaultSSOOIDCHttpAuthSchemeParametersProvider=void 0;var Rr=M(),w=hr(),fr=async(e,r,i)=>{return{operation:(0,w.getSmithyContext)(r).operation,region:await(0,w.normalizeProvider)(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};oe.defaultSSOOIDCHttpAuthSchemeParametersProvider=fr;function Fr(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:e.region},propertiesExtractor:(r,i)=>({signingProperties:{config:r,context:i}})}}function Ur(e){return{schemeId:"smithy.api#noAuth"}}var $r=(e)=>{let r=[];switch(e.operation){case"CreateToken":{r.push(Ur(e));break}default:r.push(Fr(e))}return r};oe.defaultSSOOIDCHttpAuthSchemeProvider=$r;var jr=(e)=>{let r=(0,Rr.resolveAwsSdkSigV4Config)(e);return Object.assign(r,{authSchemePreference:(0,w.normalizeProvider)(e.authSchemePreference??[])})};oe.resolveHttpAuthSchemeConfig=jr});var De=S((xe)=>{Object.defineProperty(xe,"__esModule",{value:!0});xe.ruleSet=void 0;var Ee="required",p="fn",d="argv",q="ref",se=!0,ne="isSet",N="booleanEquals",D="error",b="endpoint",I="tree",G="PartitionResult",z="getAttr",pe={[Ee]:!1,type:"string"},de={[Ee]:!0,default:!1,type:"boolean"},ce={[q]:"Endpoint"},Se={[p]:N,[d]:[{[q]:"UseFIPS"},!0]},Ie={[p]:N,[d]:[{[q]:"UseDualStack"},!0]},n={},ae={[p]:z,[d]:[{[q]:G},"supportsFIPS"]},Pe={[q]:G},le={[p]:N,[d]:[!0,{[p]:z,[d]:[Pe,"supportsDualStack"]}]},ue=[Se],Oe=[Ie],ve=[{[q]:"Region"}],Ar={version:"1.0",parameters:{Region:pe,UseDualStack:de,UseFIPS:de,Endpoint:pe},rules:[{conditions:[{[p]:ne,[d]:[ce]}],rules:[{conditions:ue,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:D},{conditions:Oe,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:D},{endpoint:{url:ce,properties:n,headers:n},type:b}],type:I},{conditions:[{[p]:ne,[d]:ve}],rules:[{conditions:[{[p]:"aws.partition",[d]:ve,assign:G}],rules:[{conditions:[Se,Ie],rules:[{conditions:[{[p]:N,[d]:[se,ae]},le],rules:[{endpoint:{url:"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:n,headers:n},type:b}],type:I},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:D}],type:I},{conditions:ue,rules:[{conditions:[{[p]:N,[d]:[ae,se]}],rules:[{conditions:[{[p]:"stringEquals",[d]:[{[p]:z,[d]:[Pe,"name"]},"aws-us-gov"]}],endpoint:{url:"https://oidc.{Region}.amazonaws.com",properties:n,headers:n},type:b},{endpoint:{url:"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",properties:n,headers:n},type:b}],type:I},{error:"FIPS is enabled but this partition does not support FIPS",type:D}],type:I},{conditions:Oe,rules:[{conditions:[le],rules:[{endpoint:{url:"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:n,headers:n},type:b}],type:I},{error:"DualStack is enabled but this partition does not support DualStack",type:D}],type:I},{endpoint:{url:"https://oidc.{Region}.{PartitionResult#dnsSuffix}",properties:n,headers:n},type:b}],type:I}],type:I},{error:"Invalid Configuration: Missing Region",type:D}]};xe.ruleSet=Ar});var Ne=S((be)=>{Object.defineProperty(be,"__esModule",{value:!0});be.defaultEndpointResolver=void 0;var mr=zr(),m=Gr(),Hr=De(),Lr=new m.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Tr=(e,r={})=>{return Lr.get(e,()=>(0,m.resolveEndpoint)(Hr.ruleSet,{endpointParams:e,logger:r.logger}))};be.defaultEndpointResolver=Tr;m.customEndpointFunctions.aws=mr.awsEndpointFunctions});var F=S((L)=>{Object.defineProperty(L,"__esModule",{value:!0});L.SSOOIDCServiceException=L.__ServiceException=void 0;var he=f();Object.defineProperty(L,"__ServiceException",{enumerable:!0,get:function(){return he.ServiceException}});class H extends he.ServiceException{constructor(e){super(e);Object.setPrototypeOf(this,H.prototype)}}L.SSOOIDCServiceException=H});var k=S((fe)=>{Object.defineProperty(fe,"__esModule",{value:!0});fe.UnsupportedGrantTypeException=fe.UnauthorizedClientException=fe.SlowDownException=fe.InvalidScopeException=fe.InvalidRequestException=fe.InvalidGrantException=fe.InvalidClientException=fe.InternalServerException=fe.ExpiredTokenException=fe.AuthorizationPendingException=fe.AccessDeniedException=void 0;var l=F();class T extends l.SSOOIDCServiceException{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e});Object.setPrototypeOf(this,T.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}fe.AccessDeniedException=T;class B extends l.SSOOIDCServiceException{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e});Object.setPrototypeOf(this,B.prototype),this.error=e.error,this.error_description=e.error_description}}fe.AuthorizationPendingException=B;class V extends l.SSOOIDCServiceException{name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,V.prototype),this.error=e.error,this.error_description=e.error_description}}fe.ExpiredTokenException=V;class W extends l.SSOOIDCServiceException{name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e});Object.setPrototypeOf(this,W.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InternalServerException=W;class Y extends l.SSOOIDCServiceException{name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e});Object.setPrototypeOf(this,Y.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InvalidClientException=Y;class J extends l.SSOOIDCServiceException{name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e});Object.setPrototypeOf(this,J.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InvalidGrantException=J;class K extends l.SSOOIDCServiceException{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,K.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}fe.InvalidRequestException=K;class X extends l.SSOOIDCServiceException{name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e});Object.setPrototypeOf(this,X.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InvalidScopeException=X;class C extends l.SSOOIDCServiceException{name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype),this.error=e.error,this.error_description=e.error_description}}fe.SlowDownException=C;class Q extends l.SSOOIDCServiceException{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e});Object.setPrototypeOf(this,Q.prototype),this.error=e.error,this.error_description=e.error_description}}fe.UnauthorizedClientException=Q;class Z extends l.SSOOIDCServiceException{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e});Object.setPrototypeOf(this,Z.prototype),this.error=e.error,this.error_description=e.error_description}}fe.UnsupportedGrantTypeException=Z});var g=S((ze)=>{Object.defineProperty(ze,"__esModule",{value:!0});ze.CreateToken$=ze.CreateTokenResponse$=ze.CreateTokenRequest$=ze.errorTypeRegistries=ze.UnsupportedGrantTypeException$=ze.UnauthorizedClientException$=ze.SlowDownException$=ze.InvalidScopeException$=ze.InvalidRequestException$=ze.InvalidGrantException$=ze.InvalidClientException$=ze.InternalServerException$=ze.ExpiredTokenException$=ze.AuthorizationPendingException$=ze.AccessDeniedException$=ze.SSOOIDCServiceException$=void 0;var kr="AccessDeniedException",gr="AuthorizationPendingException",_r="AccessToken",et="ClientSecret",rt="CreateToken",tt="CreateTokenRequest",ot="CreateTokenResponse",it="CodeVerifier",st="ExpiredTokenException",nt="InvalidClientException",pt="InvalidGrantException",dt="InvalidRequestException",ct="InternalServerException",at="InvalidScopeException",lt="IdToken",ut="RefreshToken",Ot="SlowDownException",vt="UnauthorizedClientException",Et="UnsupportedGrantTypeException",St="accessToken",E="client",It="clientId",Pt="clientSecret",xt="codeVerifier",yt="code",Dt="deviceCode",t="error",bt="expiresIn",u="error_description",qt="grantType",Nt="http",O="httpError",ht="idToken",$e="reason",je="refreshToken",Rt="redirectUri",we="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",ft="scope",Ft="server",Ut="tokenType",o="com.amazonaws.ssooidc",Me=Ue(),v=k(),$t=F(),Ae=Me.TypeRegistry.for(we);ze.SSOOIDCServiceException$=[-3,we,"SSOOIDCServiceException",0,[],[]];Ae.registerError(ze.SSOOIDCServiceException$,$t.SSOOIDCServiceException);var c=Me.TypeRegistry.for(o);ze.AccessDeniedException$=[-3,o,kr,{[t]:E,[O]:400},[t,$e,u],[0,0,0]];c.registerError(ze.AccessDeniedException$,v.AccessDeniedException);ze.AuthorizationPendingException$=[-3,o,gr,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.AuthorizationPendingException$,v.AuthorizationPendingException);ze.ExpiredTokenException$=[-3,o,st,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.ExpiredTokenException$,v.ExpiredTokenException);ze.InternalServerException$=[-3,o,ct,{[t]:Ft,[O]:500},[t,u],[0,0]];c.registerError(ze.InternalServerException$,v.InternalServerException);ze.InvalidClientException$=[-3,o,nt,{[t]:E,[O]:401},[t,u],[0,0]];c.registerError(ze.InvalidClientException$,v.InvalidClientException);ze.InvalidGrantException$=[-3,o,pt,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.InvalidGrantException$,v.InvalidGrantException);ze.InvalidRequestException$=[-3,o,dt,{[t]:E,[O]:400},[t,$e,u],[0,0,0]];c.registerError(ze.InvalidRequestException$,v.InvalidRequestException);ze.InvalidScopeException$=[-3,o,at,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.InvalidScopeException$,v.InvalidScopeException);ze.SlowDownException$=[-3,o,Ot,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.SlowDownException$,v.SlowDownException);ze.UnauthorizedClientException$=[-3,o,vt,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.UnauthorizedClientException$,v.UnauthorizedClientException);ze.UnsupportedGrantTypeException$=[-3,o,Et,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.UnsupportedGrantTypeException$,v.UnsupportedGrantTypeException);ze.errorTypeRegistries=[Ae,c];var jt=[0,o,_r,8,0],wt=[0,o,et,8,0],Mt=[0,o,it,8,0],At=[0,o,lt,8,0],Ge=[0,o,ut,8,0];ze.CreateTokenRequest$=[3,o,tt,0,[It,Pt,qt,Dt,yt,je,ft,Rt,xt],[0,[()=>wt,0],0,0,0,[()=>Ge,0],64,0,[()=>Mt,0]],3];ze.CreateTokenResponse$=[3,o,ot,0,[St,Ut,bt,je,ht],[[()=>jt,0],0,1,[()=>Ge,0],[()=>At,0]]];ze.CreateToken$=[9,o,rt,{[Nt]:["POST","/token",200]},()=>ze.CreateTokenRequest$,()=>ze.CreateTokenResponse$]});var or=S((rr)=>{Object.defineProperty(rr,"__esModule",{value:!0});rr.getRuntimeConfig=void 0;var Tt=M(),Bt=Lt(),Vt=er(),Wt=f(),Yt=Ht(),ge=mt(),_e=zt(),Jt=A(),Kt=Ne(),Xt=g(),Ct=(e)=>{return{apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??ge.fromBase64,base64Encoder:e?.base64Encoder??ge.toBase64,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??Kt.defaultEndpointResolver,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??Jt.defaultSSOOIDCHttpAuthSchemeProvider,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(r)=>r.getIdentityProvider("aws.auth#sigv4"),signer:new Tt.AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:(r)=>r.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Vt.NoAuthSigner}],logger:e?.logger??new Wt.NoOpLogger,protocol:e?.protocol??Bt.AwsRestJsonProtocol,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:Xt.errorTypeRegistries,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:e?.serviceId??"SSO OIDC",urlParser:e?.urlParser??Yt.parseUrl,utf8Decoder:e?.utf8Decoder??_e.fromUtf8,utf8Encoder:e?.utf8Encoder??_e.toUtf8}};rr.getRuntimeConfig=Ct});var Or=S((lr)=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.getRuntimeConfig=void 0;var io=Zt(),so=io.__importDefault(_t()),ir=M(),sr=eo(),U=cr(),no=ro(),nr=ar(),x=gt(),pr=Qt(),dr=f(),po=to(),co=oo(),ao=kt(),lo=or(),uo=(e)=>{(0,dr.emitWarningIfUnsupportedVersion)(process.version);let r=(0,co.resolveDefaultsModeConfig)(e),i=()=>r().then(dr.loadConfigsForDefaultMode),a=(0,lo.getRuntimeConfig)(e);(0,ir.emitWarningIfUnsupportedVersion)(process.version);let s={profile:e?.profile,logger:a.logger};return{...a,...e,runtime:"node",defaultsMode:r,authSchemePreference:e?.authSchemePreference??(0,x.loadConfig)(ir.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:e?.bodyLengthChecker??po.calculateBodyLength,defaultUserAgentProvider:e?.defaultUserAgentProvider??(0,sr.createDefaultUserAgentProvider)({serviceId:a.serviceId,clientVersion:so.default.version}),maxAttempts:e?.maxAttempts??(0,x.loadConfig)(nr.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,e),region:e?.region??(0,x.loadConfig)(U.NODE_REGION_CONFIG_OPTIONS,{...U.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:pr.NodeHttpHandler.create(e?.requestHandler??i),retryMode:e?.retryMode??(0,x.loadConfig)({...nr.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||ao.DEFAULT_RETRY_MODE},e),sha256:e?.sha256??no.Hash.bind(null,"sha256"),streamCollector:e?.streamCollector??pr.streamCollector,useDualstackEndpoint:e?.useDualstackEndpoint??(0,x.loadConfig)(U.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:e?.useFipsEndpoint??(0,x.loadConfig)(U.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:e?.userAgentAppId??(0,x.loadConfig)(sr.NODE_APP_ID_CONFIG_OPTIONS,s)}};lr.getRuntimeConfig=uo});var Yo=S((P)=>{var vr=vo(),Do=Eo(),bo=So(),Er=Io(),qo=cr(),_=er(),No=Ue(),ho=Po(),yr=xo(),Sr=ar(),y=f(),Ir=A(),Ro=Or(),Pr=yo(),xr=Oo(),h=g(),$=k(),fo=F(),Fo=(e)=>{return Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},Uo={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},$o=(e)=>{let{httpAuthSchemes:r,httpAuthSchemeProvider:i,credentials:a}=e;return{setHttpAuthScheme(s){let R=r.findIndex((j)=>j.schemeId===s.schemeId);if(R===-1)r.push(s);else r.splice(R,1,s)},httpAuthSchemes(){return r},setHttpAuthSchemeProvider(s){i=s},httpAuthSchemeProvider(){return i},setCredentials(s){a=s},credentials(){return a}}},jo=(e)=>{return{httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}},wo=(e,r)=>{let i=Object.assign(Pr.getAwsRegionExtensionConfiguration(e),y.getDefaultExtensionConfiguration(e),xr.getHttpHandlerExtensionConfiguration(e),$o(e));return r.forEach((a)=>a.configure(i)),Object.assign(e,Pr.resolveAwsRegionExtensionConfiguration(i),y.resolveDefaultRuntimeConfig(i),xr.resolveHttpHandlerRuntimeConfig(i),jo(i))};class ee extends y.Client{config;constructor(...[e]){let r=Ro.getRuntimeConfig(e||{});super(r);this.initConfig=r;let i=Fo(r),a=Er.resolveUserAgentConfig(i),s=Sr.resolveRetryConfig(a),R=qo.resolveRegionConfig(s),j=vr.resolveHostHeaderConfig(R),Dr=yr.resolveEndpointConfig(j),br=Ir.resolveHttpAuthSchemeConfig(Dr),qr=wo(br,e?.extensions||[]);this.config=qr,this.middlewareStack.use(No.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Er.getUserAgentPlugin(this.config)),this.middlewareStack.use(Sr.getRetryPlugin(this.config)),this.middlewareStack.use(ho.getContentLengthPlugin(this.config)),this.middlewareStack.use(vr.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Do.getLoggerPlugin(this.config)),this.middlewareStack.use(bo.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(_.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:Ir.defaultSSOOIDCHttpAuthSchemeParametersProvider,identityProviderConfigProvider:async(Nr)=>new _.DefaultIdentityProviderConfig({"aws.auth#sigv4":Nr.credentials})})),this.middlewareStack.use(_.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class re extends y.Command.classBuilder().ep(Uo).m(function(e,r,i,a){return[yr.getEndpointPlugin(i,e.getEndpointParameterInstructions())]}).s("AWSSSOOIDCService","CreateToken",{}).n("SSOOIDCClient","CreateTokenCommand").sc(h.CreateToken$).build(){}var Mo={CreateTokenCommand:re};class te extends ee{}y.createAggregatedClient(Mo,te);var Ao={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},Go={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};P.$Command=y.Command;P.__Client=y.Client;P.SSOOIDCServiceException=fo.SSOOIDCServiceException;P.AccessDeniedExceptionReason=Ao;P.CreateTokenCommand=re;P.InvalidRequestExceptionReason=Go;P.SSOOIDC=te;P.SSOOIDCClient=ee;Object.prototype.hasOwnProperty.call(h,"__proto__")&&!Object.prototype.hasOwnProperty.call(P,"__proto__")&&Object.defineProperty(P,"__proto__",{enumerable:!0,value:h.__proto__});Object.keys(h).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(P,e))P[e]=h[e]});Object.prototype.hasOwnProperty.call($,"__proto__")&&!Object.prototype.hasOwnProperty.call(P,"__proto__")&&Object.defineProperty(P,"__proto__",{enumerable:!0,value:$.__proto__});Object.keys($).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(P,e))P[e]=$[e]})});export default Yo();
2
+ import{h as _t}from"./chunk-53hc0ah1.js";import{A as oo,B as Lt,C as yo,i as er,k as M,l as vo,m as Eo,n as So,p as Gr,q as zr,r as kt,s as Io,t as cr,u as Po,v as xo,w as ar,x as eo,y as ro,z as to}from"./chunk-aafanq8n.js";import{D as hr,E as mt,G as Qt,K as Ue,O as f}from"./chunk-sxa70wgn.js";import{P as Oo}from"./chunk-gwnmgkq5.js";import"./chunk-5a4qbtez.js";import{X as zt}from"./chunk-hs88b8gt.js";import{Y as gt}from"./chunk-y67evsdy.js";import{Z as Ht}from"./chunk-vd6zn8c4.js";import"./chunk-fsy344zb.js";import"./chunk-f1thqe6j.js";import"./chunk-kvas36p6.js";import{la as Zt}from"./chunk-9p7eq7bz.js";import{Jj as S}from"./chunk-ay8nat73.js";var A=S((oe)=>{Object.defineProperty(oe,"__esModule",{value:!0});oe.resolveHttpAuthSchemeConfig=oe.defaultSSOOIDCHttpAuthSchemeProvider=oe.defaultSSOOIDCHttpAuthSchemeParametersProvider=void 0;var Rr=M(),w=hr(),fr=async(e,r,i)=>{return{operation:(0,w.getSmithyContext)(r).operation,region:await(0,w.normalizeProvider)(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};oe.defaultSSOOIDCHttpAuthSchemeParametersProvider=fr;function Fr(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:e.region},propertiesExtractor:(r,i)=>({signingProperties:{config:r,context:i}})}}function Ur(e){return{schemeId:"smithy.api#noAuth"}}var $r=(e)=>{let r=[];switch(e.operation){case"CreateToken":{r.push(Ur(e));break}default:r.push(Fr(e))}return r};oe.defaultSSOOIDCHttpAuthSchemeProvider=$r;var jr=(e)=>{let r=(0,Rr.resolveAwsSdkSigV4Config)(e);return Object.assign(r,{authSchemePreference:(0,w.normalizeProvider)(e.authSchemePreference??[])})};oe.resolveHttpAuthSchemeConfig=jr});var De=S((xe)=>{Object.defineProperty(xe,"__esModule",{value:!0});xe.ruleSet=void 0;var Ee="required",p="fn",d="argv",q="ref",se=!0,ne="isSet",N="booleanEquals",D="error",b="endpoint",I="tree",G="PartitionResult",z="getAttr",pe={[Ee]:!1,type:"string"},de={[Ee]:!0,default:!1,type:"boolean"},ce={[q]:"Endpoint"},Se={[p]:N,[d]:[{[q]:"UseFIPS"},!0]},Ie={[p]:N,[d]:[{[q]:"UseDualStack"},!0]},n={},ae={[p]:z,[d]:[{[q]:G},"supportsFIPS"]},Pe={[q]:G},le={[p]:N,[d]:[!0,{[p]:z,[d]:[Pe,"supportsDualStack"]}]},ue=[Se],Oe=[Ie],ve=[{[q]:"Region"}],Ar={version:"1.0",parameters:{Region:pe,UseDualStack:de,UseFIPS:de,Endpoint:pe},rules:[{conditions:[{[p]:ne,[d]:[ce]}],rules:[{conditions:ue,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:D},{conditions:Oe,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:D},{endpoint:{url:ce,properties:n,headers:n},type:b}],type:I},{conditions:[{[p]:ne,[d]:ve}],rules:[{conditions:[{[p]:"aws.partition",[d]:ve,assign:G}],rules:[{conditions:[Se,Ie],rules:[{conditions:[{[p]:N,[d]:[se,ae]},le],rules:[{endpoint:{url:"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:n,headers:n},type:b}],type:I},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:D}],type:I},{conditions:ue,rules:[{conditions:[{[p]:N,[d]:[ae,se]}],rules:[{conditions:[{[p]:"stringEquals",[d]:[{[p]:z,[d]:[Pe,"name"]},"aws-us-gov"]}],endpoint:{url:"https://oidc.{Region}.amazonaws.com",properties:n,headers:n},type:b},{endpoint:{url:"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",properties:n,headers:n},type:b}],type:I},{error:"FIPS is enabled but this partition does not support FIPS",type:D}],type:I},{conditions:Oe,rules:[{conditions:[le],rules:[{endpoint:{url:"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:n,headers:n},type:b}],type:I},{error:"DualStack is enabled but this partition does not support DualStack",type:D}],type:I},{endpoint:{url:"https://oidc.{Region}.{PartitionResult#dnsSuffix}",properties:n,headers:n},type:b}],type:I}],type:I},{error:"Invalid Configuration: Missing Region",type:D}]};xe.ruleSet=Ar});var Ne=S((be)=>{Object.defineProperty(be,"__esModule",{value:!0});be.defaultEndpointResolver=void 0;var mr=zr(),m=Gr(),Hr=De(),Lr=new m.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),Tr=(e,r={})=>{return Lr.get(e,()=>(0,m.resolveEndpoint)(Hr.ruleSet,{endpointParams:e,logger:r.logger}))};be.defaultEndpointResolver=Tr;m.customEndpointFunctions.aws=mr.awsEndpointFunctions});var F=S((L)=>{Object.defineProperty(L,"__esModule",{value:!0});L.SSOOIDCServiceException=L.__ServiceException=void 0;var he=f();Object.defineProperty(L,"__ServiceException",{enumerable:!0,get:function(){return he.ServiceException}});class H extends he.ServiceException{constructor(e){super(e);Object.setPrototypeOf(this,H.prototype)}}L.SSOOIDCServiceException=H});var k=S((fe)=>{Object.defineProperty(fe,"__esModule",{value:!0});fe.UnsupportedGrantTypeException=fe.UnauthorizedClientException=fe.SlowDownException=fe.InvalidScopeException=fe.InvalidRequestException=fe.InvalidGrantException=fe.InvalidClientException=fe.InternalServerException=fe.ExpiredTokenException=fe.AuthorizationPendingException=fe.AccessDeniedException=void 0;var l=F();class T extends l.SSOOIDCServiceException{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e});Object.setPrototypeOf(this,T.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}fe.AccessDeniedException=T;class B extends l.SSOOIDCServiceException{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e});Object.setPrototypeOf(this,B.prototype),this.error=e.error,this.error_description=e.error_description}}fe.AuthorizationPendingException=B;class V extends l.SSOOIDCServiceException{name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e});Object.setPrototypeOf(this,V.prototype),this.error=e.error,this.error_description=e.error_description}}fe.ExpiredTokenException=V;class W extends l.SSOOIDCServiceException{name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e});Object.setPrototypeOf(this,W.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InternalServerException=W;class Y extends l.SSOOIDCServiceException{name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e});Object.setPrototypeOf(this,Y.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InvalidClientException=Y;class J extends l.SSOOIDCServiceException{name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e});Object.setPrototypeOf(this,J.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InvalidGrantException=J;class K extends l.SSOOIDCServiceException{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e});Object.setPrototypeOf(this,K.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}}fe.InvalidRequestException=K;class X extends l.SSOOIDCServiceException{name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e});Object.setPrototypeOf(this,X.prototype),this.error=e.error,this.error_description=e.error_description}}fe.InvalidScopeException=X;class C extends l.SSOOIDCServiceException{name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e});Object.setPrototypeOf(this,C.prototype),this.error=e.error,this.error_description=e.error_description}}fe.SlowDownException=C;class Q extends l.SSOOIDCServiceException{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e});Object.setPrototypeOf(this,Q.prototype),this.error=e.error,this.error_description=e.error_description}}fe.UnauthorizedClientException=Q;class Z extends l.SSOOIDCServiceException{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e});Object.setPrototypeOf(this,Z.prototype),this.error=e.error,this.error_description=e.error_description}}fe.UnsupportedGrantTypeException=Z});var g=S((ze)=>{Object.defineProperty(ze,"__esModule",{value:!0});ze.CreateToken$=ze.CreateTokenResponse$=ze.CreateTokenRequest$=ze.errorTypeRegistries=ze.UnsupportedGrantTypeException$=ze.UnauthorizedClientException$=ze.SlowDownException$=ze.InvalidScopeException$=ze.InvalidRequestException$=ze.InvalidGrantException$=ze.InvalidClientException$=ze.InternalServerException$=ze.ExpiredTokenException$=ze.AuthorizationPendingException$=ze.AccessDeniedException$=ze.SSOOIDCServiceException$=void 0;var kr="AccessDeniedException",gr="AuthorizationPendingException",_r="AccessToken",et="ClientSecret",rt="CreateToken",tt="CreateTokenRequest",ot="CreateTokenResponse",it="CodeVerifier",st="ExpiredTokenException",nt="InvalidClientException",pt="InvalidGrantException",dt="InvalidRequestException",ct="InternalServerException",at="InvalidScopeException",lt="IdToken",ut="RefreshToken",Ot="SlowDownException",vt="UnauthorizedClientException",Et="UnsupportedGrantTypeException",St="accessToken",E="client",It="clientId",Pt="clientSecret",xt="codeVerifier",yt="code",Dt="deviceCode",t="error",bt="expiresIn",u="error_description",qt="grantType",Nt="http",O="httpError",ht="idToken",$e="reason",je="refreshToken",Rt="redirectUri",we="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",ft="scope",Ft="server",Ut="tokenType",o="com.amazonaws.ssooidc",Me=Ue(),v=k(),$t=F(),Ae=Me.TypeRegistry.for(we);ze.SSOOIDCServiceException$=[-3,we,"SSOOIDCServiceException",0,[],[]];Ae.registerError(ze.SSOOIDCServiceException$,$t.SSOOIDCServiceException);var c=Me.TypeRegistry.for(o);ze.AccessDeniedException$=[-3,o,kr,{[t]:E,[O]:400},[t,$e,u],[0,0,0]];c.registerError(ze.AccessDeniedException$,v.AccessDeniedException);ze.AuthorizationPendingException$=[-3,o,gr,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.AuthorizationPendingException$,v.AuthorizationPendingException);ze.ExpiredTokenException$=[-3,o,st,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.ExpiredTokenException$,v.ExpiredTokenException);ze.InternalServerException$=[-3,o,ct,{[t]:Ft,[O]:500},[t,u],[0,0]];c.registerError(ze.InternalServerException$,v.InternalServerException);ze.InvalidClientException$=[-3,o,nt,{[t]:E,[O]:401},[t,u],[0,0]];c.registerError(ze.InvalidClientException$,v.InvalidClientException);ze.InvalidGrantException$=[-3,o,pt,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.InvalidGrantException$,v.InvalidGrantException);ze.InvalidRequestException$=[-3,o,dt,{[t]:E,[O]:400},[t,$e,u],[0,0,0]];c.registerError(ze.InvalidRequestException$,v.InvalidRequestException);ze.InvalidScopeException$=[-3,o,at,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.InvalidScopeException$,v.InvalidScopeException);ze.SlowDownException$=[-3,o,Ot,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.SlowDownException$,v.SlowDownException);ze.UnauthorizedClientException$=[-3,o,vt,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.UnauthorizedClientException$,v.UnauthorizedClientException);ze.UnsupportedGrantTypeException$=[-3,o,Et,{[t]:E,[O]:400},[t,u],[0,0]];c.registerError(ze.UnsupportedGrantTypeException$,v.UnsupportedGrantTypeException);ze.errorTypeRegistries=[Ae,c];var jt=[0,o,_r,8,0],wt=[0,o,et,8,0],Mt=[0,o,it,8,0],At=[0,o,lt,8,0],Ge=[0,o,ut,8,0];ze.CreateTokenRequest$=[3,o,tt,0,[It,Pt,qt,Dt,yt,je,ft,Rt,xt],[0,[()=>wt,0],0,0,0,[()=>Ge,0],64,0,[()=>Mt,0]],3];ze.CreateTokenResponse$=[3,o,ot,0,[St,Ut,bt,je,ht],[[()=>jt,0],0,1,[()=>Ge,0],[()=>At,0]]];ze.CreateToken$=[9,o,rt,{[Nt]:["POST","/token",200]},()=>ze.CreateTokenRequest$,()=>ze.CreateTokenResponse$]});var or=S((rr)=>{Object.defineProperty(rr,"__esModule",{value:!0});rr.getRuntimeConfig=void 0;var Tt=M(),Bt=Lt(),Vt=er(),Wt=f(),Yt=Ht(),ge=mt(),_e=zt(),Jt=A(),Kt=Ne(),Xt=g(),Ct=(e)=>{return{apiVersion:"2019-06-10",base64Decoder:e?.base64Decoder??ge.fromBase64,base64Encoder:e?.base64Encoder??ge.toBase64,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??Kt.defaultEndpointResolver,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??Jt.defaultSSOOIDCHttpAuthSchemeProvider,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(r)=>r.getIdentityProvider("aws.auth#sigv4"),signer:new Tt.AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:(r)=>r.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new Vt.NoAuthSigner}],logger:e?.logger??new Wt.NoOpLogger,protocol:e?.protocol??Bt.AwsRestJsonProtocol,protocolSettings:e?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:Xt.errorTypeRegistries,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:e?.serviceId??"SSO OIDC",urlParser:e?.urlParser??Yt.parseUrl,utf8Decoder:e?.utf8Decoder??_e.fromUtf8,utf8Encoder:e?.utf8Encoder??_e.toUtf8}};rr.getRuntimeConfig=Ct});var Or=S((lr)=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.getRuntimeConfig=void 0;var io=Zt(),so=io.__importDefault(_t()),ir=M(),sr=eo(),U=cr(),no=ro(),nr=ar(),x=gt(),pr=Qt(),dr=f(),po=to(),co=oo(),ao=kt(),lo=or(),uo=(e)=>{(0,dr.emitWarningIfUnsupportedVersion)(process.version);let r=(0,co.resolveDefaultsModeConfig)(e),i=()=>r().then(dr.loadConfigsForDefaultMode),a=(0,lo.getRuntimeConfig)(e);(0,ir.emitWarningIfUnsupportedVersion)(process.version);let s={profile:e?.profile,logger:a.logger};return{...a,...e,runtime:"node",defaultsMode:r,authSchemePreference:e?.authSchemePreference??(0,x.loadConfig)(ir.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:e?.bodyLengthChecker??po.calculateBodyLength,defaultUserAgentProvider:e?.defaultUserAgentProvider??(0,sr.createDefaultUserAgentProvider)({serviceId:a.serviceId,clientVersion:so.default.version}),maxAttempts:e?.maxAttempts??(0,x.loadConfig)(nr.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,e),region:e?.region??(0,x.loadConfig)(U.NODE_REGION_CONFIG_OPTIONS,{...U.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:pr.NodeHttpHandler.create(e?.requestHandler??i),retryMode:e?.retryMode??(0,x.loadConfig)({...nr.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||ao.DEFAULT_RETRY_MODE},e),sha256:e?.sha256??no.Hash.bind(null,"sha256"),streamCollector:e?.streamCollector??pr.streamCollector,useDualstackEndpoint:e?.useDualstackEndpoint??(0,x.loadConfig)(U.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:e?.useFipsEndpoint??(0,x.loadConfig)(U.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:e?.userAgentAppId??(0,x.loadConfig)(sr.NODE_APP_ID_CONFIG_OPTIONS,s)}};lr.getRuntimeConfig=uo});var Yo=S((P)=>{var vr=vo(),Do=Eo(),bo=So(),Er=Io(),qo=cr(),_=er(),No=Ue(),ho=Po(),yr=xo(),Sr=ar(),y=f(),Ir=A(),Ro=Or(),Pr=yo(),xr=Oo(),h=g(),$=k(),fo=F(),Fo=(e)=>{return Object.assign(e,{useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},Uo={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},$o=(e)=>{let{httpAuthSchemes:r,httpAuthSchemeProvider:i,credentials:a}=e;return{setHttpAuthScheme(s){let R=r.findIndex((j)=>j.schemeId===s.schemeId);if(R===-1)r.push(s);else r.splice(R,1,s)},httpAuthSchemes(){return r},setHttpAuthSchemeProvider(s){i=s},httpAuthSchemeProvider(){return i},setCredentials(s){a=s},credentials(){return a}}},jo=(e)=>{return{httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}},wo=(e,r)=>{let i=Object.assign(Pr.getAwsRegionExtensionConfiguration(e),y.getDefaultExtensionConfiguration(e),xr.getHttpHandlerExtensionConfiguration(e),$o(e));return r.forEach((a)=>a.configure(i)),Object.assign(e,Pr.resolveAwsRegionExtensionConfiguration(i),y.resolveDefaultRuntimeConfig(i),xr.resolveHttpHandlerRuntimeConfig(i),jo(i))};class ee extends y.Client{config;constructor(...[e]){let r=Ro.getRuntimeConfig(e||{});super(r);this.initConfig=r;let i=Fo(r),a=Er.resolveUserAgentConfig(i),s=Sr.resolveRetryConfig(a),R=qo.resolveRegionConfig(s),j=vr.resolveHostHeaderConfig(R),Dr=yr.resolveEndpointConfig(j),br=Ir.resolveHttpAuthSchemeConfig(Dr),qr=wo(br,e?.extensions||[]);this.config=qr,this.middlewareStack.use(No.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Er.getUserAgentPlugin(this.config)),this.middlewareStack.use(Sr.getRetryPlugin(this.config)),this.middlewareStack.use(ho.getContentLengthPlugin(this.config)),this.middlewareStack.use(vr.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Do.getLoggerPlugin(this.config)),this.middlewareStack.use(bo.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(_.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:Ir.defaultSSOOIDCHttpAuthSchemeParametersProvider,identityProviderConfigProvider:async(Nr)=>new _.DefaultIdentityProviderConfig({"aws.auth#sigv4":Nr.credentials})})),this.middlewareStack.use(_.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class re extends y.Command.classBuilder().ep(Uo).m(function(e,r,i,a){return[yr.getEndpointPlugin(i,e.getEndpointParameterInstructions())]}).s("AWSSSOOIDCService","CreateToken",{}).n("SSOOIDCClient","CreateTokenCommand").sc(h.CreateToken$).build(){}var Mo={CreateTokenCommand:re};class te extends ee{}y.createAggregatedClient(Mo,te);var Ao={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},Go={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};P.$Command=y.Command;P.__Client=y.Client;P.SSOOIDCServiceException=fo.SSOOIDCServiceException;P.AccessDeniedExceptionReason=Ao;P.CreateTokenCommand=re;P.InvalidRequestExceptionReason=Go;P.SSOOIDC=te;P.SSOOIDCClient=ee;Object.prototype.hasOwnProperty.call(h,"__proto__")&&!Object.prototype.hasOwnProperty.call(P,"__proto__")&&Object.defineProperty(P,"__proto__",{enumerable:!0,value:h.__proto__});Object.keys(h).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(P,e))P[e]=h[e]});Object.prototype.hasOwnProperty.call($,"__proto__")&&!Object.prototype.hasOwnProperty.call(P,"__proto__")&&Object.defineProperty(P,"__proto__",{enumerable:!0,value:$.__proto__});Object.keys($).forEach(function(e){if(e!=="default"&&!Object.prototype.hasOwnProperty.call(P,e))P[e]=$[e]})});export default Yo();
3
3
 
4
- //# debugId=D98D79D0DC2733C264756E2164756E21
4
+ //# debugId=012EB147B1D7562664756E2164756E21