@stackframe/js 2.7.21 → 2.7.22

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 (130) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/admin-app-impl-Co__PI-r.d.ts +357 -0
  3. package/dist/admin-app-impl-s-tPjfRz.d.mts +357 -0
  4. package/dist/esm/lib/stack-app/api-keys/index.js +14 -0
  5. package/dist/esm/lib/stack-app/api-keys/index.js.map +1 -0
  6. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js +257 -0
  7. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -0
  8. package/dist/esm/lib/{stack-app.js → stack-app/apps/implementations/client-app-impl.js} +33 -950
  9. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -0
  10. package/dist/esm/lib/stack-app/apps/implementations/common.js +107 -0
  11. package/dist/esm/lib/stack-app/apps/implementations/common.js.map +1 -0
  12. package/dist/esm/lib/stack-app/apps/implementations/index.js +24 -0
  13. package/dist/esm/lib/stack-app/apps/implementations/index.js.map +1 -0
  14. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js +430 -0
  15. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -0
  16. package/dist/esm/lib/stack-app/apps/index.js +16 -0
  17. package/dist/esm/lib/stack-app/apps/index.js.map +1 -0
  18. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js +7 -0
  19. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js.map +1 -0
  20. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js +7 -0
  21. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js.map +1 -0
  22. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js +7 -0
  23. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js.map +1 -0
  24. package/dist/esm/lib/stack-app/common.js +6 -0
  25. package/dist/esm/lib/stack-app/common.js.map +1 -0
  26. package/dist/esm/lib/stack-app/connected-accounts/index.js +1 -0
  27. package/dist/esm/lib/stack-app/connected-accounts/index.js.map +1 -0
  28. package/dist/esm/lib/stack-app/contact-channels/index.js +39 -0
  29. package/dist/esm/lib/stack-app/contact-channels/index.js.map +1 -0
  30. package/dist/esm/lib/stack-app/email-templates/index.js +11 -0
  31. package/dist/esm/lib/stack-app/email-templates/index.js.map +1 -0
  32. package/dist/esm/lib/stack-app/index.js +16 -0
  33. package/dist/esm/lib/stack-app/index.js.map +1 -0
  34. package/dist/esm/lib/stack-app/permissions/index.js +20 -0
  35. package/dist/esm/lib/stack-app/permissions/index.js.map +1 -0
  36. package/dist/esm/lib/stack-app/project-configs/index.js +1 -0
  37. package/dist/esm/lib/stack-app/project-configs/index.js.map +1 -0
  38. package/dist/esm/lib/stack-app/projects/index.js +57 -0
  39. package/dist/esm/lib/stack-app/projects/index.js.map +1 -0
  40. package/dist/esm/lib/stack-app/teams/index.js +38 -0
  41. package/dist/esm/lib/stack-app/teams/index.js.map +1 -0
  42. package/dist/esm/lib/stack-app/users/index.js +47 -0
  43. package/dist/esm/lib/stack-app/users/index.js.map +1 -0
  44. package/dist/{lib/stack-app.d.mts → index-COYzPcGI.d.mts} +127 -338
  45. package/dist/{lib/stack-app.d.ts → index-CueS5Qbi.d.ts} +127 -338
  46. package/dist/index.d.mts +17 -5
  47. package/dist/index.d.ts +17 -5
  48. package/dist/lib/stack-app/api-keys/index.d.mts +40 -0
  49. package/dist/lib/stack-app/api-keys/index.d.ts +40 -0
  50. package/dist/lib/stack-app/api-keys/index.js +39 -0
  51. package/dist/lib/stack-app/api-keys/index.js.map +1 -0
  52. package/dist/lib/stack-app/apps/implementations/admin-app-impl.d.mts +30 -0
  53. package/dist/lib/stack-app/apps/implementations/admin-app-impl.d.ts +30 -0
  54. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js +282 -0
  55. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -0
  56. package/dist/lib/stack-app/apps/implementations/client-app-impl.d.mts +30 -0
  57. package/dist/lib/stack-app/apps/implementations/client-app-impl.d.ts +30 -0
  58. package/dist/lib/{stack-app.js → stack-app/apps/implementations/client-app-impl.js} +60 -982
  59. package/dist/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -0
  60. package/dist/lib/stack-app/apps/implementations/common.d.mts +44 -0
  61. package/dist/lib/stack-app/apps/implementations/common.d.ts +44 -0
  62. package/dist/lib/stack-app/apps/implementations/common.js +141 -0
  63. package/dist/lib/stack-app/apps/implementations/common.js.map +1 -0
  64. package/dist/lib/stack-app/apps/implementations/index.d.mts +36 -0
  65. package/dist/lib/stack-app/apps/implementations/index.d.ts +36 -0
  66. package/dist/lib/stack-app/apps/implementations/index.js +51 -0
  67. package/dist/lib/stack-app/apps/implementations/index.js.map +1 -0
  68. package/dist/lib/stack-app/apps/implementations/server-app-impl.d.mts +30 -0
  69. package/dist/lib/stack-app/apps/implementations/server-app-impl.d.ts +30 -0
  70. package/dist/lib/stack-app/apps/implementations/server-app-impl.js +455 -0
  71. package/dist/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -0
  72. package/dist/lib/stack-app/apps/index.d.mts +23 -0
  73. package/dist/lib/stack-app/apps/index.d.ts +23 -0
  74. package/dist/lib/stack-app/apps/index.js +37 -0
  75. package/dist/lib/stack-app/apps/index.js.map +1 -0
  76. package/dist/lib/stack-app/apps/interfaces/admin-app.d.mts +23 -0
  77. package/dist/lib/stack-app/apps/interfaces/admin-app.d.ts +23 -0
  78. package/dist/lib/stack-app/apps/interfaces/admin-app.js +32 -0
  79. package/dist/lib/stack-app/apps/interfaces/admin-app.js.map +1 -0
  80. package/dist/lib/stack-app/apps/interfaces/client-app.d.mts +23 -0
  81. package/dist/lib/stack-app/apps/interfaces/client-app.d.ts +23 -0
  82. package/dist/lib/stack-app/apps/interfaces/client-app.js +32 -0
  83. package/dist/lib/stack-app/apps/interfaces/client-app.js.map +1 -0
  84. package/dist/lib/stack-app/apps/interfaces/server-app.d.mts +23 -0
  85. package/dist/lib/stack-app/apps/interfaces/server-app.d.ts +23 -0
  86. package/dist/lib/stack-app/apps/interfaces/server-app.js +32 -0
  87. package/dist/lib/stack-app/apps/interfaces/server-app.js.map +1 -0
  88. package/dist/lib/stack-app/common.d.mts +61 -0
  89. package/dist/lib/stack-app/common.d.ts +61 -0
  90. package/dist/lib/stack-app/common.js +31 -0
  91. package/dist/lib/stack-app/common.js.map +1 -0
  92. package/dist/lib/stack-app/connected-accounts/index.d.mts +10 -0
  93. package/dist/lib/stack-app/connected-accounts/index.d.ts +10 -0
  94. package/dist/lib/stack-app/connected-accounts/index.js +19 -0
  95. package/dist/lib/stack-app/connected-accounts/index.js.map +1 -0
  96. package/dist/lib/stack-app/contact-channels/index.d.mts +38 -0
  97. package/dist/lib/stack-app/contact-channels/index.d.ts +38 -0
  98. package/dist/lib/stack-app/contact-channels/index.js +67 -0
  99. package/dist/lib/stack-app/contact-channels/index.js.map +1 -0
  100. package/dist/lib/stack-app/email-templates/index.d.mts +15 -0
  101. package/dist/lib/stack-app/email-templates/index.d.ts +15 -0
  102. package/dist/lib/stack-app/email-templates/index.js +36 -0
  103. package/dist/lib/stack-app/email-templates/index.js.map +1 -0
  104. package/dist/lib/stack-app/index.d.mts +23 -0
  105. package/dist/lib/stack-app/index.d.ts +23 -0
  106. package/dist/lib/stack-app/index.js +38 -0
  107. package/dist/lib/stack-app/index.js.map +1 -0
  108. package/dist/lib/stack-app/permissions/index.d.mts +21 -0
  109. package/dist/lib/stack-app/permissions/index.d.ts +21 -0
  110. package/dist/lib/stack-app/permissions/index.js +46 -0
  111. package/dist/lib/stack-app/permissions/index.js.map +1 -0
  112. package/dist/lib/stack-app/project-configs/index.d.mts +82 -0
  113. package/dist/lib/stack-app/project-configs/index.d.ts +82 -0
  114. package/dist/lib/stack-app/project-configs/index.js +19 -0
  115. package/dist/lib/stack-app/project-configs/index.js.map +1 -0
  116. package/dist/lib/stack-app/projects/index.d.mts +23 -0
  117. package/dist/lib/stack-app/projects/index.d.ts +23 -0
  118. package/dist/lib/stack-app/projects/index.js +83 -0
  119. package/dist/lib/stack-app/projects/index.js.map +1 -0
  120. package/dist/lib/stack-app/teams/index.d.mts +23 -0
  121. package/dist/lib/stack-app/teams/index.d.ts +23 -0
  122. package/dist/lib/stack-app/teams/index.js +66 -0
  123. package/dist/lib/stack-app/teams/index.js.map +1 -0
  124. package/dist/lib/stack-app/users/index.d.mts +23 -0
  125. package/dist/lib/stack-app/users/index.d.ts +23 -0
  126. package/dist/lib/stack-app/users/index.js +74 -0
  127. package/dist/lib/stack-app/users/index.js.map +1 -0
  128. package/package.json +2 -2
  129. package/dist/esm/lib/stack-app.js.map +0 -1
  130. 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, 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 { Result } from "@stackframe/stack-shared/dist/utils/results";
