@stackframe/stack 2.3.4 → 2.3.7

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 (262) hide show
  1. package/README.md +2 -2
  2. package/dist/components/card-frame.d.mts +9 -0
  3. package/dist/components/card-frame.d.ts +8 -5
  4. package/dist/components/card-frame.js +58 -23
  5. package/dist/components/credential-sign-in.d.mts +5 -0
  6. package/dist/components/credential-sign-in.d.ts +5 -1
  7. package/dist/components/credential-sign-in.js +109 -41
  8. package/dist/components/credential-sign-up.d.mts +5 -0
  9. package/dist/components/credential-sign-up.d.ts +5 -1
  10. package/dist/components/credential-sign-up.js +140 -62
  11. package/dist/components/forgot-password.d.mts +7 -0
  12. package/dist/components/forgot-password.d.ts +6 -2
  13. package/dist/components/forgot-password.js +83 -26
  14. package/dist/components/form-warning.d.mts +7 -0
  15. package/dist/components/form-warning.d.ts +6 -2
  16. package/dist/components/form-warning.js +34 -8
  17. package/dist/components/magic-link-sign-in.d.mts +5 -0
  18. package/dist/components/magic-link-sign-in.d.ts +5 -1
  19. package/dist/components/magic-link-sign-in.js +89 -31
  20. package/dist/components/message-card.d.mts +10 -0
  21. package/dist/components/message-card.d.ts +8 -4
  22. package/dist/components/message-card.js +45 -6
  23. package/dist/components/oauth-button.d.mts +8 -0
  24. package/dist/components/oauth-button.d.ts +6 -2
  25. package/dist/components/oauth-button.js +142 -63
  26. package/dist/components/oauth-group.d.mts +7 -0
  27. package/dist/components/oauth-group.d.ts +6 -2
  28. package/dist/components/oauth-group.js +46 -8
  29. package/dist/components/password-field.d.mts +5 -0
  30. package/dist/components/password-field.d.ts +5 -3
  31. package/dist/components/password-field.js +111 -41
  32. package/dist/components/password-reset-inner.d.mts +8 -0
  33. package/dist/components/password-reset-inner.d.ts +6 -2
  34. package/dist/components/password-reset-inner.js +120 -58
  35. package/dist/components/redirect-message-card.d.mts +8 -0
  36. package/dist/components/redirect-message-card.d.ts +6 -2
  37. package/dist/components/redirect-message-card.js +110 -58
  38. package/dist/components/separator-with-text.d.mts +7 -0
  39. package/dist/components/separator-with-text.d.ts +6 -2
  40. package/dist/components/separator-with-text.js +35 -5
  41. package/dist/components/user-avatar.d.mts +13 -0
  42. package/dist/components/user-avatar.d.ts +12 -2
  43. package/dist/components/user-avatar.js +34 -8
  44. package/dist/components/user-button.d.mts +15 -0
  45. package/dist/components/user-button.d.ts +14 -3
  46. package/dist/components/user-button.js +160 -24
  47. package/dist/components-core/avatar.d.mts +8 -0
  48. package/dist/components-core/avatar.d.ts +7 -5
  49. package/dist/components-core/avatar.js +73 -18
  50. package/dist/components-core/button.d.mts +12 -0
  51. package/dist/components-core/button.d.ts +8 -6
  52. package/dist/components-core/button.js +177 -113
  53. package/dist/components-core/card.d.mts +8 -0
  54. package/dist/components-core/card.d.ts +4 -2
  55. package/dist/components-core/card.js +73 -22
  56. package/dist/components-core/collapsible.d.mts +8 -0
  57. package/dist/components-core/collapsible.d.ts +8 -6
  58. package/dist/components-core/collapsible.js +48 -5
  59. package/dist/components-core/container.d.mts +8 -0
  60. package/dist/components-core/container.d.ts +5 -3
  61. package/dist/components-core/container.js +61 -11
  62. package/dist/components-core/dropdown.d.mts +15 -0
  63. package/dist/components-core/dropdown.d.ts +10 -8
  64. package/dist/components-core/dropdown.js +108 -36
  65. package/dist/components-core/index.d.mts +59 -0
  66. package/dist/components-core/index.d.ts +52 -38
  67. package/dist/components-core/index.js +144 -45
  68. package/dist/components-core/input.d.mts +6 -0
  69. package/dist/components-core/input.d.ts +5 -3
  70. package/dist/components-core/input.js +97 -28
  71. package/dist/components-core/label.d.mts +6 -0
  72. package/dist/components-core/label.d.ts +5 -3
  73. package/dist/components-core/label.js +65 -15
  74. package/dist/components-core/link.d.mts +10 -0
  75. package/dist/components-core/link.d.ts +7 -6
  76. package/dist/components-core/link.js +72 -18
  77. package/dist/components-core/loading-indicator.d.mts +13 -0
  78. package/dist/components-core/loading-indicator.d.ts +11 -4
  79. package/dist/components-core/loading-indicator.js +46 -6
  80. package/dist/components-core/popover.d.mts +8 -0
  81. package/dist/components-core/popover.d.ts +8 -6
  82. package/dist/components-core/popover.js +72 -16
  83. package/dist/components-core/separator.d.mts +6 -0
  84. package/dist/components-core/separator.d.ts +5 -3
  85. package/dist/components-core/separator.js +66 -16
  86. package/dist/components-core/skeleton.d.mts +7 -0
  87. package/dist/components-core/skeleton.d.ts +7 -0
  88. package/dist/components-core/skeleton.js +86 -0
  89. package/dist/components-core/tabs.d.mts +9 -0
  90. package/dist/components-core/tabs.d.ts +8 -6
  91. package/dist/components-core/tabs.js +87 -20
  92. package/dist/components-core/text.d.mts +10 -0
  93. package/dist/components-core/text.d.ts +5 -3
  94. package/dist/components-core/text.js +95 -40
  95. package/dist/components-core-joy/button.d.mts +6 -0
  96. package/dist/components-core-joy/button.d.ts +6 -2
  97. package/dist/components-core-joy/button.js +86 -28
  98. package/dist/components-core-joy/input.d.mts +5 -0
  99. package/dist/components-core-joy/input.d.ts +5 -2
  100. package/dist/components-core-joy/input.js +51 -6
  101. package/dist/components-core-joy/separator.d.mts +6 -0
  102. package/dist/components-core-joy/separator.d.ts +6 -2
  103. package/dist/components-core-joy/separator.js +50 -6
  104. package/dist/components-core-joy/tabs.d.mts +9 -0
  105. package/dist/components-core-joy/tabs.d.ts +9 -5
  106. package/dist/components-core-joy/tabs.js +62 -16
  107. package/dist/components-core-joy/text.d.mts +9 -0
  108. package/dist/components-core-joy/text.d.ts +6 -3
  109. package/dist/components-core-joy/text.js +68 -28
  110. package/dist/components-page/account-settings.d.mts +7 -0
  111. package/dist/components-page/account-settings.d.ts +6 -2
  112. package/dist/components-page/account-settings.js +213 -81
  113. package/dist/components-page/auth-page.d.mts +8 -0
  114. package/dist/components-page/auth-page.d.ts +6 -2
  115. package/dist/components-page/auth-page.js +79 -19
  116. package/dist/components-page/email-verification.d.mts +8 -0
  117. package/dist/components-page/email-verification.d.ts +6 -2
  118. package/dist/components-page/email-verification.js +65 -28
  119. package/dist/components-page/forgot-password.d.mts +7 -0
  120. package/dist/components-page/forgot-password.d.ts +6 -2
  121. package/dist/components-page/forgot-password.js +64 -20
  122. package/dist/components-page/magic-link-callback.d.mts +8 -0
  123. package/dist/components-page/magic-link-callback.d.ts +6 -2
  124. package/dist/components-page/magic-link-callback.js +72 -34
  125. package/dist/components-page/oauth-callback.d.mts +5 -0
  126. package/dist/components-page/oauth-callback.d.ts +5 -1
  127. package/dist/components-page/oauth-callback.js +52 -16
  128. package/dist/components-page/password-reset.d.mts +8 -0
  129. package/dist/components-page/password-reset.d.ts +6 -2
  130. package/dist/components-page/password-reset.js +70 -34
  131. package/dist/components-page/sign-in.d.mts +7 -0
  132. package/dist/components-page/sign-in.d.ts +6 -2
  133. package/dist/components-page/sign-in.js +41 -5
  134. package/dist/components-page/sign-out.d.mts +5 -0
  135. package/dist/components-page/sign-out.d.ts +5 -1
  136. package/dist/components-page/sign-out.js +47 -11
  137. package/dist/components-page/sign-up.d.mts +7 -0
  138. package/dist/components-page/sign-up.d.ts +6 -2
  139. package/dist/components-page/sign-up.js +41 -5
  140. package/dist/components-page/stack-handler.d.mts +16 -0
  141. package/dist/components-page/stack-handler.d.ts +11 -3
  142. package/dist/components-page/stack-handler.js +102 -64
  143. package/dist/esm/components/card-frame.js +39 -0
  144. package/dist/esm/components/credential-sign-in.js +82 -0
  145. package/dist/esm/components/credential-sign-up.js +114 -0
  146. package/dist/esm/components/forgot-password.js +55 -0
  147. package/dist/esm/components/form-warning.js +15 -0
  148. package/dist/esm/components/magic-link-sign-in.js +61 -0
  149. package/dist/esm/components/message-card.js +16 -0
  150. package/dist/esm/components/oauth-button.js +124 -0
  151. package/dist/esm/components/oauth-group.js +17 -0
  152. package/dist/esm/components/password-field.js +82 -0
  153. package/dist/esm/components/password-reset-inner.js +93 -0
  154. package/dist/esm/components/redirect-message-card.js +83 -0
  155. package/dist/esm/components/separator-with-text.js +16 -0
  156. package/dist/esm/components/user-avatar.js +14 -0
  157. package/dist/esm/components/user-button.js +133 -0
  158. package/dist/esm/components-core/avatar.js +56 -0
  159. package/dist/esm/components-core/button.js +165 -0
  160. package/dist/esm/components-core/card.js +51 -0
  161. package/dist/esm/components-core/collapsible.js +13 -0
  162. package/dist/esm/components-core/container.js +35 -0
  163. package/dist/esm/components-core/dropdown.js +106 -0
  164. package/dist/esm/components-core/index.js +93 -0
  165. package/dist/esm/components-core/input.js +80 -0
  166. package/dist/esm/components-core/label.js +38 -0
  167. package/dist/esm/components-core/link.js +38 -0
  168. package/dist/esm/components-core/loading-indicator.js +27 -0
  169. package/dist/esm/components-core/popover.js +43 -0
  170. package/dist/esm/components-core/separator.js +36 -0
  171. package/dist/esm/components-core/skeleton.js +52 -0
  172. package/dist/esm/components-core/tabs.js +79 -0
  173. package/dist/esm/components-core/text.js +63 -0
  174. package/dist/esm/components-core-joy/button.js +53 -0
  175. package/dist/esm/components-core-joy/input.js +18 -0
  176. package/dist/esm/components-core-joy/separator.js +17 -0
  177. package/dist/esm/components-core-joy/tabs.js +29 -0
  178. package/dist/esm/components-core-joy/text.js +35 -0
  179. package/dist/esm/components-page/account-settings.js +197 -0
  180. package/dist/esm/components-page/auth-page.js +50 -0
  181. package/dist/esm/components-page/email-verification.js +36 -0
  182. package/dist/esm/components-page/forgot-password.js +35 -0
  183. package/dist/esm/components-page/magic-link-callback.js +43 -0
  184. package/dist/esm/components-page/oauth-callback.js +23 -0
  185. package/dist/esm/components-page/password-reset.js +42 -0
  186. package/dist/esm/components-page/sign-in.js +12 -0
  187. package/dist/esm/components-page/sign-out.js +18 -0
  188. package/dist/esm/components-page/sign-up.js +12 -0
  189. package/dist/esm/components-page/stack-handler.js +75 -0
  190. package/dist/esm/index.js +47 -0
  191. package/dist/esm/joy.js +5 -0
  192. package/dist/esm/lib/auth.js +62 -0
  193. package/dist/esm/lib/cookie.js +185 -0
  194. package/dist/esm/lib/hooks.js +29 -0
  195. package/dist/esm/lib/stack-app.js +940 -0
  196. package/dist/esm/providers/component-provider.js +76 -0
  197. package/dist/esm/providers/design-provider.js +36 -0
  198. package/dist/esm/providers/joy-provider.js +35 -0
  199. package/dist/esm/providers/stack-provider-client.js +31 -0
  200. package/dist/esm/providers/stack-provider.js +21 -0
  201. package/dist/esm/providers/styled-components-registry.js +24 -0
  202. package/dist/esm/providers/theme-provider.js +22 -0
  203. package/dist/esm/utils/browser-script.js +25 -0
  204. package/dist/esm/utils/constants.js +34 -0
  205. package/dist/esm/utils/email.js +10 -0
  206. package/dist/esm/utils/next.js +7 -0
  207. package/dist/esm/utils/url.js +21 -0
  208. package/dist/index.d.mts +37 -0
  209. package/dist/index.d.ts +37 -22
  210. package/dist/index.js +106 -21
  211. package/dist/joy.d.mts +16 -0
  212. package/dist/joy.d.ts +16 -1
  213. package/dist/joy.js +30 -1
  214. package/dist/lib/auth.d.mts +11 -0
  215. package/dist/lib/auth.d.ts +8 -4
  216. package/dist/lib/auth.js +83 -57
  217. package/dist/lib/cookie.d.mts +14 -0
  218. package/dist/lib/cookie.d.ts +8 -6
  219. package/dist/lib/cookie.js +217 -45
  220. package/dist/lib/hooks.d.mts +35 -0
  221. package/dist/lib/hooks.d.ts +14 -8
  222. package/dist/lib/hooks.js +53 -28
  223. package/dist/lib/stack-app.d.mts +227 -0
  224. package/dist/lib/stack-app.d.ts +45 -44
  225. package/dist/lib/stack-app.js +937 -861
  226. package/dist/providers/component-provider.d.mts +113 -0
  227. package/dist/providers/component-provider.d.ts +97 -73
  228. package/dist/providers/component-provider.js +92 -56
  229. package/dist/providers/design-provider.d.mts +34 -0
  230. package/dist/providers/design-provider.d.ts +16 -21
  231. package/dist/providers/design-provider.js +57 -64
  232. package/dist/providers/joy-provider.d.mts +36 -0
  233. package/dist/providers/joy-provider.d.ts +30 -14
  234. package/dist/providers/joy-provider.js +58 -30
  235. package/dist/providers/stack-provider-client.d.mts +20 -0
  236. package/dist/providers/stack-provider-client.d.ts +18 -7
  237. package/dist/providers/stack-provider-client.js +65 -12
  238. package/dist/providers/stack-provider.d.mts +14 -0
  239. package/dist/providers/stack-provider.d.ts +13 -5
  240. package/dist/providers/stack-provider.js +41 -5
  241. package/dist/providers/styled-components-registry.d.mts +8 -0
  242. package/dist/providers/styled-components-registry.d.ts +8 -4
  243. package/dist/providers/styled-components-registry.js +43 -17
  244. package/dist/providers/theme-provider.d.mts +22 -0
  245. package/dist/providers/theme-provider.d.ts +21 -9
  246. package/dist/providers/theme-provider.js +55 -19
  247. package/dist/utils/browser-script.d.mts +5 -0
  248. package/dist/utils/browser-script.d.ts +5 -0
  249. package/dist/utils/browser-script.js +50 -0
  250. package/dist/utils/constants.d.mts +48 -0
  251. package/dist/utils/constants.d.ts +11 -9
  252. package/dist/utils/constants.js +66 -21
  253. package/dist/utils/email.d.mts +3 -0
  254. package/dist/utils/email.d.ts +3 -1
  255. package/dist/utils/email.js +44 -6
  256. package/dist/utils/next.d.mts +3 -0
  257. package/dist/utils/next.d.ts +3 -1
  258. package/dist/utils/next.js +31 -3
  259. package/dist/utils/url.d.mts +4 -0
  260. package/dist/utils/url.d.ts +4 -2
  261. package/dist/utils/url.js +44 -13
  262. package/package.json +20 -11
