@stackframe/stack 2.8.41 → 2.8.44

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 (51) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/esm/integrations/convex/component/convex.config.js +8 -0
  3. package/dist/esm/integrations/convex/component/convex.config.js.map +1 -0
  4. package/dist/esm/integrations/convex.js +5 -4
  5. package/dist/esm/integrations/convex.js.map +1 -1
  6. package/dist/esm/lib/hooks.js +3 -0
  7. package/dist/esm/lib/hooks.js.map +1 -1
  8. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js +31 -42
  9. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -1
  10. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js +107 -32
  11. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -1
  12. package/dist/esm/lib/stack-app/apps/implementations/common.js +16 -2
  13. package/dist/esm/lib/stack-app/apps/implementations/common.js.map +1 -1
  14. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js +119 -60
  15. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -1
  16. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js.map +1 -1
  17. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js.map +1 -1
  18. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js.map +1 -1
  19. package/dist/esm/lib/stack-app/projects/index.js.map +1 -1
  20. package/dist/esm/lib/stack-app/users/index.js +16 -0
  21. package/dist/esm/lib/stack-app/users/index.js.map +1 -1
  22. package/dist/esm/providers/stack-provider.js +2 -6
  23. package/dist/esm/providers/stack-provider.js.map +1 -1
  24. package/dist/index.d.mts +86 -23
  25. package/dist/index.d.ts +86 -23
  26. package/dist/integrations/convex/component/convex.config.d.mts +5 -0
  27. package/dist/integrations/convex/component/convex.config.d.ts +5 -0
  28. package/dist/integrations/convex/component/convex.config.js +29 -0
  29. package/dist/integrations/convex/component/convex.config.js.map +1 -0
  30. package/dist/integrations/convex.js +4 -3
  31. package/dist/integrations/convex.js.map +1 -1
  32. package/dist/lib/hooks.js +3 -0
  33. package/dist/lib/hooks.js.map +1 -1
  34. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js +30 -41
  35. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -1
  36. package/dist/lib/stack-app/apps/implementations/client-app-impl.js +105 -30
  37. package/dist/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -1
  38. package/dist/lib/stack-app/apps/implementations/common.js +17 -1
  39. package/dist/lib/stack-app/apps/implementations/common.js.map +1 -1
  40. package/dist/lib/stack-app/apps/implementations/server-app-impl.js +117 -58
  41. package/dist/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -1
  42. package/dist/lib/stack-app/apps/interfaces/admin-app.js.map +1 -1
  43. package/dist/lib/stack-app/apps/interfaces/client-app.js.map +1 -1
  44. package/dist/lib/stack-app/apps/interfaces/server-app.js.map +1 -1
  45. package/dist/lib/stack-app/customers/index.js.map +1 -1
  46. package/dist/lib/stack-app/projects/index.js.map +1 -1
  47. package/dist/lib/stack-app/users/index.js +17 -0
  48. package/dist/lib/stack-app/users/index.js.map +1 -1
  49. package/dist/providers/stack-provider.js +1 -5
  50. package/dist/providers/stack-provider.js.map +1 -1
  51. package/package.json +19 -10
@@ -2,12 +2,14 @@
2
2
  import { AsyncCache } from "@stackframe/stack-shared/dist/utils/caches";
3
3
  import { isBrowserLike } from "@stackframe/stack-shared/dist/utils/env";
4
4
  import { StackAssertionError, concatStacktraces, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
5
- import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects";
5
+ import { getGlobal } from "@stackframe/stack-shared/dist/utils/globals";
6
+ import { filterUndefined, omit } from "@stackframe/stack-shared/dist/utils/objects";
6
7
  import { suspendIfSsr } from "@stackframe/stack-shared/dist/utils/react";
7
8
  import { Result } from "@stackframe/stack-shared/dist/utils/results";
8
9
  import { Store } from "@stackframe/stack-shared/dist/utils/stores";
9
10
  import React, { useCallback } from "react";
10
- var clientVersion = "js @stackframe/stack@2.8.41";
11
+ import { stackAppInternalsSymbol } from "../../common.js";
12
+ var clientVersion = "js @stackframe/stack@2.8.44";
11
13
  if (clientVersion.startsWith("STACK_COMPILE_TIME")) {
12
14
  throw new StackAssertionError("Client version was not replaced. Something went wrong during build!");
13
15
  }
@@ -28,6 +30,12 @@ var createCacheBySession = (fetcher) => {
28
30
  }
29
31
  );
30
32
  };
