@stackframe/react 2.7.21 → 2.7.23

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 (145) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +2 -2
  3. package/dist/admin-app-impl-BN0oFR_r.d.mts +395 -0
  4. package/dist/admin-app-impl-DUgwqr7u.d.ts +395 -0
  5. package/dist/components/selected-team-switcher.d.mts +18 -6
  6. package/dist/components/selected-team-switcher.d.ts +18 -6
  7. package/dist/components/team-icon.d.mts +18 -6
  8. package/dist/components/team-icon.d.ts +18 -6
  9. package/dist/components-page/stack-handler.d.mts +18 -6
  10. package/dist/components-page/stack-handler.d.ts +18 -6
  11. package/dist/esm/lib/stack-app/api-keys/index.js +14 -0
  12. package/dist/esm/lib/stack-app/api-keys/index.js.map +1 -0
  13. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js +291 -0
  14. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -0
  15. package/dist/esm/lib/{stack-app.js → stack-app/apps/implementations/client-app-impl.js} +35 -1108
  16. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -0
  17. package/dist/esm/lib/stack-app/apps/implementations/common.js +143 -0
  18. package/dist/esm/lib/stack-app/apps/implementations/common.js.map +1 -0
  19. package/dist/esm/lib/stack-app/apps/implementations/index.js +24 -0
  20. package/dist/esm/lib/stack-app/apps/implementations/index.js.map +1 -0
  21. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js +527 -0
  22. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -0
  23. package/dist/esm/lib/stack-app/apps/index.js +16 -0
  24. package/dist/esm/lib/stack-app/apps/index.js.map +1 -0
  25. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js +7 -0
  26. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js.map +1 -0
  27. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js +7 -0
  28. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js.map +1 -0
  29. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js +7 -0
  30. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js.map +1 -0
  31. package/dist/esm/lib/stack-app/common.js +6 -0
  32. package/dist/esm/lib/stack-app/common.js.map +1 -0
  33. package/dist/esm/lib/stack-app/connected-accounts/index.js +1 -0
  34. package/dist/esm/lib/stack-app/connected-accounts/index.js.map +1 -0
  35. package/dist/esm/lib/stack-app/contact-channels/index.js +39 -0
  36. package/dist/esm/lib/stack-app/contact-channels/index.js.map +1 -0
  37. package/dist/esm/lib/stack-app/email-templates/index.js +11 -0
  38. package/dist/esm/lib/stack-app/email-templates/index.js.map +1 -0
  39. package/dist/esm/lib/stack-app/index.js +16 -0
  40. package/dist/esm/lib/stack-app/index.js.map +1 -0
  41. package/dist/esm/lib/stack-app/permissions/index.js +20 -0
  42. package/dist/esm/lib/stack-app/permissions/index.js.map +1 -0
  43. package/dist/esm/lib/stack-app/project-configs/index.js +1 -0
  44. package/dist/esm/lib/stack-app/project-configs/index.js.map +1 -0
  45. package/dist/esm/lib/stack-app/projects/index.js +57 -0
  46. package/dist/esm/lib/stack-app/projects/index.js.map +1 -0
  47. package/dist/esm/lib/stack-app/teams/index.js +38 -0
  48. package/dist/esm/lib/stack-app/teams/index.js.map +1 -0
  49. package/dist/esm/lib/stack-app/users/index.js +47 -0
  50. package/dist/esm/lib/stack-app/users/index.js.map +1 -0
  51. package/dist/generated/quetzal-translations.d.mts +2 -2
  52. package/dist/generated/quetzal-translations.d.ts +2 -2
  53. package/dist/{lib/stack-app.d.mts → index-CLnvv7mq.d.ts} +138 -354
  54. package/dist/{lib/stack-app.d.ts → index-aU2I3xr5.d.mts} +138 -354
  55. package/dist/index.d.mts +17 -5
  56. package/dist/index.d.ts +17 -5
  57. package/dist/lib/hooks.d.mts +17 -5
  58. package/dist/lib/hooks.d.ts +17 -5
  59. package/dist/lib/stack-app/api-keys/index.d.mts +40 -0
  60. package/dist/lib/stack-app/api-keys/index.d.ts +40 -0
  61. package/dist/lib/stack-app/api-keys/index.js +39 -0
  62. package/dist/lib/stack-app/api-keys/index.js.map +1 -0
  63. package/dist/lib/stack-app/apps/implementations/admin-app-impl.d.mts +30 -0
  64. package/dist/lib/stack-app/apps/implementations/admin-app-impl.d.ts +30 -0
  65. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js +316 -0
  66. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -0
  67. package/dist/lib/stack-app/apps/implementations/client-app-impl.d.mts +30 -0
  68. package/dist/lib/stack-app/apps/implementations/client-app-impl.d.ts +30 -0
  69. package/dist/lib/{stack-app.js → stack-app/apps/implementations/client-app-impl.js} +73 -1151
  70. package/dist/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -0
  71. package/dist/lib/stack-app/apps/implementations/common.d.mts +45 -0
  72. package/dist/lib/stack-app/apps/implementations/common.d.ts +45 -0
  73. package/dist/lib/stack-app/apps/implementations/common.js +188 -0
  74. package/dist/lib/stack-app/apps/implementations/common.js.map +1 -0
  75. package/dist/lib/stack-app/apps/implementations/index.d.mts +36 -0
  76. package/dist/lib/stack-app/apps/implementations/index.d.ts +36 -0
  77. package/dist/lib/stack-app/apps/implementations/index.js +51 -0
  78. package/dist/lib/stack-app/apps/implementations/index.js.map +1 -0
  79. package/dist/lib/stack-app/apps/implementations/server-app-impl.d.mts +30 -0
  80. package/dist/lib/stack-app/apps/implementations/server-app-impl.d.ts +30 -0
  81. package/dist/lib/stack-app/apps/implementations/server-app-impl.js +552 -0
  82. package/dist/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -0
  83. package/dist/lib/stack-app/apps/index.d.mts +23 -0
  84. package/dist/lib/stack-app/apps/index.d.ts +23 -0
  85. package/dist/lib/stack-app/apps/index.js +37 -0
  86. package/dist/lib/stack-app/apps/index.js.map +1 -0
  87. package/dist/lib/stack-app/apps/interfaces/admin-app.d.mts +23 -0
  88. package/dist/lib/stack-app/apps/interfaces/admin-app.d.ts +23 -0
  89. package/dist/lib/stack-app/apps/interfaces/admin-app.js +32 -0
  90. package/dist/lib/stack-app/apps/interfaces/admin-app.js.map +1 -0
  91. package/dist/lib/stack-app/apps/interfaces/client-app.d.mts +23 -0
  92. package/dist/lib/stack-app/apps/interfaces/client-app.d.ts +23 -0
  93. package/dist/lib/stack-app/apps/interfaces/client-app.js +32 -0
  94. package/dist/lib/stack-app/apps/interfaces/client-app.js.map +1 -0
  95. package/dist/lib/stack-app/apps/interfaces/server-app.d.mts +23 -0
  96. package/dist/lib/stack-app/apps/interfaces/server-app.d.ts +23 -0
  97. package/dist/lib/stack-app/apps/interfaces/server-app.js +32 -0
  98. package/dist/lib/stack-app/apps/interfaces/server-app.js.map +1 -0
  99. package/dist/lib/stack-app/common.d.mts +63 -0
  100. package/dist/lib/stack-app/common.d.ts +63 -0
  101. package/dist/lib/stack-app/common.js +31 -0
  102. package/dist/lib/stack-app/common.js.map +1 -0
  103. package/dist/lib/stack-app/connected-accounts/index.d.mts +13 -0
  104. package/dist/lib/stack-app/connected-accounts/index.d.ts +13 -0
  105. package/dist/lib/stack-app/connected-accounts/index.js +19 -0
  106. package/dist/lib/stack-app/connected-accounts/index.js.map +1 -0
  107. package/dist/lib/stack-app/contact-channels/index.d.mts +38 -0
  108. package/dist/lib/stack-app/contact-channels/index.d.ts +38 -0
  109. package/dist/lib/stack-app/contact-channels/index.js +67 -0
  110. package/dist/lib/stack-app/contact-channels/index.js.map +1 -0
  111. package/dist/lib/stack-app/email-templates/index.d.mts +15 -0
  112. package/dist/lib/stack-app/email-templates/index.d.ts +15 -0
  113. package/dist/lib/stack-app/email-templates/index.js +36 -0
  114. package/dist/lib/stack-app/email-templates/index.js.map +1 -0
  115. package/dist/lib/stack-app/index.d.mts +23 -0
  116. package/dist/lib/stack-app/index.d.ts +23 -0
  117. package/dist/lib/stack-app/index.js +38 -0
  118. package/dist/lib/stack-app/index.js.map +1 -0
  119. package/dist/lib/stack-app/permissions/index.d.mts +21 -0
  120. package/dist/lib/stack-app/permissions/index.d.ts +21 -0
  121. package/dist/lib/stack-app/permissions/index.js +46 -0
  122. package/dist/lib/stack-app/permissions/index.js.map +1 -0
  123. package/dist/lib/stack-app/project-configs/index.d.mts +82 -0
  124. package/dist/lib/stack-app/project-configs/index.d.ts +82 -0
  125. package/dist/lib/stack-app/project-configs/index.js +19 -0
  126. package/dist/lib/stack-app/project-configs/index.js.map +1 -0
  127. package/dist/lib/stack-app/projects/index.d.mts +23 -0
  128. package/dist/lib/stack-app/projects/index.d.ts +23 -0
  129. package/dist/lib/stack-app/projects/index.js +83 -0
  130. package/dist/lib/stack-app/projects/index.js.map +1 -0
  131. package/dist/lib/stack-app/teams/index.d.mts +23 -0
  132. package/dist/lib/stack-app/teams/index.d.ts +23 -0
  133. package/dist/lib/stack-app/teams/index.js +66 -0
  134. package/dist/lib/stack-app/teams/index.js.map +1 -0
  135. package/dist/lib/stack-app/users/index.d.mts +23 -0
  136. package/dist/lib/stack-app/users/index.d.ts +23 -0
  137. package/dist/lib/stack-app/users/index.js +74 -0
  138. package/dist/lib/stack-app/users/index.js.map +1 -0
  139. package/dist/providers/stack-provider-client.d.mts +17 -5
  140. package/dist/providers/stack-provider-client.d.ts +17 -5
  141. package/dist/providers/stack-provider.d.mts +18 -6
  142. package/dist/providers/stack-provider.d.ts +18 -6
  143. package/package.json +3 -3
  144. package/dist/esm/lib/stack-app.js.map +0 -1
  145. package/dist/lib/stack-app.js.map +0 -1