@@ -1,902 +1,978 @@
1
- import React, { use, useCallback, useMemo } from "react";
2
- import { KnownError, StackAdminInterface, StackClientInterface, StackServerInterface } from "@stackframe/stack-shared";
3
- import { getCookie, setOrDeleteCookie } from "./cookie";
4
- import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
5
- import { generateUuid } from "@stackframe/stack-shared/dist/utils/uuids";
6
- import { AsyncResult, Result } from "@stackframe/stack-shared/dist/utils/results";
7
- import { suspendIfSsr } from "@stackframe/stack-shared/dist/utils/react";
8
- import { AsyncStore } from "@stackframe/stack-shared/dist/utils/stores";
9
- import { getProductionModeErrors } from "@stackframe/stack-shared/dist/interface/clientInterface";
10
- import { isClient } from "../utils/next";
11
- import { callOAuthCallback, signInWithOAuth } from "./auth";
12
- import { RedirectType, redirect, useRouter } from "next/navigation";
13
- import { constructRedirectUrl } from "../utils/url";
14
- import { filterUndefined, omit } from "@stackframe/stack-shared/dist/utils/objects";
15
- import { neverResolve, resolved, runAsynchronously } from "@stackframe/stack-shared/dist/utils/promises";
16
- import { AsyncCache } from "@stackframe/stack-shared/dist/utils/caches";
17
- import { suspend } from "@stackframe/stack-shared/dist/utils/react";
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/lib/stack-app.ts
31
+ var stack_app_exports = {};
32
+ __export(stack_app_exports, {
33
+ StackAdminApp: () => StackAdminApp,
34
+ StackClientApp: () => StackClientApp,
35
+ StackServerApp: () => StackServerApp,
36
+ stackAppInternalsSymbol: () => stackAppInternalsSymbol
37
+ });
38
+ module.exports = __toCommonJS(stack_app_exports);
39
+ var import_react = __toESM(require("react"));
40
+ var import_stack_shared = require("@stackframe/stack-shared");
41
+ var import_cookie = require("./cookie");
42
+ var import_errors = require("@stackframe/stack-shared/dist/utils/errors");
43
+ var import_uuids = require("@stackframe/stack-shared/dist/utils/uuids");
44
+ var import_results = require("@stackframe/stack-shared/dist/utils/results");
45
+ var import_react2 = require("@stackframe/stack-shared/dist/utils/react");
46
+ var import_stores = require("@stackframe/stack-shared/dist/utils/stores");
47
+ var import_clientInterface = require("@stackframe/stack-shared/dist/interface/clientInterface");
48
+ var import_next = require("../utils/next");
49
+ var import_auth = require("./auth");
50
+ var NextNavigation = __toESM(require("next/navigation"));
51
+ var import_url = require("../utils/url");
52
+ var import_objects = require("@stackframe/stack-shared/dist/utils/objects");
53
+ var import_promises = require("@stackframe/stack-shared/dist/utils/promises");
54
+ var import_caches = require("@stackframe/stack-shared/dist/utils/caches");
55
+ var import_react3 = require("@stackframe/stack-shared/dist/utils/react");
18
56
  function getUrls(partial) {
19
- const handler = partial.handler ?? "/handler";
20
- return {
21
- handler,
22
- signIn: `${handler}/signin`,
23
- afterSignIn: "/",
24
- signUp: `${handler}/signup`,
25
- afterSignUp: "/",
26
- signOut: `${handler}/signout`,
27
- afterSignOut: "/",
28
- emailVerification: `${handler}/email-verification`,
29
- passwordReset: `${handler}/password-reset`,
30
- forgotPassword: `${handler}/forgot-password`,
31
- oauthCallback: `${handler}/oauth-callback`,
32
- magicLinkCallback: `${handler}/magic-link-callback`,
33
- home: "/",
34
- accountSettings: `${handler}/account-settings`,
35
- ...filterUndefined(partial),
36
- };
57
+ const handler = partial.handler ?? "/handler";
58
+ return {
59
+ handler,
60
+ signIn: `${handler}/signin`,
61
+ afterSignIn: "/",
62
+ signUp: `${handler}/signup`,
63
+ afterSignUp: "/",
64
+ signOut: `${handler}/signout`,
65
+ afterSignOut: "/",
66
+ emailVerification: `${handler}/email-verification`,
67
+ passwordReset: `${handler}/password-reset`,
68
+ forgotPassword: `${handler}/forgot-password`,
69
+ oauthCallback: `${handler}/oauth-callback`,
70
+ magicLinkCallback: `${handler}/magic-link-callback`,
71
+ home: "/",
72
+ accountSettings: `${handler}/account-settings`,
73
+ ...(0, import_objects.filterUndefined)(partial)
74
+ };
37
75
  }
38
76
  function getDefaultProjectId() {
39
- return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || throwErr("Welcome to Stack! It seems that you haven't provided a project ID. Please create a project on the Stack dashboard at https://app.stack-auth.com and put it in the NEXT_PUBLIC_STACK_PROJECT_ID environment variable.");
77
+ return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || (0, import_errors.throwErr)("Welcome to Stack! It seems that you haven't provided a project ID. Please create a project on the Stack dashboard at https://app.stack-auth.com and put it in the NEXT_PUBLIC_STACK_PROJECT_ID environment variable.");
40
78
  }
41
79
  function getDefaultPublishableClientKey() {
42
- return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || throwErr("Welcome to Stack! It seems that you haven't provided a publishable client key. Please create an API key for your project on the Stack dashboard at https://app.stack-auth.com and copy your publishable client key into the NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY environment variable.");
80
+ return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || (0, import_errors.throwErr)("Welcome to Stack! It seems that you haven't provided a publishable client key. Please create an API key for your project on the Stack dashboard at https://app.stack-auth.com and copy your publishable client key into the NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY environment variable.");
43
81
  }
44
82
  function getDefaultSecretServerKey() {
45
- return process.env.STACK_SECRET_SERVER_KEY || throwErr("No secret server key provided. Please copy your publishable client key from the Stack dashboard and put your it in the STACK_SECRET_SERVER_KEY environment variable.");
83
+ return process.env.STACK_SECRET_SERVER_KEY || (0, import_errors.throwErr)("No secret server key provided. Please copy your publishable client key from the Stack dashboard and put your it in the STACK_SECRET_SERVER_KEY environment variable.");
46
84
  }
47
85
  function getDefaultSuperSecretAdminKey() {
48
- return process.env.STACK_SUPER_SECRET_ADMIN_KEY || throwErr("No super secret admin key provided. Please copy your publishable client key from the Stack dashboard and put it in the STACK_SUPER_SECRET_ADMIN_KEY environment variable.");
86
+ return process.env.STACK_SUPER_SECRET_ADMIN_KEY || (0, import_errors.throwErr)("No super secret admin key provided. Please copy your publishable client key from the Stack dashboard and put it in the STACK_SUPER_SECRET_ADMIN_KEY environment variable.");
49
87
  }
50
88
  function getDefaultBaseUrl() {
51
- return process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;
89
+ return process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;
52
90
  }