33
+ function resolveConstructorOptions(options) {
34
+ return {
35
+ ...options.inheritsFrom?.[stackAppInternalsSymbol].getConstructorOptions() ?? {},
36
+ ...filterUndefined(omit(options, ["inheritsFrom"]))
37
+ };
38
+ }
31
39
  function getUrls(partial) {
32
40
  const handler = partial.handler ?? "/handler";
33
41
  const home = partial.home ?? "/";
@@ -100,6 +108,10 @@ function createEmptyTokenStore() {
100
108
  var cachePromiseByHookId = /* @__PURE__ */ new Map();
101
109
  function useAsyncCache(cache, dependencies, caller) {
102
110
  suspendIfSsr(caller);
111
+ const asyncCacheHooks = getGlobal("use-async-cache-execution-hooks") ?? [];
112
+ for (const hook of asyncCacheHooks) {
113
+ hook({ cache, caller, dependencies });
114
+ }
103
115
  const id = React.useId();
104
116
  React.useEffect(() => {
105
117
  cachePromiseByHookId.delete(id);
@@ -138,6 +150,7 @@ export {
138
150
  createCache,
139
151
  createCacheBySession,
140
152
  createEmptyTokenStore,
153
+ defaultBaseUrl,
141
154
  getBaseUrl,
142
155
  getDefaultExtraRequestHeaders,
143
156
  getDefaultProjectId,
@@ -145,6 +158,7 @@ export {
145
158
  getDefaultSecretServerKey,
146
159
  getDefaultSuperSecretAdminKey,
147
160
  getUrls,
161
+ resolveConstructorOptions,
148
162
  useAsyncCache
149
163
  };
150
164
  //# sourceMappingURL=common.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../src/lib/stack-app/apps/implementations/common.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { AsyncCache } from \"@stackframe/stack-shared/dist/utils/caches\";\nimport { isBrowserLike } from \"@stackframe/stack-shared/dist/utils/env\";\nimport { StackAssertionError, concatStacktraces, throwErr } from \"@stackframe/stack-shared/dist/utils/errors\";\nimport { filterUndefined } from \"@stackframe/stack-shared/dist/utils/objects\";\nimport { ReactPromise } from \"@stackframe/stack-shared/dist/utils/promises\";\nimport { suspendIfSsr } from \"@stackframe/stack-shared/dist/utils/react\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { Store } from \"@stackframe/stack-shared/dist/utils/stores\";\nimport React, { useCallback } from \"react\"; // THIS_LINE_PLATFORM react-like\nimport { HandlerUrls } from \"../../common\";\n\n// hack to make sure process is defined in non-node environments\n\nexport const clientVersion = \"js @stackframe/stack@2.8.41\";\nif (clientVersion.startsWith(\"STACK_COMPILE_TIME\")) {\n throw new StackAssertionError(\"Client version was not replaced. Something went wrong during build!\");\n}\n\n\nexport const createCache = <D extends any[], T>(fetcher: (dependencies: D) => Promise<T>) => {\n return new AsyncCache<D, Result<T>>(\n async (dependencies) => await Result.fromThrowingAsync(async () => await fetcher(dependencies)),\n {},\n );\n};\n\nexport const createCacheBySession = <D extends any[], T>(fetcher: (session: InternalSession, extraDependencies: D) => Promise<T> ) => {\n return new AsyncCache<[InternalSession, ...D], Result<T>>(\n async ([session, ...extraDependencies]) => await Result.fromThrowingAsync(async () => await fetcher(session, extraDependencies)),\n {\n onSubscribe: ([session], refresh) => {\n const handler = session.onInvalidate(() => refresh());\n return () => handler.unsubscribe();\n },\n },\n );\n};\n\nexport function getUrls(partial: Partial<HandlerUrls>): HandlerUrls {\n const handler = partial.handler ?? \"/handler\";\n const home = partial.home ?? \"/\";\n const afterSignIn = partial.afterSignIn ?? home;\n return {\n handler,\n signIn: `${handler}/sign-in`,\n afterSignIn: home,\n signUp: `${handler}/sign-up`,\n afterSignUp: afterSignIn,\n signOut: `${handler}/sign-out`,\n afterSignOut: home,\n emailVerification: `${handler}/email-verification`,\n passwordReset: `${handler}/password-reset`,\n forgotPassword: `${handler}/forgot-password`,\n oauthCallback: `${handler}/oauth-callback`,\n magicLinkCallback: `${handler}/magic-link-callback`,\n home: home,\n accountSettings: `${handler}/account-settings`,\n error: `${handler}/error`,\n teamInvitation: `${handler}/team-invitation`,\n mfa: `${handler}/mfa`,\n ...filterUndefined(partial),\n };\n}\n\nexport function getDefaultProjectId() {\n return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || process.env.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.\"));\n}\n\nexport function getDefaultPublishableClientKey() {\n return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || process.env.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.\"));\n}\n\nexport function getDefaultSecretServerKey() {\n 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 it in the STACK_SECRET_SERVER_KEY environment variable.\"));\n}\n\nexport function getDefaultSuperSecretAdminKey() {\n 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.\"));\n}\n\nexport function getDefaultExtraRequestHeaders() {\n return JSON.parse(process.env.NEXT_PUBLIC_STACK_EXTRA_REQUEST_HEADERS || process.env.STACK_EXTRA_REQUEST_HEADERS || '{}');\n}\n\n/**\n * Returns the base URL for the Stack API.\n *\n * The URL can be specified in several ways, in order of precedence:\n * 1. Directly through userSpecifiedBaseUrl parameter as string or browser/server object\n * 2. Through environment variables:\n * - Browser: NEXT_PUBLIC_BROWSER_STACK_API_URL\n * - Server: NEXT_PUBLIC_SERVER_STACK_API_URL\n * - Fallback: NEXT_PUBLIC_STACK_API_URL or NEXT_PUBLIC_STACK_URL\n * 3. Default base URL if none of the above are specified\n *\n * The function also ensures the URL doesn't end with a trailing slash\n * by removing it if present.\n *\n * @param userSpecifiedBaseUrl - Optional URL override as string or {browser, server} object\n * @returns The configured base URL without trailing slash\n\n */\nexport function getBaseUrl(userSpecifiedBaseUrl: string | { browser: string, server: string } | undefined) {\n let url;\n if (userSpecifiedBaseUrl) {\n if (typeof userSpecifiedBaseUrl === \"string\") {\n url = userSpecifiedBaseUrl;\n } else {\n if (isBrowserLike()) {\n url = userSpecifiedBaseUrl.browser;\n } else {\n url = userSpecifiedBaseUrl.server;\n }\n }\n } else {\n // note: NEXT_PUBLIC_BROWSER_STACK_API_URL was renamed to NEXT_PUBLIC_STACK_API_URL_BROWSER, and NEXT_PUBLIC_STACK_URL to NEXT_PUBLIC_STACK_API_URL\n if (isBrowserLike()) {\n url = process.env.NEXT_PUBLIC_BROWSER_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_API_URL_BROWSER || process.env.STACK_API_URL_BROWSER;\n } else {\n url = process.env.NEXT_PUBLIC_SERVER_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_API_URL_SERVER || process.env.STACK_API_URL_SERVER;\n }\n url = url || process.env.NEXT_PUBLIC_STACK_API_URL || process.env.STACK_API_URL || process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;\n }\n\n return url.endsWith('/') ? url.slice(0, -1) : url;\n}\nconst defaultBaseUrl = \"https://api.stack-auth.com\";\n\nexport type TokenObject = {\n accessToken: string | null,\n refreshToken: string | null,\n};\n\nexport function createEmptyTokenStore() {\n return new Store<TokenObject>({\n refreshToken: null,\n accessToken: null,\n });\n}\n\n\nconst cachePromiseByHookId = new Map<string, ReactPromise<Result<unknown>>>();\nexport function useAsyncCache<D extends any[], T>(cache: AsyncCache<D, Result<T>>, dependencies: D, caller: string): T {\n // we explicitly don't want to run this hook in SSR\n suspendIfSsr(caller);\n\n const id = React.useId();\n\n // whenever the dependencies change, we need to refresh the promise cache\n React.useEffect(() => {\n cachePromiseByHookId.delete(id);\n }, [...dependencies, id]);\n\n const subscribe = useCallback((cb: () => void) => {\n const { unsubscribe } = cache.onStateChange(dependencies, () => {\n cachePromiseByHookId.delete(id);\n cb();\n });\n return unsubscribe;\n }, [cache, ...dependencies]);\n const getSnapshot = useCallback(() => {\n // React checks whether a promise passed to `use` is still the same as the previous one by comparing the reference.\n // If we didn't cache here, this wouldn't work because the promise would be recreated every time the value changes.\n if (!cachePromiseByHookId.has(id)) {\n cachePromiseByHookId.set(id, cache.getOrWait(dependencies, \"read-write\"));\n }\n return cachePromiseByHookId.get(id) as ReactPromise<Result<T>>;\n }, [cache, ...dependencies]);\n\n // note: we must use React.useSyncExternalStore instead of importing the function directly, as it will otherwise\n // throw an error on Next.js (\"can't import useSyncExternalStore from the server\")\n const promise = React.useSyncExternalStore(\n subscribe,\n getSnapshot,\n () => throwErr(new Error(\"getServerSnapshot should never be called in useAsyncCache because we restrict to CSR earlier\"))\n );\n\n const result = React.use(promise);\n if (result.status === \"error\") {\n const error = result.error;\n if (error instanceof Error && !(error as any).__stackHasConcatenatedStacktraces) {\n concatStacktraces(error, new Error());\n (error as any).__stackHasConcatenatedStacktraces = true;\n }\n throw error;\n }\n return result.data;\n}\n"],"mappings":";AAKA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB,mBAAmB,gBAAgB;AACjE,SAAS,uBAAuB;AAEhC,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,OAAO,SAAS,mBAAmB;AAK5B,IAAM,gBAAgB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H;AAGA,IAAM,uBAAuB,oBAAI,IAA2C;AACrE,SAAS,cAAkC,OAAiC,cAAiB,QAAmB;AAErH,eAAa,MAAM;AAEnB,QAAM,KAAK,MAAM,MAAM;AAGvB,QAAM,UAAU,MAAM;AACpB,yBAAqB,OAAO,EAAE;AAAA,EAChC,GAAG,CAAC,GAAG,cAAc,EAAE,CAAC;AAExB,QAAM,YAAY,YAAY,CAAC,OAAmB;AAChD,UAAM,EAAE,YAAY,IAAI,MAAM,cAAc,cAAc,MAAM;AAC9D,2BAAqB,OAAO,EAAE;AAC9B,SAAG;AAAA,IACL,CAAC;AACD,WAAO;AAAA,EACT,GAAG,CAAC,OAAO,GAAG,YAAY,CAAC;AAC3B,QAAM,cAAc,YAAY,MAAM;AAGpC,QAAI,CAAC,qBAAqB,IAAI,EAAE,GAAG;AACjC,2BAAqB,IAAI,IAAI,MAAM,UAAU,cAAc,YAAY,CAAC;AAAA,IAC1E;AACA,WAAO,qBAAqB,IAAI,EAAE;AAAA,EACpC,GAAG,CAAC,OAAO,GAAG,YAAY,CAAC;AAI3B,QAAM,UAAU,MAAM;AAAA,IACpB;AAAA,IACA;AAAA,IACA,MAAM,SAAS,IAAI,MAAM,8FAA8F,CAAC;AAAA,EAC1H;AAEA,QAAM,SAAS,MAAM,IAAI,OAAO;AAChC,MAAI,OAAO,WAAW,SAAS;AAC7B,UAAM,QAAQ,OAAO;AACrB,QAAI,iBAAiB,SAAS,CAAE,MAAc,mCAAmC;AAC/E,wBAAkB,OAAO,IAAI,MAAM,CAAC;AACpC,MAAC,MAAc,oCAAoC;AAAA,IACrD;AACA,UAAM;AAAA,EACR;AACA,SAAO,OAAO;AAChB;","names":[]}
1
+ {"version":3,"sources":["../../../../../../src/lib/stack-app/apps/implementations/common.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { AsyncCache } from \"@stackframe/stack-shared/dist/utils/caches\";\nimport { isBrowserLike } from \"@stackframe/stack-shared/dist/utils/env\";\nimport { StackAssertionError, concatStacktraces, throwErr } from \"@stackframe/stack-shared/dist/utils/errors\";\nimport { getGlobal } from \"@stackframe/stack-shared/dist/utils/globals\";\nimport { filterUndefined, omit } from \"@stackframe/stack-shared/dist/utils/objects\";\nimport { ReactPromise } from \"@stackframe/stack-shared/dist/utils/promises\";\nimport { suspendIfSsr } from \"@stackframe/stack-shared/dist/utils/react\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { Store } from \"@stackframe/stack-shared/dist/utils/stores\";\nimport React, { useCallback } from \"react\"; // THIS_LINE_PLATFORM react-like\nimport { HandlerUrls, stackAppInternalsSymbol } from \"../../common\";\n\n// hack to make sure process is defined in non-node environments\n\nexport const clientVersion = \"js @stackframe/stack@2.8.44\";\nif (clientVersion.startsWith(\"STACK_COMPILE_TIME\")) {\n throw new StackAssertionError(\"Client version was not replaced. Something went wrong during build!\");\n}\n\n\nexport const createCache = <D extends any[], T>(fetcher: (dependencies: D) => Promise<T>) => {\n return new AsyncCache<D, Result<T>>(\n async (dependencies) => await Result.fromThrowingAsync(async () => await fetcher(dependencies)),\n {},\n );\n};\n\nexport const createCacheBySession = <D extends any[], T>(fetcher: (session: InternalSession, extraDependencies: D) => Promise<T> ) => {\n return new AsyncCache<[InternalSession, ...D], Result<T>>(\n async ([session, ...extraDependencies]) => await Result.fromThrowingAsync(async () => await fetcher(session, extraDependencies)),\n {\n onSubscribe: ([session], refresh) => {\n const handler = session.onInvalidate(() => refresh());\n return () => handler.unsubscribe();\n },\n },\n );\n};\n\n\ntype AppLike = { [stackAppInternalsSymbol]: { getConstructorOptions: () => any } };\nexport function resolveConstructorOptions<T extends { inheritsFrom?: AppLike }>(options: T): T & { inheritsFrom?: undefined } {\n return {\n ...options.inheritsFrom?.[stackAppInternalsSymbol].getConstructorOptions() ?? {},\n ...filterUndefined(omit(options, [\"inheritsFrom\"])),\n };\n}\n\nexport function getUrls(partial: Partial<HandlerUrls>): HandlerUrls {\n const handler = partial.handler ?? \"/handler\";\n const home = partial.home ?? \"/\";\n const afterSignIn = partial.afterSignIn ?? home;\n return {\n handler,\n signIn: `${handler}/sign-in`,\n afterSignIn: home,\n signUp: `${handler}/sign-up`,\n afterSignUp: afterSignIn,\n signOut: `${handler}/sign-out`,\n afterSignOut: home,\n emailVerification: `${handler}/email-verification`,\n passwordReset: `${handler}/password-reset`,\n forgotPassword: `${handler}/forgot-password`,\n oauthCallback: `${handler}/oauth-callback`,\n magicLinkCallback: `${handler}/magic-link-callback`,\n home: home,\n accountSettings: `${handler}/account-settings`,\n error: `${handler}/error`,\n teamInvitation: `${handler}/team-invitation`,\n mfa: `${handler}/mfa`,\n ...filterUndefined(partial),\n };\n}\n\nexport function getDefaultProjectId() {\n return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || process.env.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.\"));\n}\n\nexport function getDefaultPublishableClientKey() {\n return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || process.env.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.\"));\n}\n\nexport function getDefaultSecretServerKey() {\n 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 it in the STACK_SECRET_SERVER_KEY environment variable.\"));\n}\n\nexport function getDefaultSuperSecretAdminKey() {\n 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.\"));\n}\n\nexport function getDefaultExtraRequestHeaders() {\n return JSON.parse(process.env.NEXT_PUBLIC_STACK_EXTRA_REQUEST_HEADERS || process.env.STACK_EXTRA_REQUEST_HEADERS || '{}');\n}\n\n/**\n * Returns the base URL for the Stack API.\n *\n * The URL can be specified in several ways, in order of precedence:\n * 1. Directly through userSpecifiedBaseUrl parameter as string or browser/server object\n * 2. Through environment variables:\n * - Browser: NEXT_PUBLIC_BROWSER_STACK_API_URL\n * - Server: NEXT_PUBLIC_SERVER_STACK_API_URL\n * - Fallback: NEXT_PUBLIC_STACK_API_URL or NEXT_PUBLIC_STACK_URL\n * 3. Default base URL if none of the above are specified\n *\n * The function also ensures the URL doesn't end with a trailing slash\n * by removing it if present.\n *\n * @param userSpecifiedBaseUrl - Optional URL override as string or {browser, server} object\n * @returns The configured base URL without trailing slash\n\n */\nexport function getBaseUrl(userSpecifiedBaseUrl: string | { browser: string, server: string } | undefined) {\n let url;\n if (userSpecifiedBaseUrl) {\n if (typeof userSpecifiedBaseUrl === \"string\") {\n url = userSpecifiedBaseUrl;\n } else {\n if (isBrowserLike()) {\n url = userSpecifiedBaseUrl.browser;\n } else {\n url = userSpecifiedBaseUrl.server;\n }\n }\n } else {\n // note: NEXT_PUBLIC_BROWSER_STACK_API_URL was renamed to NEXT_PUBLIC_STACK_API_URL_BROWSER, and NEXT_PUBLIC_STACK_URL to NEXT_PUBLIC_STACK_API_URL\n if (isBrowserLike()) {\n url = process.env.NEXT_PUBLIC_BROWSER_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_API_URL_BROWSER || process.env.STACK_API_URL_BROWSER;\n } else {\n url = process.env.NEXT_PUBLIC_SERVER_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_API_URL_SERVER || process.env.STACK_API_URL_SERVER;\n }\n url = url || process.env.NEXT_PUBLIC_STACK_API_URL || process.env.STACK_API_URL || process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;\n }\n\n return url.endsWith('/') ? url.slice(0, -1) : url;\n}\nexport const defaultBaseUrl = \"https://api.stack-auth.com\";\n\nexport type TokenObject = {\n accessToken: string | null,\n refreshToken: string | null,\n};\n\nexport function createEmptyTokenStore() {\n return new Store<TokenObject>({\n refreshToken: null,\n accessToken: null,\n });\n}\n\n\nconst cachePromiseByHookId = new Map<string, ReactPromise<Result<unknown>>>();\nexport function useAsyncCache<D extends any[], T>(cache: AsyncCache<D, Result<T>>, dependencies: D, caller: string): T {\n // we explicitly don't want to run this hook in SSR\n suspendIfSsr(caller);\n\n // on the dashboard, we do some perf monitoring for pre-fetching which should hook right in here\n const asyncCacheHooks: any[] = getGlobal(\"use-async-cache-execution-hooks\") ?? [];\n for (const hook of asyncCacheHooks) {\n hook({ cache, caller, dependencies });\n }\n\n const id = React.useId();\n\n // whenever the dependencies change, we need to refresh the promise cache\n React.useEffect(() => {\n cachePromiseByHookId.delete(id);\n }, [...dependencies, id]);\n\n const subscribe = useCallback((cb: () => void) => {\n const { unsubscribe } = cache.onStateChange(dependencies, () => {\n cachePromiseByHookId.delete(id);\n cb();\n });\n return unsubscribe;\n }, [cache, ...dependencies]);\n const getSnapshot = useCallback(() => {\n // React checks whether a promise passed to `use` is still the same as the previous one by comparing the reference.\n // If we didn't cache here, this wouldn't work because the promise would be recreated every time the value changes.\n if (!cachePromiseByHookId.has(id)) {\n cachePromiseByHookId.set(id, cache.getOrWait(dependencies, \"read-write\"));\n }\n return cachePromiseByHookId.get(id) as ReactPromise<Result<T>>;\n }, [cache, ...dependencies]);\n\n // note: we must use React.useSyncExternalStore instead of importing the function directly, as it will otherwise\n // throw an error on Next.js (\"can't import useSyncExternalStore from the server\")\n const promise = React.useSyncExternalStore(\n subscribe,\n getSnapshot,\n () => throwErr(new Error(\"getServerSnapshot should never be called in useAsyncCache because we restrict to CSR earlier\"))\n );\n\n const result = React.use(promise);\n if (result.status === \"error\") {\n const error = result.error;\n if (error instanceof Error && !(error as any).__stackHasConcatenatedStacktraces) {\n concatStacktraces(error, new Error());\n (error as any).__stackHasConcatenatedStacktraces = true;\n }\n throw error;\n }\n return result.data;\n}\n"],"mappings":";AAKA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB,mBAAmB,gBAAgB;AACjE,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB,YAAY;AAEtC,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,OAAO,SAAS,mBAAmB;AACnC,SAAsB,+BAA+B;AAI9C,IAAM,gBAAgB;AAC7B,IAAI,cAAc,WAAW,oBAAoB,GAAG;AAClD,QAAM,IAAI,oBAAoB,qEAAqE;AACrG;AAGO,IAAM,cAAc,CAAqB,YAA6C;AAC3F,SAAO,IAAI;AAAA,IACT,OAAO,iBAAiB,MAAM,OAAO,kBAAkB,YAAY,MAAM,QAAQ,YAAY,CAAC;AAAA,IAC9F,CAAC;AAAA,EACH;AACF;AAEO,IAAM,uBAAuB,CAAqB,YAA6E;AACpI,SAAO,IAAI;AAAA,IACT,OAAO,CAAC,SAAY,oBAAiB,MAAM,MAAM,OAAO,kBAAkB,YAAY,MAAM,QAAQ,SAAS,iBAAiB,CAAC;AAAA,IAC/H;AAAA,MACE,aAAa,CAAC,CAAC,OAAO,GAAG,YAAY;AACnC,cAAM,UAAU,QAAQ,aAAa,MAAM,QAAQ,CAAC;AACpD,eAAO,MAAM,QAAQ,YAAY;AAAA,MACnC;AAAA,IACF;AAAA,EACF;AACF;AAIO,SAAS,0BAAgE,SAA8C;AAC5H,SAAO;AAAA,IACL,GAAG,QAAQ,eAAe,uBAAuB,EAAE,sBAAsB,KAAK,CAAC;AAAA,IAC/E,GAAG,gBAAgB,KAAK,SAAS,CAAC,cAAc,CAAC,CAAC;AAAA,EACpD;AACF;AAEO,SAAS,QAAQ,SAA4C;AAClE,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,OAAO,QAAQ,QAAQ;AAC7B,QAAM,cAAc,QA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AC;AAAA,IAC1E;AACA,WAAO,qBAAqB,IAAI,EAAE;AAAA,EACpC,GAAG,CAAC,OAAO,GAAG,YAAY,CAAC;AAI3B,QAAM,UAAU,MAAM;AAAA,IACpB;AAAA,IACA;AAAA,IACA,MAAM,SAAS,IAAI,MAAM,8FAA8F,CAAC;AAAA,EAC1H;AAEA,QAAM,SAAS,MAAM,IAAI,OAAO;AAChC,MAAI,OAAO,WAAW,SAAS;AAC7B,UAAM,QAAQ,OAAO;AACrB,QAAI,iBAAiB,SAAS,CAAE,MAAc,mCAAmC;AAC/E,wBAAkB,OAAO,IAAI,MAAM,CAAC;AACpC,MAAC,MAAc,oCAAoC;AAAA,IACrD;AACA,UAAM;AAAA,EACR;AACA,SAAO,OAAO;AAChB;","names":[]}
@@ -9,34 +9,23 @@ import { constructRedirectUrl } from "../../../../utils/url.js";
9
9
  import { apiKeyCreationOptionsToCrud, apiKeyUpdateOptionsToCrud } from "../../api-keys/index.js";
10
10
  import { serverContactChannelCreateOptionsToCrud, serverContactChannelUpdateOptionsToCrud } from "../../contact-channels/index.js";
11
11
  import { serverTeamCreateOptionsToCrud, serverTeamUpdateOptionsToCrud } from "../../teams/index.js";
12
- import { serverUserCreateOptionsToCrud, serverUserUpdateOptionsToCrud } from "../../users/index.js";
12
+ import { attachUserDestructureGuard, serverUserCreateOptionsToCrud, serverUserUpdateOptionsToCrud } from "../../users/index.js";
13
13
  import { _StackClientAppImplIncomplete } from "./client-app-impl.js";
14
- import { clientVersion, createCache, createCacheBySession, getBaseUrl, getDefaultExtraRequestHeaders, getDefaultProjectId, getDefaultPublishableClientKey, getDefaultSecretServerKey } from "./common.js";
14
+ import { clientVersion, createCache, createCacheBySession, getBaseUrl, getDefaultExtraRequestHeaders, getDefaultProjectId, getDefaultPublishableClientKey, getDefaultSecretServerKey, resolveConstructorOptions } from "./common.js";
15
15
  import { useAsyncCache } from "./common.js";
16
16
  var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete {
17
- constructor(options) {
18
- super("interface" in options ? {
19
- interface: options.interface,
20
- tokenStore: options.tokenStore,
21
- urls: options.urls,
22
- oauthScopesOnSignIn: options.oauthScopesOnSignIn
23
- } : {
24
- interface: new StackServerInterface({
25
- getBaseUrl: () => getBaseUrl(options.baseUrl),
26
- projectId: options.projectId ?? getDefaultProjectId(),
27
- extraRequestHeaders: options.extraRequestHeaders ?? getDefaultExtraRequestHeaders(),
17
+ constructor(options, extraOptions) {
18
+ const resolvedOptions = resolveConstructorOptions(options);
19
+ super(resolvedOptions, {
20
+ ...extraOptions,
21
+ interface: extraOptions?.interface ?? new StackServerInterface({
22
+ getBaseUrl: () => getBaseUrl(resolvedOptions.baseUrl),
23
+ projectId: resolvedOptions.projectId ?? getDefaultProjectId(),
24
+ extraRequestHeaders: resolvedOptions.extraRequestHeaders ?? getDefaultExtraRequestHeaders(),
28
25
  clientVersion,
29
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
30
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey()
31
- }),
32
- baseUrl: options.baseUrl,
33
- extraRequestHeaders: options.extraRequestHeaders,
34
- projectId: options.projectId,
35
- publishableClientKey: options.publishableClientKey,
36
- tokenStore: options.tokenStore,
37
- urls: options.urls,
38
- oauthScopesOnSignIn: options.oauthScopesOnSignIn,
39
- redirectMethod: options.redirectMethod
26
+ publishableClientKey: resolvedOptions.publishableClientKey ?? getDefaultPublishableClientKey(),
27
+ secretServerKey: resolvedOptions.secretServerKey ?? getDefaultSecretServerKey()
28
+ })
40
29
  });
41
30
  // TODO override the client user cache to use the server user cache, so we save some requests
42
31
  this._currentServerUserCache = createCacheBySession(async (session) => {
@@ -166,6 +155,70 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
166
155
  return await this._interface.getItem({ customCustomerId, itemId }, null);
167
156
  }
168
157
  );
158
+ this._serverUserProductsCache = createCache(
159
+ async ([userId, cursor, limit]) => {
160
+ return await this._interface.listProducts({
161
+ customer_type: "user",
162
+ customer_id: userId,
163
+ cursor: cursor ?? void 0,
164
+ limit: limit ?? void 0
165
+ }, null);
166
+ }
167
+ );
168
+ this._serverTeamProductsCache = createCache(
169
+ async ([teamId, cursor, limit]) => {
170
+ return await this._interface.listProducts({
171
+ customer_type: "team",
172
+ customer_id: teamId,
173
+ cursor: cursor ?? void 0,
174
+ limit: limit ?? void 0
175
+ }, null);
176
+ }
177
+ );
178
+ this._serverCustomProductsCache = createCache(
179
+ async ([customCustomerId, cursor, limit]) => {
180
+ return await this._interface.listProducts({
181
+ customer_type: "custom",
182
+ customer_id: customCustomerId,
183
+ cursor: cursor ?? void 0,
184
+ limit: limit ?? void 0
185
+ }, null);
186
+ }
187
+ );
188
+ }
189
+ _createServerCustomer(userIdOrTeamId, type) {
190
+ const app = this;
191
+ const productsCache = type === "user" ? app._serverUserProductsCache : app._serverTeamProductsCache;
192
+ const customerOptions = type === "user" ? { userId: userIdOrTeamId } : { teamId: userIdOrTeamId };
193
+ return {
194
+ ...this._createCustomer(userIdOrTeamId, type, null),
195
+ async getItem(itemId) {
196
+ return await app.getItem({ itemId, ...customerOptions });
197
+ },
198
+ useItem(itemId) {
199
+ return app.useItem({ itemId, ...customerOptions });
200
+ },
201
+ async grantProduct(productOptions) {
202
+ if (type === "user") {
203
+ if ("productId" in productOptions) {
204
+ await app.grantProduct({ userId: userIdOrTeamId, productId: productOptions.productId, quantity: productOptions.quantity });
205
+ } else {
206
+ await app.grantProduct({ userId: userIdOrTeamId, product: productOptions.product, quantity: productOptions.quantity });
207
+ }
208
+ } else {
209
+ if ("productId" in productOptions) {
210
+ await app.grantProduct({ teamId: userIdOrTeamId, productId: productOptions.productId, quantity: productOptions.quantity });
211
+ } else {
212
+ await app.grantProduct({ teamId: userIdOrTeamId, product: productOptions.product, quantity: productOptions.quantity });
213
+ }
214
+ }
215
+ await productsCache.refresh([userIdOrTeamId, null, null]);
216
+ },
217
+ async createCheckoutUrl(options) {
218
+ const productIdOrInline = "productId" in options ? options.productId : options.product;
219
+ return await app._interface.createCheckoutUrl(type, userIdOrTeamId, productIdOrInline, null, options.returnUrl);
220
+ }
221
+ };
169
222
  }
170
223
  async _updateServerUser(userId, update) {
171
224
  const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));
@@ -296,7 +349,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
296
349
  const scopeString = options?.scopes?.join(" ");
297
350
  return useAsyncCache(app._serverUserOAuthConnectionCache, [crud.id, id, scopeString || "", options?.or === "redirect"], "user.useConnectedAccount()");
298
351
  }
299
- return {
352
+ const serverUser = {
300
353
  ...super._createBaseUser(crud),
301
354
  lastActiveAt: new Date(crud.last_active_at_millis),
302
355
  serverMetadata: crud.server_metadata,
@@ -540,28 +593,21 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
540
593
  const providers = await this.listOAuthProviders();
541
594
  return providers.find((p) => p.id === id) ?? null;
542
595
  },
543
- async createCheckoutUrl(options) {
544
- const offerIdOrInline = "offerId" in options ? options.offerId : options.offer;
545
- return await app._interface.createCheckoutUrl("user", crud.id, offerIdOrInline, null);
546
- },
547
- async getItem(itemId) {
548
- const result = Result.orThrow(await app._serverUserItemsCache.getOrWait([crud.id, itemId], "write-only"));
549
- return app._serverItemFromCrud({ type: "user", id: crud.id }, result);
550
- },
551
- useItem(itemId) {
552
- const result = useAsyncCache(app._serverUserItemsCache, [crud.id, itemId], "user.useItem()");
553
- return useMemo(() => app._serverItemFromCrud({ type: "user", id: crud.id }, result), [result]);
554
- }
596
+ ...app._createServerCustomer(crud.id, "user")
555
597
  };
598
+ attachUserDestructureGuard(serverUser);
599
+ return serverUser;
556
600
  }
557
601
  _serverTeamUserFromCrud(crud) {
558
- return {
602
+ const teamUser = {
559
603
  ...this._serverUserFromCrud(crud.user),
560
604
  teamProfile: {
561
605
  displayName: crud.display_name,
562
606
  profileImageUrl: crud.profile_image_url
563
607
  }
564
608
  };
609
+ attachUserDestructureGuard(teamUser);
610
+ return teamUser;
565
611
  }
566
612
  _serverTeamInvitationFromCrud(crud) {
567
613
  return {
@@ -570,16 +616,17 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
570
616
  expiresAt: new Date(crud.expires_at_millis),
571
617
  revoke: async () => {
572
618
  await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);
619
+ await this._serverTeamInvitationsCache.refresh([crud.team_id]);
573
620
  }
574
621
  };
575
622
  }
576
623
  _currentUserFromCrud(crud, session) {
577
- const app = this;
578
624
  const currentUser = {
579
625
  ...this._serverUserFromCrud(crud),
580
626
  ...this._createAuth(session),
581
627
  ...this._isInternalProject() ? this._createInternalUserExtra(session) : {}
582
628
  };
629
+ attachUserDestructureGuard(currentUser);
583
630
  Object.freeze(currentUser);
584
631
  return currentUser;
585
632
  }
@@ -656,18 +703,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
656
703
  await app._serverTeamApiKeysCache.refresh([crud.id]);
657
704
  return app._serverApiKeyFromCrud(result);
658
705
  },
659
- async getItem(itemId) {
660
- const result = Result.orThrow(await app._serverTeamItemsCache.getOrWait([crud.id, itemId], "write-only"));
661
- return app._serverItemFromCrud({ type: "team", id: crud.id }, result);
662
- },
663
- useItem(itemId) {
664
- const result = useAsyncCache(app._serverTeamItemsCache, [crud.id, itemId], "team.useItem()");
665
- return useMemo(() => app._serverItemFromCrud({ type: "team", id: crud.id }, result), [result]);
666
- },
667
- async createCheckoutUrl(options) {
668
- const offerIdOrInline = "offerId" in options ? options.offerId : options.offer;
669
- return await app._interface.createCheckoutUrl("team", crud.id, offerIdOrInline, null);
670
- }
706
+ ...app._createServerCustomer(crud.id, "team")
671
707
  };
672
708
  }
673
709
  _serverItemFromCrud(customer, crud) {
@@ -716,11 +752,11 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
716
752
  return crud ? this._serverApiKeyFromCrud(crud) : null;
717
753
  }
718
754
  _useUserApiKey(options) {
719
- const crud = useAsyncCache(this._serverCheckApiKeyCache, ["user", options.apiKey], "useUserApiKey()");
755
+ const crud = useAsyncCache(this._serverCheckApiKeyCache, ["user", options.apiKey], "serverApp.useUserApiKey()");
720
756
  return useMemo(() => crud ? this._serverApiKeyFromCrud(crud) : null, [crud]);
721
757
  }
722
758
  _useTeamApiKey(options) {
723
- const crud = useAsyncCache(this._serverCheckApiKeyCache, ["team", options.apiKey], "useTeamApiKey()");
759
+ const crud = useAsyncCache(this._serverCheckApiKeyCache, ["team", options.apiKey], "serverApp.useTeamApiKey()");
724
760
  return useMemo(() => crud ? this._serverApiKeyFromCrud(crud) : null, [crud]);
725
761
  }
726
762
  async _getUserByApiKey(apiKey) {
@@ -742,7 +778,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
742
778
  return user;
743
779
  }
744
780
  _useUserByConvex(ctx, includeAnonymous) {
745
- const subject = useAsyncCache(this._convexIdentitySubjectCache, [ctx], "useUserByConvex()");
781
+ const subject = useAsyncCache(this._convexIdentitySubjectCache, [ctx], "serverApp.useUserByConvex()");
746
782
  if (subject === null) {
747
783
  return null;
748
784
  }
@@ -835,7 +871,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
835
871
  options = options;
836
872
  this._ensurePersistentTokenStore(options?.tokenStore);
837
873
  const session = this._useSession(options?.tokenStore);
838
- let crud = useAsyncCache(this._currentServerUserCache, [session], "useUser()");
874
+ let crud = useAsyncCache(this._currentServerUserCache, [session], "serverApp.useUser()");
839
875
  if (crud?.is_anonymous && options?.or !== "anonymous" && options?.or !== "anonymous-if-exists[deprecated]") {
840
876
  crud = null;
841
877
  }
@@ -871,7 +907,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
871
907
  }
872
908
  }
873
909
  useUserById(userId) {
874
- const crud = useAsyncCache(this._serverUserCache, [userId], "useUserById()");
910
+ const crud = useAsyncCache(this._serverUserCache, [userId], "serverApp.useUserById()");
875
911
  return useMemo(() => {
876
912
  return crud && this._serverUserFromCrud(crud);
877
913
  }, [crud]);
@@ -883,7 +919,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
883
919
  return result;
884
920
  }
885
921
  useUsers(options) {
886
- const crud = useAsyncCache(this._serverUsersCache, [options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "useServerUsers()");
922
+ const crud = useAsyncCache(this._serverUsersCache, [options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "serverApp.useUsers()");
887
923
  const result = crud.items.map((j) => this._serverUserFromCrud(j));
888
924
  result.nextCursor = crud.pagination?.next_cursor ?? null;
889
925
  return result;
@@ -941,17 +977,40 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
941
977
  cache = this._serverCustomItemsCache;
942
978
  }
943
979
  const cacheKey = [id, options.itemId];
944
- const debugLabel = `app.useItem(${type})`;
980
+ const debugLabel = "serverApp.useItem()";
945
981
  const result = useAsyncCache(cache, cacheKey, debugLabel);
946
982
  return useMemo(() => this._serverItemFromCrud({ type, id }, result), [result]);
947
983
  }
984
+ async grantProduct(options) {
985
+ let customerType;
986
+ let customerId;
987
+ if ("userId" in options) {
988
+ customerType = "user";
989
+ customerId = options.userId;
990
+ } else if ("teamId" in options) {
991
+ customerType = "team";
992
+ customerId = options.teamId;
993
+ } else {
994
+ customerType = "custom";
995
+ customerId = options.customCustomerId;
996
+ }
997
+ await this._interface.grantProduct({
998
+ customerType,
999
+ customerId,
1000
+ productId: "productId" in options ? options.productId : void 0,
1001
+ product: "product" in options ? options.product : void 0,
1002
+ quantity: options.quantity
1003
+ });
1004
+ const cache = customerType === "user" ? this._serverUserProductsCache : customerType === "team" ? this._serverTeamProductsCache : this._serverCustomProductsCache;
1005
+ await cache.refresh([customerId, null, null]);
1006
+ }
948
1007
  async createTeam(data) {
949
1008
  const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));
950
1009
  await this._serverTeamsCache.refresh([void 0]);
951
1010
  return this._serverTeamFromCrud(team);
952
1011
  }
953
1012
  useTeams() {
954
- const teams = useAsyncCache(this._serverTeamsCache, [void 0], "useServerTeams()");
1013
+ const teams = useAsyncCache(this._serverTeamsCache, [void 0], "serverApp.useTeams()");
955
1014
  return useMemo(() => {
956
1015
  return teams.map((t) => this._serverTeamFromCrud(t));
957
1016
  }, [teams]);
@@ -992,7 +1051,7 @@ var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete
992
1051
  },
993
1052
  useValue: (key, options) => {
994
1053
  validateOptions(options);
995
- return useAsyncCache(this._serverDataVaultStoreValueCache, [id, key, options.secret], `app.useDataVaultStoreValue()`);
1054
+ return useAsyncCache(this._serverDataVaultStoreValueCache, [id, key, options.secret], "store.useValue()");
996
1055
  }
997
1056
  };
998
1057
  }