@@ -1,14 +1,11 @@
1
- // src/lib/stack-app.ts
1
+ // src/lib/stack-app/apps/implementations/client-app-impl.ts
2
2
  import { WebAuthnError, startAuthentication, startRegistration } from "@simplewebauthn/browser";
3
- import { KnownErrors, StackAdminInterface, StackClientInterface, StackServerInterface } from "@stackframe/stack-shared";
4
- import { getProductionModeErrors } from "@stackframe/stack-shared/dist/helpers/production-mode";
3
+ import { KnownErrors, StackClientInterface } from "@stackframe/stack-shared";
5
4
  import { InternalSession } from "@stackframe/stack-shared/dist/sessions";
6
- import { encodeBase64 } from "@stackframe/stack-shared/dist/utils/bytes";
7
- import { AsyncCache } from "@stackframe/stack-shared/dist/utils/caches";
8
5
  import { isBrowserLike } from "@stackframe/stack-shared/dist/utils/env";
9
- import { StackAssertionError, concatStacktraces, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
6
+ import { StackAssertionError, captureError, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
10
7
  import { DependenciesMap } from "@stackframe/stack-shared/dist/utils/maps";
11
- import { deepPlainEquals, filterUndefined, omit, pick } from "@stackframe/stack-shared/dist/utils/objects";
8
+ import { deepPlainEquals, omit } from "@stackframe/stack-shared/dist/utils/objects";
12
9
  import { neverResolve, runAsynchronously, wait } from "@stackframe/stack-shared/dist/utils/promises";
13
10
  import { suspend, suspendIfSsr } from "@stackframe/stack-shared/dist/utils/react";
14
11
  import { Result } from "@stackframe/stack-shared/dist/utils/results";
@@ -18,134 +15,21 @@ import { getRelativePart, isRelative } from "@stackframe/stack-shared/dist/utils
18
15
  import { generateUuid } from "@stackframe/stack-shared/dist/utils/uuids";
19
16
  import * as cookie from "cookie";
20
17
  import React, { useCallback, useMemo } from "react";
21
- import { constructRedirectUrl } from "../utils/url";
22
- import { addNewOAuthProviderOrScope, callOAuthCallback, signInWithOAuth } from "./auth";
23
- import { createBrowserCookieHelper, createCookieHelper, createPlaceholderCookieHelper, deleteCookieClient, getCookieClient, setOrDeleteCookie, setOrDeleteCookieClient } from "./cookie";
18
+ import { constructRedirectUrl } from "../../../../utils/url";
19
+ import { addNewOAuthProviderOrScope, callOAuthCallback, signInWithOAuth } from "../../../auth";
20
+ import { createBrowserCookieHelper, createCookieHelper, createPlaceholderCookieHelper, deleteCookieClient, getCookieClient, setOrDeleteCookie, setOrDeleteCookieClient } from "../../../cookie";
21
+ import { stackAppInternalsSymbol } from "../../common";
22
+ import { contactChannelCreateOptionsToCrud, contactChannelUpdateOptionsToCrud } from "../../contact-channels";
23
+ import { adminProjectCreateOptionsToCrud } from "../../projects";
24
+ import { teamCreateOptionsToCrud, teamUpdateOptionsToCrud } from "../../teams";
25
+ import { userUpdateOptionsToCrud } from "../../users";
26
+ import { clientVersion, createCache, createCacheBySession, createEmptyTokenStore, getBaseUrl, getDefaultProjectId, getDefaultPublishableClientKey, getUrls } from "./common";
27
+ import { useAsyncCache } from "./common";
24
28
  var isReactServer = false;
25
- var clientVersion = "js @stackframe/react@2.7.21";
26
- if (clientVersion.startsWith("STACK_COMPILE_TIME")) {
27
- throw new StackAssertionError("Client version was not replaced. Something went wrong during build!");
28
- }
29
29
  var process = globalThis.process ?? { env: {} };
30
- function getUrls(partial) {
31
- const handler = partial.handler ?? "/handler";
32
- const home = partial.home ?? "/";
33
- const afterSignIn = partial.afterSignIn ?? home;
34
- return {
35
- handler,
36
- signIn: `${handler}/sign-in`,
37
- afterSignIn: home,
38
- signUp: `${handler}/sign-up`,
39
- afterSignUp: afterSignIn,
40
- signOut: `${handler}/sign-out`,
41
- afterSignOut: home,
42
- emailVerification: `${handler}/email-verification`,
43
- passwordReset: `${handler}/password-reset`,
44
- forgotPassword: `${handler}/forgot-password`,
45
- oauthCallback: `${handler}/oauth-callback`,
46
- magicLinkCallback: `${handler}/magic-link-callback`,
47
- home,
48
- accountSettings: `${handler}/account-settings`,
49
- error: `${handler}/error`,
50
- teamInvitation: `${handler}/team-invitation`,
51
- ...filterUndefined(partial)
52
- };
53
- }
54
- function getDefaultProjectId() {
55
- return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || throwErr(new Error("Welcome to Stack Auth! 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."));
56
- }
57
- function getDefaultPublishableClientKey() {
58
- return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || throwErr(new Error("Welcome to Stack Auth! 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."));
59
- }
60
- function getDefaultSecretServerKey() {
61
- return process.env.STACK_SECRET_SERVER_KEY || throwErr(new Error("No secret server key provided. Please copy your key from the Stack dashboard and put your it in the STACK_SECRET_SERVER_KEY environment variable."));
62
- }
63
- function getDefaultSuperSecretAdminKey() {
64
- return process.env.STACK_SUPER_SECRET_ADMIN_KEY || throwErr(new Error("No super secret admin key provided. Please copy your key from the Stack dashboard and put it in the STACK_SUPER_SECRET_ADMIN_KEY environment variable."));
65
- }
66
- function getBaseUrl(userSpecifiedBaseUrl) {
67
- let url;
68
- if (userSpecifiedBaseUrl) {
69
- if (typeof userSpecifiedBaseUrl === "string") {
70
- url = userSpecifiedBaseUrl;
71
- } else {
72
- if (isBrowserLike()) {
73
- url = userSpecifiedBaseUrl.browser;
74
- } else {
75
- url = userSpecifiedBaseUrl.server;
76
- }
77
- }
78
- } else {
79
- if (isBrowserLike()) {
80
- url = process.env.NEXT_PUBLIC_BROWSER_STACK_API_URL;
81
- } else {
82
- url = process.env.NEXT_PUBLIC_SERVER_STACK_API_URL;
83
- }
84
- url = url || process.env.NEXT_PUBLIC_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;
85
- }
86
- return url.endsWith("/") ? url.slice(0, -1) : url;
87
- }
88
- var defaultBaseUrl = "https://api.stack-auth.com";
89
- function createEmptyTokenStore() {
90
- return new Store({
91
- refreshToken: null,
92
- accessToken: null
93
- });
94
- }
95
- var cachePromiseByComponentId = /* @__PURE__ */ new Map();
96
- function useAsyncCache(cache, dependencies, caller) {
97
- suspendIfSsr(caller);
98
- const id = React.useId();
99
- const subscribe = useCallback((cb) => {
100
- const { unsubscribe } = cache.onStateChange(dependencies, () => {
101
- cachePromiseByComponentId.delete(id);
102
- cb();
103
- });
104
- return unsubscribe;
105
- }, [cache, ...dependencies]);
106
- const getSnapshot = useCallback(() => {
107
- if (!cachePromiseByComponentId.has(id)) {
108
- cachePromiseByComponentId.set(id, cache.getOrWait(dependencies, "read-write"));
109
- }
110
- return cachePromiseByComponentId.get(id);
111
- }, [cache, ...dependencies]);
112
- const promise = React.useSyncExternalStore(
113
- subscribe,
114
- getSnapshot,
115
- () => throwErr(new Error("getServerSnapshot should never be called in useAsyncCache because we restrict to CSR earlier"))
116
- );
117
- const result = React.use(promise);
118
- if (result.status === "error") {
119
- const error = result.error;
120
- if (error instanceof Error && !error.__stackHasConcatenatedStacktraces) {
121
- concatStacktraces(error, new Error());
122
- error.__stackHasConcatenatedStacktraces = true;
123
- }
124
- throw error;
125
- }
126
- return result.data;
127
- }
128
- var stackAppInternalsSymbol = Symbol.for("StackAuth--DO-NOT-USE-OR-YOU-WILL-BE-FIRED--StackAppInternals");
129
- var allClientApps = /* @__PURE__ */ new Map();
130
- var createCache = (fetcher) => {
131
- return new AsyncCache(
132
- async (dependencies) => await Result.fromThrowingAsync(async () => await fetcher(dependencies)),
133
- {}
134
- );
135
- };
136
- var createCacheBySession = (fetcher) => {
137
- return new AsyncCache(
138
- async ([session, ...extraDependencies]) => await Result.fromThrowingAsync(async () => await fetcher(session, extraDependencies)),
139
- {
140
- onSubscribe: ([session], refresh) => {
141
- const handler = session.onInvalidate(() => refresh());
142
- return () => handler.unsubscribe();
143
- }
144
- }
145
- );
146
- };
147
30
  var numberOfAppsCreated = 0;
148
- var _StackClientAppImpl = class __StackClientAppImpl {
31
+ var allClientApps = /* @__PURE__ */ new Map();
32
+ var __StackClientAppImplIncomplete = class __StackClientAppImplIncomplete {
149
33
  constructor(_options) {
150
34
  this._options = _options;
151
35
  this._uniqueIdentifier = void 0;
@@ -231,6 +115,9 @@ var _StackClientAppImpl = class __StackClientAppImpl {
231
115
  * - So different token stores are separated and don't leak information between each other, eg. if the same user sends two requests to the same server they should get a different session object
232
116
  */
233
117
  this._sessionsByTokenStoreAndSessionKey = /* @__PURE__ */ new WeakMap();
118
+ if (!__StackClientAppImplIncomplete.LazyStackAdminAppImpl.value) {
119
+ throw new StackAssertionError("Admin app implementation not initialized. Did you import the _StackClientApp from stack-app/apps/implementations/index.ts? You can't import it directly from ./apps/implementations/client-app-impl.ts as that causes a circular dependency (see the comment at _LazyStackAdminAppImpl for more details).");
120
+ }
234
121
  if ("interface" in _options) {
235
122
  this._interface = _options.interface;
236
123
  } else {
@@ -688,12 +575,12 @@ var _StackClientAppImpl = class __StackClientAppImpl {
688
575
  let attResp;
689
576
  try {
690
577
  attResp = await startRegistration({ optionsJSON: options_json });
691
- debugger;
692
578
  } catch (error) {
693
579
  if (error instanceof WebAuthnError) {
694
580
  return Result.error(new KnownErrors.PasskeyWebAuthnError(error.message, error.name));
695
581
  } else {
696
- return Result.error(new KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration"));
582
+ captureError("passkey-registration-failed", error);
583
+ return Result.error(new KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"));
697
584
  }
698
585
  }
699
586
  const registrationResult = await app._interface.registerPasskey({ credential: attResp, code }, session);
@@ -890,7 +777,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
890
777
  }
891
778
  _getOwnedAdminApp(forProjectId, session) {
892
779
  if (!this._ownedAdminApps.has([session, forProjectId])) {
893
- this._ownedAdminApps.set([session, forProjectId], new _StackAdminAppImpl({
780
+ this._ownedAdminApps.set([session, forProjectId], new __StackClientAppImplIncomplete.LazyStackAdminAppImpl.value({
894
781
  baseUrl: this._interface.options.getBaseUrl(),
895
782
  projectId: forProjectId,
896
783
  tokenStore: null,
@@ -933,7 +820,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
933
820
  if (typeof this._redirectMethod === "object") {
934
821
  return this._redirectMethod.useNavigate();
935
822
  } else if (this._redirectMethod === "window") {
936
- return () => window.location.assign;
823
+ return (to) => window.location.assign(to);
937
824
  } else {
938
825
  return (to) => {
939
826
  };
@@ -1386,7 +1273,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
1386
1273
  }
1387
1274
  return clientApp;
1388
1275
  }
1389
- return new __StackClientAppImpl({
1276
+ return new __StackClientAppImplIncomplete({
1390
1277
  ...json,
1391
1278
  checkString: providedCheckString
1392
1279
  });
@@ -1424,976 +1311,16 @@ var _StackClientAppImpl = class __StackClientAppImpl {
1424
1311
  };
1425
1312
  }
1426
1313
  };
1427
- var _StackServerAppImpl = class extends _StackClientAppImpl {
1428
- constructor(options) {
1429
- super("interface" in options ? {
1430
- interface: options.interface,
1431
- tokenStore: options.tokenStore,
1432
- urls: options.urls,
1433
- oauthScopesOnSignIn: options.oauthScopesOnSignIn
1434
- } : {
1435
- interface: new StackServerInterface({
1436
- getBaseUrl: () => getBaseUrl(options.baseUrl),
1437
- projectId: options.projectId ?? getDefaultProjectId(),
1438
- clientVersion,
1439
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
1440
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey()
1441
- }),
1442
- baseUrl: options.baseUrl,
1443
- projectId: options.projectId,
1444
- publishableClientKey: options.publishableClientKey,
1445
- tokenStore: options.tokenStore,
1446
- urls: options.urls ?? {},
1447
- oauthScopesOnSignIn: options.oauthScopesOnSignIn ?? {},
1448
- redirectMethod: options.redirectMethod
1449
- });
1450
- // TODO override the client user cache to use the server user cache, so we save some requests
1451
- this._currentServerUserCache = createCacheBySession(async (session) => {
1452
- if (session.isKnownToBeInvalid()) {
1453
- return null;
1454
- }
1455
- return await this._interface.getServerUserByToken(session);
1456
- });
1457
- this._serverUsersCache = createCache(async ([cursor, limit, orderBy, desc, query]) => {
1458
- return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query });
1459
- });
1460
- this._serverUserCache = createCache(async ([userId]) => {
1461
- const user = await this._interface.getServerUserById(userId);
1462
- return Result.or(user, null);
1463
- });
1464
- this._serverTeamsCache = createCache(async ([userId]) => {
1465
- return await this._interface.listServerTeams({ userId });
1466
- });
1467
- this._serverTeamUserPermissionsCache = createCache(async ([teamId, userId, recursive]) => {
1468
- return await this._interface.listServerTeamPermissions({ teamId, userId, recursive }, null);
1469
- });
1470
- this._serverUserOAuthConnectionAccessTokensCache = createCache(
1471
- async ([userId, providerId, scope]) => {
1472
- try {
1473
- const result = await this._interface.createServerProviderAccessToken(userId, providerId, scope || "");
1474
- return { accessToken: result.access_token };
1475
- } catch (err) {
1476
- if (!(err instanceof KnownErrors.OAuthConnectionDoesNotHaveRequiredScope || err instanceof KnownErrors.OAuthConnectionNotConnectedToUser)) {
1477
- throw err;
1478
- }
1479
- }
1480
- return null;
1481
- }
1482
- );
1483
- this._serverUserOAuthConnectionCache = createCache(
1484
- async ([userId, providerId, scope, redirect]) => {
1485
- return await this._getUserOAuthConnectionCacheFn({
1486
- getUser: async () => Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only")),
1487
- getOrWaitOAuthToken: async () => Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([userId, providerId, scope || ""], "write-only")),
1488
- useOAuthToken: () => useAsyncCache(this._serverUserOAuthConnectionAccessTokensCache, [userId, providerId, scope || ""], "user.useConnectedAccount()"),
1489
- providerId,
1490
- scope,
1491
- redirect,
1492
- session: null
1493
- });
1494
- }
1495
- );
1496
- this._serverTeamMemberProfilesCache = createCache(
1497
- async ([teamId]) => {
1498
- return await this._interface.listServerTeamMemberProfiles({ teamId });
1499
- }
1500
- );
1501
- this._serverTeamInvitationsCache = createCache(
1502
- async ([teamId]) => {
1503
- return await this._interface.listServerTeamInvitations({ teamId });
1504
- }
1505
- );
1506
- this._serverUserTeamProfileCache = createCache(
1507
- async ([teamId, userId]) => {
1508
- return await this._interface.getServerTeamMemberProfile({ teamId, userId });
1509
- }
1510
- );
1511
- this._serverContactChannelsCache = createCache(
1512
- async ([userId]) => {
1513
- return await this._interface.listServerContactChannels(userId);
1514
- }
1515
- );
1516
- }
1517
- async _updateServerUser(userId, update) {
1518
- const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));
1519
- await this._refreshUsers();
1520
- return result;
1521
- }
1522
- _serverEditableTeamProfileFromCrud(crud) {
1523
- const app = this;
1524
- return {
1525
- displayName: crud.display_name,
1526
- profileImageUrl: crud.profile_image_url,
1527
- async update(update) {
1528
- await app._interface.updateServerTeamMemberProfile({
1529
- teamId: crud.team_id,
1530
- userId: crud.user_id,
1531
- profile: {
1532
- display_name: update.displayName,
1533
- profile_image_url: update.profileImageUrl
1534
- }
1535
- });
1536
- await app._serverUserTeamProfileCache.refresh([crud.team_id, crud.user_id]);
1537
- }
1538
- };
1539
- }
1540
- _serverContactChannelFromCrud(userId, crud) {
1541
- const app = this;
1542
- return {
1543
- id: crud.id,
1544
- value: crud.value,
1545
- type: crud.type,
1546
- isVerified: crud.is_verified,
1547
- isPrimary: crud.is_primary,
1548
- usedForAuth: crud.used_for_auth,
1549
- async sendVerificationEmail(options) {
1550
- if (!options?.callbackUrl && !await app._getCurrentUrl()) {
1551
- throw new Error("Cannot send verification email without a callback URL from the server or without a redirect method. Make sure you pass the `callbackUrl` option: `sendVerificationEmail({ callbackUrl: ... })`");
1552
- }
1553
- await app._interface.sendServerContactChannelVerificationEmail(userId, crud.id, options?.callbackUrl ?? constructRedirectUrl(app.urls.emailVerification));
1554
- },
1555
- async update(data) {
1556
- await app._interface.updateServerContactChannel(userId, crud.id, serverContactChannelUpdateOptionsToCrud(data));
1557
- },
1558
- async delete() {
1559
- await app._interface.deleteServerContactChannel(userId, crud.id);
1560
- }
1561
- };
1562
- }
1563
- _serverUserFromCrud(crud) {
1564
- const app = this;
1565
- async function getConnectedAccount(id, options) {
1566
- const scopeString = options?.scopes?.join(" ");
1567
- return Result.orThrow(await app._serverUserOAuthConnectionCache.getOrWait([crud.id, id, scopeString || "", options?.or === "redirect"], "write-only"));
1568
- }
1569
- function useConnectedAccount(id, options) {
1570
- const scopeString = options?.scopes?.join(" ");
1571
- return useAsyncCache(app._serverUserOAuthConnectionCache, [crud.id, id, scopeString || "", options?.or === "redirect"], "user.useConnectedAccount()");
1572
- }
1573
- return {
1574
- ...super._createBaseUser(crud),
1575
- lastActiveAt: new Date(crud.last_active_at_millis),
1576
- serverMetadata: crud.server_metadata,
1577
- async setPrimaryEmail(email, options) {
1578
- await app._updateServerUser(crud.id, { primaryEmail: email, primaryEmailVerified: options?.verified });
1579
- },
1580
- async grantPermission(scope, permissionId) {
1581
- await app._interface.grantServerTeamUserPermission(scope.id, crud.id, permissionId);
1582
- for (const recursive of [true, false]) {
1583
- await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
1584
- }
1585
- },
1586
- async revokePermission(scope, permissionId) {
1587
- await app._interface.revokeServerTeamUserPermission(scope.id, crud.id, permissionId);
1588
- for (const recursive of [true, false]) {
1589
- await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
1590
- }
1591
- },
1592
- async delete() {
1593
- const res = await app._interface.deleteServerServerUser(crud.id);
1594
- await app._refreshUsers();
1595
- return res;
1596
- },
1597
- async createSession(options) {
1598
- const tokens = await app._interface.createServerUserSession(crud.id, options.expiresInMillis ?? 1e3 * 60 * 60 * 24 * 365);
1599
- return {
1600
- async getTokens() {
1601
- return tokens;
1602
- }
1603
- };
1604
- },
1605
- async setDisplayName(displayName) {
1606
- return await this.update({ displayName });
1607
- },
1608
- async setClientMetadata(metadata) {
1609
- return await this.update({ clientMetadata: metadata });
1610
- },
1611
- async setClientReadOnlyMetadata(metadata) {
1612
- return await this.update({ clientReadOnlyMetadata: metadata });
1613
- },
1614
- async setServerMetadata(metadata) {
1615
- return await this.update({ serverMetadata: metadata });
1616
- },
1617
- async setSelectedTeam(team) {
1618
- return await this.update({ selectedTeamId: team?.id ?? null });
1619
- },
1620
- getConnectedAccount,
1621
- useConnectedAccount,
1622
- selectedTeam: crud.selected_team ? app._serverTeamFromCrud(crud.selected_team) : null,
1623
- async getTeam(teamId) {
1624
- const teams = await this.listTeams();
1625
- return teams.find((t) => t.id === teamId) ?? null;
1626
- },
1627
- useTeam(teamId) {
1628
- const teams = this.useTeams();
1629
- return useMemo(() => {
1630
- return teams.find((t) => t.id === teamId) ?? null;
1631
- }, [teams, teamId]);
1632
- },
1633
- async listTeams() {
1634
- const teams = Result.orThrow(await app._serverTeamsCache.getOrWait([crud.id], "write-only"));
1635
- return teams.map((t) => app._serverTeamFromCrud(t));
1636
- },
1637
- useTeams() {
1638
- const teams = useAsyncCache(app._serverTeamsCache, [crud.id], "user.useTeams()");
1639
- return useMemo(() => teams.map((t) => app._serverTeamFromCrud(t)), [teams]);
1640
- },
1641
- createTeam: async (data) => {
1642
- const team = await app._interface.createServerTeam(serverTeamCreateOptionsToCrud({
1643
- creatorUserId: crud.id,
1644
- ...data
1645
- }));
1646
- await app._serverTeamsCache.refresh([void 0]);
1647
- return app._serverTeamFromCrud(team);
1648
- },
1649
- leaveTeam: async (team) => {
1650
- await app._interface.leaveServerTeam({ teamId: team.id, userId: crud.id });
1651
- },
1652
- async listPermissions(scope, options) {
1653
- const recursive = options?.recursive ?? true;
1654
- const permissions = Result.orThrow(await app._serverTeamUserPermissionsCache.getOrWait([scope.id, crud.id, recursive], "write-only"));
1655
- return permissions.map((crud2) => app._serverPermissionFromCrud(crud2));
1656
- },
1657
- usePermissions(scope, options) {
1658
- const recursive = options?.recursive ?? true;
1659
- const permissions = useAsyncCache(app._serverTeamUserPermissionsCache, [scope.id, crud.id, recursive], "user.usePermissions()");
1660
- return useMemo(() => permissions.map((crud2) => app._serverPermissionFromCrud(crud2)), [permissions]);
1661
- },
1662
- async getPermission(scope, permissionId) {
1663
- const permissions = await this.listPermissions(scope);
1664
- return permissions.find((p) => p.id === permissionId) ?? null;
1665
- },
1666
- usePermission(scope, permissionId) {
1667
- const permissions = this.usePermissions(scope);
1668
- return useMemo(() => permissions.find((p) => p.id === permissionId) ?? null, [permissions, permissionId]);
1669
- },
1670
- async hasPermission(scope, permissionId) {
1671
- return await this.getPermission(scope, permissionId) !== null;
1672
- },
1673
- async update(update) {
1674
- await app._updateServerUser(crud.id, update);
1675
- },
1676
- async sendVerificationEmail() {
1677
- return await app._checkFeatureSupport("sendVerificationEmail() on ServerUser", {});
1678
- },
1679
- async updatePassword(options) {
1680
- const result = await this.update({ password: options.newPassword });
1681
- await app._serverUserCache.refresh([crud.id]);
1682
- return result;
1683
- },
1684
- async setPassword(options) {
1685
- const result = await this.update(options);
1686
- await app._serverUserCache.refresh([crud.id]);
1687
- return result;
1688
- },
1689
- async getTeamProfile(team) {
1690
- const result = Result.orThrow(await app._serverUserTeamProfileCache.getOrWait([team.id, crud.id], "write-only"));
1691
- return app._serverEditableTeamProfileFromCrud(result);
1692
- },
1693
- useTeamProfile(team) {
1694
- const result = useAsyncCache(app._serverUserTeamProfileCache, [team.id, crud.id], "user.useTeamProfile()");
1695
- return useMemo(() => app._serverEditableTeamProfileFromCrud(result), [result]);
1696
- },
1697
- async listContactChannels() {
1698
- const result = Result.orThrow(await app._serverContactChannelsCache.getOrWait([crud.id], "write-only"));
1699
- return result.map((data) => app._serverContactChannelFromCrud(crud.id, data));
1700
- },
1701
- useContactChannels() {
1702
- const result = useAsyncCache(app._serverContactChannelsCache, [crud.id], "user.useContactChannels()");
1703
- return useMemo(() => result.map((data) => app._serverContactChannelFromCrud(crud.id, data)), [result]);
1704
- },
1705
- createContactChannel: async (data) => {
1706
- const contactChannel = await app._interface.createServerContactChannel(serverContactChannelCreateOptionsToCrud(crud.id, data));
1707
- await app._serverContactChannelsCache.refresh([crud.id]);
1708
- return app._serverContactChannelFromCrud(crud.id, contactChannel);
1709
- }
1710
- };
1711
- }
1712
- _serverTeamUserFromCrud(crud) {
1713
- return {
1714
- ...this._serverUserFromCrud(crud.user),
1715
- teamProfile: {
1716
- displayName: crud.display_name,
1717
- profileImageUrl: crud.profile_image_url
1718
- }
1719
- };
1720
- }
1721
- _serverTeamInvitationFromCrud(crud) {
1722
- return {
1723
- id: crud.id,
1724
- recipientEmail: crud.recipient_email,
1725
- expiresAt: new Date(crud.expires_at_millis),
1726
- revoke: async () => {
1727
- await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);
1728
- }
1729
- };
1730
- }
1731
- _currentUserFromCrud(crud, session) {
1732
- const app = this;
1733
- const currentUser = {
1734
- ...this._serverUserFromCrud(crud),
1735
- ...this._createAuth(session),
1736
- ...this._isInternalProject() ? this._createInternalUserExtra(session) : {}
1737
- };
1738
- Object.freeze(currentUser);
1739
- return currentUser;
1740
- }
1741
- _serverTeamFromCrud(crud) {
1742
- const app = this;
1743
- return {
1744
- id: crud.id,
1745
- displayName: crud.display_name,
1746
- profileImageUrl: crud.profile_image_url,
1747
- createdAt: new Date(crud.created_at_millis),
1748
- clientMetadata: crud.client_metadata,
1749
- clientReadOnlyMetadata: crud.client_read_only_metadata,
1750
- serverMetadata: crud.server_metadata,
1751
- async update(update) {
1752
- await app._interface.updateServerTeam(crud.id, serverTeamUpdateOptionsToCrud(update));
1753
- await app._serverTeamsCache.refresh([void 0]);
1754
- },
1755
- async delete() {
1756
- await app._interface.deleteServerTeam(crud.id);
1757
- await app._serverTeamsCache.refresh([void 0]);
1758
- },
1759
- async listUsers() {
1760
- const result = Result.orThrow(await app._serverTeamMemberProfilesCache.getOrWait([crud.id], "write-only"));
1761
- return result.map((u) => app._serverTeamUserFromCrud(u));
1762
- },
1763
- useUsers() {
1764
- const result = useAsyncCache(app._serverTeamMemberProfilesCache, [crud.id], "team.useUsers()");
1765
- return useMemo(() => result.map((u) => app._serverTeamUserFromCrud(u)), [result]);
1766
- },
1767
- async addUser(userId) {
1768
- await app._interface.addServerUserToTeam({
1769
- teamId: crud.id,
1770
- userId
1771
- });
1772
- await app._serverTeamMemberProfilesCache.refresh([crud.id]);
1773
- },
1774
- async removeUser(userId) {
1775
- await app._interface.removeServerUserFromTeam({
1776
- teamId: crud.id,
1777
- userId
1778
- });
1779
- await app._serverTeamMemberProfilesCache.refresh([crud.id]);
1780
- },
1781
- async inviteUser(options) {
1782
- if (!options.callbackUrl && !await app._getCurrentUrl()) {
1783
- throw new Error("Cannot invite user without a callback URL from the server or without a redirect method. Make sure you pass the `callbackUrl` option: `inviteUser({ email, callbackUrl: ... })`");
1784
- }
1785
- await app._interface.sendServerTeamInvitation({
1786
- teamId: crud.id,
1787
- email: options.email,
1788
- callbackUrl: options.callbackUrl ?? constructRedirectUrl(app.urls.teamInvitation)
1789
- });
1790
- await app._serverTeamInvitationsCache.refresh([crud.id]);
1791
- },
1792
- async listInvitations() {
1793
- const result = Result.orThrow(await app._serverTeamInvitationsCache.getOrWait([crud.id], "write-only"));
1794
- return result.map((crud2) => app._serverTeamInvitationFromCrud(crud2));
1795
- },
1796
- useInvitations() {
1797
- const result = useAsyncCache(app._serverTeamInvitationsCache, [crud.id], "team.useInvitations()");
1798
- return useMemo(() => result.map((crud2) => app._serverTeamInvitationFromCrud(crud2)), [result]);
1799
- }
1800
- };
1801
- }
1802
- async createUser(options) {
1803
- const crud = await this._interface.createServerUser(serverUserCreateOptionsToCrud(options));
1804
- await this._refreshUsers();
1805
- return this._serverUserFromCrud(crud);
1806
- }
1807
- async getUser(options) {
1808
- if (typeof options === "string") {
1809
- return await this.getServerUserById(options);
1810
- } else {
1811
- this._ensurePersistentTokenStore(options?.tokenStore);
1812
- const session = await this._getSession(options?.tokenStore);
1813
- const crud = Result.orThrow(await this._currentServerUserCache.getOrWait([session], "write-only"));
1814
- if (crud === null) {
1815
- switch (options?.or) {
1816
- case "redirect": {
1817
- await this.redirectToSignIn({ replace: true });
1818
- break;
1819
- }
1820
- case "throw": {
1821
- throw new Error("User is not signed in but getUser was called with { or: 'throw' }");
1822
- }
1823
- default: {
1824
- return null;
1825
- }
1826
- }
1827
- }
1828
- return crud && this._currentUserFromCrud(crud, session);
1829
- }
1830
- }
1831
- async getServerUser() {
1832
- console.warn("stackServerApp.getServerUser is deprecated; use stackServerApp.getUser instead");
1833
- return await this.getUser();
1834
- }
1835
- async getServerUserById(userId) {
1836
- const crud = Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only"));
1837
- return crud && this._serverUserFromCrud(crud);
1838
- }
1839
- useUser(options) {
1840
- if (typeof options === "string") {
1841
- return this.useUserById(options);
1842
- } else {
1843
- this._ensurePersistentTokenStore(options?.tokenStore);
1844
- const session = this._useSession(options?.tokenStore);
1845
- const crud = useAsyncCache(this._currentServerUserCache, [session], "useUser()");
1846
- if (crud === null) {
1847
- switch (options?.or) {
1848
- case "redirect": {
1849
- runAsynchronously(this.redirectToSignIn({ replace: true }));
1850
- suspend();
1851
- throw new StackAssertionError("suspend should never return");
1852
- }
1853
- case "throw": {
1854
- throw new Error("User is not signed in but useUser was called with { or: 'throw' }");
1855
- }
1856
- case void 0:
1857
- case "return-null": {
1858
- }
1859
- }
1860
- }
1861
- return useMemo(() => {
1862
- return crud && this._currentUserFromCrud(crud, session);
1863
- }, [crud, session, options?.or]);
1864
- }
1865
- }
1866
- useUserById(userId) {
1867
- const crud = useAsyncCache(this._serverUserCache, [userId], "useUserById()");
1868
- return useMemo(() => {
1869
- return crud && this._serverUserFromCrud(crud);
1870
- }, [crud]);
1871
- }
1872
- async listUsers(options) {
1873
- const crud = Result.orThrow(await this._serverUsersCache.getOrWait([options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "write-only"));
1874
- const result = crud.items.map((j) => this._serverUserFromCrud(j));
1875
- result.nextCursor = crud.pagination?.next_cursor ?? null;
1876
- return result;
1877
- }
1878
- useUsers(options) {
1879
- const crud = useAsyncCache(this._serverUsersCache, [options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "useServerUsers()");
1880
- const result = crud.items.map((j) => this._serverUserFromCrud(j));
1881
- result.nextCursor = crud.pagination?.next_cursor ?? null;
1882
- return result;
1883
- }
1884
- _serverPermissionFromCrud(crud) {
1885
- return {
1886
- id: crud.id
1887
- };
1888
- }
1889
- _serverTeamPermissionDefinitionFromCrud(crud) {
1890
- return {
1891
- id: crud.id,
1892
- description: crud.description,
1893
- containedPermissionIds: crud.contained_permission_ids
1894
- };
1895
- }
1896
- async listTeams() {
1897
- const teams = Result.orThrow(await this._serverTeamsCache.getOrWait([void 0], "write-only"));
1898
- return teams.map((t) => this._serverTeamFromCrud(t));
1899
- }
1900
- async createTeam(data) {
1901
- const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));
1902
- await this._serverTeamsCache.refresh([void 0]);
1903
- return this._serverTeamFromCrud(team);
1904
- }
1905
- useTeams() {
1906
- const teams = useAsyncCache(this._serverTeamsCache, [void 0], "useServerTeams()");
1907
- return useMemo(() => {
1908
- return teams.map((t) => this._serverTeamFromCrud(t));
1909
- }, [teams]);
1910
- }
1911
- async getTeam(teamId) {
1912
- const teams = await this.listTeams();
1913
- return teams.find((t) => t.id === teamId) ?? null;
1914
- }
1915
- useTeam(teamId) {
1916
- const teams = this.useTeams();
1917
- return useMemo(() => {
1918
- return teams.find((t) => t.id === teamId) ?? null;
1919
- }, [teams, teamId]);
1920
- }
1921
- async _refreshSession(session) {
1922
- await Promise.all([
1923
- super._refreshUser(session),
1924
- this._currentServerUserCache.refresh([session])
1925
- ]);
1926
- }
1927
- async _refreshUsers() {
1928
- await Promise.all([
1929
- super._refreshUsers(),
1930
- this._serverUserCache.refreshWhere(() => true),
1931
- this._serverUsersCache.refreshWhere(() => true),
1932
- this._serverContactChannelsCache.refreshWhere(() => true)
1933
- ]);
1934
- }
1935
- };
1936
- var _StackAdminAppImpl = class extends _StackServerAppImpl {
1937
- constructor(options) {
1938
- super({
1939
- interface: new StackAdminInterface({
1940
- getBaseUrl: () => getBaseUrl(options.baseUrl),
1941
- projectId: options.projectId ?? getDefaultProjectId(),
1942
- clientVersion,
1943
- ..."projectOwnerSession" in options ? {
1944
- projectOwnerSession: options.projectOwnerSession
1945
- } : {
1946
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
1947
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
1948
- superSecretAdminKey: options.superSecretAdminKey ?? getDefaultSuperSecretAdminKey()
1949
- }
1950
- }),
1951
- baseUrl: options.baseUrl,
1952
- projectId: options.projectId,
1953
- tokenStore: options.tokenStore,
1954
- urls: options.urls,
1955
- oauthScopesOnSignIn: options.oauthScopesOnSignIn,
1956
- redirectMethod: options.redirectMethod
1957
- });
1958
- this._adminProjectCache = createCache(async () => {
1959
- return await this._interface.getProject();
1960
- });
1961
- this._apiKeysCache = createCache(async () => {
1962
- return await this._interface.listApiKeys();
1963
- });
1964
- this._adminEmailTemplatesCache = createCache(async () => {
1965
- return await this._interface.listEmailTemplates();
1966
- });
1967
- this._adminTeamPermissionDefinitionsCache = createCache(async () => {
1968
- return await this._interface.listPermissionDefinitions();
1969
- });
1970
- this._svixTokenCache = createCache(async () => {
1971
- return await this._interface.getSvixToken();
1972
- });
1973
- this._metricsCache = createCache(async () => {
1974
- return await this._interface.getMetrics();
1975
- });
1976
- }
1977
- _adminOwnedProjectFromCrud(data, onRefresh) {
1978
- if (this._tokenStoreInit !== null) {
1979
- throw new StackAssertionError("Owned apps must always have tokenStore === null \u2014 did you not create this project with app._createOwnedApp()?");
1980
- ;
1981
- }
1982
- return {
1983
- ...this._adminProjectFromCrud(data, onRefresh),
1984
- app: this
1985
- };
1986
- }
1987
- _adminProjectFromCrud(data, onRefresh) {
1988
- if (data.id !== this.projectId) {
1989
- throw new StackAssertionError(`The project ID of the provided project JSON (${data.id}) does not match the project ID of the app (${this.projectId})!`);
1990
- }
1991
- const app = this;
1992
- return {
1993
- id: data.id,
1994
- displayName: data.display_name,
1995
- description: data.description,
1996
- createdAt: new Date(data.created_at_millis),
1997
- userCount: data.user_count,
1998
- isProductionMode: data.is_production_mode,
1999
- config: {
2000
- id: data.config.id,
2001
- signUpEnabled: data.config.sign_up_enabled,
2002
- credentialEnabled: data.config.credential_enabled,
2003
- magicLinkEnabled: data.config.magic_link_enabled,
2004
- passkeyEnabled: data.config.passkey_enabled,
2005
- clientTeamCreationEnabled: data.config.client_team_creation_enabled,
2006
- clientUserDeletionEnabled: data.config.client_user_deletion_enabled,
2007
- allowLocalhost: data.config.allow_localhost,
2008
- oauthProviders: data.config.oauth_providers.map((p) => p.type === "shared" ? {
2009
- id: p.id,
2010
- enabled: p.enabled,
2011
- type: "shared"
2012
- } : {
2013
- id: p.id,
2014
- enabled: p.enabled,
2015
- type: "standard",
2016
- clientId: p.client_id ?? throwErr("Client ID is missing"),
2017
- clientSecret: p.client_secret ?? throwErr("Client secret is missing"),
2018
- facebookConfigId: p.facebook_config_id,
2019
- microsoftTenantId: p.microsoft_tenant_id
2020
- }),
2021
- emailConfig: data.config.email_config.type === "shared" ? {
2022
- type: "shared"
2023
- } : {
2024
- type: "standard",
2025
- host: data.config.email_config.host ?? throwErr("Email host is missing"),
2026
- port: data.config.email_config.port ?? throwErr("Email port is missing"),
2027
- username: data.config.email_config.username ?? throwErr("Email username is missing"),
2028
- password: data.config.email_config.password ?? throwErr("Email password is missing"),
2029
- senderName: data.config.email_config.sender_name ?? throwErr("Email sender name is missing"),
2030
- senderEmail: data.config.email_config.sender_email ?? throwErr("Email sender email is missing")
2031
- },
2032
- domains: data.config.domains.map((d) => ({
2033
- domain: d.domain,
2034
- handlerPath: d.handler_path
2035
- })),
2036
- createTeamOnSignUp: data.config.create_team_on_sign_up,
2037
- teamCreatorDefaultPermissions: data.config.team_creator_default_permissions,
2038
- teamMemberDefaultPermissions: data.config.team_member_default_permissions
2039
- },
2040
- async update(update) {
2041
- await app._interface.updateProject(adminProjectUpdateOptionsToCrud(update));
2042
- await onRefresh();
2043
- },
2044
- async delete() {
2045
- await app._interface.deleteProject();
2046
- },
2047
- async getProductionModeErrors() {
2048
- return getProductionModeErrors(data);
2049
- },
2050
- useProductionModeErrors() {
2051
- return getProductionModeErrors(data);
2052
- }
2053
- };
2054
- }
2055
- _adminEmailTemplateFromCrud(data) {
2056
- return {
2057
- type: data.type,
2058
- subject: data.subject,
2059
- content: data.content,
2060
- isDefault: data.is_default
2061
- };
2062
- }
2063
- async getProject() {
2064
- return this._adminProjectFromCrud(
2065
- Result.orThrow(await this._adminProjectCache.getOrWait([], "write-only")),
2066
- () => this._refreshProject()
2067
- );
2068
- }
2069
- useProject() {
2070
- const crud = useAsyncCache(this._adminProjectCache, [], "useProjectAdmin()");
2071
- return useMemo(() => this._adminProjectFromCrud(
2072
- crud,
2073
- () => this._refreshProject()
2074
- ), [crud]);
2075
- }
2076
- _createApiKeyBaseFromCrud(data) {
2077
- const app = this;
2078
- return {
2079
- id: data.id,
2080
- description: data.description,
2081
- expiresAt: new Date(data.expires_at_millis),
2082
- manuallyRevokedAt: data.manually_revoked_at_millis ? new Date(data.manually_revoked_at_millis) : null,
2083
- createdAt: new Date(data.created_at_millis),
2084
- isValid() {
2085
- return this.whyInvalid() === null;
2086
- },
2087
- whyInvalid() {
2088
- if (this.expiresAt.getTime() < Date.now()) return "expired";
2089
- if (this.manuallyRevokedAt) return "manually-revoked";
2090
- return null;
2091
- },
2092
- async revoke() {
2093
- const res = await app._interface.revokeApiKeyById(data.id);
2094
- await app._refreshApiKeys();
2095
- return res;
2096
- }
2097
- };
2098
- }
2099
- _createApiKeyFromCrud(data) {
2100
- return {
2101
- ...this._createApiKeyBaseFromCrud(data),
2102
- publishableClientKey: data.publishable_client_key ? { lastFour: data.publishable_client_key.last_four } : null,
2103
- secretServerKey: data.secret_server_key ? { lastFour: data.secret_server_key.last_four } : null,
2104
- superSecretAdminKey: data.super_secret_admin_key ? { lastFour: data.super_secret_admin_key.last_four } : null
2105
- };
2106
- }
2107
- _createApiKeyFirstViewFromCrud(data) {
2108
- return {
2109
- ...this._createApiKeyBaseFromCrud(data),
2110
- publishableClientKey: data.publishable_client_key,
2111
- secretServerKey: data.secret_server_key,
2112
- superSecretAdminKey: data.super_secret_admin_key
2113
- };
2114
- }
2115
- async listApiKeys() {
2116
- const crud = Result.orThrow(await this._apiKeysCache.getOrWait([], "write-only"));
2117
- return crud.map((j) => this._createApiKeyFromCrud(j));
2118
- }
2119
- useApiKeys() {
2120
- const crud = useAsyncCache(this._apiKeysCache, [], "useApiKeys()");
2121
- return useMemo(() => {
2122
- return crud.map((j) => this._createApiKeyFromCrud(j));
2123
- }, [crud]);
2124
- }
2125
- async createApiKey(options) {
2126
- const crud = await this._interface.createApiKey(apiKeyCreateOptionsToCrud(options));
2127
- await this._refreshApiKeys();
2128
- return this._createApiKeyFirstViewFromCrud(crud);
2129
- }
2130
- useEmailTemplates() {
2131
- const crud = useAsyncCache(this._adminEmailTemplatesCache, [], "useEmailTemplates()");
2132
- return useMemo(() => {
2133
- return crud.map((j) => this._adminEmailTemplateFromCrud(j));
2134
- }, [crud]);
2135
- }
2136
- async listEmailTemplates() {
2137
- const crud = Result.orThrow(await this._adminEmailTemplatesCache.getOrWait([], "write-only"));
2138
- return crud.map((j) => this._adminEmailTemplateFromCrud(j));
2139
- }
2140
- async updateEmailTemplate(type, data) {
2141
- await this._interface.updateEmailTemplate(type, adminEmailTemplateUpdateOptionsToCrud(data));
2142
- await this._adminEmailTemplatesCache.refresh([]);
2143
- }
2144
- async resetEmailTemplate(type) {
2145
- await this._interface.resetEmailTemplate(type);
2146
- await this._adminEmailTemplatesCache.refresh([]);
2147
- }
2148
- async createTeamPermissionDefinition(data) {
2149
- const crud = await this._interface.createPermissionDefinition(serverTeamPermissionDefinitionCreateOptionsToCrud(data));
2150
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
2151
- return this._serverTeamPermissionDefinitionFromCrud(crud);
2152
- }
2153
- async updateTeamPermissionDefinition(permissionId, data) {
2154
- await this._interface.updatePermissionDefinition(permissionId, serverTeamPermissionDefinitionUpdateOptionsToCrud(data));
2155
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
2156
- }
2157
- async deleteTeamPermissionDefinition(permissionId) {
2158
- await this._interface.deletePermissionDefinition(permissionId);
2159
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
2160
- }
2161
- async listTeamPermissionDefinitions() {
2162
- const crud = Result.orThrow(await this._adminTeamPermissionDefinitionsCache.getOrWait([], "write-only"));
2163
- return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
2164
- }
2165
- useTeamPermissionDefinitions() {
2166
- const crud = useAsyncCache(this._adminTeamPermissionDefinitionsCache, [], "usePermissions()");
2167
- return useMemo(() => {
2168
- return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
2169
- }, [crud]);
2170
- }
2171
- useSvixToken() {
2172
- const crud = useAsyncCache(this._svixTokenCache, [], "useSvixToken()");
2173
- return crud.token;
2174
- }
2175
- async _refreshProject() {
2176
- await Promise.all([
2177
- super._refreshProject(),
2178
- this._adminProjectCache.refresh([])
2179
- ]);
2180
- }
2181
- async _refreshApiKeys() {
2182
- await this._apiKeysCache.refresh([]);
2183
- }
2184
- get [stackAppInternalsSymbol]() {
2185
- return {
2186
- ...super[stackAppInternalsSymbol],
2187
- useMetrics: () => {
2188
- return useAsyncCache(this._metricsCache, [], "useMetrics()");
2189
- }
2190
- };
2191
- }
2192
- async sendTestEmail(options) {
2193
- const response = await this._interface.sendTestEmail({
2194
- recipient_email: options.recipientEmail,
2195
- email_config: {
2196
- ...pick(options.emailConfig, ["host", "port", "username", "password"]),
2197
- sender_email: options.emailConfig.senderEmail,
2198
- sender_name: options.emailConfig.senderName
2199
- }
2200
- });
2201
- if (response.success) {
2202
- return Result.ok(void 0);
2203
- } else {
2204
- return Result.error({ errorMessage: response.error_message ?? throwErr("Email test error not specified") });
2205
- }
2206
- }
2207
- };
2208
- function contactChannelCreateOptionsToCrud(userId, options) {
2209
- return {
2210
- value: options.value,
2211
- type: options.type,
2212
- used_for_auth: options.usedForAuth,
2213
- user_id: userId
2214
- };
2215
- }
2216
- function contactChannelUpdateOptionsToCrud(options) {
2217
- return {
2218
- value: options.value,
2219
- used_for_auth: options.usedForAuth,
2220
- is_primary: options.isPrimary
2221
- };
2222
- }
2223
- function serverContactChannelUpdateOptionsToCrud(options) {
2224
- return {
2225
- value: options.value,
2226
- is_verified: options.isVerified,
2227
- used_for_auth: options.usedForAuth
2228
- };
2229
- }
2230
- function serverContactChannelCreateOptionsToCrud(userId, options) {
2231
- return {
2232
- type: options.type,
2233
- value: options.value,
2234
- is_verified: options.isVerified,
2235
- user_id: userId,
2236
- used_for_auth: options.usedForAuth
2237
- };
2238
- }
2239
- function userUpdateOptionsToCrud(options) {
2240
- return {
2241
- display_name: options.displayName,
2242
- client_metadata: options.clientMetadata,
2243
- selected_team_id: options.selectedTeamId,
2244
- totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,
2245
- profile_image_url: options.profileImageUrl,
2246
- otp_auth_enabled: options.otpAuthEnabled,
2247
- passkey_auth_enabled: options.passkeyAuthEnabled
2248
- };
2249
- }
2250
- function serverUserUpdateOptionsToCrud(options) {
2251
- return {
2252
- display_name: options.displayName,
2253
- primary_email: options.primaryEmail,
2254
- client_metadata: options.clientMetadata,
2255
- client_read_only_metadata: options.clientReadOnlyMetadata,
2256
- server_metadata: options.serverMetadata,
2257
- selected_team_id: options.selectedTeamId,
2258
- primary_email_auth_enabled: options.primaryEmailAuthEnabled,
2259
- primary_email_verified: options.primaryEmailVerified,
2260
- password: options.password,
2261
- profile_image_url: options.profileImageUrl,
2262
- totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret
2263
- };
2264
- }
2265
- function serverUserCreateOptionsToCrud(options) {
2266
- return {
2267
- primary_email: options.primaryEmail,
2268
- password: options.password,
2269
- otp_auth_enabled: options.otpAuthEnabled,
2270
- primary_email_auth_enabled: options.primaryEmailAuthEnabled,
2271
- display_name: options.displayName,
2272
- primary_email_verified: options.primaryEmailVerified,
2273
- client_metadata: options.clientMetadata,
2274
- client_read_only_metadata: options.clientReadOnlyMetadata,
2275
- server_metadata: options.serverMetadata
2276
- };
2277
- }
2278
- function adminProjectUpdateOptionsToCrud(options) {
2279
- return {
2280
- display_name: options.displayName,
2281
- description: options.description,
2282
- is_production_mode: options.isProductionMode,
2283
- config: {
2284
- domains: options.config?.domains?.map((d) => ({
2285
- domain: d.domain,
2286
- handler_path: d.handlerPath
2287
- })),
2288
- oauth_providers: options.config?.oauthProviders?.map((p) => ({
2289
- id: p.id,
2290
- enabled: p.enabled,
2291
- type: p.type,
2292
- ...p.type === "standard" && {
2293
- client_id: p.clientId,
2294
- client_secret: p.clientSecret,
2295
- facebook_config_id: p.facebookConfigId,
2296
- microsoft_tenant_id: p.microsoftTenantId
2297
- }
2298
- })),
2299
- email_config: options.config?.emailConfig && (options.config.emailConfig.type === "shared" ? {
2300
- type: "shared"
2301
- } : {
2302
- type: "standard",
2303
- host: options.config.emailConfig.host,
2304
- port: options.config.emailConfig.port,
2305
- username: options.config.emailConfig.username,
2306
- password: options.config.emailConfig.password,
2307
- sender_name: options.config.emailConfig.senderName,
2308
- sender_email: options.config.emailConfig.senderEmail
2309
- }),
2310
- sign_up_enabled: options.config?.signUpEnabled,
2311
- credential_enabled: options.config?.credentialEnabled,
2312
- magic_link_enabled: options.config?.magicLinkEnabled,
2313
- passkey_enabled: options.config?.passkeyEnabled,
2314
- allow_localhost: options.config?.allowLocalhost,
2315
- create_team_on_sign_up: options.config?.createTeamOnSignUp,
2316
- client_team_creation_enabled: options.config?.clientTeamCreationEnabled,
2317
- client_user_deletion_enabled: options.config?.clientUserDeletionEnabled,
2318
- team_creator_default_permissions: options.config?.teamCreatorDefaultPermissions,
2319
- team_member_default_permissions: options.config?.teamMemberDefaultPermissions
2320
- }
2321
- };
2322
- }
2323
- function adminProjectCreateOptionsToCrud(options) {
2324
- return {
2325
- ...adminProjectUpdateOptionsToCrud(options),
2326
- display_name: options.displayName
2327
- };
2328
- }
2329
- function apiKeyCreateOptionsToCrud(options) {
2330
- return {
2331
- description: options.description,
2332
- expires_at_millis: options.expiresAt.getTime(),
2333
- has_publishable_client_key: options.hasPublishableClientKey,
2334
- has_secret_server_key: options.hasSecretServerKey,
2335
- has_super_secret_admin_key: options.hasSuperSecretAdminKey
2336
- };
2337
- }
2338
- function teamUpdateOptionsToCrud(options) {
2339
- return {
2340
- display_name: options.displayName,
2341
- profile_image_url: options.profileImageUrl,
2342
- client_metadata: options.clientMetadata
2343
- };
2344
- }
2345
- function teamCreateOptionsToCrud(options, creatorUserId) {
2346
- return {
2347
- display_name: options.displayName,
2348
- profile_image_url: options.profileImageUrl,
2349
- creator_user_id: creatorUserId
2350
- };
2351
- }
2352
- function serverTeamCreateOptionsToCrud(options) {
2353
- return {
2354
- display_name: options.displayName,
2355
- profile_image_url: options.profileImageUrl,
2356
- creator_user_id: options.creatorUserId
2357
- };
2358
- }
2359
- function serverTeamUpdateOptionsToCrud(options) {
2360
- return {
2361
- display_name: options.displayName,
2362
- profile_image_url: options.profileImageUrl,
2363
- client_metadata: options.clientMetadata,
2364
- client_read_only_metadata: options.clientReadOnlyMetadata,
2365
- server_metadata: options.serverMetadata
2366
- };
2367
- }
2368
- function serverTeamPermissionDefinitionCreateOptionsToCrud(options) {
2369
- return {
2370
- id: options.id,
2371
- description: options.description,
2372
- contained_permission_ids: options.containedPermissionIds
2373
- };
2374
- }
2375
- function serverTeamPermissionDefinitionUpdateOptionsToCrud(options) {
2376
- return {
2377
- id: options.id,
2378
- description: options.description,
2379
- contained_permission_ids: options.containedPermissionIds
2380
- };
2381
- }
2382
- var StackClientApp = _StackClientAppImpl;
2383
- var StackServerApp = _StackServerAppImpl;
2384
- var StackAdminApp = _StackAdminAppImpl;
2385
- function adminEmailTemplateUpdateOptionsToCrud(options) {
2386
- return {
2387
- subject: options.subject,
2388
- content: options.content
2389
- };
2390
- }
1314
+ /**
1315
+ * There is a circular dependency between the admin app and the client app, as the former inherits from the latter and
1316
+ * the latter needs to use the former when creating a new instance of an internal project.
1317
+ *
1318
+ * To break it, we set the admin app here lazily instead of importing it directly. This variable is set by ./index.ts,
1319
+ * which imports both this file and ./admin-app-impl.ts.
1320
+ */
1321
+ __StackClientAppImplIncomplete.LazyStackAdminAppImpl = { value: void 0 };
1322
+ var _StackClientAppImplIncomplete = __StackClientAppImplIncomplete;
2391
1323
  export {
2392
- StackAdminApp,
2393
- StackClientApp,
2394
- StackServerApp,
2395
- serverTeamPermissionDefinitionCreateOptionsToCrud,
2396
- serverTeamPermissionDefinitionUpdateOptionsToCrud,
2397
- stackAppInternalsSymbol
1324
+ _StackClientAppImplIncomplete
2398
1325
  };
2399
- //# sourceMappingURL=stack-app.js.map
1326
+ //# sourceMappingURL=client-app-impl.js.map