53
- const defaultBaseUrl = "https://app.stack-auth.com";
91
+ var defaultBaseUrl = "https://app.stack-auth.com";
54
92
  function createEmptyTokenStore() {
55
- const store = new AsyncStore();
56
- store.set({
57
- refreshToken: null,
58
- accessToken: null,
59
- });
60
- return store;
93
+ const store = new import_stores.AsyncStore();
94
+ store.set({
95
+ refreshToken: null,
96
+ accessToken: null
97
+ });
98
+ return store;
61
99
  }
62
- const memoryTokenStore = createEmptyTokenStore();
63
- let cookieTokenStore = null;
64
- const cookieTokenStoreInitializer = () => {
65
- if (!isClient()) {
66
- throw new Error("Cannot use cookie token store on the server!");
67
- }
68
- if (cookieTokenStore === null) {
69
- cookieTokenStore = new AsyncStore();
70
- let hasSucceededInWriting = true;
71
- setInterval(() => {
72
- if (hasSucceededInWriting) {
73
- const newValue = {
74
- refreshToken: getCookie('stack-refresh'),
75
- accessToken: getCookie('stack-access'),
76
- };
77
- const res = cookieTokenStore.get();
78
- if (res.status !== "ok"
79
- || res.data.refreshToken !== newValue.refreshToken
80
- || res.data.accessToken !== newValue.accessToken) {
81
- cookieTokenStore.set(newValue);
82
- }
83
- }
84
- }, 10);
85
- cookieTokenStore.onChange((value) => {
86
- try {
87
- setOrDeleteCookie('stack-refresh', value.refreshToken);
88
- setOrDeleteCookie('stack-access', value.accessToken);
89
- hasSucceededInWriting = true;
90
- }
91
- catch (e) {
92
- hasSucceededInWriting = false;
93
- }
94
- });
95
- }
96
- return cookieTokenStore;
100
+ var memoryTokenStore = createEmptyTokenStore();
101
+ var cookieTokenStore = null;
102
+ var cookieTokenStoreInitializer = () => {
103
+ if (!(0, import_next.isClient)()) {
104
+ throw new Error("Cannot use cookie token store on the server!");
105
+ }
106
+ if (cookieTokenStore === null) {
107
+ cookieTokenStore = new import_stores.AsyncStore();
108
+ let hasSucceededInWriting = true;
109
+ setInterval(() => {
110
+ if (hasSucceededInWriting) {
111
+ const newValue = {
112
+ refreshToken: (0, import_cookie.getCookie)("stack-refresh"),
113
+ accessToken: (0, import_cookie.getCookie)("stack-access")
114
+ };
115
+ const res = cookieTokenStore.get();
116
+ if (res.status !== "ok" || res.data.refreshToken !== newValue.refreshToken || res.data.accessToken !== newValue.accessToken) {
117
+ cookieTokenStore.set(newValue);
118
+ }
119
+ }
120
+ }, 10);
121
+ cookieTokenStore.onChange((value) => {
122
+ try {
123
+ (0, import_cookie.setOrDeleteCookie)("stack-refresh", value.refreshToken);
124
+ (0, import_cookie.setOrDeleteCookie)("stack-access", value.accessToken);
125
+ hasSucceededInWriting = true;
126
+ } catch (e) {
127
+ hasSucceededInWriting = false;
128
+ }
129
+ });
130
+ }
131
+ return cookieTokenStore;
97
132
  };
98
- const tokenStoreInitializers = new Map([
99
- ["cookie", cookieTokenStoreInitializer],
100
- ["nextjs-cookie", () => {
101
- if (isClient()) {
102
- return cookieTokenStoreInitializer();
103
- }
104
- else {
105
- const store = new AsyncStore();
106
- store.set({
107
- refreshToken: getCookie('stack-refresh'),
108
- accessToken: getCookie('stack-access'),
109
- });
110
- store.onChange((value) => {
111
- try {
112
- setOrDeleteCookie('stack-refresh', value.refreshToken);
113
- setOrDeleteCookie('stack-access', value.accessToken);
114
- }
115
- catch (e) {
116
- // ignore
117
- }
118
- });
119
- return store;
120
- }
121
- }],
122
- ["memory", () => memoryTokenStore],
123
- [null, () => createEmptyTokenStore()],
133
+ var tokenStoreInitializers = /* @__PURE__ */ new Map([
134
+ ["cookie", cookieTokenStoreInitializer],
135
+ ["nextjs-cookie", () => {
136
+ if ((0, import_next.isClient)()) {
137
+ return cookieTokenStoreInitializer();
138
+ } else {
139
+ const store = new import_stores.AsyncStore();
140
+ store.set({
141
+ refreshToken: (0, import_cookie.getCookie)("stack-refresh"),
142
+ accessToken: (0, import_cookie.getCookie)("stack-access")
143
+ });
144
+ store.onChange((value) => {
145
+ try {
146
+ (0, import_cookie.setOrDeleteCookie)("stack-refresh", value.refreshToken);
147
+ (0, import_cookie.setOrDeleteCookie)("stack-access", value.accessToken);
148
+ } catch (e) {
149
+ }
150
+ });
151
+ return store;
152
+ }
153
+ }],
154
+ ["memory", () => memoryTokenStore],
155
+ [null, () => createEmptyTokenStore()]
124
156
  ]);
125
157
  function getTokenStore(tokenStoreOptions) {
126
- return (tokenStoreInitializers.get(tokenStoreOptions) ?? throwErr(`Invalid token store ${tokenStoreOptions}`))();
158
+ return (tokenStoreInitializers.get(tokenStoreOptions) ?? (0, import_errors.throwErr)(`Invalid token store ${tokenStoreOptions}`))();
127
159
  }
128
- const loadingSentinel = Symbol("stackAppCacheLoadingSentinel");
160
+ var loadingSentinel = Symbol("stackAppCacheLoadingSentinel");
129
161
  function useCache(cache, dependencies, caller) {
130
- // we explicitly don't want to run this hook in SSR
131
- suspendIfSsr(caller);
132
- const subscribe = useCallback((cb) => {
133
- const { unsubscribe } = cache.onChange(dependencies, () => cb());
134
- return unsubscribe;
135
- }, [cache, ...dependencies]);
136
- const getSnapshot = useCallback(() => {
137
- return AsyncResult.or(cache.getIfCached(dependencies), loadingSentinel);
138
- }, [cache, ...dependencies]);
139
- // note: we must use React.useSyncExternalStore instead of importing the function directly, as it will otherwise
140
- // throw an error ("can't import useSyncExternalStore from the server")
141
- const value = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
142
- if (value === loadingSentinel) {
143
- return use(cache.getOrWait(dependencies, "read-write"));
144
- }
145
- else {
146
- // still need to call `use` because React expects the control flow to not change across two re-renders with the same props/state and it detects that by hook invocations (including `use`)
147
- return use(resolved(value));
148
- }
162
+ (0, import_react2.suspendIfSsr)(caller);
163
+ const subscribe = (0, import_react.useCallback)((cb) => {
164
+ const { unsubscribe } = cache.onChange(dependencies, () => cb());
165
+ return unsubscribe;
166
+ }, [cache, ...dependencies]);
167
+ const getSnapshot = (0, import_react.useCallback)(() => {
168
+ return import_results.AsyncResult.or(cache.getIfCached(dependencies), loadingSentinel);
169
+ }, [cache, ...dependencies]);
170
+ const value = import_react.default.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
171
+ if (value === loadingSentinel) {
172
+ return (0, import_react.use)(cache.getOrWait(dependencies, "read-write"));
173
+ } else {
174
+ return (0, import_react.use)((0, import_promises.resolved)(value));
175
+ }
149
176
  }
150
- export const stackAppInternalsSymbol = Symbol.for("StackAppInternals");
151
- const allClientApps = new Map();
152
- const createCache = (fetcher) => {
153
- return new AsyncCache(async (dependencies) => await fetcher(dependencies), {});
154
- };
155
- // note that we intentionally use TokenStore (a reference type) as a key instead of a stringified version of it, as different token stores with the same tokens should be treated differently
156
- // (if we wouldn't , we would cache users across requests, which may cause issues)
157
- const createCacheByTokenStore = (fetcher) => {
158
- return new AsyncCache(async ([tokenStore, ...extraDependencies]) => await fetcher(tokenStore, extraDependencies), {
159
- onSubscribe: ([tokenStore], refresh) => {
160
- // TODO find a *clean* way to not refresh when the token change was made inside the fetcher (for example due to expired access token)
161
- const handlerObj = tokenStore.onChange((newValue, oldValue) => {
162
- if (JSON.stringify(newValue) === JSON.stringify(oldValue))
163
- return;
164
- refresh();
165
- });
166
- return () => handlerObj.unsubscribe();
167
- },
168
- });
177
+ var stackAppInternalsSymbol = Symbol.for("StackAppInternals");
178
+ var allClientApps = /* @__PURE__ */ new Map();
179
+ var createCache = (fetcher) => {
180
+ return new import_caches.AsyncCache(
181
+ async (dependencies) => await fetcher(dependencies),
182
+ {}
183
+ );
169
184
  };
170
- class _StackClientAppImpl {
171
- _uniqueIdentifier;
172
- _interface;
173
- _tokenStoreOptions;
174
- _urlOptions;
175
- _currentUserCache = createCacheByTokenStore(async (tokenStore) => {
176
- const user = await this._interface.getClientUserByToken(tokenStore);
177
- return Result.or(user, null);
178
- });
179
- _currentProjectCache = createCache(async () => {
180
- return Result.orThrow(await this._interface.getClientProject());
181
- });
182
- _ownedProjectsCache = createCacheByTokenStore(async (tokenStore) => {
183
- return await this._interface.listProjects(tokenStore);
184
- });
185
- constructor(options) {
186
- if ("interface" in options) {
187
- this._interface = options.interface;
188
- }
189
- else {
190
- this._interface = new StackClientInterface({
191
- baseUrl: options.baseUrl ?? getDefaultBaseUrl(),
192
- projectId: options.projectId ?? getDefaultProjectId(),
193
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
194
- });
195
- }
196
- this._tokenStoreOptions = options.tokenStore;
197
- this._urlOptions = options.urls ?? {};
198
- this._uniqueIdentifier = options.uniqueIdentifier ?? generateUuid();
199
- if (allClientApps.has(this._uniqueIdentifier)) {
200
- throw new StackAssertionError("A Stack client app with the same unique identifier already exists");
201
- }
202
- allClientApps.set(this._uniqueIdentifier, [options.checkString ?? "default check string", this]);
203
- // For some important calls, either use the provided cached values or start fetching them now
204
- if (options.currentClientUserJson !== undefined) {
205
- this._currentUserCache.forceSetCachedValue([getTokenStore(this._tokenStoreOptions)], options.currentClientUserJson);
206
- }
207
- else if (this.hasPersistentTokenStore()) {
208
- runAsynchronously(this.getUser(), { ignoreErrors: true });
209
- }
210
- if (options.currentProjectJson !== undefined) {
211
- this._currentProjectCache.forceSetCachedValue([], options.currentProjectJson);
212
- }
213
- else {
214
- runAsynchronously(this.getProject(), { ignoreErrors: true });
215
- }
216
- }
217
- hasPersistentTokenStore() {
218
- return this._tokenStoreOptions !== null;
219
- }
220
- _ensurePersistentTokenStore() {
221
- if (!this.hasPersistentTokenStore()) {
222
- throw new Error("Cannot call this function on a Stack app without a persistent token store. Make sure the tokenStore option is set to a non-null value when initializing Stack.");
223
- }
224
- }
225
- isInternalProject() {
226
- return this.projectId === "internal";
227
- }
228
- _ensureInternalProject() {
229
- if (!this.isInternalProject()) {
230
- throw new Error("Cannot call this function on a Stack app with a project ID other than 'internal'.");
231
- }
232
- }
233
- _userFromJson(json) {
234
- return {
235
- projectId: json.projectId,
236
- id: json.id,
237
- displayName: json.displayName,
238
- primaryEmail: json.primaryEmail,
239
- primaryEmailVerified: json.primaryEmailVerified,
240
- profileImageUrl: json.profileImageUrl,
241
- signedUpAt: new Date(json.signedUpAtMillis),
242
- clientMetadata: json.clientMetadata,
243
- authMethod: json.authMethod,
244
- hasPassword: json.hasPassword,
245
- authWithEmail: json.authWithEmail,
246
- oauthProviders: json.oauthProviders,
247
- toJson() {
248
- return json;
249
- }
250
- };
251
- }
252
- _currentUserFromJson(json, tokenStore) {
253
- if (json === null)
254
- return null;
255
- const app = this;
256
- const currentUser = {
257
- ...this._userFromJson(json),
258
- tokenStore,
259
- update(update) {
260
- return app._updateUser(update, tokenStore);
261
- },
262
- signOut() {
263
- return app._signOut(tokenStore);
264
- },
265
- sendVerificationEmail() {
266
- return app._sendVerificationEmail(tokenStore);
267
- },
268
- updatePassword(options) {
269
- return app._updatePassword(options, tokenStore);
270
- },
271
- };
272
- if (this.isInternalProject()) {
273
- const internalUser = {
274
- ...currentUser,
275
- createProject(newProject) {
276
- return app._createProject(newProject);
277
- },
278
- listOwnedProjects() {
279
- return app._listOwnedProjects();
280
- },
281
- useOwnedProjects() {
282
- return app._useOwnedProjects();
283
- },
284
- onOwnedProjectsChange(callback) {
285
- return app._onOwnedProjectsChange(callback);
286
- }
287
- };
288
- Object.freeze(internalUser);
289
- return internalUser;
290
- }
291
- else {
292
- Object.freeze(currentUser);
293
- return currentUser;
294
- }
295
- }
296
- _userToJson(user) {
297
- return {
298
- projectId: user.projectId,
299
- id: user.id,
300
- displayName: user.displayName,
301
- primaryEmail: user.primaryEmail,
302
- primaryEmailVerified: user.primaryEmailVerified,
303
- profileImageUrl: user.profileImageUrl,
304
- signedUpAtMillis: user.signedUpAt.getTime(),
305
- clientMetadata: user.clientMetadata,
306
- authMethod: user.authMethod,
307
- hasPassword: user.hasPassword,
308
- authWithEmail: user.authWithEmail,
309
- oauthProviders: user.oauthProviders,
310
- };
311
- }
312
- _projectAdminFromJson(data, adminInterface, onRefresh) {
313
- if (data.id !== adminInterface.projectId) {
314
- throw new Error(`The project ID of the provided project JSON (${data.id}) does not match the project ID of the app (${adminInterface.projectId})! This is a Stack bug.`);
315
- }
316
- return {
317
- id: data.id,
318
- displayName: data.displayName,
319
- description: data.description,
320
- createdAt: new Date(data.createdAtMillis),
321
- userCount: data.userCount,
322
- isProductionMode: data.isProductionMode,
323
- evaluatedConfig: {
324
- id: data.evaluatedConfig.id,
325
- credentialEnabled: data.evaluatedConfig.credentialEnabled,
326
- magicLinkEnabled: data.evaluatedConfig.magicLinkEnabled,
327
- allowLocalhost: data.evaluatedConfig.allowLocalhost,
328
- oauthProviders: data.evaluatedConfig.oauthProviders,
329
- emailConfig: data.evaluatedConfig.emailConfig,
330
- domains: data.evaluatedConfig.domains,
331
- },
332
- async update(update) {
333
- await adminInterface.updateProject(update);
334
- await onRefresh();
335
- },
336
- toJson() {
337
- return data;
338
- },
339
- getProductionModeErrors() {
340
- return getProductionModeErrors(this.toJson());
341
- },
342
- };
343
- }
344
- _createAdminInterface(forProjectId, tokenStore) {
345
- return new StackAdminInterface({
346
- baseUrl: this._interface.options.baseUrl,
347
- projectId: forProjectId,
348
- projectOwnerTokens: tokenStore,
349
- });
350
- }
351
- get projectId() {
352
- return this._interface.projectId;
353
- }
354
- get urls() {
355
- return getUrls(this._urlOptions);
356
- }
357
- _redirectTo(handlerName) {
358
- if (!this.urls[handlerName]) {
359
- throw new Error(`No URL for handler name ${handlerName}`);
360
- }
361
- window.location.href = this.urls[handlerName];
362
- return neverResolve();
363
- }
364
- async redirectToSignIn() { return await this._redirectTo("signIn"); }
365
- async redirectToSignUp() { return await this._redirectTo("signUp"); }
366
- async redirectToSignOut() { return await this._redirectTo("signOut"); }
367
- async redirectToEmailVerification() { return await this._redirectTo("emailVerification"); }
368
- async redirectToPasswordReset() { return await this._redirectTo("passwordReset"); }
369
- async redirectToForgotPassword() { return await this._redirectTo("forgotPassword"); }
370
- async redirectToHome() { return await this._redirectTo("home"); }
371
- async redirectToOAuthCallback() { return await this._redirectTo("oauthCallback"); }
372
- async redirectToMagicLinkCallback() { return await this._redirectTo("magicLinkCallback"); }
373
- async redirectToAfterSignIn() { return await this._redirectTo("afterSignIn"); }
374
- async redirectToAfterSignUp() { return await this._redirectTo("afterSignUp"); }
375
- async redirectToAfterSignOut() { return await this._redirectTo("afterSignOut"); }
376
- async redirectToAccountSettings() { return await this._redirectTo("accountSettings"); }
377
- async sendForgotPasswordEmail(email) {
378
- const redirectUrl = constructRedirectUrl(this.urls.passwordReset);
379
- const error = await this._interface.sendForgotPasswordEmail(email, redirectUrl);
380
- return error;
381
- }
382
- async sendMagicLinkEmail(email) {
383
- const magicLinkRedirectUrl = constructRedirectUrl(this.urls.magicLinkCallback);
384
- const error = await this._interface.sendMagicLinkEmail(email, magicLinkRedirectUrl);
385
- return error;
386
- }
387
- async resetPassword(options) {
388
- const error = await this._interface.resetPassword(options);
389
- return error;
390
- }
391
- async verifyPasswordResetCode(code) {
392
- return await this._interface.verifyPasswordResetCode(code);
393
- }
394
- async verifyEmail(code) {
395
- return await this._interface.verifyEmail(code);
396
- }
397
- async getUser(options) {
398
- this._ensurePersistentTokenStore();
399
- const tokenStore = getTokenStore(this._tokenStoreOptions);
400
- const userJson = await this._currentUserCache.getOrWait([tokenStore], "write-only");
401
- if (userJson === null) {
402
- switch (options?.or) {
403
- case 'redirect': {
404
- redirect(this.urls.signIn, RedirectType.replace);
405
- throw new Error("redirect should never return!");
406
- }
407
- case 'throw': {
408
- throw new Error("User is not signed in but getUser was called with { or: 'throw' }");
409
- }
410
- default: {
411
- return null;
412
- }
413
- }
414
- }
415
- return this._currentUserFromJson(userJson, tokenStore);
416
- }
417
- useUser(options) {
418
- this._ensurePersistentTokenStore();
419
- const router = useRouter();
420
- const tokenStore = getTokenStore(this._tokenStoreOptions);
421
- const userJson = useCache(this._currentUserCache, [tokenStore], "useUser()");
422
- if (userJson === null) {
423
- switch (options?.or) {
424
- case 'redirect': {
425
- router.replace(this.urls.signIn);
426
- suspend();
427
- throw new Error("suspend should never return! This is a bug in Stack.");
428
- }
429
- case 'throw': {
430
- throw new Error("User is not signed in but useUser was called with { or: 'throw' }");
431
- }
432
- case undefined:
433
- case "return-null": {
434
- // do nothing
435
- }
436
- }
437
- }
438
- return useMemo(() => {
439
- return this._currentUserFromJson(userJson, tokenStore);
440
- }, [userJson, tokenStore, options?.or]);
441
- }
442
- onUserChange(callback) {
443
- this._ensurePersistentTokenStore();
444
- const tokenStore = getTokenStore(this._tokenStoreOptions);
445
- return this._currentUserCache.onChange([tokenStore], (userJson) => {
446
- callback(this._currentUserFromJson(userJson, tokenStore));
185
+ var createCacheByTokenStore = (fetcher) => {
186
+ return new import_caches.AsyncCache(
187
+ async ([tokenStore, ...extraDependencies]) => await fetcher(tokenStore, extraDependencies),
188
+ {
189
+ onSubscribe: ([tokenStore], refresh) => {
190
+ const handlerObj = tokenStore.onChange((newValue, oldValue) => {
191
+ if (JSON.stringify(newValue) === JSON.stringify(oldValue))
192
+ return;
193
+ refresh();
447
194
  });
195
+ return () => handlerObj.unsubscribe();
196
+ }
448
197
  }
449
- async _updateUser(update, tokenStore) {
450
- const res = await this._interface.setClientUserCustomizableData(update, tokenStore);
451
- await this._refreshUser(tokenStore);
452
- return res;
453
- }
454
- async signInWithOAuth(provider) {
455
- this._ensurePersistentTokenStore();
456
- await signInWithOAuth(this._interface, { provider, redirectUrl: this.urls.oauthCallback });
457
- }
458
- async signInWithCredential(options) {
459
- this._ensurePersistentTokenStore();
460
- const tokenStore = getTokenStore(this._tokenStoreOptions);
461
- const errorCode = await this._interface.signInWithCredential(options.email, options.password, tokenStore);
462
- if (!errorCode) {
463
- window.location.assign(this.urls.afterSignIn);
464
- }
465
- return errorCode;
466
- }
467
- async signUpWithCredential(options) {
468
- this._ensurePersistentTokenStore();
469
- const tokenStore = getTokenStore(this._tokenStoreOptions);
470
- const emailVerificationRedirectUrl = constructRedirectUrl(this.urls.emailVerification);
471
- const errorCode = await this._interface.signUpWithCredential(options.email, options.password, emailVerificationRedirectUrl, tokenStore);
472
- if (!errorCode) {
473
- window.location.assign(this.urls.afterSignUp);
198
+ );
199
+ };
200
+ var _StackClientAppImpl = class __StackClientAppImpl {
201
+ _uniqueIdentifier;
202
+ _interface;
203
+ _tokenStoreOptions;
204
+ _urlOptions;
205
+ __DEMO_ENABLE_SLIGHT_FETCH_DELAY = false;
206
+ _currentUserCache = createCacheByTokenStore(async (tokenStore) => {
207
+ if (this.__DEMO_ENABLE_SLIGHT_FETCH_DELAY) {
208
+ await (0, import_promises.wait)(2e3);
209
+ }
210
+ const user = await this._interface.getClientUserByToken(tokenStore);
211
+ return import_results.Result.or(user, null);
212
+ });
213
+ _currentProjectCache = createCache(async () => {
214
+ return import_results.Result.orThrow(await this._interface.getClientProject());
215
+ });
216
+ _ownedProjectsCache = createCacheByTokenStore(async (tokenStore) => {
217
+ return await this._interface.listProjects(tokenStore);
218
+ });
219
+ constructor(options) {
220
+ if ("interface" in options) {
221
+ this._interface = options.interface;
222
+ } else {
223
+ this._interface = new import_stack_shared.StackClientInterface({
224
+ baseUrl: options.baseUrl ?? getDefaultBaseUrl(),
225
+ projectId: options.projectId ?? getDefaultProjectId(),
226
+ publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey()
227
+ });
228
+ }
229
+ this._tokenStoreOptions = options.tokenStore;
230
+ this._urlOptions = options.urls ?? {};
231
+ this._uniqueIdentifier = options.uniqueIdentifier ?? (0, import_uuids.generateUuid)();
232
+ if (allClientApps.has(this._uniqueIdentifier)) {
233
+ throw new import_errors.StackAssertionError("A Stack client app with the same unique identifier already exists");
234
+ }
235
+ allClientApps.set(this._uniqueIdentifier, [options.checkString ?? "default check string", this]);
236
+ }
237
+ hasPersistentTokenStore() {
238
+ return this._tokenStoreOptions !== null;
239
+ }
240
+ _ensurePersistentTokenStore() {
241
+ if (!this.hasPersistentTokenStore()) {
242
+ throw new Error("Cannot call this function on a Stack app without a persistent token store. Make sure the tokenStore option is set to a non-null value when initializing Stack.");
243
+ }
244
+ }
245
+ isInternalProject() {
246
+ return this.projectId === "internal";
247
+ }
248
+ _ensureInternalProject() {
249
+ if (!this.isInternalProject()) {
250
+ throw new Error("Cannot call this function on a Stack app with a project ID other than 'internal'.");
251
+ }
252
+ }
253
+ _userFromJson(json) {
254
+ return {
255
+ projectId: json.projectId,
256
+ id: json.id,
257
+ displayName: json.displayName,
258
+ primaryEmail: json.primaryEmail,
259
+ primaryEmailVerified: json.primaryEmailVerified,
260
+ profileImageUrl: json.profileImageUrl,
261
+ signedUpAt: new Date(json.signedUpAtMillis),
262
+ clientMetadata: json.clientMetadata,
263
+ authMethod: json.authMethod,
264
+ hasPassword: json.hasPassword,
265
+ authWithEmail: json.authWithEmail,
266
+ oauthProviders: json.oauthProviders,
267
+ toJson() {
268
+ return json;
269
+ }
270
+ };
271
+ }
272
+ _currentUserFromJson(json, tokenStore) {
273
+ if (json === null)
274
+ return null;
275
+ const app = this;
276
+ const currentUser = {
277
+ ...this._userFromJson(json),
278
+ tokenStore,
279
+ update(update) {
280
+ return app._updateUser(update, tokenStore);
281
+ },
282
+ signOut() {
283
+ return app._signOut(tokenStore);
284
+ },
285
+ sendVerificationEmail() {
286
+ return app._sendVerificationEmail(tokenStore);
287
+ },
288
+ updatePassword(options) {
289
+ return app._updatePassword(options, tokenStore);
290
+ }
291
+ };
292
+ if (this.isInternalProject()) {
293
+ const internalUser = {
294
+ ...currentUser,
295
+ createProject(newProject) {
296
+ return app._createProject(newProject);
297
+ },
298
+ listOwnedProjects() {
299
+ return app._listOwnedProjects();
300
+ },
301
+ useOwnedProjects() {
302
+ return app._useOwnedProjects();
303
+ },
304
+ onOwnedProjectsChange(callback) {
305
+ return app._onOwnedProjectsChange(callback);
474
306
  }
475
- return errorCode;
307
+ };
308
+ Object.freeze(internalUser);
309
+ return internalUser;
310
+ } else {
311
+ Object.freeze(currentUser);
312
+ return currentUser;
313
+ }
314
+ }
315
+ _userToJson(user) {
316
+ return {
317
+ projectId: user.projectId,
318
+ id: user.id,
319
+ displayName: user.displayName,
320
+ primaryEmail: user.primaryEmail,
321
+ primaryEmailVerified: user.primaryEmailVerified,
322
+ profileImageUrl: user.profileImageUrl,
323
+ signedUpAtMillis: user.signedUpAt.getTime(),
324
+ clientMetadata: user.clientMetadata,
325
+ authMethod: user.authMethod,
326
+ hasPassword: user.hasPassword,
327
+ authWithEmail: user.authWithEmail,
328
+ oauthProviders: user.oauthProviders
329
+ };
330
+ }
331
+ _projectAdminFromJson(data, adminInterface, onRefresh) {
332
+ if (data.id !== adminInterface.projectId) {
333
+ throw new Error(`The project ID of the provided project JSON (${data.id}) does not match the project ID of the app (${adminInterface.projectId})! This is a Stack bug.`);
476
334
  }
477
- async signInWithMagicLink(code) {
478
- this._ensurePersistentTokenStore();
479
- const tokenStore = getTokenStore(this._tokenStoreOptions);
480
- const result = await this._interface.signInWithMagicLink(code, tokenStore);
481
- if (result instanceof KnownError) {
482
- return result;
335
+ return {
336
+ id: data.id,
337
+ displayName: data.displayName,
338
+ description: data.description,
339
+ createdAt: new Date(data.createdAtMillis),
340
+ userCount: data.userCount,
341
+ isProductionMode: data.isProductionMode,
342
+ evaluatedConfig: {
343
+ id: data.evaluatedConfig.id,
344
+ credentialEnabled: data.evaluatedConfig.credentialEnabled,
345
+ magicLinkEnabled: data.evaluatedConfig.magicLinkEnabled,
346
+ allowLocalhost: data.evaluatedConfig.allowLocalhost,
347
+ oauthProviders: data.evaluatedConfig.oauthProviders,
348
+ emailConfig: data.evaluatedConfig.emailConfig,
349
+ domains: data.evaluatedConfig.domains
350
+ },
351
+ async update(update) {
352
+ await adminInterface.updateProject(update);
353
+ await onRefresh();
354
+ },
355
+ toJson() {
356
+ return data;
357
+ },
358
+ getProductionModeErrors() {
359
+ return (0, import_clientInterface.getProductionModeErrors)(this.toJson());
360
+ }
361
+ };
362
+ }
363
+ _createAdminInterface(forProjectId, tokenStore) {
364
+ return new import_stack_shared.StackAdminInterface({
365
+ baseUrl: this._interface.options.baseUrl,
366
+ projectId: forProjectId,
367
+ projectOwnerTokens: tokenStore
368
+ });
369
+ }
370
+ get projectId() {
371
+ return this._interface.projectId;
372
+ }
373
+ get urls() {
374
+ return getUrls(this._urlOptions);
375
+ }
376
+ _redirectTo(handlerName) {
377
+ if (!this.urls[handlerName]) {
378
+ throw new Error(`No URL for handler name ${handlerName}`);
379
+ }
380
+ window.location.href = this.urls[handlerName];
381
+ return (0, import_promises.neverResolve)();
382
+ }
383
+ async redirectToSignIn() {
384
+ return await this._redirectTo("signIn");
385
+ }
386
+ async redirectToSignUp() {
387
+ return await this._redirectTo("signUp");
388
+ }
389
+ async redirectToSignOut() {
390
+ return await this._redirectTo("signOut");
391
+ }
392
+ async redirectToEmailVerification() {
393
+ return await this._redirectTo("emailVerification");
394
+ }
395
+ async redirectToPasswordReset() {
396
+ return await this._redirectTo("passwordReset");
397
+ }
398
+ async redirectToForgotPassword() {
399
+ return await this._redirectTo("forgotPassword");
400
+ }
401
+ async redirectToHome() {
402
+ return await this._redirectTo("home");
403
+ }
404
+ async redirectToOAuthCallback() {
405
+ return await this._redirectTo("oauthCallback");
406
+ }
407
+ async redirectToMagicLinkCallback() {
408
+ return await this._redirectTo("magicLinkCallback");
409
+ }
410
+ async redirectToAfterSignIn() {
411
+ return await this._redirectTo("afterSignIn");
412
+ }
413
+ async redirectToAfterSignUp() {
414
+ return await this._redirectTo("afterSignUp");
415
+ }
416
+ async redirectToAfterSignOut() {
417
+ return await this._redirectTo("afterSignOut");
418
+ }
419
+ async redirectToAccountSettings() {
420
+ return await this._redirectTo("accountSettings");
421
+ }
422
+ async sendForgotPasswordEmail(email) {
423
+ const redirectUrl = (0, import_url.constructRedirectUrl)(this.urls.passwordReset);
424
+ const error = await this._interface.sendForgotPasswordEmail(email, redirectUrl);
425
+ return error;
426
+ }
427
+ async sendMagicLinkEmail(email) {
428
+ const magicLinkRedirectUrl = (0, import_url.constructRedirectUrl)(this.urls.magicLinkCallback);
429
+ const error = await this._interface.sendMagicLinkEmail(email, magicLinkRedirectUrl);
430
+ return error;
431
+ }
432
+ async resetPassword(options) {
433
+ const error = await this._interface.resetPassword(options);
434
+ return error;
435
+ }
436
+ async verifyPasswordResetCode(code) {
437
+ return await this._interface.verifyPasswordResetCode(code);
438
+ }
439
+ async verifyEmail(code) {
440
+ return await this._interface.verifyEmail(code);
441
+ }
442
+ async getUser(options) {
443
+ this._ensurePersistentTokenStore();
444
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
445
+ const userJson = await this._currentUserCache.getOrWait([tokenStore], "write-only");
446
+ if (userJson === null) {
447
+ switch (options?.or) {
448
+ case "redirect": {
449
+ NextNavigation.redirect(this.urls.signIn, NextNavigation.RedirectType.replace);
450
+ throw new Error("redirect should never return!");
483
451
  }
484
- if (result.newUser) {
485
- window.location.replace(this.urls.afterSignUp);
452
+ case "throw": {
453
+ throw new Error("User is not signed in but getUser was called with { or: 'throw' }");
486
454
  }
487
- else {
488
- window.location.replace(this.urls.afterSignIn);
455
+ default: {
456
+ return null;
489
457
  }
490
- await neverResolve();
491
- }
492
- async callOAuthCallback() {
493
- this._ensurePersistentTokenStore();
494
- const tokenStore = getTokenStore(this._tokenStoreOptions);
495
- const result = await callOAuthCallback(this._interface, tokenStore, this.urls.oauthCallback);
496
- if (result?.newUser) {
497
- window.location.replace(this.urls.afterSignUp);
458
+ }
459
+ }
460
+ return this._currentUserFromJson(userJson, tokenStore);
461
+ }
462
+ useUser(options) {
463
+ this._ensurePersistentTokenStore();
464
+ const router = NextNavigation.useRouter();
465
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
466
+ const userJson = useCache(this._currentUserCache, [tokenStore], "useUser()");
467
+ if (userJson === null) {
468
+ switch (options?.or) {
469
+ case "redirect": {
470
+ router.replace(this.urls.signIn);
471
+ (0, import_react3.suspend)();
472
+ throw new Error("suspend should never return! This is a bug in Stack.");
498
473
  }
499
- else {
500
- window.location.replace(this.urls.afterSignIn);
474
+ case "throw": {
475
+ throw new Error("User is not signed in but useUser was called with { or: 'throw' }");
501
476
  }
502
- await neverResolve();
503
- }
504
- async _signOut(tokenStore) {
505
- await this._interface.signOut(tokenStore);
506
- window.location.assign(this.urls.afterSignOut);
507
- }
508
- async _sendVerificationEmail(tokenStore) {
509
- const emailVerificationRedirectUrl = constructRedirectUrl(this.urls.emailVerification);
510
- return await this._interface.sendVerificationEmail(emailVerificationRedirectUrl, tokenStore);
511
- }
512
- async _updatePassword(options, tokenStore) {
513
- return await this._interface.updatePassword(options, tokenStore);
514
- }
515
- async signOut() {
516
- const user = await this.getUser();
517
- if (user) {
518
- await user.signOut();
477
+ case void 0:
478
+ case "return-null": {
519
479
  }
520
- }
521
- async getProject() {
522
- return await this._currentProjectCache.getOrWait([], "write-only");
523
- }
524
- useProject() {
525
- return useCache(this._currentProjectCache, [], "useProject()");
526
- }
527
- onProjectChange(callback) {
528
- return this._currentProjectCache.onChange([], callback);
529
- }
530
- async _listOwnedProjects() {
531
- this._ensureInternalProject();
532
- const tokenStore = getTokenStore(this._tokenStoreOptions);
533
- const json = await this._ownedProjectsCache.getOrWait([tokenStore], "write-only");
534
- return json.map((j) => this._projectAdminFromJson(j, this._createAdminInterface(j.id, tokenStore), () => this._refreshOwnedProjects(tokenStore)));
535
- }
536
- _useOwnedProjects() {
537
- this._ensureInternalProject();
538
- const tokenStore = getTokenStore(this._tokenStoreOptions);
539
- const json = useCache(this._ownedProjectsCache, [tokenStore], "useOwnedProjects()");
540
- return useMemo(() => json.map((j) => this._projectAdminFromJson(j, this._createAdminInterface(j.id, tokenStore), () => this._refreshOwnedProjects(tokenStore))), [json]);
541
- }
542
- _onOwnedProjectsChange(callback) {
543
- this._ensureInternalProject();
544
- const tokenStore = getTokenStore(this._tokenStoreOptions);
545
- return this._ownedProjectsCache.onChange([tokenStore], (projects) => {
546
- callback(projects.map((j) => this._projectAdminFromJson(j, this._createAdminInterface(j.id, tokenStore), () => this._refreshOwnedProjects(tokenStore))));
547
- });
548
- }
549
- async _createProject(newProject) {
550
- this._ensureInternalProject();
551
- const tokenStore = getTokenStore(this._tokenStoreOptions);
552
- const json = await this._interface.createProject(newProject, tokenStore);
553
- const res = this._projectAdminFromJson(json, this._createAdminInterface(json.id, tokenStore), () => this._refreshOwnedProjects(tokenStore));
554
- await this._refreshOwnedProjects(tokenStore);
555
- return res;
556
- }
557
- async _refreshUser(tokenStore) {
558
- await this._currentUserCache.refresh([tokenStore]);
559
- }
560
- async _refreshUsers() {
561
- // nothing yet
562
- }
563
- async _refreshProject() {
564
- await this._currentProjectCache.refresh([]);
565
- }
566
- async _refreshOwnedProjects(tokenStore) {
567
- await this._ownedProjectsCache.refresh([tokenStore]);
568
- }
569
- static get [stackAppInternalsSymbol]() {
570
- return {
571
- fromClientJson: (json) => {
572
- const providedCheckString = JSON.stringify(omit(json, ["currentClientUserJson", "currentProjectJson"]));
573
- const existing = allClientApps.get(json.uniqueIdentifier);
574
- if (existing) {
575
- const [existingCheckString, clientApp] = existing;
576
- if (existingCheckString !== providedCheckString) {
577
- throw new StackAssertionError("The provided app JSON does not match the configuration of the existing client app with the same unique identifier", { providedObj: json, existingString: existingCheckString });
578
- }
579
- return clientApp;
580
- }
581
- return new _StackClientAppImpl({
582
- ...json,
583
- checkString: providedCheckString,
584
- });
585
- }
586
- };
587
- }
588
- get [stackAppInternalsSymbol]() {
589
- return {
590
- toClientJson: async () => {
591
- if (!("publishableClientKey" in this._interface.options)) {
592
- // TODO find a way to do this
593
- throw Error("Cannot serialize to JSON from an application without a publishable client key");
594
- }
595
- const [user, project] = await Promise.all([
596
- this.getUser(),
597
- this.getProject(),
598
- ]);
599
- return {
600
- baseUrl: this._interface.options.baseUrl,
601
- projectId: this.projectId,
602
- publishableClientKey: this._interface.options.publishableClientKey,
603
- tokenStore: this._tokenStoreOptions,
604
- urls: this._urlOptions,
605
- uniqueIdentifier: this._uniqueIdentifier,
606
- currentClientUserJson: user?.toJson() ?? null,
607
- currentProjectJson: project,
608
- };
609
- }
610
- };
611
- }
612
- ;
613
- }
614
- class _StackServerAppImpl extends _StackClientAppImpl {
615
- // TODO override the client user cache to use the server user cache, so we save some requests
616
- _currentServerUserCache = createCacheByTokenStore(async (tokenStore) => {
617
- const user = await this._interface.getServerUserByToken(tokenStore);
618
- return Result.or(user, null);
480
+ }
481
+ }
482
+ return (0, import_react.useMemo)(() => {
483
+ return this._currentUserFromJson(userJson, tokenStore);
484
+ }, [userJson, tokenStore, options?.or]);
485
+ }
486
+ onUserChange(callback) {
487
+ this._ensurePersistentTokenStore();
488
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
489
+ return this._currentUserCache.onChange([tokenStore], (userJson) => {
490
+ callback(this._currentUserFromJson(userJson, tokenStore));
619
491
  });
620
- _serverUsersCache = createCache(async () => {
621
- return await this._interface.listUsers();
492
+ }
493
+ async _updateUser(update, tokenStore) {
494
+ const res = await this._interface.setClientUserCustomizableData(update, tokenStore);
495
+ await this._refreshUser(tokenStore);
496
+ return res;
497
+ }
498
+ async signInWithOAuth(provider) {
499
+ this._ensurePersistentTokenStore();
500
+ await (0, import_auth.signInWithOAuth)(this._interface, { provider, redirectUrl: this.urls.oauthCallback });
501
+ }
502
+ async signInWithCredential(options) {
503
+ this._ensurePersistentTokenStore();
504
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
505
+ const errorCode = await this._interface.signInWithCredential(options.email, options.password, tokenStore);
506
+ if (!errorCode) {
507
+ window.location.assign(this.urls.afterSignIn);
508
+ }
509
+ return errorCode;
510
+ }
511
+ async signUpWithCredential(options) {
512
+ this._ensurePersistentTokenStore();
513
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
514
+ const emailVerificationRedirectUrl = (0, import_url.constructRedirectUrl)(this.urls.emailVerification);
515
+ const errorCode = await this._interface.signUpWithCredential(
516
+ options.email,
517
+ options.password,
518
+ emailVerificationRedirectUrl,
519
+ tokenStore
520
+ );
521
+ if (!errorCode) {
522
+ window.location.assign(this.urls.afterSignUp);
523
+ }
524
+ return errorCode;
525
+ }
526
+ async signInWithMagicLink(code) {
527
+ this._ensurePersistentTokenStore();
528
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
529
+ const result = await this._interface.signInWithMagicLink(code, tokenStore);
530
+ if (result instanceof import_stack_shared.KnownError) {
531
+ return result;
532
+ }
533
+ if (result.newUser) {
534
+ window.location.replace(this.urls.afterSignUp);
535
+ } else {
536
+ window.location.replace(this.urls.afterSignIn);
537
+ }
538
+ await (0, import_promises.neverResolve)();
539
+ }
540
+ async callOAuthCallback() {
541
+ this._ensurePersistentTokenStore();
542
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
543
+ const result = await (0, import_auth.callOAuthCallback)(this._interface, tokenStore, this.urls.oauthCallback);
544
+ if (result?.newUser) {
545
+ window.location.replace(this.urls.afterSignUp);
546
+ } else {
547
+ window.location.replace(this.urls.afterSignIn);
548
+ }
549
+ await (0, import_promises.neverResolve)();
550
+ }
551
+ async _signOut(tokenStore) {
552
+ await this._interface.signOut(tokenStore);
553
+ window.location.assign(this.urls.afterSignOut);
554
+ }
555
+ async _sendVerificationEmail(tokenStore) {
556
+ const emailVerificationRedirectUrl = (0, import_url.constructRedirectUrl)(this.urls.emailVerification);
557
+ return await this._interface.sendVerificationEmail(emailVerificationRedirectUrl, tokenStore);
558
+ }
559
+ async _updatePassword(options, tokenStore) {
560
+ return await this._interface.updatePassword(options, tokenStore);
561
+ }
562
+ async signOut() {
563
+ const user = await this.getUser();
564
+ if (user) {
565
+ await user.signOut();
566
+ }
567
+ }
568
+ async getProject() {
569
+ return await this._currentProjectCache.getOrWait([], "write-only");
570
+ }
571
+ useProject() {
572
+ return useCache(this._currentProjectCache, [], "useProject()");
573
+ }
574
+ onProjectChange(callback) {
575
+ return this._currentProjectCache.onChange([], callback);
576
+ }
577
+ async _listOwnedProjects() {
578
+ this._ensureInternalProject();
579
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
580
+ const json = await this._ownedProjectsCache.getOrWait([tokenStore], "write-only");
581
+ return json.map((j) => this._projectAdminFromJson(
582
+ j,
583
+ this._createAdminInterface(j.id, tokenStore),
584
+ () => this._refreshOwnedProjects(tokenStore)
585
+ ));
586
+ }
587
+ _useOwnedProjects() {
588
+ this._ensureInternalProject();
589
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
590
+ const json = useCache(this._ownedProjectsCache, [tokenStore], "useOwnedProjects()");
591
+ return (0, import_react.useMemo)(() => json.map((j) => this._projectAdminFromJson(
592
+ j,
593
+ this._createAdminInterface(j.id, tokenStore),
594
+ () => this._refreshOwnedProjects(tokenStore)
595
+ )), [json]);
596
+ }
597
+ _onOwnedProjectsChange(callback) {
598
+ this._ensureInternalProject();
599
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
600
+ return this._ownedProjectsCache.onChange([tokenStore], (projects) => {
601
+ callback(projects.map((j) => this._projectAdminFromJson(
602
+ j,
603
+ this._createAdminInterface(j.id, tokenStore),
604
+ () => this._refreshOwnedProjects(tokenStore)
605
+ )));
622
606
  });
623
- constructor(options) {
624
- if ("interface" in options) {
625
- super({
626
- interface: options.interface,
627
- tokenStore: options.tokenStore,
628
- urls: options.urls,
629
- });
607
+ }
608
+ async _createProject(newProject) {
609
+ this._ensureInternalProject();
610
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
611
+ const json = await this._interface.createProject(newProject, tokenStore);
612
+ const res = this._projectAdminFromJson(
613
+ json,
614
+ this._createAdminInterface(json.id, tokenStore),
615
+ () => this._refreshOwnedProjects(tokenStore)
616
+ );
617
+ await this._refreshOwnedProjects(tokenStore);
618
+ return res;
619
+ }
620
+ async _refreshUser(tokenStore) {
621
+ await this._currentUserCache.refresh([tokenStore]);
622
+ }
623
+ async _refreshUsers() {
624
+ }
625
+ async _refreshProject() {
626
+ await this._currentProjectCache.refresh([]);
627
+ }
628
+ async _refreshOwnedProjects(tokenStore) {
629
+ await this._ownedProjectsCache.refresh([tokenStore]);
630
+ }
631
+ static get [stackAppInternalsSymbol]() {
632
+ return {
633
+ fromClientJson: (json) => {
634
+ const providedCheckString = JSON.stringify((0, import_objects.omit)(json, [
635
+ /* none currently */
636
+ ]));
637
+ const existing = allClientApps.get(json.uniqueIdentifier);
638
+ if (existing) {
639
+ const [existingCheckString, clientApp] = existing;
640
+ if (existingCheckString !== providedCheckString) {
641
+ throw new import_errors.StackAssertionError("The provided app JSON does not match the configuration of the existing client app with the same unique identifier", { providedObj: json, existingString: existingCheckString });
642
+ }
643
+ return clientApp;
630
644
  }
631
- else {
632
- super({
633
- interface: new StackServerInterface({
634
- baseUrl: options.baseUrl ?? getDefaultBaseUrl(),
635
- projectId: options.projectId ?? getDefaultProjectId(),
636
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
637
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
638
- }),
639
- tokenStore: options.tokenStore,
640
- urls: options.urls ?? {},
641
- });
645
+ return new __StackClientAppImpl({
646
+ ...json,
647
+ checkString: providedCheckString
648
+ });
649
+ }
650
+ };
651
+ }
652
+ get [stackAppInternalsSymbol]() {
653
+ return {
654
+ toClientJson: () => {
655
+ if (!("publishableClientKey" in this._interface.options)) {
656
+ throw Error("Cannot serialize to JSON from an application without a publishable client key");
642
657
  }
643
- }
644
- _serverUserFromJson(json) {
645
- if (json === null)
646
- return null;
647
- const app = this;
648
658
  return {
649
- ...this._userFromJson(json),
650
- serverMetadata: json.serverMetadata,
651
- async delete() {
652
- const res = await app._interface.deleteServerUser(this.id);
653
- await app._refreshUsers();
654
- return res;
655
- },
656
- async update(update) {
657
- const res = await app._interface.setServerUserCustomizableData(this.id, update);
658
- await app._refreshUsers();
659
- return res;
660
- },
661
- getClientUser() {
662
- return app._userFromJson(json);
663
- },
664
- toJson() {
665
- return app._serverUserToJson(this);
666
- },
659
+ baseUrl: this._interface.options.baseUrl,
660
+ projectId: this.projectId,
661
+ publishableClientKey: this._interface.options.publishableClientKey,
662
+ tokenStore: this._tokenStoreOptions,
663
+ urls: this._urlOptions,
664
+ uniqueIdentifier: this._uniqueIdentifier
667
665
  };
668
- }
669
- _currentServerUserFromJson(json, tokenStore) {
670
- if (json === null)
671
- return null;
672
- const app = this;
673
- const nonCurrentServerUser = this._serverUserFromJson(json);
674
- const currentUser = {
675
- ...nonCurrentServerUser,
676
- tokenStore,
677
- async delete() {
678
- const res = await nonCurrentServerUser.delete();
679
- await app._refreshUser(tokenStore);
680
- return res;
681
- },
682
- async update(update) {
683
- const res = await nonCurrentServerUser.update(update);
684
- await app._refreshUser(tokenStore);
685
- return res;
686
- },
687
- signOut() {
688
- return app._signOut(tokenStore);
689
- },
690
- getClientUser() {
691
- return app._currentUserFromJson(json, tokenStore);
692
- },
693
- sendVerificationEmail() {
694
- return app._sendVerificationEmail(tokenStore);
695
- },
696
- updatePassword(options) {
697
- return app._updatePassword(options, tokenStore);
698
- },
699
- };
700
- if (this.isInternalProject()) {
701
- const internalUser = {
702
- ...currentUser,
703
- createProject(newProject) {
704
- return app._createProject(newProject);
705
- },
706
- listOwnedProjects() {
707
- return app._listOwnedProjects();
708
- },
709
- useOwnedProjects() {
710
- return app._useOwnedProjects();
711
- },
712
- onOwnedProjectsChange(callback) {
713
- return app._onOwnedProjectsChange(callback);
714
- }
715
- };
716
- Object.freeze(internalUser);
717
- return internalUser;
666
+ },
667
+ setCurrentUser: (userJsonPromise) => {
668
+ (0, import_promises.runAsynchronously)(this._currentUserCache.forceSetCachedValueAsync([getTokenStore(this._tokenStoreOptions)], userJsonPromise));
669
+ }
670
+ };
671
+ }
672
+ };
673
+ var _StackServerAppImpl = class extends _StackClientAppImpl {
674
+ // TODO override the client user cache to use the server user cache, so we save some requests
675
+ _currentServerUserCache = createCacheByTokenStore(async (tokenStore) => {
676
+ const user = await this._interface.getServerUserByToken(tokenStore);
677
+ return import_results.Result.or(user, null);
678
+ });
679
+ _serverUsersCache = createCache(async () => {
680
+ return await this._interface.listUsers();
681
+ });
682
+ constructor(options) {
683
+ if ("interface" in options) {
684
+ super({
685
+ interface: options.interface,
686
+ tokenStore: options.tokenStore,
687
+ urls: options.urls
688
+ });
689
+ } else {
690
+ super({
691
+ interface: new import_stack_shared.StackServerInterface({
692
+ baseUrl: options.baseUrl ?? getDefaultBaseUrl(),
693
+ projectId: options.projectId ?? getDefaultProjectId(),
694
+ publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
695
+ secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey()
696
+ }),
697
+ tokenStore: options.tokenStore,
698
+ urls: options.urls ?? {}
699
+ });
700
+ }
701
+ }
702
+ _serverUserFromJson(json) {
703
+ if (json === null)
704
+ return null;
705
+ const app = this;
706
+ return {
707
+ ...this._userFromJson(json),
708
+ serverMetadata: json.serverMetadata,
709
+ async delete() {
710
+ const res = await app._interface.deleteServerUser(this.id);
711
+ await app._refreshUsers();
712
+ return res;
713
+ },
714
+ async update(update) {
715
+ const res = await app._interface.setServerUserCustomizableData(this.id, update);
716
+ await app._refreshUsers();
717
+ return res;
718
+ },
719
+ getClientUser() {
720
+ return app._userFromJson(json);
721
+ },
722
+ toJson() {
723
+ return app._serverUserToJson(this);
724
+ }
725
+ };
726
+ }
727
+ _currentServerUserFromJson(json, tokenStore) {
728
+ if (json === null)
729
+ return null;
730
+ const app = this;
731
+ const nonCurrentServerUser = this._serverUserFromJson(json);
732
+ const currentUser = {
733
+ ...nonCurrentServerUser,
734
+ tokenStore,
735
+ async delete() {
736
+ const res = await nonCurrentServerUser.delete();
737
+ await app._refreshUser(tokenStore);
738
+ return res;
739
+ },
740
+ async update(update) {
741
+ const res = await nonCurrentServerUser.update(update);
742
+ await app._refreshUser(tokenStore);
743
+ return res;
744
+ },
745
+ signOut() {
746
+ return app._signOut(tokenStore);
747
+ },
748
+ getClientUser() {
749
+ return app._currentUserFromJson(json, tokenStore);
750
+ },
751
+ sendVerificationEmail() {
752
+ return app._sendVerificationEmail(tokenStore);
753
+ },
754
+ updatePassword(options) {
755
+ return app._updatePassword(options, tokenStore);
756
+ }
757
+ };
758
+ if (this.isInternalProject()) {
759
+ const internalUser = {
760
+ ...currentUser,
761
+ createProject(newProject) {
762
+ return app._createProject(newProject);
763
+ },
764
+ listOwnedProjects() {
765
+ return app._listOwnedProjects();
766
+ },
767
+ useOwnedProjects() {
768
+ return app._useOwnedProjects();
769
+ },
770
+ onOwnedProjectsChange(callback) {
771
+ return app._onOwnedProjectsChange(callback);
718
772
  }
719
- else {
720
- Object.freeze(currentUser);
721
- return currentUser;
773
+ };
774
+ Object.freeze(internalUser);
775
+ return internalUser;
776
+ } else {
777
+ Object.freeze(currentUser);
778
+ return currentUser;
779
+ }
780
+ }
781
+ _serverUserToJson(user) {
782
+ return {
783
+ projectId: user.projectId,
784
+ id: user.id,
785
+ displayName: user.displayName,
786
+ primaryEmail: user.primaryEmail,
787
+ primaryEmailVerified: user.primaryEmailVerified,
788
+ profileImageUrl: user.profileImageUrl,
789
+ signedUpAtMillis: user.signedUpAt.getTime(),
790
+ clientMetadata: user.clientMetadata,
791
+ serverMetadata: user.serverMetadata,
792
+ authMethod: user.authMethod,
793
+ hasPassword: user.hasPassword,
794
+ authWithEmail: user.authWithEmail,
795
+ oauthProviders: user.oauthProviders
796
+ };
797
+ }
798
+ async getServerUser() {
799
+ this._ensurePersistentTokenStore();
800
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
801
+ const userJson = await this._currentServerUserCache.getOrWait([tokenStore], "write-only");
802
+ return this._currentServerUserFromJson(userJson, tokenStore);
803
+ }
804
+ useServerUser(options) {
805
+ this._ensurePersistentTokenStore();
806
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
807
+ const userJson = useCache(this._currentServerUserCache, [tokenStore], "useServerUser()");
808
+ return (0, import_react.useMemo)(() => {
809
+ if (options?.required && userJson === null) {
810
+ (0, import_react.use)(this.redirectToSignIn());
811
+ }
812
+ return this._currentServerUserFromJson(userJson, tokenStore);
813
+ }, [userJson, tokenStore, options?.required]);
814
+ }
815
+ onServerUserChange(callback) {
816
+ this._ensurePersistentTokenStore();
817
+ const tokenStore = getTokenStore(this._tokenStoreOptions);
818
+ return this._currentServerUserCache.onChange([tokenStore], (userJson) => {
819
+ callback(this._currentServerUserFromJson(userJson, tokenStore));
820
+ });
821
+ }
822
+ async listServerUsers() {
823
+ const json = await this._serverUsersCache.getOrWait([], "write-only");
824
+ return json.map((j) => this._serverUserFromJson(j));
825
+ }
826
+ useServerUsers() {
827
+ const json = useCache(this._serverUsersCache, [], "useServerUsers()");
828
+ return (0, import_react.useMemo)(() => {
829
+ return json.map((j) => this._serverUserFromJson(j));
830
+ }, [json]);
831
+ }
832
+ onServerUsersChange(callback) {
833
+ return this._serverUsersCache.onChange([], (users) => {
834
+ callback(users.map((j) => this._serverUserFromJson(j)));
835
+ });
836
+ }
837
+ async _refreshUser(tokenStore) {
838
+ await Promise.all([
839
+ super._refreshUser(tokenStore),
840
+ this._currentServerUserCache.refresh([tokenStore])
841
+ ]);
842
+ }
843
+ async _refreshUsers() {
844
+ await Promise.all([
845
+ super._refreshUsers(),
846
+ this._serverUsersCache.refresh([])
847
+ ]);
848
+ }
849
+ };
850
+ var _StackAdminAppImpl = class extends _StackServerAppImpl {
851
+ _adminProjectCache = createCache(async () => {
852
+ return await this._interface.getProject();
853
+ });
854
+ _apiKeySetsCache = createCache(async () => {
855
+ return await this._interface.listApiKeySets();
856
+ });
857
+ constructor(options) {
858
+ super({
859
+ interface: new import_stack_shared.StackAdminInterface({
860
+ baseUrl: options.baseUrl ?? getDefaultBaseUrl(),
861
+ projectId: options.projectId ?? getDefaultProjectId(),
862
+ ..."projectOwnerTokens" in options ? {
863
+ projectOwnerTokens: options.projectOwnerTokens
864
+ } : {
865
+ publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
866
+ secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
867
+ superSecretAdminKey: options.superSecretAdminKey ?? getDefaultSuperSecretAdminKey()
722
868
  }
723
- }
724
- _serverUserToJson(user) {
725
- return {
726
- projectId: user.projectId,
727
- id: user.id,
728
- displayName: user.displayName,
729
- primaryEmail: user.primaryEmail,
730
- primaryEmailVerified: user.primaryEmailVerified,
731
- profileImageUrl: user.profileImageUrl,
732
- signedUpAtMillis: user.signedUpAt.getTime(),
733
- clientMetadata: user.clientMetadata,
734
- serverMetadata: user.serverMetadata,
735
- authMethod: user.authMethod,
736
- hasPassword: user.hasPassword,
737
- authWithEmail: user.authWithEmail,
738
- oauthProviders: user.oauthProviders,
739
- };
740
- }
741
- async getServerUser() {
742
- this._ensurePersistentTokenStore();
743
- const tokenStore = getTokenStore(this._tokenStoreOptions);
744
- const userJson = await this._currentServerUserCache.getOrWait([tokenStore], "write-only");
745
- return this._currentServerUserFromJson(userJson, tokenStore);
746
- }
747
- useServerUser(options) {
748
- this._ensurePersistentTokenStore();
749
- const tokenStore = getTokenStore(this._tokenStoreOptions);
750
- const userJson = useCache(this._currentServerUserCache, [tokenStore], "useServerUser()");
751
- return useMemo(() => {
752
- if (options?.required && userJson === null) {
753
- use(this.redirectToSignIn());
754
- }
755
- return this._currentServerUserFromJson(userJson, tokenStore);
756
- }, [userJson, tokenStore, options?.required]);
757
- }
758
- onServerUserChange(callback) {
759
- this._ensurePersistentTokenStore();
760
- const tokenStore = getTokenStore(this._tokenStoreOptions);
761
- return this._currentServerUserCache.onChange([tokenStore], (userJson) => {
762
- callback(this._currentServerUserFromJson(userJson, tokenStore));
763
- });
764
- }
765
- async listServerUsers() {
766
- const json = await this._serverUsersCache.getOrWait([], "write-only");
767
- return json.map((j) => this._serverUserFromJson(j));
768
- }
769
- useServerUsers() {
770
- const json = useCache(this._serverUsersCache, [], "useServerUsers()");
771
- return useMemo(() => {
772
- return json.map((j) => this._serverUserFromJson(j));
773
- }, [json]);
774
- }
775
- onServerUsersChange(callback) {
776
- return this._serverUsersCache.onChange([], (users) => {
777
- callback(users.map((j) => this._serverUserFromJson(j)));
778
- });
779
- }
780
- async _refreshUser(tokenStore) {
781
- await Promise.all([
782
- super._refreshUser(tokenStore),
783
- this._currentServerUserCache.refresh([tokenStore]),
784
- ]);
785
- }
786
- async _refreshUsers() {
787
- await Promise.all([
788
- super._refreshUsers(),
789
- this._serverUsersCache.refresh([]),
790
- ]);
791
- }
792
- }
793
- class _StackAdminAppImpl extends _StackServerAppImpl {
794
- _adminProjectCache = createCache(async () => {
795
- return await this._interface.getProject();
869
+ }),
870
+ tokenStore: options.tokenStore,
871
+ urls: options.urls
796
872
  });
797
- _apiKeySetsCache = createCache(async () => {
798
- return await this._interface.listApiKeySets();
873
+ }
874
+ _createApiKeySetBaseFromJson(data) {
875
+ const app = this;
876
+ return {
877
+ id: data.id,
878
+ description: data.description,
879
+ expiresAt: new Date(data.expiresAtMillis),
880
+ manuallyRevokedAt: data.manuallyRevokedAtMillis ? new Date(data.manuallyRevokedAtMillis) : null,
881
+ createdAt: new Date(data.createdAtMillis),
882
+ isValid() {
883
+ return this.whyInvalid() === null;
884
+ },
885
+ whyInvalid() {
886
+ if (this.expiresAt.getTime() < Date.now())
887
+ return "expired";
888
+ if (this.manuallyRevokedAt)
889
+ return "manually-revoked";
890
+ return null;
891
+ },
892
+ async revoke() {
893
+ const res = await app._interface.revokeApiKeySetById(data.id);
894
+ await app._refreshApiKeySets();
895
+ return res;
896
+ }
897
+ };
898
+ }
899
+ _createApiKeySetFromJson(data) {
900
+ return {
901
+ ...this._createApiKeySetBaseFromJson(data),
902
+ publishableClientKey: data.publishableClientKey ? { lastFour: data.publishableClientKey.lastFour } : null,
903
+ secretServerKey: data.secretServerKey ? { lastFour: data.secretServerKey.lastFour } : null,
904
+ superSecretAdminKey: data.superSecretAdminKey ? { lastFour: data.superSecretAdminKey.lastFour } : null
905
+ };
906
+ }
907
+ _createApiKeySetFirstViewFromJson(data) {
908
+ return {
909
+ ...this._createApiKeySetBaseFromJson(data),
910
+ publishableClientKey: data.publishableClientKey,
911
+ secretServerKey: data.secretServerKey,
912
+ superSecretAdminKey: data.superSecretAdminKey
913
+ };
914
+ }
915
+ async getProjectAdmin() {
916
+ return this._projectAdminFromJson(
917
+ await this._adminProjectCache.getOrWait([], "write-only"),
918
+ this._interface,
919
+ () => this._refreshProject()
920
+ );
921
+ }
922
+ useProjectAdmin() {
923
+ const json = useCache(this._adminProjectCache, [], "useProjectAdmin()");
924
+ return (0, import_react.useMemo)(() => this._projectAdminFromJson(
925
+ json,
926
+ this._interface,
927
+ () => this._refreshProject()
928
+ ), [json]);
929
+ }
930
+ onProjectAdminChange(callback) {
931
+ return this._adminProjectCache.onChange([], (project) => {
932
+ callback(this._projectAdminFromJson(
933
+ project,
934
+ this._interface,
935
+ () => this._refreshProject()
936
+ ));
799
937
  });
800
- constructor(options) {
801
- super({
802
- interface: new StackAdminInterface({
803
- baseUrl: options.baseUrl ?? getDefaultBaseUrl(),
804
- projectId: options.projectId ?? getDefaultProjectId(),
805
- ..."projectOwnerTokens" in options ? {
806
- projectOwnerTokens: options.projectOwnerTokens,
807
- } : {
808
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
809
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
810
- superSecretAdminKey: options.superSecretAdminKey ?? getDefaultSuperSecretAdminKey(),
811
- },
812
- }),
813
- tokenStore: options.tokenStore,
814
- urls: options.urls,
815
- });
816
- }
817
- _createApiKeySetBaseFromJson(data) {
818
- const app = this;
819
- return {
820
- id: data.id,
821
- description: data.description,
822
- expiresAt: new Date(data.expiresAtMillis),
823
- manuallyRevokedAt: data.manuallyRevokedAtMillis ? new Date(data.manuallyRevokedAtMillis) : null,
824
- createdAt: new Date(data.createdAtMillis),
825
- isValid() {
826
- return this.whyInvalid() === null;
827
- },
828
- whyInvalid() {
829
- if (this.expiresAt.getTime() < Date.now())
830
- return "expired";
831
- if (this.manuallyRevokedAt)
832
- return "manually-revoked";
833
- return null;
834
- },
835
- async revoke() {
836
- const res = await app._interface.revokeApiKeySetById(data.id);
837
- await app._refreshApiKeySets();
838
- return res;
839
- }
840
- };
841
- }
842
- _createApiKeySetFromJson(data) {
843
- return {
844
- ...this._createApiKeySetBaseFromJson(data),
845
- publishableClientKey: data.publishableClientKey ? { lastFour: data.publishableClientKey.lastFour } : null,
846
- secretServerKey: data.secretServerKey ? { lastFour: data.secretServerKey.lastFour } : null,
847
- superSecretAdminKey: data.superSecretAdminKey ? { lastFour: data.superSecretAdminKey.lastFour } : null,
848
- };
849
- }
850
- _createApiKeySetFirstViewFromJson(data) {
851
- return {
852
- ...this._createApiKeySetBaseFromJson(data),
853
- publishableClientKey: data.publishableClientKey,
854
- secretServerKey: data.secretServerKey,
855
- superSecretAdminKey: data.superSecretAdminKey,
856
- };
857
- }
858
- async getProjectAdmin() {
859
- return this._projectAdminFromJson(await this._adminProjectCache.getOrWait([], "write-only"), this._interface, () => this._refreshProject());
860
- }
861
- useProjectAdmin() {
862
- const json = useCache(this._adminProjectCache, [], "useProjectAdmin()");
863
- return useMemo(() => this._projectAdminFromJson(json, this._interface, () => this._refreshProject()), [json]);
864
- }
865
- onProjectAdminChange(callback) {
866
- return this._adminProjectCache.onChange([], (project) => {
867
- callback(this._projectAdminFromJson(project, this._interface, () => this._refreshProject()));
868
- });
869
- }
870
- async listApiKeySets() {
871
- const json = await this._apiKeySetsCache.getOrWait([], "write-only");
872
- return json.map((j) => this._createApiKeySetFromJson(j));
873
- }
874
- useApiKeySets() {
875
- const json = useCache(this._apiKeySetsCache, [], "useApiKeySets()");
876
- return useMemo(() => {
877
- return json.map((j) => this._createApiKeySetFromJson(j));
878
- }, [json]);
879
- }
880
- onApiKeySetsChange(callback) {
881
- return this._apiKeySetsCache.onChange([], (apiKeySets) => {
882
- callback(apiKeySets.map((j) => this._createApiKeySetFromJson(j)));
883
- });
884
- }
885
- async createApiKeySet(options) {
886
- const json = await this._interface.createApiKeySet(options);
887
- await this._refreshApiKeySets();
888
- return this._createApiKeySetFirstViewFromJson(json);
889
- }
890
- async _refreshProject() {
891
- await Promise.all([
892
- super._refreshProject(),
893
- this._adminProjectCache.refresh([]),
894
- ]);
895
- }
896
- async _refreshApiKeySets() {
897
- await this._apiKeySetsCache.refresh([]);
898
- }
899
- }
900
- export const StackClientApp = _StackClientAppImpl;
901
- export const StackServerApp = _StackServerAppImpl;
902
- export const StackAdminApp = _StackAdminAppImpl;
938
+ }
939
+ async listApiKeySets() {
940
+ const json = await this._apiKeySetsCache.getOrWait([], "write-only");
941
+ return json.map((j) => this._createApiKeySetFromJson(j));
942
+ }
943
+ useApiKeySets() {
944
+ const json = useCache(this._apiKeySetsCache, [], "useApiKeySets()");
945
+ return (0, import_react.useMemo)(() => {
946
+ return json.map((j) => this._createApiKeySetFromJson(j));
947
+ }, [json]);
948
+ }
949
+ onApiKeySetsChange(callback) {
950
+ return this._apiKeySetsCache.onChange([], (apiKeySets) => {
951
+ callback(apiKeySets.map((j) => this._createApiKeySetFromJson(j)));
952
+ });
953
+ }
954
+ async createApiKeySet(options) {
955
+ const json = await this._interface.createApiKeySet(options);
956
+ await this._refreshApiKeySets();
957
+ return this._createApiKeySetFirstViewFromJson(json);
958
+ }
959
+ async _refreshProject() {
960
+ await Promise.all([
961
+ super._refreshProject(),
962
+ this._adminProjectCache.refresh([])
963
+ ]);
964
+ }
965
+ async _refreshApiKeySets() {
966
+ await this._apiKeySetsCache.refresh([]);
967
+ }
968
+ };
969
+ var StackClientApp = _StackClientAppImpl;
970
+ var StackServerApp = _StackServerAppImpl;
971
+ var StackAdminApp = _StackAdminAppImpl;
972
+ // Annotate the CommonJS export names for ESM import in node:
973
+ 0 && (module.exports = {
974
+ StackAdminApp,
975
+ StackClientApp,
976
+ StackServerApp,
977
+ stackAppInternalsSymbol
978
+ });