@stackframe/stack-shared 2.8.8 → 2.8.11

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 (476) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/config/format.d.cts +39 -0
  3. package/dist/config/format.d.ts +14 -13
  4. package/dist/config/format.js +147 -206
  5. package/dist/config/format.js.map +1 -0
  6. package/dist/config/schema.d.cts +729 -0
  7. package/dist/config/schema.d.ts +59 -51
  8. package/dist/config/schema.js +232 -172
  9. package/dist/config/schema.js.map +1 -0
  10. package/dist/crud.d.cts +102 -0
  11. package/dist/crud.d.ts +15 -13
  12. package/dist/crud.js +83 -128
  13. package/dist/crud.js.map +1 -0
  14. package/dist/esm/config/format.js +135 -0
  15. package/dist/esm/config/format.js.map +1 -0
  16. package/dist/esm/config/schema.js +201 -0
  17. package/dist/esm/config/schema.js.map +1 -0
  18. package/dist/esm/crud.js +60 -0
  19. package/dist/esm/crud.js.map +1 -0
  20. package/dist/esm/global.d.js +1 -0
  21. package/dist/esm/global.d.js.map +1 -0
  22. package/dist/esm/helpers/password.js +17 -0
  23. package/dist/esm/helpers/password.js.map +1 -0
  24. package/dist/esm/helpers/production-mode.js +50 -0
  25. package/dist/esm/helpers/production-mode.js.map +1 -0
  26. package/dist/esm/hooks/use-async-callback.js +38 -0
  27. package/dist/esm/hooks/use-async-callback.js.map +1 -0
  28. package/dist/esm/hooks/use-async-external-store.js +23 -0
  29. package/dist/esm/hooks/use-async-external-store.js.map +1 -0
  30. package/dist/esm/hooks/use-hash.js +17 -0
  31. package/dist/esm/hooks/use-hash.js.map +1 -0
  32. package/dist/esm/hooks/use-strict-memo.js +61 -0
  33. package/dist/esm/hooks/use-strict-memo.js.map +1 -0
  34. package/dist/esm/index.js +22 -0
  35. package/dist/esm/index.js.map +1 -0
  36. package/dist/esm/interface/adminInterface.js +244 -0
  37. package/dist/esm/interface/adminInterface.js.map +1 -0
  38. package/dist/esm/interface/clientInterface.js +2041 -0
  39. package/dist/esm/interface/clientInterface.js.map +1 -0
  40. package/dist/esm/interface/crud/contact-channels.js +77 -0
  41. package/dist/esm/interface/crud/contact-channels.js.map +1 -0
  42. package/dist/esm/interface/crud/current-user.js +65 -0
  43. package/dist/esm/interface/crud/current-user.js.map +1 -0
  44. package/dist/esm/interface/crud/email-templates.js +52 -0
  45. package/dist/esm/interface/crud/email-templates.js.map +1 -0
  46. package/dist/esm/interface/crud/emails.js +20 -0
  47. package/dist/esm/interface/crud/emails.js.map +1 -0
  48. package/dist/esm/interface/crud/internal-api-keys.js +69 -0
  49. package/dist/esm/interface/crud/internal-api-keys.js.map +1 -0
  50. package/dist/esm/interface/crud/oauth.js +24 -0
  51. package/dist/esm/interface/crud/oauth.js.map +1 -0
  52. package/dist/esm/interface/crud/project-api-keys.js +93 -0
  53. package/dist/esm/interface/crud/project-api-keys.js.map +1 -0
  54. package/dist/esm/interface/crud/project-permissions.js +113 -0
  55. package/dist/esm/interface/crud/project-permissions.js.map +1 -0
  56. package/dist/esm/interface/crud/projects.js +180 -0
  57. package/dist/esm/interface/crud/projects.js.map +1 -0
  58. package/dist/esm/interface/crud/sessions.js +62 -0
  59. package/dist/esm/interface/crud/sessions.js.map +1 -0
  60. package/dist/esm/interface/crud/svix-token.js +22 -0
  61. package/dist/esm/interface/crud/svix-token.js.map +1 -0
  62. package/dist/esm/interface/crud/team-invitation-details.js +23 -0
  63. package/dist/esm/interface/crud/team-invitation-details.js.map +1 -0
  64. package/dist/esm/interface/crud/team-invitation.js +36 -0
  65. package/dist/esm/interface/crud/team-invitation.js.map +1 -0
  66. package/dist/esm/interface/crud/team-member-profiles.js +62 -0
  67. package/dist/esm/interface/crud/team-member-profiles.js.map +1 -0
  68. package/dist/esm/interface/crud/team-memberships.js +60 -0
  69. package/dist/esm/interface/crud/team-memberships.js.map +1 -0
  70. package/dist/esm/interface/crud/team-permissions.js +114 -0
  71. package/dist/esm/interface/crud/team-permissions.js.map +1 -0
  72. package/dist/esm/interface/crud/teams.js +143 -0
  73. package/dist/esm/interface/crud/teams.js.map +1 -0
  74. package/dist/esm/interface/crud/users.js +139 -0
  75. package/dist/esm/interface/crud/users.js.map +1 -0
  76. package/dist/esm/interface/serverInterface.js +485 -0
  77. package/dist/esm/interface/serverInterface.js.map +1 -0
  78. package/dist/esm/interface/webhooks.js +21 -0
  79. package/dist/esm/interface/webhooks.js.map +1 -0
  80. package/dist/esm/known-errors.js +1238 -0
  81. package/dist/esm/known-errors.js.map +1 -0
  82. package/dist/esm/schema-fields.js +484 -0
  83. package/dist/esm/schema-fields.js.map +1 -0
  84. package/dist/esm/sessions.js +168 -0
  85. package/dist/esm/sessions.js.map +1 -0
  86. package/dist/esm/utils/api-keys.js +79 -0
  87. package/dist/esm/utils/api-keys.js.map +1 -0
  88. package/dist/esm/utils/arrays.js +78 -0
  89. package/dist/esm/utils/arrays.js.map +1 -0
  90. package/dist/esm/utils/base64.js +18 -0
  91. package/dist/esm/utils/base64.js.map +1 -0
  92. package/dist/esm/utils/booleans.js +12 -0
  93. package/dist/esm/utils/booleans.js.map +1 -0
  94. package/dist/esm/utils/browser-compat.js +21 -0
  95. package/dist/esm/utils/browser-compat.js.map +1 -0
  96. package/dist/esm/utils/bytes.js +160 -0
  97. package/dist/esm/utils/bytes.js.map +1 -0
  98. package/dist/esm/utils/caches.js +167 -0
  99. package/dist/esm/utils/caches.js.map +1 -0
  100. package/dist/esm/utils/compile-time.js +11 -0
  101. package/dist/esm/utils/compile-time.js.map +1 -0
  102. package/dist/esm/utils/crypto.js +25 -0
  103. package/dist/esm/utils/crypto.js.map +1 -0
  104. package/dist/esm/utils/dates.js +64 -0
  105. package/dist/esm/utils/dates.js.map +1 -0
  106. package/dist/esm/utils/dom.js +11 -0
  107. package/dist/esm/utils/dom.js.map +1 -0
  108. package/dist/esm/utils/env.js +58 -0
  109. package/dist/esm/utils/env.js.map +1 -0
  110. package/dist/esm/utils/errors.js +174 -0
  111. package/dist/esm/utils/errors.js.map +1 -0
  112. package/dist/esm/utils/fs.js +37 -0
  113. package/dist/esm/utils/fs.js.map +1 -0
  114. package/dist/esm/utils/functions.js +12 -0
  115. package/dist/esm/utils/functions.js.map +1 -0
  116. package/dist/esm/utils/geo.js +15 -0
  117. package/dist/esm/utils/geo.js.map +1 -0
  118. package/dist/esm/utils/globals.js +18 -0
  119. package/dist/esm/utils/globals.js.map +1 -0
  120. package/dist/esm/utils/hashes.js +55 -0
  121. package/dist/esm/utils/hashes.js.map +1 -0
  122. package/dist/esm/utils/html.js +13 -0
  123. package/dist/esm/utils/html.js.map +1 -0
  124. package/dist/esm/utils/http.js +60 -0
  125. package/dist/esm/utils/http.js.map +1 -0
  126. package/dist/esm/utils/ips.js +15 -0
  127. package/dist/esm/utils/ips.js.map +1 -0
  128. package/dist/esm/utils/json.js +31 -0
  129. package/dist/esm/utils/json.js.map +1 -0
  130. package/dist/esm/utils/jwt.js +87 -0
  131. package/dist/esm/utils/jwt.js.map +1 -0
  132. package/dist/esm/utils/locks.js +57 -0
  133. package/dist/esm/utils/locks.js.map +1 -0
  134. package/dist/esm/utils/maps.js +181 -0
  135. package/dist/esm/utils/maps.js.map +1 -0
  136. package/dist/esm/utils/math.js +8 -0
  137. package/dist/esm/utils/math.js.map +1 -0
  138. package/dist/esm/utils/node-http.js +42 -0
  139. package/dist/esm/utils/node-http.js.map +1 -0
  140. package/dist/esm/utils/numbers.js +32 -0
  141. package/dist/esm/utils/numbers.js.map +1 -0
  142. package/dist/esm/utils/oauth.js +10 -0
  143. package/dist/esm/utils/oauth.js.map +1 -0
  144. package/dist/esm/utils/objects.js +177 -0
  145. package/dist/esm/utils/objects.js.map +1 -0
  146. package/dist/esm/utils/passkey.js +1 -0
  147. package/dist/esm/utils/passkey.js.map +1 -0
  148. package/dist/esm/utils/promises.js +233 -0
  149. package/dist/esm/utils/promises.js.map +1 -0
  150. package/dist/esm/utils/proxies.js +128 -0
  151. package/dist/esm/utils/proxies.js.map +1 -0
  152. package/dist/esm/utils/react.js +78 -0
  153. package/dist/esm/utils/react.js.map +1 -0
  154. package/dist/esm/utils/results.js +141 -0
  155. package/dist/esm/utils/results.js.map +1 -0
  156. package/dist/esm/utils/sentry.js +20 -0
  157. package/dist/esm/utils/sentry.js.map +1 -0
  158. package/dist/esm/utils/stores.js +195 -0
  159. package/dist/esm/utils/stores.js.map +1 -0
  160. package/dist/esm/utils/strings.js +295 -0
  161. package/dist/esm/utils/strings.js.map +1 -0
  162. package/dist/esm/utils/strings.nicify.test.js +222 -0
  163. package/dist/esm/utils/strings.nicify.test.js.map +1 -0
  164. package/dist/esm/utils/types.js +1 -0
  165. package/dist/esm/utils/types.js.map +1 -0
  166. package/dist/esm/utils/unicode.js +11 -0
  167. package/dist/esm/utils/unicode.js.map +1 -0
  168. package/dist/esm/utils/urls.js +53 -0
  169. package/dist/esm/utils/urls.js.map +1 -0
  170. package/dist/esm/utils/uuids.js +16 -0
  171. package/dist/esm/utils/uuids.js.map +1 -0
  172. package/dist/global.d.d.cts +1 -0
  173. package/dist/global.d.d.ts +1 -0
  174. package/dist/global.d.js +2 -0
  175. package/dist/global.d.js.map +1 -0
  176. package/dist/helpers/password.d.cts +11 -0
  177. package/dist/helpers/password.d.ts +11 -2
  178. package/dist/helpers/password.js +41 -11
  179. package/dist/helpers/password.js.map +1 -0
  180. package/dist/helpers/production-mode.d.cts +12 -0
  181. package/dist/helpers/production-mode.d.ts +9 -3
  182. package/dist/helpers/production-mode.js +72 -45
  183. package/dist/helpers/production-mode.js.map +1 -0
  184. package/dist/hooks/use-async-callback.d.cts +6 -0
  185. package/dist/hooks/use-async-callback.d.ts +6 -3
  186. package/dist/hooks/use-async-callback.js +72 -30
  187. package/dist/hooks/use-async-callback.js.map +1 -0
  188. package/dist/hooks/use-async-external-store.d.cts +7 -0
  189. package/dist/hooks/use-async-external-store.d.ts +5 -2
  190. package/dist/hooks/use-async-external-store.js +47 -19
  191. package/dist/hooks/use-async-external-store.js.map +1 -0
  192. package/dist/hooks/use-hash.d.cts +3 -0
  193. package/dist/hooks/use-hash.d.ts +3 -1
  194. package/dist/hooks/use-hash.js +41 -8
  195. package/dist/hooks/use-hash.js.map +1 -0
  196. package/dist/hooks/use-strict-memo.d.cts +8 -0
  197. package/dist/hooks/use-strict-memo.d.ts +3 -1
  198. package/dist/hooks/use-strict-memo.js +78 -131
  199. package/dist/hooks/use-strict-memo.js.map +1 -0
  200. package/dist/index.d.cts +30 -0
  201. package/dist/index.d.ts +30 -4
  202. package/dist/index.js +42 -4
  203. package/dist/index.js.map +1 -0
  204. package/dist/interface/adminInterface.d.cts +94 -0
  205. package/dist/interface/adminInterface.d.ts +38 -15
  206. package/dist/interface/adminInterface.js +269 -174
  207. package/dist/interface/adminInterface.js.map +1 -0
  208. package/dist/interface/clientInterface.d.cts +260 -0
  209. package/dist/interface/clientInterface.d.ts +25 -18
  210. package/dist/interface/clientInterface.js +2054 -995
  211. package/dist/interface/clientInterface.js.map +1 -0
  212. package/dist/interface/crud/contact-channels.d.cts +180 -0
  213. package/dist/interface/crud/contact-channels.d.ts +30 -25
  214. package/dist/interface/crud/contact-channels.js +101 -59
  215. package/dist/interface/crud/contact-channels.js.map +1 -0
  216. package/dist/interface/crud/current-user.d.cts +205 -0
  217. package/dist/interface/crud/current-user.d.ts +17 -12
  218. package/dist/interface/crud/current-user.js +86 -56
  219. package/dist/interface/crud/current-user.js.map +1 -0
  220. package/dist/interface/crud/email-templates.d.cts +84 -0
  221. package/dist/interface/crud/email-templates.d.ts +24 -19
  222. package/dist/interface/crud/email-templates.js +77 -37
  223. package/dist/interface/crud/email-templates.js.map +1 -0
  224. package/dist/interface/crud/emails.d.cts +69 -0
  225. package/dist/interface/crud/emails.d.ts +12 -7
  226. package/dist/interface/crud/emails.js +54 -12
  227. package/dist/interface/crud/emails.js.map +1 -0
  228. package/dist/interface/crud/internal-api-keys.d.cts +139 -0
  229. package/dist/interface/crud/internal-api-keys.d.ts +22 -17
  230. package/dist/interface/crud/internal-api-keys.js +92 -54
  231. package/dist/interface/crud/internal-api-keys.js.map +1 -0
  232. package/dist/interface/crud/oauth.d.cts +34 -0
  233. package/dist/interface/crud/oauth.d.ts +16 -11
  234. package/dist/interface/crud/oauth.js +48 -14
  235. package/dist/interface/crud/oauth.js.map +1 -0
  236. package/dist/interface/crud/project-api-keys.d.cts +196 -0
  237. package/dist/interface/crud/project-api-keys.d.ts +20 -12
  238. package/dist/interface/crud/project-api-keys.js +121 -74
  239. package/dist/interface/crud/project-api-keys.js.map +1 -0
  240. package/dist/interface/crud/project-permissions.d.cts +160 -0
  241. package/dist/interface/crud/project-permissions.d.ts +38 -33
  242. package/dist/interface/crud/project-permissions.js +148 -90
  243. package/dist/interface/crud/project-permissions.js.map +1 -0
  244. package/dist/interface/crud/projects.d.cts +627 -0
  245. package/dist/interface/crud/projects.d.ts +43 -51
  246. package/dist/interface/crud/projects.js +210 -156
  247. package/dist/interface/crud/projects.js.map +1 -0
  248. package/dist/interface/crud/sessions.d.cts +149 -0
  249. package/dist/interface/crud/sessions.d.ts +21 -16
  250. package/dist/interface/crud/sessions.js +86 -50
  251. package/dist/interface/crud/sessions.js.map +1 -0
  252. package/dist/interface/crud/svix-token.d.cts +26 -0
  253. package/dist/interface/crud/svix-token.d.ts +14 -9
  254. package/dist/interface/crud/svix-token.js +46 -12
  255. package/dist/interface/crud/svix-token.js.map +1 -0
  256. package/dist/interface/crud/team-invitation-details.d.cts +30 -0
  257. package/dist/interface/crud/team-invitation-details.d.ts +12 -7
  258. package/dist/interface/crud/team-invitation-details.js +57 -15
  259. package/dist/interface/crud/team-invitation-details.js.map +1 -0
  260. package/dist/interface/crud/team-invitation.d.cts +49 -0
  261. package/dist/interface/crud/team-invitation.d.ts +13 -8
  262. package/dist/interface/crud/team-invitation.js +69 -27
  263. package/dist/interface/crud/team-invitation.js.map +1 -0
  264. package/dist/interface/crud/team-member-profiles.d.cts +229 -0
  265. package/dist/interface/crud/team-member-profiles.d.ts +20 -15
  266. package/dist/interface/crud/team-member-profiles.js +95 -49
  267. package/dist/interface/crud/team-member-profiles.js.map +1 -0
  268. package/dist/interface/crud/team-memberships.d.cts +74 -0
  269. package/dist/interface/crud/team-memberships.d.ts +22 -17
  270. package/dist/interface/crud/team-memberships.js +85 -45
  271. package/dist/interface/crud/team-memberships.js.map +1 -0
  272. package/dist/interface/crud/team-permissions.d.cts +168 -0
  273. package/dist/interface/crud/team-permissions.d.ts +38 -33
  274. package/dist/interface/crud/team-permissions.js +149 -91
  275. package/dist/interface/crud/team-permissions.js.map +1 -0
  276. package/dist/interface/crud/teams.d.cts +298 -0
  277. package/dist/interface/crud/teams.d.ts +45 -40
  278. package/dist/interface/crud/teams.js +177 -119
  279. package/dist/interface/crud/teams.js.map +1 -0
  280. package/dist/interface/crud/users.d.cts +469 -0
  281. package/dist/interface/crud/users.d.ts +31 -26
  282. package/dist/interface/crud/users.js +172 -118
  283. package/dist/interface/crud/users.js.map +1 -0
  284. package/dist/interface/serverInterface.d.cts +128 -0
  285. package/dist/interface/serverInterface.d.ts +29 -17
  286. package/dist/interface/serverInterface.js +506 -339
  287. package/dist/interface/serverInterface.js.map +1 -0
  288. package/dist/interface/webhooks.d.cts +292 -0
  289. package/dist/interface/webhooks.d.ts +6 -3
  290. package/dist/interface/webhooks.js +45 -15
  291. package/dist/interface/webhooks.js.map +1 -0
  292. package/dist/known-errors.d.cts +447 -0
  293. package/dist/known-errors.d.ts +15 -9
  294. package/dist/known-errors.js +1104 -562
  295. package/dist/known-errors.js.map +1 -0
  296. package/dist/schema-fields.d.cts +163 -0
  297. package/dist/schema-fields.d.ts +116 -114
  298. package/dist/schema-fields.js +593 -427
  299. package/dist/schema-fields.js.map +1 -0
  300. package/dist/sessions.d.cts +109 -0
  301. package/dist/sessions.d.ts +6 -3
  302. package/dist/sessions.js +201 -172
  303. package/dist/sessions.js.map +1 -0
  304. package/dist/utils/api-keys.d.cts +24 -0
  305. package/dist/utils/api-keys.d.ts +5 -4
  306. package/dist/utils/api-keys.js +106 -66
  307. package/dist/utils/api-keys.js.map +1 -0
  308. package/dist/utils/arrays.d.cts +18 -0
  309. package/dist/utils/arrays.d.ts +15 -13
  310. package/dist/utils/arrays.js +101 -168
  311. package/dist/utils/arrays.js.map +1 -0
  312. package/dist/utils/base64.d.cts +4 -0
  313. package/dist/utils/base64.d.ts +4 -2
  314. package/dist/utils/base64.js +41 -20
  315. package/dist/utils/base64.js.map +1 -0
  316. package/dist/utils/booleans.d.cts +6 -0
  317. package/dist/utils/booleans.d.ts +6 -4
  318. package/dist/utils/booleans.js +35 -27
  319. package/dist/utils/booleans.js.map +1 -0
  320. package/dist/utils/browser-compat.d.cts +8 -0
  321. package/dist/utils/browser-compat.d.ts +3 -1
  322. package/dist/utils/browser-compat.js +45 -16
  323. package/dist/utils/browser-compat.js.map +1 -0
  324. package/dist/utils/bytes.d.cts +15 -0
  325. package/dist/utils/bytes.d.ts +15 -13
  326. package/dist/utils/bytes.js +182 -270
  327. package/dist/utils/bytes.js.map +1 -0
  328. package/dist/utils/caches.d.cts +98 -0
  329. package/dist/utils/caches.d.ts +17 -14
  330. package/dist/utils/caches.js +188 -193
  331. package/dist/utils/caches.js.map +1 -0
  332. package/dist/utils/compile-time.d.cts +8 -0
  333. package/dist/utils/compile-time.d.ts +3 -1
  334. package/dist/utils/compile-time.js +35 -10
  335. package/dist/utils/compile-time.js.map +1 -0
  336. package/dist/utils/crypto.d.cts +8 -0
  337. package/dist/utils/crypto.d.ts +4 -2
  338. package/dist/utils/crypto.js +49 -21
  339. package/dist/utils/crypto.js.map +1 -0
  340. package/dist/utils/dates.d.cts +15 -0
  341. package/dist/utils/dates.d.ts +6 -4
  342. package/dist/utils/dates.js +83 -105
  343. package/dist/utils/dates.js.map +1 -0
  344. package/dist/utils/dom.d.cts +3 -0
  345. package/dist/utils/dom.d.ts +3 -1
  346. package/dist/utils/dom.js +35 -7
  347. package/dist/utils/dom.js.map +1 -0
  348. package/dist/utils/env.d.cts +9 -0
  349. package/dist/utils/env.d.ts +6 -4
  350. package/dist/utils/env.js +70 -43
  351. package/dist/utils/env.js.map +1 -0
  352. package/dist/utils/errors.d.cts +223 -0
  353. package/dist/utils/errors.d.ts +14 -11
  354. package/dist/utils/errors.js +148 -126
  355. package/dist/utils/errors.js.map +1 -0
  356. package/dist/utils/fs.d.cts +7 -0
  357. package/dist/utils/fs.d.ts +5 -3
  358. package/dist/utils/fs.js +70 -27
  359. package/dist/utils/fs.js.map +1 -0
  360. package/dist/utils/functions.d.cts +4 -0
  361. package/dist/utils/functions.d.ts +4 -2
  362. package/dist/utils/functions.js +35 -18
  363. package/dist/utils/functions.js.map +1 -0
  364. package/dist/utils/geo.d.cts +22 -0
  365. package/dist/utils/geo.d.ts +6 -3
  366. package/dist/utils/geo.js +39 -9
  367. package/dist/utils/geo.js.map +1 -0
  368. package/dist/utils/globals.d.cts +5 -0
  369. package/dist/utils/globals.d.ts +4 -2
  370. package/dist/utils/globals.js +41 -14
  371. package/dist/utils/globals.js.map +1 -0
  372. package/dist/utils/hashes.d.cts +7 -0
  373. package/dist/utils/hashes.d.ts +7 -5
  374. package/dist/utils/hashes.js +87 -41
  375. package/dist/utils/hashes.js.map +1 -0
  376. package/dist/utils/html.d.cts +4 -0
  377. package/dist/utils/html.d.ts +4 -2
  378. package/dist/utils/html.js +36 -37
  379. package/dist/utils/html.js.map +1 -0
  380. package/dist/utils/http.d.cts +43 -0
  381. package/dist/utils/http.d.ts +6 -4
  382. package/dist/utils/http.js +83 -83
  383. package/dist/utils/http.js.map +1 -0
  384. package/dist/utils/ips.d.cts +6 -0
  385. package/dist/utils/ips.d.ts +6 -4
  386. package/dist/utils/ips.js +48 -35
  387. package/dist/utils/ips.js.map +1 -0
  388. package/dist/utils/json.d.cts +13 -0
  389. package/dist/utils/json.d.ts +9 -6
  390. package/dist/utils/json.js +54 -157
  391. package/dist/utils/json.js.map +1 -0
  392. package/dist/utils/jwt.d.cts +44 -0
  393. package/dist/utils/jwt.d.ts +14 -11
  394. package/dist/utils/jwt.js +119 -84
  395. package/dist/utils/jwt.js.map +1 -0
  396. package/dist/utils/locks.d.cts +15 -0
  397. package/dist/utils/locks.d.ts +3 -2
  398. package/dist/utils/locks.js +76 -56
  399. package/dist/utils/locks.js.map +1 -0
  400. package/dist/utils/maps.d.cts +59 -0
  401. package/dist/utils/maps.d.ts +6 -4
  402. package/dist/utils/maps.js +207 -343
  403. package/dist/utils/maps.js.map +1 -0
  404. package/dist/utils/math.d.cts +6 -0
  405. package/dist/utils/math.d.ts +3 -1
  406. package/dist/utils/math.js +31 -16
  407. package/dist/utils/math.js.map +1 -0
  408. package/dist/utils/node-http.d.cts +15 -0
  409. package/dist/utils/node-http.d.ts +5 -5
  410. package/dist/utils/node-http.js +65 -36
  411. package/dist/utils/node-http.js.map +1 -0
  412. package/dist/utils/numbers.d.cts +5 -0
  413. package/dist/utils/numbers.d.ts +5 -3
  414. package/dist/utils/numbers.js +53 -66
  415. package/dist/utils/numbers.js.map +1 -0
  416. package/dist/utils/oauth.d.cts +8 -0
  417. package/dist/utils/oauth.d.ts +8 -6
  418. package/dist/utils/oauth.js +37 -4
  419. package/dist/utils/oauth.js.map +1 -0
  420. package/dist/utils/objects.d.cts +69 -0
  421. package/dist/utils/objects.d.ts +37 -32
  422. package/dist/utils/objects.js +224 -374
  423. package/dist/utils/objects.js.map +1 -0
  424. package/dist/utils/passkey.d.cts +1 -0
  425. package/dist/utils/passkey.d.ts +1 -1
  426. package/dist/utils/passkey.js +19 -1
  427. package/dist/utils/passkey.js.map +1 -0
  428. package/dist/utils/promises.d.cts +74 -0
  429. package/dist/utils/promises.d.ts +20 -18
  430. package/dist/utils/promises.js +252 -393
  431. package/dist/utils/promises.js.map +1 -0
  432. package/dist/utils/proxies.d.cts +4 -0
  433. package/dist/utils/proxies.d.ts +4 -2
  434. package/dist/utils/proxies.js +150 -161
  435. package/dist/utils/proxies.js.map +1 -0
  436. package/dist/utils/react.d.cts +25 -0
  437. package/dist/utils/react.d.ts +9 -6
  438. package/dist/utils/react.js +88 -134
  439. package/dist/utils/react.js.map +1 -0
  440. package/dist/utils/results.d.cts +78 -0
  441. package/dist/utils/results.d.ts +10 -9
  442. package/dist/utils/results.js +143 -324
  443. package/dist/utils/results.js.map +1 -0
  444. package/dist/utils/sentry.d.cts +5 -0
  445. package/dist/utils/sentry.d.ts +5 -2
  446. package/dist/utils/sentry.js +44 -14
  447. package/dist/utils/sentry.js.map +1 -0
  448. package/dist/utils/stores.d.cts +102 -0
  449. package/dist/utils/stores.d.ts +12 -9
  450. package/dist/utils/stores.js +219 -189
  451. package/dist/utils/stores.js.map +1 -0
  452. package/dist/utils/strings.d.cts +72 -0
  453. package/dist/utils/strings.d.ts +22 -20
  454. package/dist/utils/strings.js +300 -580
  455. package/dist/utils/strings.js.map +1 -0
  456. package/dist/utils/strings.nicify.test.d.cts +2 -0
  457. package/dist/utils/strings.nicify.test.d.ts +2 -1
  458. package/dist/utils/strings.nicify.test.js +168 -158
  459. package/dist/utils/strings.nicify.test.js.map +1 -0
  460. package/dist/utils/types.d.cts +23 -0
  461. package/dist/utils/types.d.ts +8 -6
  462. package/dist/utils/types.js +19 -1
  463. package/dist/utils/types.js.map +1 -0
  464. package/dist/utils/unicode.d.cts +3 -0
  465. package/dist/utils/unicode.d.ts +3 -1
  466. package/dist/utils/unicode.js +34 -21
  467. package/dist/utils/unicode.js.map +1 -0
  468. package/dist/utils/urls.d.cts +20 -0
  469. package/dist/utils/urls.d.ts +10 -8
  470. package/dist/utils/urls.js +76 -165
  471. package/dist/utils/urls.js.map +1 -0
  472. package/dist/utils/uuids.d.cts +4 -0
  473. package/dist/utils/uuids.d.ts +4 -2
  474. package/dist/utils/uuids.js +39 -35
  475. package/dist/utils/uuids.js.map +1 -0
  476. package/package.json +5 -5
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/schema-fields.ts"],"sourcesContent":["import * as yup from \"yup\";\nimport { KnownErrors } from \".\";\nimport { isBase64 } from \"./utils/bytes\";\nimport { StackAssertionError, throwErr } from \"./utils/errors\";\nimport { decodeBasicAuthorizationHeader } from \"./utils/http\";\nimport { allProviders } from \"./utils/oauth\";\nimport { deepPlainClone, omit } from \"./utils/objects\";\nimport { isValidUrl } from \"./utils/urls\";\nimport { isUuid } from \"./utils/uuids\";\n\ndeclare module \"yup\" {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface StringSchema<TType, TContext, TDefault, TFlags> {\n nonEmpty(message?: string): StringSchema<TType, TContext, TDefault, TFlags>,\n empty(): StringSchema<TType, TContext, TDefault, TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Schema<TType, TContext, TDefault, TFlags> {\n getNested<K extends keyof NonNullable<TType>>(path: K): yup.Schema<NonNullable<TType>[K], TContext, TDefault, TFlags>,\n\n // the default types for concat kinda suck, so let's fix that\n concat<U extends yup.AnySchema>(schema: U): yup.Schema<Omit<NonNullable<TType>, keyof yup.InferType<U>> & yup.InferType<U> | (TType & (null | undefined)), TContext, TDefault, TFlags>,\n }\n}\n\n// eslint-disable-next-line no-restricted-syntax\nyup.addMethod(yup.string, \"nonEmpty\", function (message?: string) {\n return this.test(\n \"non-empty\",\n message ?? (({ path }) => `${path} must not be empty`),\n (value) => {\n return value !== \"\";\n }\n );\n});\n\nyup.addMethod(yup.Schema, \"getNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) throw new StackAssertionError(`yupSchema.getNested can currently only be used with alphanumeric keys. Fix this in the future. Provided key: ${path}`);\n return yup.reach(this, path) as any;\n});\n\nexport async function yupValidate<S extends yup.ISchema<any>>(\n schema: S,\n obj: unknown,\n options?: yup.ValidateOptions & { currentUserId?: string | null }\n): Promise<yup.InferType<S>> {\n try {\n return await schema.validate(obj, {\n ...omit(options ?? {}, ['currentUserId']),\n context: {\n ...options?.context,\n stackAllowUserIdMe: options?.currentUserId !== undefined,\n },\n });\n } catch (error) {\n if (error instanceof ReplaceFieldWithOwnUserId) {\n const currentUserId = options?.currentUserId;\n if (!currentUserId) throw new KnownErrors.CannotGetOwnUserWithoutUser();\n\n // parse yup path\n let pathRemaining = error.path;\n const fieldPath = [];\n while (pathRemaining.length > 0) {\n if (pathRemaining.startsWith(\"[\")) {\n const index = pathRemaining.indexOf(\"]\");\n if (index < 0) throw new StackAssertionError(\"Invalid path\");\n fieldPath.push(JSON.parse(pathRemaining.slice(1, index)));\n pathRemaining = pathRemaining.slice(index + 1);\n } else {\n let dotIndex = pathRemaining.indexOf(\".\");\n if (dotIndex === -1) dotIndex = pathRemaining.length;\n fieldPath.push(pathRemaining.slice(0, dotIndex));\n pathRemaining = pathRemaining.slice(dotIndex + 1);\n }\n }\n\n const newObj = deepPlainClone(obj);\n let it = newObj;\n for (const field of fieldPath.slice(0, -1)) {\n if (!Object.prototype.hasOwnProperty.call(it, field)) {\n throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`);\n }\n it = (it as any)[field];\n }\n (it as any)[fieldPath[fieldPath.length - 1]] = currentUserId;\n\n return await yupValidate(schema, newObj, options);\n }\n throw error;\n }\n}\n\nconst _idDescription = (identify: string) => `The unique identifier of the ${identify}`;\nconst _displayNameDescription = (identify: string) => `Human-readable ${identify} display name. This is not a unique identifier.`;\nconst _clientMetaDataDescription = (identify: string) => `Client metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client.`;\nconst _clientReadOnlyMetaDataDescription = (identify: string) => `Client read-only, server-writable metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client. The client can read this data, but cannot modify it. This is useful for things like subscription status.`;\nconst _profileImageUrlDescription = (identify: string) => `URL of the profile image for ${identify}. Can be a Base64 encoded image. Must be smaller than 100KB. Please compress and crop to a square before passing in.`;\nconst _serverMetaDataDescription = (identify: string) => `Server metadata. Used as a data store, only accessible from the server side. You can store secret information related to the ${identify} here.`;\nconst _atMillisDescription = (identify: string) => `(the number of milliseconds since epoch, January 1, 1970, UTC)`;\nconst _createdAtMillisDescription = (identify: string) => `The time the ${identify} was created ${_atMillisDescription(identify)}`;\nconst _signedUpAtMillisDescription = `The time the user signed up ${_atMillisDescription}`;\nconst _lastActiveAtMillisDescription = `The time the user was last active ${_atMillisDescription}`;\n\n\ndeclare const StackAdaptSentinel: unique symbol;\nexport type StackAdaptSentinel = typeof StackAdaptSentinel;\n\n// Built-in replacements\nexport function yupString<A extends string, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.string<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.string(...args);\n}\nexport function yupNumber<A extends number, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.number<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.number(...args);\n}\nexport function yupBoolean<A extends boolean, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.boolean<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.boolean(...args);\n}\n/**\n * @deprecated, use number of milliseconds since epoch instead\n */\nexport function yupDate<A extends Date, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.date<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.date(...args);\n}\nexport function yupMixed<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.mixed(...args);\n}\nexport function yupArray<A extends yup.Maybe<yup.AnyObject> = yup.AnyObject, B = any>(...args: Parameters<typeof yup.array<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.array(...args);\n}\nexport function yupTuple<T extends [unknown, ...unknown[]]>(...args: Parameters<typeof yup.tuple<T>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.tuple<T>(...args);\n}\nexport function yupObject<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n const object = yup.object(...args).test(\n 'no-unknown-object-properties',\n ({ path }) => `${path} contains unknown properties`,\n (value: any, context) => {\n if (context.options.context?.noUnknownPathPrefixes?.some((prefix: string) => context.path.startsWith(prefix))) {\n if (context.schema.spec.noUnknown !== false) {\n const availableKeys = new Set(Object.keys(context.schema.fields));\n const unknownKeys = Object.keys(value ?? {}).filter(key => !availableKeys.has(key));\n if (unknownKeys.length > 0) {\n // TODO \"did you mean XYZ\"\n return context.createError({\n message: `${context.path || \"Object\"} contains unknown properties: ${unknownKeys.join(', ')}`,\n path: context.path,\n params: { unknownKeys, availableKeys },\n });\n }\n }\n }\n return true;\n },\n );\n\n // we don't want to update the type of `object` to have a default flag\n return object.default(undefined) as any as typeof object;\n}\n\nexport function yupNever(): yup.MixedSchema<never> {\n return yupMixed().test('never', 'This value should never be reached', () => false) as any;\n}\n\nexport function yupUnion<T extends yup.ISchema<any>[]>(...args: T): yup.MixedSchema<yup.InferType<T[number]>> {\n if (args.length === 0) throw new Error('yupUnion must have at least one schema');\n\n const [first] = args;\n const firstDesc = first.describe();\n for (const schema of args) {\n const desc = schema.describe();\n if (desc.type !== firstDesc.type) throw new StackAssertionError(`yupUnion must have schemas of the same type (got: ${firstDesc.type} and ${desc.type})`, { first, schema, firstDesc, desc });\n }\n\n return yupMixed().test('is-one-of', 'Invalid value', async (value, context) => {\n const errors = [];\n for (const schema of args) {\n try {\n await yupValidate(schema, value, context.options);\n return true;\n } catch (e) {\n errors.push(e);\n }\n }\n return context.createError({\n message: `${context.path} is not matched by any of the provided schemas:\\n${errors.map((e: any, i) => '\\tSchema ' + i + \": \\n\\t\\t\" + e.errors.join('\\n\\t\\t')).join('\\n')}`,\n path: context.path,\n });\n });\n}\n\nexport function yupRecord<K extends yup.StringSchema, T extends yup.AnySchema>(\n keySchema: K,\n valueSchema: T,\n): yup.MixedSchema<Record<string, yup.InferType<T>>> {\n return yupObject().unknown(true).test(\n 'record',\n '${path} must be a record of valid values',\n async function (value: unknown, context: yup.TestContext) {\n if (value == null) return true;\n const { path, createError } = this as any;\n if (typeof value !== 'object') {\n return createError({ message: `${path} must be an object` });\n }\n\n // Validate each property using the provided valueSchema\n for (const key of Object.keys(value)) {\n // Validate the key\n await yupValidate(keySchema, key, context.options);\n\n // Validate the value\n try {\n await yupValidate(valueSchema, (value as Record<string, unknown>)[key], {\n ...context.options,\n context: {\n ...context.options.context,\n path: path ? `${path}.${key}` : key,\n },\n });\n } catch (e: any) {\n return createError({\n path: path ? `${path}.${key}` : key,\n message: e.message,\n });\n }\n }\n\n return true;\n },\n ) as any;\n}\n\nexport function ensureObjectSchema<T extends yup.AnyObject>(schema: yup.Schema<T>): yup.ObjectSchema<T> & typeof schema {\n if (!(schema instanceof yup.ObjectSchema)) throw new StackAssertionError(`assertObjectSchema: schema is not an ObjectSchema: ${schema.describe().type}`);\n return schema as any;\n}\n\n// Common\nexport const adaptSchema = yupMixed<StackAdaptSentinel>();\n/**\n * Yup's URL schema does not recognize some URLs (including `http://localhost`) as a valid URL. This schema is a workaround for that.\n */\nexport const urlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'url',\n message: (params) => `${params.path} is not a valid URL`,\n test: (value) => value == null || isValidUrl(value)\n});\nexport const jsonSchema = yupMixed().nullable().defined().transform((value) => JSON.parse(JSON.stringify(value)));\nexport const jsonStringSchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (value == null) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const jsonStringOrEmptySchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (!value) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const base64Schema = yupString().test(\"is-base64\", (params) => `${params.path} is not valid base64`, (value) => {\n if (value == null) return true;\n return isBase64(value);\n});\nexport const passwordSchema = yupString().max(70);\n\n/**\n * A stricter email schema that does some additional checks for UX input. (Some emails are allowed by the spec, for\n * example `test@localhost` or `abc@gmail`, but almost certainly a user input error.)\n *\n * Note that some users in the DB have an email that doesn't match this regex, so most of the time you should use\n * `emailSchema` instead until we do the DB migration.\n */\n// eslint-disable-next-line no-restricted-syntax\nexport const strictEmailSchema = (message: string | undefined) => yupString().email(message).matches(/^[^.]+(\\.[^.]+)*@.*\\.[^.][^.]+$/, message);\n// eslint-disable-next-line no-restricted-syntax\nexport const emailSchema = yupString().email();\n\nundefined?.test('strictEmailSchema', ({ expect }) => {\n const validEmails = [\n \"a@example.com\",\n \"abc@example.com\",\n \"a.b@example.com\",\n \"throwaway.mail+token@example.com\",\n \"email-alt-dash@demo-mail.com\",\n \"test-account@weird-domain.net\",\n \"%!~&+{}=|`#@domain.test\",\n \"admin@a.longtldexample\",\n ];\n for (const email of validEmails) {\n expect(strictEmailSchema(undefined).validateSync(email)).toBe(email);\n }\n const invalidEmails = [\n \"test@localhost\",\n \"test@gmail\",\n \"test@gmail.com.a\",\n \"test@gmail.a\",\n \"test.@example.com\",\n \"test..test@example.com\",\n \".test@example.com\",\n ];\n for (const email of invalidEmails) {\n expect(() => strictEmailSchema(undefined).validateSync(email)).toThrow();\n }\n});\n\n// Request auth\nexport const clientOrHigherAuthTypeSchema = yupString().oneOf(['client', 'server', 'admin']).defined();\nexport const serverOrHigherAuthTypeSchema = yupString().oneOf(['server', 'admin']).defined();\nexport const adminAuthTypeSchema = yupString().oneOf(['admin']).defined();\n\n// Projects\nexport const projectIdSchema = yupString().test((v) => v === undefined || v === \"internal\" || isUuid(v)).meta({ openapiField: { description: _idDescription('project'), exampleValue: 'e0b52f4d-dece-408c-af49-d23061bb0f8d' } });\nexport const projectDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('project'), exampleValue: 'MyMusic' } });\nexport const projectDescriptionSchema = yupString().nullable().meta({ openapiField: { description: 'A human readable description of the project', exampleValue: 'A music streaming service' } });\nexport const projectCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('project'), exampleValue: 1630000000000 } });\nexport const projectUserCountSchema = yupNumber().meta({ openapiField: { description: 'The number of users in this project', exampleValue: 10 } });\nexport const projectIsProductionModeSchema = yupBoolean().meta({ openapiField: { description: 'Whether the project is in production mode', exampleValue: true } });\n// Project config\nexport const projectConfigIdSchema = yupString().meta({ openapiField: { description: _idDescription('project config'), exampleValue: 'd09201f0-54f5-40bd-89ff-6d1815ddad24' } });\nexport const projectAllowLocalhostSchema = yupBoolean().meta({ openapiField: { description: 'Whether localhost is allowed as a domain for this project. Should only be allowed in development mode', exampleValue: true } });\nexport const projectCreateTeamOnSignUpSchema = yupBoolean().meta({ openapiField: { description: 'Whether a team should be created for each user that signs up', exampleValue: true } });\nexport const projectMagicLinkEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether magic link authentication is enabled for this project', exampleValue: true } });\nexport const projectPasskeyEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether passkey authentication is enabled for this project', exampleValue: true } });\nexport const projectClientTeamCreationEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can create teams', exampleValue: true } });\nexport const projectClientUserDeletionEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can delete their own account from the client', exampleValue: true } });\nexport const projectSignUpEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether users can sign up new accounts, or whether they are only allowed to sign in to existing accounts. Regardless of this option, the server API can always create new users with the `POST /users` endpoint.', exampleValue: true } });\nexport const projectCredentialEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether email password authentication is enabled for this project', exampleValue: true } });\n// Project OAuth config\nexport const oauthIdSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider ID, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the OAuth provider is enabled. If an provider is first enabled, then disabled, it will be shown in the list but with enabled=false', exampleValue: true } });\nexport const oauthTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'OAuth provider type, one of shared, standard. \"shared\" uses Stack shared OAuth keys and it is only meant for development. \"standard\" uses your own OAuth keys and will show your logo and company name when signing in with the provider.', exampleValue: 'standard' } });\nexport const oauthClientIdSchema = yupString().meta({ openapiField: { description: 'OAuth client ID. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-id' } });\nexport const oauthClientSecretSchema = yupString().meta({ openapiField: { description: 'OAuth client secret. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-secret' } });\nexport const oauthFacebookConfigIdSchema = yupString().meta({ openapiField: { description: 'The configuration id for Facebook business login (for things like ads and marketing). This is only required if you are using the standard OAuth with Facebook and you are using Facebook business login.' } });\nexport const oauthMicrosoftTenantIdSchema = yupString().meta({ openapiField: { description: 'The Microsoft tenant id for Microsoft directory. This is only required if you are using the standard OAuth with Microsoft and you have an Azure AD tenant.' } });\nexport const oauthAccountMergeStrategySchema = yupString().oneOf(['link_method', 'raise_error', 'allow_duplicates']).meta({ openapiField: { description: 'Determines how to handle OAuth logins that match an existing user by email. `link_method` adds the OAuth method to the existing user. `raise_error` rejects the login with an error. `allow_duplicates` creates a new user.', exampleValue: 'link_method' } });\n// Project email config\nexport const emailTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'Email provider type, one of shared, standard. \"shared\" uses Stack shared email provider and it is only meant for development. \"standard\" uses your own email server and will have your email address as the sender.', exampleValue: 'standard' } });\nexport const emailSenderNameSchema = yupString().meta({ openapiField: { description: 'Email sender name. Needs to be specified when using type=\"standard\"', exampleValue: 'Stack' } });\nexport const emailHostSchema = yupString().meta({ openapiField: { description: 'Email host. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp.your-domain.com' } });\nexport const emailPortSchema = yupNumber().min(0).max(65535).meta({ openapiField: { description: 'Email port. Needs to be specified when using type=\"standard\"', exampleValue: 587 } });\nexport const emailUsernameSchema = yupString().meta({ openapiField: { description: 'Email username. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp-email' } });\nexport const emailSenderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email sender email. Needs to be specified when using type=\"standard\"', exampleValue: 'example@your-domain.com' } });\nexport const emailPasswordSchema = passwordSchema.meta({ openapiField: { description: 'Email password. Needs to be specified when using type=\"standard\"', exampleValue: 'your-email-password' } });\n// Project domain config\nexport const handlerPathSchema = yupString().test('is-handler-path', 'Handler path must start with /', (value) => value?.startsWith('/')).meta({ openapiField: { description: 'Handler path. If you did not setup a custom handler path, it should be \"/handler\" by default. It needs to start with /', exampleValue: '/handler' } });\n\n// Users\nexport class ReplaceFieldWithOwnUserId extends Error {\n constructor(public readonly path: string) {\n super(`This error should be caught by whoever validated the schema, and the field in the path '${path}' should be replaced with the current user's id. This is a workaround to yup not providing access to the context inside the transform function.`);\n }\n}\nconst userIdMeSentinelUuid = \"cad564fd-f81b-43f4-b390-98abf3fcc17e\";\nexport const userIdOrMeSchema = yupString().uuid().transform(v => {\n if (v === \"me\") return userIdMeSentinelUuid;\n else return v;\n}).test((v, context) => {\n if (!(\"stackAllowUserIdMe\" in (context.options.context ?? {}))) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re using yupValidate from schema-fields.ts to validate, instead of schema.validate(...).');\n if (!context.options.context?.stackAllowUserIdMe) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re passing in the currentUserId option in yupValidate.');\n if (v === userIdMeSentinelUuid) throw new ReplaceFieldWithOwnUserId(context.path);\n return true;\n}).meta({ openapiField: { description: 'The ID of the user, or the special value `me` for the currently authenticated user', exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const userIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('user'), exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const primaryEmailSchema = emailSchema.meta({ openapiField: { description: 'Primary email', exampleValue: 'johndoe@example.com' } });\nexport const primaryEmailAuthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email is used for authentication. If this is set to `false`, the user will not be able to sign in with the primary email with password or OTP', exampleValue: true } });\nexport const primaryEmailVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email has been verified to belong to this user', exampleValue: true } });\nexport const userDisplayNameSchema = yupString().nullable().meta({ openapiField: { description: _displayNameDescription('user'), exampleValue: 'John Doe' } });\nexport const selectedTeamIdSchema = yupString().uuid().meta({ openapiField: { description: 'ID of the team currently selected by the user', exampleValue: 'team-id' } });\nexport const profileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('user'), exampleValue: 'https://example.com/image.jpg' } });\nexport const signedUpAtMillisSchema = yupNumber().meta({ openapiField: { description: _signedUpAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userOAuthProviderSchema = yupObject({\n id: yupString().defined(),\n type: yupString().oneOf(allProviders).defined(),\n provider_user_id: yupString().defined(),\n});\nexport const userLastActiveAtMillisSchema = yupNumber().nullable().meta({ openapiField: { description: _lastActiveAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userPasskeyAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has passkeys enabled', exampleValue: false } });\nexport const userOtpAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. ', exampleValue: true } });\nexport const userOtpAuthEnabledMutationSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. Note that only accounts with verified emails can sign-in with OTP.', exampleValue: true } });\nexport const userHasPasswordSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has a password set. If the user does not have a password set, they will not be able to sign in with email/password.', exampleValue: true } });\nexport const userPasswordMutationSchema = passwordSchema.nullable().meta({ openapiField: { description: 'Sets the user\\'s password. Doing so revokes all current sessions.', exampleValue: 'my-new-password' } }).max(70);\nexport const userPasswordHashMutationSchema = yupString()\n .nonEmpty()\n .meta({ openapiField: { description: 'If `password` is not given, sets the user\\'s password hash to the given string in Modular Crypt Format (ex.: `$2a$10$VIhIOofSMqGdGlL4wzE//e.77dAQGqNtF/1dT7bqCrVtQuInWy2qi`). Doing so revokes all current sessions.' } }); // we don't set an exampleValue here because it's exclusive with the password field and having both would break the generated example\nexport const userTotpSecretMutationSchema = base64Schema.nullable().meta({ openapiField: { description: 'Enables 2FA and sets a TOTP secret for the user. Set to null to disable 2FA.', exampleValue: 'dG90cC1zZWNyZXQ=' } });\n\n// Auth\nexport const signInEmailSchema = strictEmailSchema(undefined).meta({ openapiField: { description: 'The email to sign in with.', exampleValue: 'johndoe@example.com' } });\nexport const emailOtpSignInCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct the magic link from. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/auth/otp/sign-in` endpoint.', exampleValue: 'https://example.com/handler/magic-link-callback' } });\nexport const emailVerificationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct a verification link for the verification e-mail. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/contact-channels/verify` endpoint.', exampleValue: 'https://example.com/handler/email-verification' } });\nexport const accessTokenResponseSchema = yupString().meta({ openapiField: { description: 'Short-lived access token that can be used to authenticate the user', exampleValue: 'eyJhmMiJB2TO...diI4QT' } });\nexport const refreshTokenResponseSchema = yupString().meta({ openapiField: { description: 'Long-lived refresh token that can be used to obtain a new access token', exampleValue: 'i8ns3aq2...14y' } });\nexport const signInResponseSchema = yupObject({\n refresh_token: refreshTokenResponseSchema.defined(),\n access_token: accessTokenResponseSchema.defined(),\n is_new_user: yupBoolean().meta({ openapiField: { description: 'Whether the user is a new user', exampleValue: true } }).defined(),\n user_id: userIdSchema.defined(),\n});\n\n// Permissions\nexport const teamSystemPermissions = [\n '$update_team',\n '$delete_team',\n '$read_members',\n '$remove_members',\n '$invite_members',\n '$manage_api_keys',\n] as const;\nexport const permissionDefinitionIdSchema = yupString()\n .matches(/^\\$?[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" and optional \"$\" at the beginning are allowed')\n .test('is-system-permission', 'System permissions must start with a dollar sign', (value, ctx) => {\n if (!value) return true;\n if (value.startsWith('$') && !teamSystemPermissions.includes(value as any)) {\n return ctx.createError({ message: 'Invalid system permission' });\n }\n return true;\n })\n .meta({ openapiField: { description: `The permission ID used to uniquely identify a permission. Can either be a custom permission with lowercase letters, numbers, \\`:\\`, and \\`_\\` characters, or one of the system permissions: ${teamSystemPermissions.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'read_secret_info' } });\nexport const customPermissionDefinitionIdSchema = yupString()\n .matches(/^[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" are allowed')\n .meta({ openapiField: { description: 'The permission ID used to uniquely identify a permission. Can only contain lowercase letters, numbers, \":\", and \"_\" characters', exampleValue: 'read_secret_info' } });\nexport const teamPermissionDescriptionSchema = yupString().meta({ openapiField: { description: 'A human-readable description of the permission', exampleValue: 'Read secret information' } });\nexport const containedPermissionIdsSchema = yupArray(permissionDefinitionIdSchema.defined()).meta({ openapiField: { description: 'The IDs of the permissions that are contained in this permission', exampleValue: ['read_public_info'] } });\n\n// Teams\nexport const teamIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('team'), exampleValue: 'ad962777-8244-496a-b6a2-e0c6a449c79e' } });\nexport const teamDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team'), exampleValue: 'My Team' } });\nexport const teamProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team'), exampleValue: 'https://example.com/image.jpg' } });\nexport const teamClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('team'), exampleValue: 1630000000000 } });\nexport const teamInvitationEmailSchema = emailSchema.meta({ openapiField: { description: 'The email of the user to invite.', exampleValue: 'johndoe@example.com' } });\nexport const teamInvitationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct an invite link with. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/team-invitations/accept` endpoint.', exampleValue: 'https://example.com/handler/team-invitation' } });\nexport const teamCreatorUserIdSchema = userIdOrMeSchema.meta({ openapiField: { description: 'The ID of the creator of the team. If not specified, the user will not be added to the team. Can be either \"me\" or the ID of the user. Only used on the client side.', exampleValue: 'me' } });\n\n// Team member profiles\nexport const teamMemberDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team member') + ' Note that this is separate from the display_name of the user.', exampleValue: 'John Doe' } });\nexport const teamMemberProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team member'), exampleValue: 'https://example.com/image.jpg' } });\n\n// Contact channels\nexport const contactChannelIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('contact channel'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const contactChannelTypeSchema = yupString().oneOf(['email']).meta({ openapiField: { description: `The type of the contact channel. Currently only \"email\" is supported.`, exampleValue: 'email' } });\nexport const contactChannelValueSchema = yupString().when('type', {\n is: 'email',\n then: (schema) => schema.email(),\n}).meta({ openapiField: { description: 'The value of the contact channel. For email, this should be a valid email address.', exampleValue: 'johndoe@example.com' } });\nexport const contactChannelUsedForAuthSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is used for authentication. If this is set to `true`, the user will be able to sign in with the contact channel with password or OTP.', exampleValue: true } });\nexport const contactChannelIsVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel has been verified. If this is set to `true`, the contact channel has been verified to belong to the user.', exampleValue: true } });\nexport const contactChannelIsPrimarySchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is the primary contact channel. If this is set to `true`, it will be used for authentication and notifications by default.', exampleValue: true } });\n\n// Headers\nexport const basicAuthorizationHeaderSchema = yupString().test('is-basic-authorization-header', 'Authorization header must be in the format \"Basic <base64>\"', (value) => {\n if (!value) return true;\n return decodeBasicAuthorizationHeader(value) !== null;\n});\n\n// Neon integration\nexport const neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test('is-neon-authorization-header', 'Invalid client_id:client_secret values; did you use the correct values for the Neon integration?', (value) => {\n if (!value) return true;\n const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Neon authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);\n for (const neonClientConfig of JSON.parse(process.env.STACK_NEON_INTEGRATION_CLIENTS_CONFIG || '[]')) {\n if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;\n }\n return false;\n});\n\n// Utils\nexport function yupDefinedWhen<S extends yup.AnyObject>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport function yupDefinedAndNonEmptyWhen<S extends yup.StringSchema>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),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yC,IAAI,GAAG;AACpG,QAAI,aAAa,iBAAiB,aAAa,iBAAiB,iBAAiB,cAAe,QAAO;AAAA,EACzG;AACA,SAAO;AACT,CAAC;AAGM,SAAS,eACd,QACA,UACG;AACH,QAAM,UAAU,OAAO,QAAQ,QAAQ;AACvC,SAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,MAAM,GAAG,GAAG;AAAA,IAC9C,IAAI,IAAI,WAAkB,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,UAAU,UAAU,OAAO,KAAK,CAAC;AAAA,IACxF,MAAM,CAACC,YAAcA,QAAO,QAAQ;AAAA,IACpC,WAAW,CAACA,YAAcA,QAAO,SAAS;AAAA,EAC5C,CAAC;AACH;AAEO,SAAS,0BACd,QACA,UACG;AACH,QAAM,UAAU,OAAO,QAAQ,QAAQ;AACvC,SAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,MAAM,GAAG,GAAG;AAAA,IAC9C,IAAI,IAAI,WAAkB,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,UAAU,UAAU,OAAO,KAAK,CAAC;AAAA,IACxF,MAAM,CAACA,YAAcA,QAAO,QAAQ,EAAE,SAAS;AAAA,IAC/C,WAAW,CAACA,YAAcA,QAAO,SAAS;AAAA,EAC5C,CAAC;AACH;","names":["object","schema"]}
@@ -0,0 +1,168 @@
1
+ // src/sessions.ts
2
+ import * as jose from "jose";
3
+ import { StackAssertionError } from "./utils/errors";
4
+ import { Store } from "./utils/stores";
5
+ var AccessToken = class {
6
+ constructor(token) {
7
+ this.token = token;
8
+ if (token === "undefined") {
9
+ throw new StackAssertionError("Access token is the string 'undefined'; it's unlikely this is the correct value. They're supposed to be unguessable!");
10
+ }
11
+ }
12
+ get decoded() {
13
+ return jose.decodeJwt(this.token);
14
+ }
15
+ get expiresAt() {
16
+ const { exp } = this.decoded;
17
+ if (exp === void 0) return /* @__PURE__ */ new Date(864e13);
18
+ return new Date(exp * 1e3);
19
+ }
20
+ /**
21
+ * @returns The number of milliseconds until the access token expires, or 0 if it has already expired.
22
+ */
23
+ get expiresInMillis() {
24
+ return Math.max(0, this.expiresAt.getTime() - Date.now());
25
+ }
26
+ isExpired() {
27
+ return this.expiresInMillis <= 0;
28
+ }
29
+ };
30
+ var RefreshToken = class {
31
+ constructor(token) {
32
+ this.token = token;
33
+ if (token === "undefined") {
34
+ throw new StackAssertionError("Refresh token is the string 'undefined'; it's unlikely this is the correct value. They're supposed to be unguessable!");
35
+ }
36
+ }
37
+ };
38
+ var InternalSession = class _InternalSession {
39
+ constructor(_options) {
40
+ this._options = _options;
41
+ /**
42
+ * Whether the session as a whole is known to be invalid (ie. both access and refresh tokens are invalid). Used as a cache to avoid making multiple requests to the server (sessions never go back to being valid after being invalidated).
43
+ *
44
+ * It is possible for the access token to be invalid but the refresh token to be valid, in which case the session is
45
+ * still valid (just needs a refresh). It is also possible for the access token to be valid but the refresh token to
46
+ * be invalid, in which case the session is also valid (eg. if the refresh token is null because the user only passed
47
+ * in an access token, eg. in a server-side request handler).
48
+ */
49
+ this._knownToBeInvalid = new Store(false);
50
+ this._refreshPromise = null;
51
+ this._accessToken = new Store(_options.accessToken ? new AccessToken(_options.accessToken) : null);
52
+ this._refreshToken = _options.refreshToken ? new RefreshToken(_options.refreshToken) : null;
53
+ if (_options.accessToken === null && _options.refreshToken === null) {
54
+ this._knownToBeInvalid.set(true);
55
+ }
56
+ this.sessionKey = _InternalSession.calculateSessionKey({ accessToken: _options.accessToken ?? null, refreshToken: _options.refreshToken });
57
+ }
58
+ static calculateSessionKey(ofTokens) {
59
+ if (ofTokens.refreshToken) {
60
+ return `refresh-${ofTokens.refreshToken}`;
61
+ } else if (ofTokens.accessToken) {
62
+ return `access-${ofTokens.accessToken}`;
63
+ } else {
64
+ return "not-logged-in";
65
+ }
66
+ }
67
+ isKnownToBeInvalid() {
68
+ return this._knownToBeInvalid.get();
69
+ }
70
+ /**
71
+ * Marks the session object as invalid, meaning that the refresh and access tokens can no longer be used.
72
+ */
73
+ markInvalid() {
74
+ this._accessToken.set(null);
75
+ this._knownToBeInvalid.set(true);
76
+ }
77
+ onInvalidate(callback) {
78
+ return this._knownToBeInvalid.onChange(() => callback());
79
+ }
80
+ /**
81
+ * Returns the access token if it is found in the cache, fetching it otherwise.
82
+ *
83
+ * This is usually the function you want to call to get an access token. Either set `minMillisUntilExpiration` to a reasonable value, or catch errors that occur if it expires, and call `markAccessTokenExpired` to mark the token as expired if so (after which a call to this function will always refetch the token).
84
+ *
85
+ * @returns null if the session is known to be invalid, cached tokens if they exist in the cache (which may or may not be valid still), or new tokens otherwise.
86
+ */
87
+ async getOrFetchLikelyValidTokens(minMillisUntilExpiration) {
88
+ if (minMillisUntilExpiration >= 6e4) {
89
+ throw new Error(`Required access token expiry ${minMillisUntilExpiration}ms is too long; access tokens are too short to be used for more than 60s`);
90
+ }
91
+ const accessToken = this._getPotentiallyInvalidAccessTokenIfAvailable();
92
+ if (!accessToken || accessToken.expiresInMillis < minMillisUntilExpiration) {
93
+ const newTokens = await this.fetchNewTokens();
94
+ const expiresInMillis = newTokens?.accessToken.expiresInMillis;
95
+ if (expiresInMillis && expiresInMillis < minMillisUntilExpiration) {
96
+ throw new StackAssertionError(`Required access token expiry ${minMillisUntilExpiration}ms is too long; access tokens are too short when they're generated (${expiresInMillis}ms)`);
97
+ }
98
+ return newTokens;
99
+ }
100
+ return { accessToken, refreshToken: this._refreshToken };
101
+ }
102
+ /**
103
+ * Fetches new tokens that are, at the time of fetching, guaranteed to be valid.
104
+ *
105
+ * The newly generated tokens are short-lived, so it's good practice not to rely on their validity (if possible). However, this function is useful in some cases where you only want to pass access tokens to a service, and you want to make sure said access token has the longest possible lifetime.
106
+ *
107
+ * In most cases, you should prefer `getOrFetchLikelyValidTokens`.
108
+ *
109
+ * @returns null if the session is known to be invalid, or new tokens otherwise (which, at the time of fetching, are guaranteed to be valid).
110
+ */
111
+ async fetchNewTokens() {
112
+ const accessToken = await this._getNewlyFetchedAccessToken();
113
+ return accessToken ? { accessToken, refreshToken: this._refreshToken } : null;
114
+ }
115
+ markAccessTokenExpired(accessToken) {
116
+ if (this._accessToken.get() === accessToken) {
117
+ this._accessToken.set(null);
118
+ }
119
+ }
120
+ /**
121
+ * Note that a callback invocation with `null` does not mean the session has been invalidated; the access token may just have expired. Use `onInvalidate` to detect invalidation.
122
+ */
123
+ onAccessTokenChange(callback) {
124
+ return this._accessToken.onChange(callback);
125
+ }
126
+ /**
127
+ * @returns An access token, which may be expired or expire soon, or null if it is known to be invalid.
128
+ */
129
+ _getPotentiallyInvalidAccessTokenIfAvailable() {
130
+ if (!this._refreshToken) return null;
131
+ if (this.isKnownToBeInvalid()) return null;
132
+ const accessToken = this._accessToken.get();
133
+ if (accessToken && !accessToken.isExpired()) return accessToken;
134
+ return null;
135
+ }
136
+ /**
137
+ * You should prefer `_getOrFetchPotentiallyInvalidAccessToken` in almost all cases.
138
+ *
139
+ * @returns A newly fetched access token (never read from cache), or null if the session either does not represent a user or the session is invalid.
140
+ */
141
+ async _getNewlyFetchedAccessToken() {
142
+ if (!this._refreshToken) return null;
143
+ if (this._knownToBeInvalid.get()) return null;
144
+ if (!this._refreshPromise) {
145
+ this._refreshAndSetRefreshPromise(this._refreshToken);
146
+ }
147
+ return await this._refreshPromise;
148
+ }
149
+ _refreshAndSetRefreshPromise(refreshToken) {
150
+ let refreshPromise = this._options.refreshAccessTokenCallback(refreshToken).then((accessToken) => {
151
+ if (refreshPromise === this._refreshPromise) {
152
+ this._refreshPromise = null;
153
+ this._accessToken.set(accessToken);
154
+ if (!accessToken) {
155
+ this.markInvalid();
156
+ }
157
+ }
158
+ return accessToken;
159
+ });
160
+ this._refreshPromise = refreshPromise;
161
+ }
162
+ };
163
+ export {
164
+ AccessToken,
165
+ InternalSession,
166
+ RefreshToken
167
+ };
168
+ //# sourceMappingURL=sessions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/sessions.ts"],"sourcesContent":["import * as jose from 'jose';\nimport { StackAssertionError } from \"./utils/errors\";\nimport { Store } from \"./utils/stores\";\n\nexport class AccessToken {\n constructor(\n public readonly token: string,\n ) {\n if (token === \"undefined\") {\n throw new StackAssertionError(\"Access token is the string 'undefined'; it's unlikely this is the correct value. They're supposed to be unguessable!\");\n }\n }\n\n get decoded() {\n return jose.decodeJwt(this.token);\n }\n\n get expiresAt(): Date {\n const { exp } = this.decoded;\n if (exp === undefined) return new Date(8640000000000000); // max date value\n return new Date(exp * 1000);\n }\n\n /**\n * @returns The number of milliseconds until the access token expires, or 0 if it has already expired.\n */\n get expiresInMillis(): number {\n return Math.max(0, this.expiresAt.getTime() - Date.now());\n }\n\n isExpired(): boolean {\n return this.expiresInMillis <= 0;\n }\n}\n\nexport class RefreshToken {\n constructor(\n public readonly token: string,\n ) {\n if (token === \"undefined\") {\n throw new StackAssertionError(\"Refresh token is the string 'undefined'; it's unlikely this is the correct value. They're supposed to be unguessable!\");\n }\n }\n}\n\n/**\n * An InternalSession represents a user's session, which may or may not be valid. It may contain an access token, a refresh token, or both.\n *\n * A session never changes which user or session it belongs to, but the tokens in it may change over time.\n */\nexport class InternalSession {\n /**\n * Each session has a session key that depends on the tokens inside. If the session has a refresh token, the session key depends only on the refresh token. If the session does not have a refresh token, the session key depends only on the access token.\n *\n * Multiple Session objects may have the same session key, which implies that they represent the same session by the same user. Furthermore, a session's key never changes over the lifetime of a session object.\n *\n * This is useful for caching and indexing sessions.\n */\n public readonly sessionKey: string;\n\n /**\n * An access token that is not known to be invalid (ie. may be valid, but may have expired).\n */\n private _accessToken: Store<AccessToken | null>;\n private readonly _refreshToken: RefreshToken | null;\n\n /**\n * Whether the session as a whole is known to be invalid (ie. both access and refresh tokens are invalid). Used as a cache to avoid making multiple requests to the server (sessions never go back to being valid after being invalidated).\n *\n * It is possible for the access token to be invalid but the refresh token to be valid, in which case the session is\n * still valid (just needs a refresh). It is also possible for the access token to be valid but the refresh token to\n * be invalid, in which case the session is also valid (eg. if the refresh token is null because the user only passed\n * in an access token, eg. in a server-side request handler).\n */\n private _knownToBeInvalid = new Store<boolean>(false);\n\n private _refreshPromise: Promise<AccessToken | null> | null = null;\n\n constructor(private readonly _options: {\n refreshAccessTokenCallback(refreshToken: RefreshToken): Promise<AccessToken | null>,\n refreshToken: string | null,\n accessToken?: string | null,\n }) {\n this._accessToken = new Store(_options.accessToken ? new AccessToken(_options.accessToken) : null);\n this._refreshToken = _options.refreshToken ? new RefreshToken(_options.refreshToken) : null;\n if (_options.accessToken === null && _options.refreshToken === null) {\n // this session is already invalid\n this._knownToBeInvalid.set(true);\n }\n this.sessionKey = InternalSession.calculateSessionKey({ accessToken: _options.accessToken ?? null, refreshToken: _options.refreshToken });\n }\n\n static calculateSessionKey(ofTokens: { refreshToken: string | null, accessToken?: string | null }): string {\n if (ofTokens.refreshToken) {\n return `refresh-${ofTokens.refreshToken}`;\n } else if (ofTokens.accessToken) {\n return `access-${ofTokens.accessToken}`;\n } else {\n return \"not-logged-in\";\n }\n }\n\n isKnownToBeInvalid() {\n return this._knownToBeInvalid.get();\n }\n\n /**\n * Marks the session object as invalid, meaning that the refresh and access tokens can no longer be used.\n */\n markInvalid() {\n this._accessToken.set(null);\n this._knownToBeInvalid.set(true);\n }\n\n onInvalidate(callback: () => void): { unsubscribe: () => void } {\n return this._knownToBeInvalid.onChange(() => callback());\n }\n\n /**\n * Returns the access token if it is found in the cache, fetching it otherwise.\n *\n * This is usually the function you want to call to get an access token. Either set `minMillisUntilExpiration` to a reasonable value, or catch errors that occur if it expires, and call `markAccessTokenExpired` to mark the token as expired if so (after which a call to this function will always refetch the token).\n *\n * @returns null if the session is known to be invalid, cached tokens if they exist in the cache (which may or may not be valid still), or new tokens otherwise.\n */\n async getOrFetchLikelyValidTokens(minMillisUntilExpiration: number): Promise<{ accessToken: AccessToken, refreshToken: RefreshToken | null } | null> {\n if (minMillisUntilExpiration >= 60_000) {\n throw new Error(`Required access token expiry ${minMillisUntilExpiration}ms is too long; access tokens are too short to be used for more than 60s`);\n }\n\n const accessToken = this._getPotentiallyInvalidAccessTokenIfAvailable();\n if (!accessToken || accessToken.expiresInMillis < minMillisUntilExpiration) {\n const newTokens = await this.fetchNewTokens();\n const expiresInMillis = newTokens?.accessToken.expiresInMillis;\n if (expiresInMillis && expiresInMillis < minMillisUntilExpiration) {\n throw new StackAssertionError(`Required access token expiry ${minMillisUntilExpiration}ms is too long; access tokens are too short when they're generated (${expiresInMillis}ms)`);\n }\n return newTokens;\n }\n return { accessToken, refreshToken: this._refreshToken };\n }\n\n /**\n * Fetches new tokens that are, at the time of fetching, guaranteed to be valid.\n *\n * The newly generated tokens are short-lived, so it's good practice not to rely on their validity (if possible). However, this function is useful in some cases where you only want to pass access tokens to a service, and you want to make sure said access token has the longest possible lifetime.\n *\n * In most cases, you should prefer `getOrFetchLikelyValidTokens`.\n *\n * @returns null if the session is known to be invalid, or new tokens otherwise (which, at the time of fetching, are guaranteed to be valid).\n */\n async fetchNewTokens(): Promise<{ accessToken: AccessToken, refreshToken: RefreshToken | null } | null> {\n const accessToken = await this._getNewlyFetchedAccessToken();\n return accessToken ? { accessToken, refreshToken: this._refreshToken } : null;\n }\n\n markAccessTokenExpired(accessToken: AccessToken) {\n // TODO we don't need this anymore, since we now check the expiry by ourselves\n if (this._accessToken.get() === accessToken) {\n this._accessToken.set(null);\n }\n }\n\n /**\n * Note that a callback invocation with `null` does not mean the session has been invalidated; the access token may just have expired. Use `onInvalidate` to detect invalidation.\n */\n onAccessTokenChange(callback: (newAccessToken: AccessToken | null) => void): { unsubscribe: () => void } {\n return this._accessToken.onChange(callback);\n }\n\n /**\n * @returns An access token, which may be expired or expire soon, or null if it is known to be invalid.\n */\n private _getPotentiallyInvalidAccessTokenIfAvailable(): AccessToken | null {\n if (!this._refreshToken) return null;\n if (this.isKnownToBeInvalid()) return null;\n\n const accessToken = this._accessToken.get();\n if (accessToken && !accessToken.isExpired()) return accessToken;\n\n return null;\n }\n\n /**\n * You should prefer `_getOrFetchPotentiallyInvalidAccessToken` in almost all cases.\n *\n * @returns A newly fetched access token (never read from cache), or null if the session either does not represent a user or the session is invalid.\n */\n private async _getNewlyFetchedAccessToken(): Promise<AccessToken | null> {\n if (!this._refreshToken) return null;\n if (this._knownToBeInvalid.get()) return null;\n\n if (!this._refreshPromise) {\n this._refreshAndSetRefreshPromise(this._refreshToken);\n }\n return await this._refreshPromise;\n }\n\n private _refreshAndSetRefreshPromise(refreshToken: RefreshToken) {\n let refreshPromise: Promise<AccessToken | null> = this._options.refreshAccessTokenCallback(refreshToken).then((accessToken) => {\n if (refreshPromise === this._refreshPromise) {\n this._refreshPromise = null;\n this._accessToken.set(accessToken);\n if (!accessToken) {\n this.markInvalid();\n }\n }\n return accessToken;\n });\n this._refreshPromise = refreshPromise;\n }\n}\n"],"mappings":";AAAA,YAAY,UAAU;AACtB,SAAS,2BAA2B;AACpC,SAAS,aAAa;AAEf,IAAM,cAAN,MAAkB;AAAA,EACvB,YACkB,OAChB;AADgB;AAEhB,QAAI,UAAU,aAAa;AACzB,YAAM,IAAI,oBAAoB,sHAAsH;AAAA,IACtJ;AAAA,EACF;AAAA,EAEA,IAAI,UAAU;AACZ,WAAY,eAAU,KAAK,KAAK;AAAA,EAClC;AAAA,EAEA,IAAI,YAAkB;AACpB,UAAM,EAAE,IAAI,IAAI,KAAK;AACrB,QAAI,QAAQ,OAAW,QAAO,oBAAI,KAAK,MAAgB;AACvD,WAAO,IAAI,KAAK,MAAM,GAAI;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,kBAA0B;AAC5B,WAAO,KAAK,IAAI,GAAG,KAAK,UAAU,QAAQ,IAAI,KAAK,IAAI,CAAC;AAAA,EAC1D;AAAA,EAEA,YAAqB;AACnB,WAAO,KAAK,mBAAmB;AAAA,EACjC;AACF;AAEO,IAAM,eAAN,MAAmB;AAAA,EACxB,YACkB,OAChB;AADgB;AAEhB,QAAI,UAAU,aAAa;AACzB,YAAM,IAAI,oBAAoB,uHAAu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C,KAAK,SAAS,2BAA2B,YAAY,EAAE,KAAK,CAAC,gBAAgB;AAC7H,UAAI,mBAAmB,KAAK,iBAAiB;AAC3C,aAAK,kBAAkB;AACvB,aAAK,aAAa,IAAI,WAAW;AACjC,YAAI,CAAC,aAAa;AAChB,eAAK,YAAY;AAAA,QACnB;AAAA,MACF;AACA,aAAO;AAAA,IACT,CAAC;AACD,SAAK,kBAAkB;AAAA,EACzB;AACF;","names":[]}
@@ -0,0 +1,79 @@
1
+ // src/utils/api-keys.tsx
2
+ import crc32 from "crc/crc32";
3
+ import { getBase32CharacterFromIndex } from "./bytes";
4
+ import { generateSecureRandomString } from "./crypto";
5
+ import { StackAssertionError } from "./errors";
6
+ var STACK_AUTH_MARKER = "574ck4u7h";
7
+ var API_KEY_LENGTHS = {
8
+ SECRET_PART: 45,
9
+ ID_PART: 32,
10
+ TYPE_PART: 4,
11
+ SCANNER: 1,
12
+ MARKER: 9,
13
+ CHECKSUM: 8
14
+ };
15
+ function createChecksumSync(checksummablePart) {
16
+ const data = new TextEncoder().encode(checksummablePart);
17
+ const calculated_checksum = crc32(data);
18
+ return calculated_checksum.toString(16).padStart(8, "0");
19
+ }
20
+ function createApiKeyParts(options) {
21
+ const { id, isPublic, isCloudVersion, type } = options;
22
+ const prefix = isPublic ? "pk" : "sk";
23
+ const scannerFlag = (isCloudVersion ? 0 : 1) + (isPublic ? 2 : 0) + /* version */
24
+ 0;
25
+ const secretPart = generateSecureRandomString();
26
+ const idPart = id.replace(/-/g, "");
27
+ const scannerAndMarker = getBase32CharacterFromIndex(scannerFlag).toLowerCase() + STACK_AUTH_MARKER;
28
+ const checksummablePart = `${prefix}_${secretPart}${idPart}${type}${scannerAndMarker}`;
29
+ return { checksummablePart, idPart, prefix, scannerAndMarker, type };
30
+ }
31
+ function parseApiKeyParts(secret) {
32
+ const regex = new RegExp(
33
+ `^([a-zA-Z0-9_]+)_([a-zA-Z0-9_]{${API_KEY_LENGTHS.SECRET_PART}})([a-zA-Z0-9_]{${API_KEY_LENGTHS.ID_PART}})([a-zA-Z0-9_]{${API_KEY_LENGTHS.TYPE_PART}})([a-zA-Z0-9_]{${API_KEY_LENGTHS.SCANNER}})(${STACK_AUTH_MARKER})([a-zA-Z0-9_]{${API_KEY_LENGTHS.CHECKSUM}})$`
34
+ // checksum
35
+ );
36
+ const match = secret.match(regex);
37
+ if (!match) {
38
+ throw new StackAssertionError("Invalid API key format");
39
+ }
40
+ const [, prefix, secretPart, idPart, type, scannerFlag, marker, checksum] = match;
41
+ const isCloudVersion = parseInt(scannerFlag, 32) % 2 === 0;
42
+ const isPublic = (parseInt(scannerFlag, 32) & 2) !== 0;
43
+ const checksummablePart = `${prefix}_${secretPart}${idPart}${type}${scannerFlag}${marker}`;
44
+ const restored_id = idPart.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
45
+ if (!["user", "team"].includes(type)) {
46
+ throw new StackAssertionError("Invalid type");
47
+ }
48
+ return { checksummablePart, checksum, id: restored_id, isCloudVersion, isPublic, prefix, type };
49
+ }
50
+ function isApiKey(secret) {
51
+ return secret.includes("_") && secret.includes(STACK_AUTH_MARKER);
52
+ }
53
+ function createProjectApiKey(options) {
54
+ const { checksummablePart } = createApiKeyParts(options);
55
+ const checksum = createChecksumSync(checksummablePart);
56
+ return `${checksummablePart}${checksum}`;
57
+ }
58
+ function parseProjectApiKey(secret) {
59
+ const { checksummablePart, checksum, id, isCloudVersion, isPublic, prefix, type } = parseApiKeyParts(secret);
60
+ const calculated_checksum = createChecksumSync(checksummablePart);
61
+ if (calculated_checksum !== checksum) {
62
+ throw new StackAssertionError("Checksum mismatch");
63
+ }
64
+ return {
65
+ id,
66
+ prefix,
67
+ isPublic,
68
+ isCloudVersion,
69
+ secret,
70
+ checksum,
71
+ type
72
+ };
73
+ }
74
+ export {
75
+ createProjectApiKey,
76
+ isApiKey,
77
+ parseProjectApiKey
78
+ };
79
+ //# sourceMappingURL=api-keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/api-keys.tsx"],"sourcesContent":["import crc32 from 'crc/crc32';\nimport { getBase32CharacterFromIndex } from \"./bytes\";\nimport { generateSecureRandomString } from \"./crypto\";\nimport { StackAssertionError } from \"./errors\";\n\n\nconst STACK_AUTH_MARKER = \"574ck4u7h\";\n\n// API key part lengths\nconst API_KEY_LENGTHS = {\n SECRET_PART: 45,\n ID_PART: 32,\n TYPE_PART: 4,\n SCANNER: 1,\n MARKER: 9,\n CHECKSUM: 8,\n} as const;\n\n/**\n * An api key has the following format:\n * <prefix_without_underscores>_<secret_part_45_chars><id_part_32_chars><type_user_or_team_4_chars><scanner_and_marker_10_chars><checksum_8_chars>\n *\n * The scanner and marker is a base32 character that is used to determine if the api key is a public or private key\n * and if it is a cloud or self-hosted key.\n *\n * The checksum is a crc32 checksum of the api key encoded in hex.\n *\n */\n\ntype ProjectApiKey = {\n id: string,\n prefix: string,\n isPublic: boolean,\n isCloudVersion: boolean,\n secret: string,\n checksum: string,\n type: \"user\" | \"team\",\n}\n\n\nfunction createChecksumSync(checksummablePart: string): string {\n const data = new TextEncoder().encode(checksummablePart);\n const calculated_checksum = crc32(data);\n return calculated_checksum.toString(16).padStart(8, \"0\");\n}\n\nfunction createApiKeyParts(options: Pick<ProjectApiKey, \"id\" | \"isPublic\" | \"isCloudVersion\" | \"type\">) {\n const { id, isPublic, isCloudVersion, type } = options;\n const prefix = isPublic ? \"pk\" : \"sk\";\n const scannerFlag = (isCloudVersion ? 0 : 1) + (isPublic ? 2 : 0) + (/* version */ 0);\n\n const secretPart = generateSecureRandomString();\n const idPart = id.replace(/-/g, \"\");\n const scannerAndMarker = getBase32CharacterFromIndex(scannerFlag).toLowerCase() + STACK_AUTH_MARKER;\n const checksummablePart = `${prefix}_${secretPart}${idPart}${type}${scannerAndMarker}`;\n\n return { checksummablePart, idPart, prefix, scannerAndMarker, type };\n}\n\n\nfunction parseApiKeyParts(secret: string) {\n const regex = new RegExp(\n `^([a-zA-Z0-9_]+)_` + // prefix\n `([a-zA-Z0-9_]{${API_KEY_LENGTHS.SECRET_PART}})` + // secretPart\n `([a-zA-Z0-9_]{${API_KEY_LENGTHS.ID_PART}})` + // idPart\n `([a-zA-Z0-9_]{${API_KEY_LENGTHS.TYPE_PART}})` + // type\n `([a-zA-Z0-9_]{${API_KEY_LENGTHS.SCANNER}})` + // scanner\n `(${STACK_AUTH_MARKER})` + // marker\n `([a-zA-Z0-9_]{${API_KEY_LENGTHS.CHECKSUM}})$` // checksum\n );\n\n const match = secret.match(regex);\n if (!match) {\n throw new StackAssertionError(\"Invalid API key format\");\n }\n\n const [, prefix, secretPart, idPart, type, scannerFlag, marker, checksum] = match;\n\n const isCloudVersion = parseInt(scannerFlag, 32) % 2 === 0;\n const isPublic = (parseInt(scannerFlag, 32) & 2) !== 0;\n\n const checksummablePart = `${prefix}_${secretPart}${idPart}${type}${scannerFlag}${marker}`;\n const restored_id = idPart.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, \"$1-$2-$3-$4-$5\");\n\n if (![\"user\", \"team\"].includes(type)) {\n throw new StackAssertionError(\"Invalid type\");\n }\n\n return { checksummablePart, checksum, id: restored_id, isCloudVersion, isPublic, prefix, type: type as \"user\" | \"team\" };\n}\n\n\nexport function isApiKey(secret: string): boolean {\n return secret.includes(\"_\") && secret.includes(STACK_AUTH_MARKER);\n}\n\nexport function createProjectApiKey(options: Pick<ProjectApiKey, \"id\" | \"isPublic\" | \"isCloudVersion\" | \"type\">): string {\n const { checksummablePart } = createApiKeyParts(options);\n const checksum = createChecksumSync(checksummablePart);\n return `${checksummablePart}${checksum}`;\n}\n\n\nexport function parseProjectApiKey(secret: string): ProjectApiKey {\n const { checksummablePart, checksum, id, isCloudVersion, isPublic, prefix, type } = parseApiKeyParts(secret);\n const calculated_checksum = createChecksumSync(checksummablePart);\n\n if (calculated_checksum !== checksum) {\n throw new StackAssertionError(\"Checksum mismatch\");\n }\n\n return {\n id,\n prefix,\n isPublic,\n isCloud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C,EAAE,QAAQ,YAAY,QAAQ,MAAM,aAAa,QAAQ,QAAQ,IAAI;AAE5E,QAAM,iBAAiB,SAAS,aAAa,EAAE,IAAI,MAAM;AACzD,QAAM,YAAY,SAAS,aAAa,EAAE,IAAI,OAAO;AAErD,QAAM,oBAAoB,GAAG,MAAM,IAAI,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,WAAW,GAAG,MAAM;AACxF,QAAM,cAAc,OAAO,QAAQ,mCAAmC,gBAAgB;AAEtF,MAAI,CAAC,CAAC,QAAQ,MAAM,EAAE,SAAS,IAAI,GAAG;AACpC,UAAM,IAAI,oBAAoB,cAAc;AAAA,EAC9C;AAEA,SAAO,EAAE,mBAAmB,UAAU,IAAI,aAAa,gBAAgB,UAAU,QAAQ,KAA8B;AACzH;AAGO,SAAS,SAAS,QAAyB;AAChD,SAAO,OAAO,SAAS,GAAG,KAAK,OAAO,SAAS,iBAAiB;AAClE;AAEO,SAAS,oBAAoB,SAAqF;AACvH,QAAM,EAAE,kBAAkB,IAAI,kBAAkB,OAAO;AACvD,QAAM,WAAW,mBAAmB,iBAAiB;AACrD,SAAO,GAAG,iBAAiB,GAAG,QAAQ;AACxC;AAGO,SAAS,mBAAmB,QAA+B;AAChE,QAAM,EAAE,mBAAmB,UAAU,IAAI,gBAAgB,UAAU,QAAQ,KAAK,IAAI,iBAAiB,MAAM;AAC3G,QAAM,sBAAsB,mBAAmB,iBAAiB;AAEhE,MAAI,wBAAwB,UAAU;AACpC,UAAM,IAAI,oBAAoB,mBAAmB;AAAA,EACnD;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,78 @@
1
+ // src/utils/arrays.tsx
2
+ import { remainder } from "./math";
3
+ function typedIncludes(arr, item) {
4
+ return arr.includes(item);
5
+ }
6
+ function enumerate(arr) {
7
+ return arr.map((item, index) => [index, item]);
8
+ }
9
+ function isShallowEqual(a, b) {
10
+ if (a.length !== b.length) return false;
11
+ for (let i = 0; i < a.length; i++) {
12
+ if (a[i] !== b[i]) return false;
13
+ }
14
+ return true;
15
+ }
16
+ function findLastIndex(arr, predicate) {
17
+ for (let i = arr.length - 1; i >= 0; i--) {
18
+ if (predicate(arr[i])) return i;
19
+ }
20
+ return -1;
21
+ }
22
+ function groupBy(arr, key) {
23
+ const result = /* @__PURE__ */ new Map();
24
+ for (const item of arr) {
25
+ const k = key(item);
26
+ if (result.get(k) === void 0) result.set(k, []);
27
+ result.get(k).push(item);
28
+ }
29
+ return result;
30
+ }
31
+ function range(startInclusive, endExclusive, step) {
32
+ if (endExclusive === void 0) {
33
+ endExclusive = startInclusive;
34
+ startInclusive = 0;
35
+ }
36
+ if (step === void 0) step = 1;
37
+ const result = [];
38
+ for (let i = startInclusive; step > 0 ? i < endExclusive : i > endExclusive; i += step) {
39
+ result.push(i);
40
+ }
41
+ return result;
42
+ }
43
+ function rotateLeft(arr, n) {
44
+ if (arr.length === 0) return [];
45
+ const index = remainder(n, arr.length);
46
+ return [...arr.slice(index), ...arr.slice(0, index)];
47
+ }
48
+ function rotateRight(arr, n) {
49
+ return rotateLeft(arr, -n);
50
+ }
51
+ function shuffle(arr) {
52
+ const result = [...arr];
53
+ for (let i = result.length - 1; i > 0; i--) {
54
+ const j = Math.floor(Math.random() * (i + 1));
55
+ [result[i], result[j]] = [result[j], result[i]];
56
+ }
57
+ return result;
58
+ }
59
+ function outerProduct(arr1, arr2) {
60
+ return arr1.flatMap((item1) => arr2.map((item2) => [item1, item2]));
61
+ }
62
+ function unique(arr) {
63
+ return [...new Set(arr)];
64
+ }
65
+ export {
66
+ enumerate,
67
+ findLastIndex,
68
+ groupBy,
69
+ isShallowEqual,
70
+ outerProduct,
71
+ range,
72
+ rotateLeft,
73
+ rotateRight,
74
+ shuffle,
75
+ typedIncludes,
76
+ unique
77
+ };
78
+ //# sourceMappingURL=arrays.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/arrays.tsx"],"sourcesContent":["import { remainder } from \"./math\";\n\nexport function typedIncludes<T extends readonly any[]>(arr: T, item: unknown): item is T[number] {\n return arr.includes(item);\n}\nundefined?.test(\"typedIncludes\", ({ expect }) => {\n const arr = [1, 2, 3] as const;\n expect(typedIncludes(arr, 1)).toBe(true);\n expect(typedIncludes(arr, 4)).toBe(false);\n expect(typedIncludes(arr, \"1\")).toBe(false);\n\n const strArr = [\"a\", \"b\", \"c\"] as const;\n expect(typedIncludes(strArr, \"a\")).toBe(true);\n expect(typedIncludes(strArr, \"d\")).toBe(false);\n});\n\nexport function enumerate<T extends readonly any[]>(arr: T): [number, T[number]][] {\n return arr.map((item, index) => [index, item]);\n}\nundefined?.test(\"enumerate\", ({ expect }) => {\n expect(enumerate([])).toEqual([]);\n expect(enumerate([1, 2, 3])).toEqual([[0, 1], [1, 2], [2, 3]]);\n expect(enumerate([\"a\", \"b\", \"c\"])).toEqual([[0, \"a\"], [1, \"b\"], [2, \"c\"]]);\n});\n\nexport function isShallowEqual(a: readonly any[], b: readonly any[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\nundefined?.test(\"isShallowEqual\", ({ expect }) => {\n expect(isShallowEqual([], [])).toBe(true);\n expect(isShallowEqual([1, 2, 3], [1, 2, 3])).toBe(true);\n expect(isShallowEqual([1, 2, 3], [1, 2, 4])).toBe(false);\n expect(isShallowEqual([1, 2, 3], [1, 2])).toBe(false);\n expect(isShallowEqual([1, 2], [1, 2, 3])).toBe(false);\n // Test with objects (reference equality)\n const obj1 = { a: 1 };\n const obj2 = { a: 1 };\n expect(isShallowEqual([obj1], [obj1])).toBe(true);\n expect(isShallowEqual([obj1], [obj2])).toBe(false);\n});\n\n/**\n * Ponyfill for ES2023's findLastIndex.\n */\nexport function findLastIndex<T>(arr: readonly T[], predicate: (item: T) => boolean): number {\n for (let i = arr.length - 1; i >= 0; i--) {\n if (predicate(arr[i])) return i;\n }\n return -1;\n}\nundefined?.test(\"findLastIndex\", ({ expect }) => {\n expect(findLastIndex([], () => true)).toBe(-1);\n expect(findLastIndex([1, 2, 3, 4, 5], x => x % 2 === 0)).toBe(3); // 4 is at index 3\n expect(findLastIndex([1, 2, 3, 4, 5], x => x > 10)).toBe(-1);\n expect(findLastIndex([1, 2, 3, 2, 1], x => x === 2)).toBe(3);\n expect(findLastIndex([1, 2, 3], x => x === 1)).toBe(0);\n});\n\nexport function groupBy<T extends any, K>(\n arr: Iterable<T>,\n key: (item: T) => K,\n): Map<K, T[]> {\n const result = new Map<K, T[]>;\n for (const item of arr) {\n const k = key(item);\n if (result.get(k) === undefined) result.set(k, []);\n result.get(k)!.push(item);\n }\n return result;\n}\nundefined?.test(\"groupBy\", ({ expect }) => {\n expect(groupBy([], (x) => x)).toEqual(new Map());\n\n const numbers = [1, 2, 3, 4, 5, 6];\n const grouped = groupBy(numbers, (n) => n % 2 === 0 ? \"even\" : \"odd\");\n expect(grouped.get(\"even\")).toEqual([2, 4, 6]);\n expect(grouped.get(\"odd\")).toEqual([1, 3, 5]);\n\n // Check the actual lengths of the words to ensure our test is correct\n const words = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\"];\n\n const byLength = groupBy(words, (w) => w.length);\n // Adjust expectations based on actual word lengths\n expect(byLength.get(5)).toEqual([\"apple\"]);\n expect(byLength.get(6)).toEqual([\"banana\", \"cherry\"]);\n expect(byLength.get(4)).toEqual([\"date\"]);\n expect(byLength.get(10)).toEqual([\"elderberry\"]);\n});\n\nexport function range(endExclusive: number): number[];\nexport function range(startInclusive: number, endExclusive: number): number[];\nexport function range(startInclusive: number, endExclusive: number, step: number): number[];\nexport function range(startInclusive: number, endExclusive?: number, step?: number): number[] {\n if (endExclusive === undefined) {\n endExclusive = startInclusive;\n startInclusive = 0;\n }\n if (step === undefined) step = 1;\n\n const result = [];\n for (let i = startInclusive; step > 0 ? (i < endExclusive) : (i > endExclusive); i += step) {\n result.push(i);\n }\n return result;\n}\nundefined?.test(\"range\", ({ expect }) => {\n expect(range(5)).toEqual([0, 1, 2, 3, 4]);\n expect(range(2, 5)).toEqual([2, 3, 4]);\n expect(range(1, 10, 2)).toEqual([1, 3, 5, 7, 9]);\n expect(range(5, 0, -1)).toEqual([5, 4, 3, 2, 1]);\n expect(range(0, 0)).toEqual([]);\n expect(range(0, 10, 3)).toEqual([0, 3, 6, 9]);\n});\n\n\nexport function rotateLeft(arr: readonly any[], n: number): any[] {\n if (arr.length === 0) return [];\n const index = remainder(n, arr.length);\n return [...arr.slice(index), ...arr.slice(0, index)];\n}\nundefined?.test(\"rotateLeft\", ({ expect }) => {\n expect(rotateLeft([], 1)).toEqual([]);\n expect(rotateLeft([1, 2, 3, 4, 5], 0)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateLeft([1, 2, 3, 4, 5], 1)).toEqual([2, 3, 4, 5, 1]);\n expect(rotateLeft([1, 2, 3, 4, 5], 3)).toEqual([4, 5, 1, 2, 3]);\n expect(rotateLeft([1, 2, 3, 4, 5], 5)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateLeft([1, 2, 3, 4, 5], 6)).toEqual([2, 3, 4, 5, 1]);\n});\n\nexport function rotateRight(arr: readonly any[], n: number): any[] {\n return rotateLeft(arr, -n);\n}\nundefined?.test(\"rotateRight\", ({ expect }) => {\n expect(rotateRight([], 1)).toEqual([]);\n expect(rotateRight([1, 2, 3, 4, 5], 0)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateRight([1, 2, 3, 4, 5], 1)).toEqual([5, 1, 2, 3, 4]);\n expect(rotateRight([1, 2, 3, 4, 5], 3)).toEqual([3, 4, 5, 1, 2]);\n expect(rotateRight([1, 2, 3, 4, 5], 5)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateRight([1, 2, 3, 4, 5], 6)).toEqual([5, 1, 2, 3, 4]);\n});\n\n\nexport function shuffle<T>(arr: readonly T[]): T[] {\n const result = [...arr];\n for (let i = result.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [result[i], result[j]] = [result[j], result[i]];\n }\n return result;\n}\nundefined?.test(\"shuffle\", ({ expect }) => {\n // Test empty array\n expect(shuffle([])).toEqual([]);\n\n // Test single element array\n expect(shuffle([1])).toEqual([1]);\n\n // Test that shuffle returns a new array\n const original = [1, 2, 3, 4, 5];\n const shuffled = shuffle(original);\n expect(shuffled).not.toBe(original);\n\n // Test that all elements are preserved\n expect(shuffled.sort((a, b) => a - b)).toEqual(original);\n\n // Test with a larger array to ensure randomness\n // This is a probabilistic test, but it's very unlikely to fail\n const large = Array.from({ length: 100 }, (_, i) => i);\n const shuffledLarge = shuffle(large);\n expect(shuffledLarge).not.toEqual(large);\n expect(shuffledLarge.sort((a, b) => a - b)).toEqual(large);\n});\n\n\nexport function outerProduct<T, U>(arr1: readonly T[], arr2: readonly U[]): [T, U][] {\n return arr1.flatMap((item1) => arr2.map((item2) => [item1, item2] as [T, U]));\n}\nundefined?.test(\"outerProduct\", ({ expect }) => {\n expect(outerProduct([], [])).toEqual([]);\n expect(outerProduct([1], [])).toEqual([]);\n expect(outerProduct([], [1])).toEqual([]);\n expect(outerProduct([1], [2])).toEqual([[1, 2]]);\n expect(outerProduct([1, 2], [3, 4])).toEqual([[1, 3], [1, 4], [2, 3], [2, 4]]);\n expect(outerProduct([\"a\", \"b\"], [1, 2])).toEqual([[\"a\", 1], [\"a\", 2], [\"b\", 1], [\"b\", 2]]);\n});\n\nexport function unique<T>(arr: readonly T[]): T[] {\n return [...new Set(arr)];\n}\nundefined?.test(\"unique\", ({ expect }) => {\n expect(unique([])).toEqual([]);\n expect(unique([1, 2, 3])).toEqual([1, 2, 3]);\n expect(unique([1, 2, 2, 3, 1, 3])).toEqual([1, 2, 3]);\n // Test with objects (reference equality)\n const obj = { a: 1 };\n expect(unique([obj, obj])).toEqual([obj]);\n // Test with different types\n expect(unique([1, \"1\", true, 1, \"1\", true])).toEqual([1, \"1\", true]);\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I,MAAM;AACrC,SAAO,CAAC,GAAG,IAAI,MAAM,KAAK,GAAG,GAAG,IAAI,MAAM,GAAG,KAAK,CAAC;AACrD;AAUO,SAAS,YAAY,KAAqB,GAAkB;AACjE,SAAO,WAAW,KAAK,CAAC,CAAC;AAC3B;AAWO,SAAS,QAAW,KAAwB;AACjD,QAAM,SAAS,CAAC,GAAG,GAAG;AACtB,WAAS,IAAI,OAAO,SAAS,GAAG,IAAI,GAAG,KAAK;AAC1C,UAAM,IAAI,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,EAAE;AAC5C,KAAC,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;AAAA,EAChD;AACA,SAAO;AACT;AAyBO,SAAS,aAAmB,MAAoB,MAA8B;AACnF,SAAO,KAAK,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,CAAC,OAAO,KAAK,CAAW,CAAC;AAC9E;AAUO,SAAS,OAAU,KAAwB;AAChD,SAAO,CAAC,GAAG,IAAI,IAAI,GAAG,CAAC;AACzB;","names":[]}
@@ -0,0 +1,18 @@
1
+ // src/utils/base64.tsx
2
+ function fileToBase64(file) {
3
+ return new Promise((resolve, reject) => {
4
+ const reader = new FileReader();
5
+ reader.readAsDataURL(file);
6
+ reader.onload = () => resolve(reader.result);
7
+ reader.onerror = (error) => reject(error);
8
+ });
9
+ }
10
+ function validateBase64Image(base64) {
11
+ const base64ImageRegex = /^data:image\/(png|jpg|jpeg|gif|bmp|webp);base64,[A-Za-z0-9+/]+={0,2}$|^[A-Za-z0-9+/]+={0,2}$/;
12
+ return base64ImageRegex.test(base64);
13
+ }
14
+ export {
15
+ fileToBase64,
16
+ validateBase64Image
17
+ };
18
+ //# sourceMappingURL=base64.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/base64.tsx"],"sourcesContent":["export function fileToBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.readAsDataURL(file);\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = error => reject(error);\n });\n}\n\nexport function validateBase64Image(base64: string): boolean {\n const base64ImageRegex = /^data:image\\/(png|jpg|jpeg|gif|bmp|webp);base64,[A-Za-z0-9+/]+={0,2}$|^[A-Za-z0-9+/]+={0,2}$/;\n return base64ImageRegex.test(base64);\n}\nundefined?.test(\"validateBase64Image\", ({ expect }) => {\n // Valid base64 image strings\n expect(validateBase64Image(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==\")).toBe(true);\n expect(validateBase64Image(\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBA\")).toBe(true);\n expect(validateBase64Image(\"ABC123\")).toBe(true);\n // Invalid base64 image strings\n expect(validateBase64Image(\"data:text/plain;base64,SGVsbG8gV29ybGQ=\")).toBe(false);\n expect(validateBase64Image(\"data:image/png;base64,invalid!base64\")).toBe(false);\n expect(validateBase64Image(\"not a base64 string\")).toBe(false);\n expect(validateBase64Image(\"\")).toBe(false);\n});\n"],"mappings":";AAAO,SAAS,aAAa,MAA6B;AACxD,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,SAAS,IAAI,WAAW;AAC9B,WAAO,cAAc,IAAI;AACzB,WAAO,SAAS,MAAM,QAAQ,OAAO,MAAgB;AACrD,WAAO,UAAU,WAAS,OAAO,KAAK;AAAA,EACxC,CAAC;AACH;AAEO,SAAS,oBAAoB,QAAyB;AAC3D,QAAM,mBAAmB;AACzB,SAAO,iBAAiB,KAAK,MAAM;AACrC;","names":[]}
@@ -0,0 +1,12 @@
1
+ // src/utils/booleans.tsx
2
+ function isTruthy(value) {
3
+ return !!value;
4
+ }
5
+ function isFalsy(value) {
6
+ return !value;
7
+ }
8
+ export {
9
+ isFalsy,
10
+ isTruthy
11
+ };
12
+ //# sourceMappingURL=booleans.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/booleans.tsx"],"sourcesContent":["export type Truthy<T> = T extends null | undefined | 0 | \"\" | false ? false : true;\nexport type Falsy<T> = T extends null | undefined | 0 | \"\" | false ? true : false;\n\nexport function isTruthy<T>(value: T): value is T & Truthy<T> {\n return !!value;\n}\nundefined?.test(\"isTruthy\", ({ expect }) => {\n expect(isTruthy(true)).toBe(true);\n expect(isTruthy(1)).toBe(true);\n expect(isTruthy(\"hello\")).toBe(true);\n expect(isTruthy({})).toBe(true);\n expect(isTruthy([])).toBe(true);\n expect(isTruthy(false)).toBe(false);\n expect(isTruthy(0)).toBe(false);\n expect(isTruthy(\"\")).toBe(false);\n expect(isTruthy(null)).toBe(false);\n expect(isTruthy(undefined)).toBe(false);\n});\n\nexport function isFalsy<T>(value: T): value is T & Falsy<T> {\n return !value;\n}\nundefined?.test(\"isFalsy\", ({ expect }) => {\n expect(isFalsy(false)).toBe(true);\n expect(isFalsy(0)).toBe(true);\n expect(isFalsy(\"\")).toBe(true);\n expect(isFalsy(null)).toBe(true);\n expect(isFalsy(undefined)).toBe(true);\n expect(isFalsy(true)).toBe(false);\n expect(isFalsy(1)).toBe(false);\n expect(isFalsy(\"hello\")).toBe(false);\n expect(isFalsy({})).toBe(false);\n expect(isFalsy([])).toBe(false);\n});\n"],"mappings":";AAGO,SAAS,SAAY,OAAkC;AAC5D,SAAO,CAAC,CAAC;AACX;AAcO,SAAS,QAAW,OAAiC;AAC1D,SAAO,CAAC;AACV;","names":[]}
@@ -0,0 +1,21 @@
1
+ // src/utils/browser-compat.tsx
2
+ function getBrowserCompatibilityReport() {
3
+ const test = (snippet) => {
4
+ try {
5
+ (0, eval)(snippet);
6
+ return true;
7
+ } catch (e) {
8
+ return `FAILED: ${e}`;
9
+ }
10
+ };
11
+ return {
12
+ optionalChaining: test("({})?.b?.c"),
13
+ nullishCoalescing: test("0 ?? 1"),
14
+ weakRef: test("new WeakRef({})"),
15
+ cryptoUuid: test("crypto.randomUUID()")
16
+ };
17
+ }
18
+ export {
19
+ getBrowserCompatibilityReport
20
+ };
21
+ //# sourceMappingURL=browser-compat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/browser-compat.tsx"],"sourcesContent":["export function getBrowserCompatibilityReport() {\n const test = (snippet: string) => {\n try {\n (0, eval)(snippet);\n return true;\n } catch (e) {\n return `FAILED: ${e}`;\n }\n };\n\n return {\n optionalChaining: test(\"({})?.b?.c\"),\n nullishCoalescing: test(\"0 ?? 1\"),\n weakRef: test(\"new WeakRef({})\"),\n cryptoUuid: test(\"crypto.randomUUID()\"),\n };\n}\n"],"mappings":";AAAO,SAAS,gCAAgC;AAC9C,QAAM,OAAO,CAAC,YAAoB;AAChC,QAAI;AACF,OAAC,GAAG,MAAM,OAAO;AACjB,aAAO;AAAA,IACT,SAAS,GAAG;AACV,aAAO,WAAW,CAAC;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,kBAAkB,KAAK,YAAY;AAAA,IACnC,mBAAmB,KAAK,QAAQ;AAAA,IAChC,SAAS,KAAK,iBAAiB;AAAA,IAC/B,YAAY,KAAK,qBAAqB;AAAA,EACxC;AACF;","names":[]}