14
11
  import { Store, storeLock } from "@stackframe/stack-shared/dist/utils/stores";
@@ -16,101 +13,20 @@ import { mergeScopeStrings } from "@stackframe/stack-shared/dist/utils/strings";
16
13
  import { getRelativePart, isRelative } from "@stackframe/stack-shared/dist/utils/urls";
17
14
  import { generateUuid } from "@stackframe/stack-shared/dist/utils/uuids";
18
15
  import * as cookie from "cookie";
19
- import { constructRedirectUrl } from "../utils/url";
20
- import { addNewOAuthProviderOrScope, callOAuthCallback, signInWithOAuth } from "./auth";
21
- import { createCookieHelper, createPlaceholderCookieHelper, deleteCookieClient, getCookieClient, setOrDeleteCookie, setOrDeleteCookieClient } from "./cookie";
16
+ import { constructRedirectUrl } from "../../../../utils/url";
17
+ import { addNewOAuthProviderOrScope, callOAuthCallback, signInWithOAuth } from "../../../auth";
18
+ import { createCookieHelper, createPlaceholderCookieHelper, deleteCookieClient, getCookieClient, setOrDeleteCookie, setOrDeleteCookieClient } from "../../../cookie";
19
+ import { stackAppInternalsSymbol } from "../../common";
20
+ import { contactChannelCreateOptionsToCrud, contactChannelUpdateOptionsToCrud } from "../../contact-channels";
21
+ import { adminProjectCreateOptionsToCrud } from "../../projects";
22
+ import { teamCreateOptionsToCrud, teamUpdateOptionsToCrud } from "../../teams";
23
+ import { userUpdateOptionsToCrud } from "../../users";
24
+ import { clientVersion, createCache, createCacheBySession, createEmptyTokenStore, getBaseUrl, getDefaultProjectId, getDefaultPublishableClientKey, getUrls } from "./common";
22
25
  var isReactServer = false;
23
- var clientVersion = "js @stackframe/js@2.7.21";
24
- if (clientVersion.startsWith("STACK_COMPILE_TIME")) {
25
- throw new StackAssertionError("Client version was not replaced. Something went wrong during build!");
26
- }
27
26
  var process = globalThis.process ?? { env: {} };
28
- function getUrls(partial) {
29
- const handler = partial.handler ?? "/handler";
30
- const home = partial.home ?? "/";
31
- const afterSignIn = partial.afterSignIn ?? home;
32
- return {
33
- handler,
34
- signIn: `${handler}/sign-in`,
35
- afterSignIn: home,
36
- signUp: `${handler}/sign-up`,
37
- afterSignUp: afterSignIn,
38
- signOut: `${handler}/sign-out`,
39
- afterSignOut: home,
40
- emailVerification: `${handler}/email-verification`,
41
- passwordReset: `${handler}/password-reset`,
42
- forgotPassword: `${handler}/forgot-password`,
43
- oauthCallback: `${handler}/oauth-callback`,
44
- magicLinkCallback: `${handler}/magic-link-callback`,
45
- home,
46
- accountSettings: `${handler}/account-settings`,
47
- error: `${handler}/error`,
48
- teamInvitation: `${handler}/team-invitation`,
49
- ...filterUndefined(partial)
50
- };
51
- }
52
- function getDefaultProjectId() {
53
- 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."));
54
- }
55
- function getDefaultPublishableClientKey() {
56
- 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."));
57
- }
58
- function getDefaultSecretServerKey() {
59
- 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."));
60
- }
61
- function getDefaultSuperSecretAdminKey() {
62
- 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."));
63
- }
64
- function getBaseUrl(userSpecifiedBaseUrl) {
65
- let url;
66
- if (userSpecifiedBaseUrl) {
67
- if (typeof userSpecifiedBaseUrl === "string") {
68
- url = userSpecifiedBaseUrl;
69
- } else {
70
- if (isBrowserLike()) {
71
- url = userSpecifiedBaseUrl.browser;
72
- } else {
73
- url = userSpecifiedBaseUrl.server;
74
- }
75
- }
76
- } else {
77
- if (isBrowserLike()) {
78
- url = process.env.NEXT_PUBLIC_BROWSER_STACK_API_URL;
79
- } else {
80
- url = process.env.NEXT_PUBLIC_SERVER_STACK_API_URL;
81
- }
82
- url = url || process.env.NEXT_PUBLIC_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;
83
- }
84
- return url.endsWith("/") ? url.slice(0, -1) : url;
85
- }
86
- var defaultBaseUrl = "https://api.stack-auth.com";
87
- function createEmptyTokenStore() {
88
- return new Store({
89
- refreshToken: null,
90
- accessToken: null
91
- });
92
- }
93
- var stackAppInternalsSymbol = Symbol.for("StackAuth--DO-NOT-USE-OR-YOU-WILL-BE-FIRED--StackAppInternals");
94
- var allClientApps = /* @__PURE__ */ new Map();
95
- var createCache = (fetcher) => {
96
- return new AsyncCache(
97
- async (dependencies) => await Result.fromThrowingAsync(async () => await fetcher(dependencies)),
98
- {}
99
- );
100
- };
101
- var createCacheBySession = (fetcher) => {
102
- return new AsyncCache(
103
- async ([session, ...extraDependencies]) => await Result.fromThrowingAsync(async () => await fetcher(session, extraDependencies)),
104
- {
105
- onSubscribe: ([session], refresh) => {
106
- const handler = session.onInvalidate(() => refresh());
107
- return () => handler.unsubscribe();
108
- }
109
- }
110
- );
111
- };
112
27
  var numberOfAppsCreated = 0;
113
- var _StackClientAppImpl = class __StackClientAppImpl {
28
+ var allClientApps = /* @__PURE__ */ new Map();
29
+ var __StackClientAppImplIncomplete = class __StackClientAppImplIncomplete {
114
30
  constructor(_options) {
115
31
  this._options = _options;
116
32
  this._uniqueIdentifier = void 0;
@@ -195,6 +111,9 @@ var _StackClientAppImpl = class __StackClientAppImpl {
195
111
  * - 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
196
112
  */
197
113
  this._sessionsByTokenStoreAndSessionKey = /* @__PURE__ */ new WeakMap();
114
+ if (!__StackClientAppImplIncomplete.LazyStackAdminAppImpl.value) {
115
+ 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).");
116
+ }
198
117
  if ("interface" in _options) {
199
118
  this._interface = _options.interface;
200
119
  } else {
@@ -620,12 +539,12 @@ var _StackClientAppImpl = class __StackClientAppImpl {
620
539
  let attResp;
621
540
  try {
622
541
  attResp = await startRegistration({ optionsJSON: options_json });
623
- debugger;
624
542
  } catch (error) {
625
543
  if (error instanceof WebAuthnError) {
626
544
  return Result.error(new KnownErrors.PasskeyWebAuthnError(error.message, error.name));
627
545
  } else {
628
- return Result.error(new KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration"));
546
+ captureError("passkey-registration-failed", error);
547
+ return Result.error(new KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"));
629
548
  }
630
549
  }
631
550
  const registrationResult = await app._interface.registerPasskey({ credential: attResp, code }, session);
@@ -787,7 +706,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
787
706
  }
788
707
  _getOwnedAdminApp(forProjectId, session) {
789
708
  if (!this._ownedAdminApps.has([session, forProjectId])) {
790
- this._ownedAdminApps.set([session, forProjectId], new _StackAdminAppImpl({
709
+ this._ownedAdminApps.set([session, forProjectId], new __StackClientAppImplIncomplete.LazyStackAdminAppImpl.value({
791
710
  baseUrl: this._interface.options.getBaseUrl(),
792
711
  projectId: forProjectId,
793
712
  tokenStore: null,
@@ -1238,7 +1157,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
1238
1157
  }
1239
1158
  return clientApp;
1240
1159
  }
1241
- return new __StackClientAppImpl({
1160
+ return new __StackClientAppImplIncomplete({
1242
1161
  ...json,
1243
1162
  checkString: providedCheckString
1244
1163
  });
@@ -1276,852 +1195,16 @@ var _StackClientAppImpl = class __StackClientAppImpl {
1276
1195
  };
1277
1196
  }
1278
1197
  };
1279
- var _StackServerAppImpl = class extends _StackClientAppImpl {
1280
- constructor(options) {
1281
- super("interface" in options ? {
1282
- interface: options.interface,
1283
- tokenStore: options.tokenStore,
1284
- urls: options.urls,
1285
- oauthScopesOnSignIn: options.oauthScopesOnSignIn
1286
- } : {
1287
- interface: new StackServerInterface({
1288
- getBaseUrl: () => getBaseUrl(options.baseUrl),
1289
- projectId: options.projectId ?? getDefaultProjectId(),
1290
- clientVersion,
1291
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
1292
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey()
1293
- }),
1294
- baseUrl: options.baseUrl,
1295
- projectId: options.projectId,
1296
- publishableClientKey: options.publishableClientKey,
1297
- tokenStore: options.tokenStore,
1298
- urls: options.urls ?? {},
1299
- oauthScopesOnSignIn: options.oauthScopesOnSignIn ?? {},
1300
- redirectMethod: options.redirectMethod
1301
- });
1302
- // TODO override the client user cache to use the server user cache, so we save some requests
1303
- this._currentServerUserCache = createCacheBySession(async (session) => {
1304
- if (session.isKnownToBeInvalid()) {
1305
- return null;
1306
- }
1307
- return await this._interface.getServerUserByToken(session);
1308
- });
1309
- this._serverUsersCache = createCache(async ([cursor, limit, orderBy, desc, query]) => {
1310
- return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query });
1311
- });
1312
- this._serverUserCache = createCache(async ([userId]) => {
1313
- const user = await this._interface.getServerUserById(userId);
1314
- return Result.or(user, null);
1315
- });
1316
- this._serverTeamsCache = createCache(async ([userId]) => {
1317
- return await this._interface.listServerTeams({ userId });
1318
- });
1319
- this._serverTeamUserPermissionsCache = createCache(async ([teamId, userId, recursive]) => {
1320
- return await this._interface.listServerTeamPermissions({ teamId, userId, recursive }, null);
1321
- });
1322
- this._serverUserOAuthConnectionAccessTokensCache = createCache(
1323
- async ([userId, providerId, scope]) => {
1324
- try {
1325
- const result = await this._interface.createServerProviderAccessToken(userId, providerId, scope || "");
1326
- return { accessToken: result.access_token };
1327
- } catch (err) {
1328
- if (!(err instanceof KnownErrors.OAuthConnectionDoesNotHaveRequiredScope || err instanceof KnownErrors.OAuthConnectionNotConnectedToUser)) {
1329
- throw err;
1330
- }
1331
- }
1332
- return null;
1333
- }
1334
- );
1335
- this._serverUserOAuthConnectionCache = createCache(
1336
- async ([userId, providerId, scope, redirect]) => {
1337
- return await this._getUserOAuthConnectionCacheFn({
1338
- getUser: async () => Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only")),
1339
- getOrWaitOAuthToken: async () => Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([userId, providerId, scope || ""], "write-only")),
1340
- providerId,
1341
- scope,
1342
- redirect,
1343
- session: null
1344
- });
1345
- }
1346
- );
1347
- this._serverTeamMemberProfilesCache = createCache(
1348
- async ([teamId]) => {
1349
- return await this._interface.listServerTeamMemberProfiles({ teamId });
1350
- }
1351
- );
1352
- this._serverTeamInvitationsCache = createCache(
1353
- async ([teamId]) => {
1354
- return await this._interface.listServerTeamInvitations({ teamId });
1355
- }
1356
- );
1357
- this._serverUserTeamProfileCache = createCache(
1358
- async ([teamId, userId]) => {
1359
- return await this._interface.getServerTeamMemberProfile({ teamId, userId });
1360
- }
1361
- );
1362
- this._serverContactChannelsCache = createCache(
1363
- async ([userId]) => {
1364
- return await this._interface.listServerContactChannels(userId);
1365
- }
1366
- );
1367
- }
1368
- async _updateServerUser(userId, update) {
1369
- const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));
1370
- await this._refreshUsers();
1371
- return result;
1372
- }
1373
- _serverEditableTeamProfileFromCrud(crud) {
1374
- const app = this;
1375
- return {
1376
- displayName: crud.display_name,
1377
- profileImageUrl: crud.profile_image_url,
1378
- async update(update) {
1379
- await app._interface.updateServerTeamMemberProfile({
1380
- teamId: crud.team_id,
1381
- userId: crud.user_id,
1382
- profile: {
1383
- display_name: update.displayName,
1384
- profile_image_url: update.profileImageUrl
1385
- }
1386
- });
1387
- await app._serverUserTeamProfileCache.refresh([crud.team_id, crud.user_id]);
1388
- }
1389
- };
1390
- }
1391
- _serverContactChannelFromCrud(userId, crud) {
1392
- const app = this;
1393
- return {
1394
- id: crud.id,
1395
- value: crud.value,
1396
- type: crud.type,
1397
- isVerified: crud.is_verified,
1398
- isPrimary: crud.is_primary,
1399
- usedForAuth: crud.used_for_auth,
1400
- async sendVerificationEmail(options) {
1401
- if (!options?.callbackUrl && !await app._getCurrentUrl()) {
1402
- 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: ... })`");
1403
- }
1404
- await app._interface.sendServerContactChannelVerificationEmail(userId, crud.id, options?.callbackUrl ?? constructRedirectUrl(app.urls.emailVerification));
1405
- },
1406
- async update(data) {
1407
- await app._interface.updateServerContactChannel(userId, crud.id, serverContactChannelUpdateOptionsToCrud(data));
1408
- },
1409
- async delete() {
1410
- await app._interface.deleteServerContactChannel(userId, crud.id);
1411
- }
1412
- };
1413
- }
1414
- _serverUserFromCrud(crud) {
1415
- const app = this;
1416
- async function getConnectedAccount(id, options) {
1417
- const scopeString = options?.scopes?.join(" ");
1418
- return Result.orThrow(await app._serverUserOAuthConnectionCache.getOrWait([crud.id, id, scopeString || "", options?.or === "redirect"], "write-only"));
1419
- }
1420
- return {
1421
- ...super._createBaseUser(crud),
1422
- lastActiveAt: new Date(crud.last_active_at_millis),
1423
- serverMetadata: crud.server_metadata,
1424
- async setPrimaryEmail(email, options) {
1425
- await app._updateServerUser(crud.id, { primaryEmail: email, primaryEmailVerified: options?.verified });
1426
- },
1427
- async grantPermission(scope, permissionId) {
1428
- await app._interface.grantServerTeamUserPermission(scope.id, crud.id, permissionId);
1429
- for (const recursive of [true, false]) {
1430
- await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
1431
- }
1432
- },
1433
- async revokePermission(scope, permissionId) {
1434
- await app._interface.revokeServerTeamUserPermission(scope.id, crud.id, permissionId);
1435
- for (const recursive of [true, false]) {
1436
- await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
1437
- }
1438
- },
1439
- async delete() {
1440
- const res = await app._interface.deleteServerServerUser(crud.id);
1441
- await app._refreshUsers();
1442
- return res;
1443
- },
1444
- async createSession(options) {
1445
- const tokens = await app._interface.createServerUserSession(crud.id, options.expiresInMillis ?? 1e3 * 60 * 60 * 24 * 365);
1446
- return {
1447
- async getTokens() {
1448
- return tokens;
1449
- }
1450
- };
1451
- },
1452
- async setDisplayName(displayName) {
1453
- return await this.update({ displayName });
1454
- },
1455
- async setClientMetadata(metadata) {
1456
- return await this.update({ clientMetadata: metadata });
1457
- },
1458
- async setClientReadOnlyMetadata(metadata) {
1459
- return await this.update({ clientReadOnlyMetadata: metadata });
1460
- },
1461
- async setServerMetadata(metadata) {
1462
- return await this.update({ serverMetadata: metadata });
1463
- },
1464
- async setSelectedTeam(team) {
1465
- return await this.update({ selectedTeamId: team?.id ?? null });
1466
- },
1467
- getConnectedAccount,
1468
- selectedTeam: crud.selected_team ? app._serverTeamFromCrud(crud.selected_team) : null,
1469
- async getTeam(teamId) {
1470
- const teams = await this.listTeams();
1471
- return teams.find((t) => t.id === teamId) ?? null;
1472
- },
1473
- async listTeams() {
1474
- const teams = Result.orThrow(await app._serverTeamsCache.getOrWait([crud.id], "write-only"));
1475
- return teams.map((t) => app._serverTeamFromCrud(t));
1476
- },
1477
- createTeam: async (data) => {
1478
- const team = await app._interface.createServerTeam(serverTeamCreateOptionsToCrud({
1479
- creatorUserId: crud.id,
1480
- ...data
1481
- }));
1482
- await app._serverTeamsCache.refresh([void 0]);
1483
- return app._serverTeamFromCrud(team);
1484
- },
1485
- leaveTeam: async (team) => {
1486
- await app._interface.leaveServerTeam({ teamId: team.id, userId: crud.id });
1487
- },
1488
- async listPermissions(scope, options) {
1489
- const recursive = options?.recursive ?? true;
1490
- const permissions = Result.orThrow(await app._serverTeamUserPermissionsCache.getOrWait([scope.id, crud.id, recursive], "write-only"));
1491
- return permissions.map((crud2) => app._serverPermissionFromCrud(crud2));
1492
- },
1493
- async getPermission(scope, permissionId) {
1494
- const permissions = await this.listPermissions(scope);
1495
- return permissions.find((p) => p.id === permissionId) ?? null;
1496
- },
1497
- async hasPermission(scope, permissionId) {
1498
- return await this.getPermission(scope, permissionId) !== null;
1499
- },
1500
- async update(update) {
1501
- await app._updateServerUser(crud.id, update);
1502
- },
1503
- async sendVerificationEmail() {
1504
- return await app._checkFeatureSupport("sendVerificationEmail() on ServerUser", {});
1505
- },
1506
- async updatePassword(options) {
1507
- const result = await this.update({ password: options.newPassword });
1508
- await app._serverUserCache.refresh([crud.id]);
1509
- return result;
1510
- },
1511
- async setPassword(options) {
1512
- const result = await this.update(options);
1513
- await app._serverUserCache.refresh([crud.id]);
1514
- return result;
1515
- },
1516
- async getTeamProfile(team) {
1517
- const result = Result.orThrow(await app._serverUserTeamProfileCache.getOrWait([team.id, crud.id], "write-only"));
1518
- return app._serverEditableTeamProfileFromCrud(result);
1519
- },
1520
- async listContactChannels() {
1521
- const result = Result.orThrow(await app._serverContactChannelsCache.getOrWait([crud.id], "write-only"));
1522
- return result.map((data) => app._serverContactChannelFromCrud(crud.id, data));
1523
- },
1524
- createContactChannel: async (data) => {
1525
- const contactChannel = await app._interface.createServerContactChannel(serverContactChannelCreateOptionsToCrud(crud.id, data));
1526
- await app._serverContactChannelsCache.refresh([crud.id]);
1527
- return app._serverContactChannelFromCrud(crud.id, contactChannel);
1528
- }
1529
- };
1530
- }
1531
- _serverTeamUserFromCrud(crud) {
1532
- return {
1533
- ...this._serverUserFromCrud(crud.user),
1534
- teamProfile: {
1535
- displayName: crud.display_name,
1536
- profileImageUrl: crud.profile_image_url
1537
- }
1538
- };
1539
- }
1540
- _serverTeamInvitationFromCrud(crud) {
1541
- return {
1542
- id: crud.id,
1543
- recipientEmail: crud.recipient_email,
1544
- expiresAt: new Date(crud.expires_at_millis),
1545
- revoke: async () => {
1546
- await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);
1547
- }
1548
- };
1549
- }
1550
- _currentUserFromCrud(crud, session) {
1551
- const app = this;
1552
- const currentUser = {
1553
- ...this._serverUserFromCrud(crud),
1554
- ...this._createAuth(session),
1555
- ...this._isInternalProject() ? this._createInternalUserExtra(session) : {}
1556
- };
1557
- Object.freeze(currentUser);
1558
- return currentUser;
1559
- }
1560
- _serverTeamFromCrud(crud) {
1561
- const app = this;
1562
- return {
1563
- id: crud.id,
1564
- displayName: crud.display_name,
1565
- profileImageUrl: crud.profile_image_url,
1566
- createdAt: new Date(crud.created_at_millis),
1567
- clientMetadata: crud.client_metadata,
1568
- clientReadOnlyMetadata: crud.client_read_only_metadata,
1569
- serverMetadata: crud.server_metadata,
1570
- async update(update) {
1571
- await app._interface.updateServerTeam(crud.id, serverTeamUpdateOptionsToCrud(update));
1572
- await app._serverTeamsCache.refresh([void 0]);
1573
- },
1574
- async delete() {
1575
- await app._interface.deleteServerTeam(crud.id);
1576
- await app._serverTeamsCache.refresh([void 0]);
1577
- },
1578
- async listUsers() {
1579
- const result = Result.orThrow(await app._serverTeamMemberProfilesCache.getOrWait([crud.id], "write-only"));
1580
- return result.map((u) => app._serverTeamUserFromCrud(u));
1581
- },
1582
- async addUser(userId) {
1583
- await app._interface.addServerUserToTeam({
1584
- teamId: crud.id,
1585
- userId
1586
- });
1587
- await app._serverTeamMemberProfilesCache.refresh([crud.id]);
1588
- },
1589
- async removeUser(userId) {
1590
- await app._interface.removeServerUserFromTeam({
1591
- teamId: crud.id,
1592
- userId
1593
- });
1594
- await app._serverTeamMemberProfilesCache.refresh([crud.id]);
1595
- },
1596
- async inviteUser(options) {
1597
- if (!options.callbackUrl && !await app._getCurrentUrl()) {
1598
- 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: ... })`");
1599
- }
1600
- await app._interface.sendServerTeamInvitation({
1601
- teamId: crud.id,
1602
- email: options.email,
1603
- callbackUrl: options.callbackUrl ?? constructRedirectUrl(app.urls.teamInvitation)
1604
- });
1605
- await app._serverTeamInvitationsCache.refresh([crud.id]);
1606
- },
1607
- async listInvitations() {
1608
- const result = Result.orThrow(await app._serverTeamInvitationsCache.getOrWait([crud.id], "write-only"));
1609
- return result.map((crud2) => app._serverTeamInvitationFromCrud(crud2));
1610
- }
1611
- };
1612
- }
1613
- async createUser(options) {
1614
- const crud = await this._interface.createServerUser(serverUserCreateOptionsToCrud(options));
1615
- await this._refreshUsers();
1616
- return this._serverUserFromCrud(crud);
1617
- }
1618
- async getUser(options) {
1619
- if (typeof options === "string") {
1620
- return await this.getServerUserById(options);
1621
- } else {
1622
- this._ensurePersistentTokenStore(options?.tokenStore);
1623
- const session = await this._getSession(options?.tokenStore);
1624
- const crud = Result.orThrow(await this._currentServerUserCache.getOrWait([session], "write-only"));
1625
- if (crud === null) {
1626
- switch (options?.or) {
1627
- case "redirect": {
1628
- await this.redirectToSignIn({ replace: true });
1629
- break;
1630
- }
1631
- case "throw": {
1632
- throw new Error("User is not signed in but getUser was called with { or: 'throw' }");
1633
- }
1634
- default: {
1635
- return null;
1636
- }
1637
- }
1638
- }
1639
- return crud && this._currentUserFromCrud(crud, session);
1640
- }
1641
- }
1642
- async getServerUser() {
1643
- console.warn("stackServerApp.getServerUser is deprecated; use stackServerApp.getUser instead");
1644
- return await this.getUser();
1645
- }
1646
- async getServerUserById(userId) {
1647
- const crud = Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only"));
1648
- return crud && this._serverUserFromCrud(crud);
1649
- }
1650
- async listUsers(options) {
1651
- const crud = Result.orThrow(await this._serverUsersCache.getOrWait([options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "write-only"));
1652
- const result = crud.items.map((j) => this._serverUserFromCrud(j));
1653
- result.nextCursor = crud.pagination?.next_cursor ?? null;
1654
- return result;
1655
- }
1656
- _serverPermissionFromCrud(crud) {
1657
- return {
1658
- id: crud.id
1659
- };
1660
- }
1661
- _serverTeamPermissionDefinitionFromCrud(crud) {
1662
- return {
1663
- id: crud.id,
1664
- description: crud.description,
1665
- containedPermissionIds: crud.contained_permission_ids
1666
- };
1667
- }
1668
- async listTeams() {
1669
- const teams = Result.orThrow(await this._serverTeamsCache.getOrWait([void 0], "write-only"));
1670
- return teams.map((t) => this._serverTeamFromCrud(t));
1671
- }
1672
- async createTeam(data) {
1673
- const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));
1674
- await this._serverTeamsCache.refresh([void 0]);
1675
- return this._serverTeamFromCrud(team);
1676
- }
1677
- async getTeam(teamId) {
1678
- const teams = await this.listTeams();
1679
- return teams.find((t) => t.id === teamId) ?? null;
1680
- }
1681
- async _refreshSession(session) {
1682
- await Promise.all([
1683
- super._refreshUser(session),
1684
- this._currentServerUserCache.refresh([session])
1685
- ]);
1686
- }
1687
- async _refreshUsers() {
1688
- await Promise.all([
1689
- super._refreshUsers(),
1690
- this._serverUserCache.refreshWhere(() => true),
1691
- this._serverUsersCache.refreshWhere(() => true),
1692
- this._serverContactChannelsCache.refreshWhere(() => true)
1693
- ]);
1694
- }
1695
- };
1696
- var _StackAdminAppImpl = class extends _StackServerAppImpl {
1697
- constructor(options) {
1698
- super({
1699
- interface: new StackAdminInterface({
1700
- getBaseUrl: () => getBaseUrl(options.baseUrl),
1701
- projectId: options.projectId ?? getDefaultProjectId(),
1702
- clientVersion,
1703
- ..."projectOwnerSession" in options ? {
1704
- projectOwnerSession: options.projectOwnerSession
1705
- } : {
1706
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
1707
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
1708
- superSecretAdminKey: options.superSecretAdminKey ?? getDefaultSuperSecretAdminKey()
1709
- }
1710
- }),
1711
- baseUrl: options.baseUrl,
1712
- projectId: options.projectId,
1713
- tokenStore: options.tokenStore,
1714
- urls: options.urls,
1715
- oauthScopesOnSignIn: options.oauthScopesOnSignIn,
1716
- redirectMethod: options.redirectMethod
1717
- });
1718
- this._adminProjectCache = createCache(async () => {
1719
- return await this._interface.getProject();
1720
- });
1721
- this._apiKeysCache = createCache(async () => {
1722
- return await this._interface.listApiKeys();
1723
- });
1724
- this._adminEmailTemplatesCache = createCache(async () => {
1725
- return await this._interface.listEmailTemplates();
1726
- });
1727
- this._adminTeamPermissionDefinitionsCache = createCache(async () => {
1728
- return await this._interface.listPermissionDefinitions();
1729
- });
1730
- this._svixTokenCache = createCache(async () => {
1731
- return await this._interface.getSvixToken();
1732
- });
1733
- this._metricsCache = createCache(async () => {
1734
- return await this._interface.getMetrics();
1735
- });
1736
- }
1737
- _adminOwnedProjectFromCrud(data, onRefresh) {
1738
- if (this._tokenStoreInit !== null) {
1739
- throw new StackAssertionError("Owned apps must always have tokenStore === null \u2014 did you not create this project with app._createOwnedApp()?");
1740
- ;
1741
- }
1742
- return {
1743
- ...this._adminProjectFromCrud(data, onRefresh),
1744
- app: this
1745
- };
1746
- }
1747
- _adminProjectFromCrud(data, onRefresh) {
1748
- if (data.id !== this.projectId) {
1749
- throw new StackAssertionError(`The project ID of the provided project JSON (${data.id}) does not match the project ID of the app (${this.projectId})!`);
1750
- }
1751
- const app = this;
1752
- return {
1753
- id: data.id,
1754
- displayName: data.display_name,
1755
- description: data.description,
1756
- createdAt: new Date(data.created_at_millis),
1757
- userCount: data.user_count,
1758
- isProductionMode: data.is_production_mode,
1759
- config: {
1760
- id: data.config.id,
1761
- signUpEnabled: data.config.sign_up_enabled,
1762
- credentialEnabled: data.config.credential_enabled,
1763
- magicLinkEnabled: data.config.magic_link_enabled,
1764
- passkeyEnabled: data.config.passkey_enabled,
1765
- clientTeamCreationEnabled: data.config.client_team_creation_enabled,
1766
- clientUserDeletionEnabled: data.config.client_user_deletion_enabled,
1767
- allowLocalhost: data.config.allow_localhost,
1768
- oauthProviders: data.config.oauth_providers.map((p) => p.type === "shared" ? {
1769
- id: p.id,
1770
- enabled: p.enabled,
1771
- type: "shared"
1772
- } : {
1773
- id: p.id,
1774
- enabled: p.enabled,
1775
- type: "standard",
1776
- clientId: p.client_id ?? throwErr("Client ID is missing"),
1777
- clientSecret: p.client_secret ?? throwErr("Client secret is missing"),
1778
- facebookConfigId: p.facebook_config_id,
1779
- microsoftTenantId: p.microsoft_tenant_id
1780
- }),
1781
- emailConfig: data.config.email_config.type === "shared" ? {
1782
- type: "shared"
1783
- } : {
1784
- type: "standard",
1785
- host: data.config.email_config.host ?? throwErr("Email host is missing"),
1786
- port: data.config.email_config.port ?? throwErr("Email port is missing"),
1787
- username: data.config.email_config.username ?? throwErr("Email username is missing"),
1788
- password: data.config.email_config.password ?? throwErr("Email password is missing"),
1789
- senderName: data.config.email_config.sender_name ?? throwErr("Email sender name is missing"),
1790
- senderEmail: data.config.email_config.sender_email ?? throwErr("Email sender email is missing")
1791
- },
1792
- domains: data.config.domains.map((d) => ({
1793
- domain: d.domain,
1794
- handlerPath: d.handler_path
1795
- })),
1796
- createTeamOnSignUp: data.config.create_team_on_sign_up,
1797
- teamCreatorDefaultPermissions: data.config.team_creator_default_permissions,
1798
- teamMemberDefaultPermissions: data.config.team_member_default_permissions
1799
- },
1800
- async update(update) {
1801
- await app._interface.updateProject(adminProjectUpdateOptionsToCrud(update));
1802
- await onRefresh();
1803
- },
1804
- async delete() {
1805
- await app._interface.deleteProject();
1806
- },
1807
- async getProductionModeErrors() {
1808
- return getProductionModeErrors(data);
1809
- },
1810
- useProductionModeErrors() {
1811
- return getProductionModeErrors(data);
1812
- }
1813
- };
1814
- }
1815
- _adminEmailTemplateFromCrud(data) {
1816
- return {
1817
- type: data.type,
1818
- subject: data.subject,
1819
- content: data.content,
1820
- isDefault: data.is_default
1821
- };
1822
- }
1823
- async getProject() {
1824
- return this._adminProjectFromCrud(
1825
- Result.orThrow(await this._adminProjectCache.getOrWait([], "write-only")),
1826
- () => this._refreshProject()
1827
- );
1828
- }
1829
- _createApiKeyBaseFromCrud(data) {
1830
- const app = this;
1831
- return {
1832
- id: data.id,
1833
- description: data.description,
1834
- expiresAt: new Date(data.expires_at_millis),
1835
- manuallyRevokedAt: data.manually_revoked_at_millis ? new Date(data.manually_revoked_at_millis) : null,
1836
- createdAt: new Date(data.created_at_millis),
1837
- isValid() {
1838
- return this.whyInvalid() === null;
1839
- },
1840
- whyInvalid() {
1841
- if (this.expiresAt.getTime() < Date.now()) return "expired";
1842
- if (this.manuallyRevokedAt) return "manually-revoked";
1843
- return null;
1844
- },
1845
- async revoke() {
1846
- const res = await app._interface.revokeApiKeyById(data.id);
1847
- await app._refreshApiKeys();
1848
- return res;
1849
- }
1850
- };
1851
- }
1852
- _createApiKeyFromCrud(data) {
1853
- return {
1854
- ...this._createApiKeyBaseFromCrud(data),
1855
- publishableClientKey: data.publishable_client_key ? { lastFour: data.publishable_client_key.last_four } : null,
1856
- secretServerKey: data.secret_server_key ? { lastFour: data.secret_server_key.last_four } : null,
1857
- superSecretAdminKey: data.super_secret_admin_key ? { lastFour: data.super_secret_admin_key.last_four } : null
1858
- };
1859
- }
1860
- _createApiKeyFirstViewFromCrud(data) {
1861
- return {
1862
- ...this._createApiKeyBaseFromCrud(data),
1863
- publishableClientKey: data.publishable_client_key,
1864
- secretServerKey: data.secret_server_key,
1865
- superSecretAdminKey: data.super_secret_admin_key
1866
- };
1867
- }
1868
- async listApiKeys() {
1869
- const crud = Result.orThrow(await this._apiKeysCache.getOrWait([], "write-only"));
1870
- return crud.map((j) => this._createApiKeyFromCrud(j));
1871
- }
1872
- async createApiKey(options) {
1873
- const crud = await this._interface.createApiKey(apiKeyCreateOptionsToCrud(options));
1874
- await this._refreshApiKeys();
1875
- return this._createApiKeyFirstViewFromCrud(crud);
1876
- }
1877
- async listEmailTemplates() {
1878
- const crud = Result.orThrow(await this._adminEmailTemplatesCache.getOrWait([], "write-only"));
1879
- return crud.map((j) => this._adminEmailTemplateFromCrud(j));
1880
- }
1881
- async updateEmailTemplate(type, data) {
1882
- await this._interface.updateEmailTemplate(type, adminEmailTemplateUpdateOptionsToCrud(data));
1883
- await this._adminEmailTemplatesCache.refresh([]);
1884
- }
1885
- async resetEmailTemplate(type) {
1886
- await this._interface.resetEmailTemplate(type);
1887
- await this._adminEmailTemplatesCache.refresh([]);
1888
- }
1889
- async createTeamPermissionDefinition(data) {
1890
- const crud = await this._interface.createPermissionDefinition(serverTeamPermissionDefinitionCreateOptionsToCrud(data));
1891
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
1892
- return this._serverTeamPermissionDefinitionFromCrud(crud);
1893
- }
1894
- async updateTeamPermissionDefinition(permissionId, data) {
1895
- await this._interface.updatePermissionDefinition(permissionId, serverTeamPermissionDefinitionUpdateOptionsToCrud(data));
1896
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
1897
- }
1898
- async deleteTeamPermissionDefinition(permissionId) {
1899
- await this._interface.deletePermissionDefinition(permissionId);
1900
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
1901
- }
1902
- async listTeamPermissionDefinitions() {
1903
- const crud = Result.orThrow(await this._adminTeamPermissionDefinitionsCache.getOrWait([], "write-only"));
1904
- return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
1905
- }
1906
- async _refreshProject() {
1907
- await Promise.all([
1908
- super._refreshProject(),
1909
- this._adminProjectCache.refresh([])
1910
- ]);
1911
- }
1912
- async _refreshApiKeys() {
1913
- await this._apiKeysCache.refresh([]);
1914
- }
1915
- get [stackAppInternalsSymbol]() {
1916
- return {
1917
- ...super[stackAppInternalsSymbol]
1918
- };
1919
- }
1920
- async sendTestEmail(options) {
1921
- const response = await this._interface.sendTestEmail({
1922
- recipient_email: options.recipientEmail,
1923
- email_config: {
1924
- ...pick(options.emailConfig, ["host", "port", "username", "password"]),
1925
- sender_email: options.emailConfig.senderEmail,
1926
- sender_name: options.emailConfig.senderName
1927
- }
1928
- });
1929
- if (response.success) {
1930
- return Result.ok(void 0);
1931
- } else {
1932
- return Result.error({ errorMessage: response.error_message ?? throwErr("Email test error not specified") });
1933
- }
1934
- }
1935
- };
1936
- function contactChannelCreateOptionsToCrud(userId, options) {
1937
- return {
1938
- value: options.value,
1939
- type: options.type,
1940
- used_for_auth: options.usedForAuth,
1941
- user_id: userId
1942
- };
1943
- }
1944
- function contactChannelUpdateOptionsToCrud(options) {
1945
- return {
1946
- value: options.value,
1947
- used_for_auth: options.usedForAuth,
1948
- is_primary: options.isPrimary
1949
- };
1950
- }
1951
- function serverContactChannelUpdateOptionsToCrud(options) {
1952
- return {
1953
- value: options.value,
1954
- is_verified: options.isVerified,
1955
- used_for_auth: options.usedForAuth
1956
- };
1957
- }
1958
- function serverContactChannelCreateOptionsToCrud(userId, options) {
1959
- return {
1960
- type: options.type,
1961
- value: options.value,
1962
- is_verified: options.isVerified,
1963
- user_id: userId,
1964
- used_for_auth: options.usedForAuth
1965
- };
1966
- }
1967
- function userUpdateOptionsToCrud(options) {
1968
- return {
1969
- display_name: options.displayName,
1970
- client_metadata: options.clientMetadata,
1971
- selected_team_id: options.selectedTeamId,
1972
- totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,
1973
- profile_image_url: options.profileImageUrl,
1974
- otp_auth_enabled: options.otpAuthEnabled,
1975
- passkey_auth_enabled: options.passkeyAuthEnabled
1976
- };
1977
- }
1978
- function serverUserUpdateOptionsToCrud(options) {
1979
- return {
1980
- display_name: options.displayName,
1981
- primary_email: options.primaryEmail,
1982
- client_metadata: options.clientMetadata,
1983
- client_read_only_metadata: options.clientReadOnlyMetadata,
1984
- server_metadata: options.serverMetadata,
1985
- selected_team_id: options.selectedTeamId,
1986
- primary_email_auth_enabled: options.primaryEmailAuthEnabled,
1987
- primary_email_verified: options.primaryEmailVerified,
1988
- password: options.password,
1989
- profile_image_url: options.profileImageUrl,
1990
- totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret
1991
- };
1992
- }
1993
- function serverUserCreateOptionsToCrud(options) {
1994
- return {
1995
- primary_email: options.primaryEmail,
1996
- password: options.password,
1997
- otp_auth_enabled: options.otpAuthEnabled,
1998
- primary_email_auth_enabled: options.primaryEmailAuthEnabled,
1999
- display_name: options.displayName,
2000
- primary_email_verified: options.primaryEmailVerified,
2001
- client_metadata: options.clientMetadata,
2002
- client_read_only_metadata: options.clientReadOnlyMetadata,
2003
- server_metadata: options.serverMetadata
2004
- };
2005
- }
2006
- function adminProjectUpdateOptionsToCrud(options) {
2007
- return {
2008
- display_name: options.displayName,
2009
- description: options.description,
2010
- is_production_mode: options.isProductionMode,
2011
- config: {
2012
- domains: options.config?.domains?.map((d) => ({
2013
- domain: d.domain,
2014
- handler_path: d.handlerPath
2015
- })),
2016
- oauth_providers: options.config?.oauthProviders?.map((p) => ({
2017
- id: p.id,
2018
- enabled: p.enabled,
2019
- type: p.type,
2020
- ...p.type === "standard" && {
2021
- client_id: p.clientId,
2022
- client_secret: p.clientSecret,
2023
- facebook_config_id: p.facebookConfigId,
2024
- microsoft_tenant_id: p.microsoftTenantId
2025
- }
2026
- })),
2027
- email_config: options.config?.emailConfig && (options.config.emailConfig.type === "shared" ? {
2028
- type: "shared"
2029
- } : {
2030
- type: "standard",
2031
- host: options.config.emailConfig.host,
2032
- port: options.config.emailConfig.port,
2033
- username: options.config.emailConfig.username,
2034
- password: options.config.emailConfig.password,
2035
- sender_name: options.config.emailConfig.senderName,
2036
- sender_email: options.config.emailConfig.senderEmail
2037
- }),
2038
- sign_up_enabled: options.config?.signUpEnabled,
2039
- credential_enabled: options.config?.credentialEnabled,
2040
- magic_link_enabled: options.config?.magicLinkEnabled,
2041
- passkey_enabled: options.config?.passkeyEnabled,
2042
- allow_localhost: options.config?.allowLocalhost,
2043
- create_team_on_sign_up: options.config?.createTeamOnSignUp,
2044
- client_team_creation_enabled: options.config?.clientTeamCreationEnabled,
2045
- client_user_deletion_enabled: options.config?.clientUserDeletionEnabled,
2046
- team_creator_default_permissions: options.config?.teamCreatorDefaultPermissions,
2047
- team_member_default_permissions: options.config?.teamMemberDefaultPermissions
2048
- }
2049
- };
2050
- }
2051
- function adminProjectCreateOptionsToCrud(options) {
2052
- return {
2053
- ...adminProjectUpdateOptionsToCrud(options),
2054
- display_name: options.displayName
2055
- };
2056
- }
2057
- function apiKeyCreateOptionsToCrud(options) {
2058
- return {
2059
- description: options.description,
2060
- expires_at_millis: options.expiresAt.getTime(),
2061
- has_publishable_client_key: options.hasPublishableClientKey,
2062
- has_secret_server_key: options.hasSecretServerKey,
2063
- has_super_secret_admin_key: options.hasSuperSecretAdminKey
2064
- };
2065
- }
2066
- function teamUpdateOptionsToCrud(options) {
2067
- return {
2068
- display_name: options.displayName,
2069
- profile_image_url: options.profileImageUrl,
2070
- client_metadata: options.clientMetadata
2071
- };
2072
- }
2073
- function teamCreateOptionsToCrud(options, creatorUserId) {
2074
- return {
2075
- display_name: options.displayName,
2076
- profile_image_url: options.profileImageUrl,
2077
- creator_user_id: creatorUserId
2078
- };
2079
- }
2080
- function serverTeamCreateOptionsToCrud(options) {
2081
- return {
2082
- display_name: options.displayName,
2083
- profile_image_url: options.profileImageUrl,
2084
- creator_user_id: options.creatorUserId
2085
- };
2086
- }
2087
- function serverTeamUpdateOptionsToCrud(options) {
2088
- return {
2089
- display_name: options.displayName,
2090
- profile_image_url: options.profileImageUrl,
2091
- client_metadata: options.clientMetadata,
2092
- client_read_only_metadata: options.clientReadOnlyMetadata,
2093
- server_metadata: options.serverMetadata
2094
- };
2095
- }
2096
- function serverTeamPermissionDefinitionCreateOptionsToCrud(options) {
2097
- return {
2098
- id: options.id,
2099
- description: options.description,
2100
- contained_permission_ids: options.containedPermissionIds
2101
- };
2102
- }
2103
- function serverTeamPermissionDefinitionUpdateOptionsToCrud(options) {
2104
- return {
2105
- id: options.id,
2106
- description: options.description,
2107
- contained_permission_ids: options.containedPermissionIds
2108
- };
2109
- }
2110
- var StackClientApp = _StackClientAppImpl;
2111
- var StackServerApp = _StackServerAppImpl;
2112
- var StackAdminApp = _StackAdminAppImpl;
2113
- function adminEmailTemplateUpdateOptionsToCrud(options) {
2114
- return {
2115
- subject: options.subject,
2116
- content: options.content
2117
- };
2118
- }
1198
+ /**
1199
+ * There is a circular dependency between the admin app and the client app, as the former inherits from the latter and
1200
+ * the latter needs to use the former when creating a new instance of an internal project.
1201
+ *
1202
+ * To break it, we set the admin app here lazily instead of importing it directly. This variable is set by ./index.ts,
1203
+ * which imports both this file and ./admin-app-impl.ts.
1204
+ */
1205
+ __StackClientAppImplIncomplete.LazyStackAdminAppImpl = { value: void 0 };
1206
+ var _StackClientAppImplIncomplete = __StackClientAppImplIncomplete;
2119
1207
  export {
2120
- StackAdminApp,
2121
- StackClientApp,
2122
- StackServerApp,
2123
- serverTeamPermissionDefinitionCreateOptionsToCrud,
2124
- serverTeamPermissionDefinitionUpdateOptionsToCrud,
2125
- stackAppInternalsSymbol
1208
+ _StackClientAppImplIncomplete
2126
1209
  };
2127
- //# sourceMappingURL=stack-app.js.map
1210
+ //# sourceMappingURL=client-app-impl.js.map