@stackframe/js 2.8.56 → 2.8.59

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 (72) hide show
  1. package/dist/esm/index.js.map +1 -1
  2. package/dist/esm/integrations/convex/component/convex.config.js.map +1 -1
  3. package/dist/esm/integrations/convex.js.map +1 -1
  4. package/dist/esm/lib/auth.js.map +1 -1
  5. package/dist/esm/lib/cookie.js.map +1 -1
  6. package/dist/esm/lib/stack-app/api-keys/index.js.map +1 -1
  7. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js +235 -0
  8. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -1
  9. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js +133 -23
  10. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -1
  11. package/dist/esm/lib/stack-app/apps/implementations/common.js +2 -1
  12. package/dist/esm/lib/stack-app/apps/implementations/common.js.map +1 -1
  13. package/dist/esm/lib/stack-app/apps/implementations/index.js.map +1 -1
  14. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js +31 -23
  15. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -1
  16. package/dist/esm/lib/stack-app/apps/index.js.map +1 -1
  17. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js.map +1 -1
  18. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js.map +1 -1
  19. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js.map +1 -1
  20. package/dist/esm/lib/stack-app/common.js.map +1 -1
  21. package/dist/esm/lib/stack-app/contact-channels/index.js.map +1 -1
  22. package/dist/esm/lib/stack-app/email-templates/index.js.map +1 -1
  23. package/dist/esm/lib/stack-app/index.js.map +1 -1
  24. package/dist/esm/lib/stack-app/internal-api-keys/index.js.map +1 -1
  25. package/dist/esm/lib/stack-app/permissions/index.js.map +1 -1
  26. package/dist/esm/lib/stack-app/projects/index.js +4 -0
  27. package/dist/esm/lib/stack-app/projects/index.js.map +1 -1
  28. package/dist/esm/lib/stack-app/teams/index.js.map +1 -1
  29. package/dist/esm/lib/stack-app/users/index.js +13 -12
  30. package/dist/esm/lib/stack-app/users/index.js.map +1 -1
  31. package/dist/esm/utils/url.js.map +1 -1
  32. package/dist/index.d.mts +285 -17
  33. package/dist/index.d.ts +285 -17
  34. package/dist/index.js.map +1 -1
  35. package/dist/integrations/convex/component/convex.config.js.map +1 -1
  36. package/dist/integrations/convex.js.map +1 -1
  37. package/dist/lib/auth.js.map +1 -1
  38. package/dist/lib/cookie.js.map +1 -1
  39. package/dist/lib/stack-app/api-keys/index.js.map +1 -1
  40. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js +235 -0
  41. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -1
  42. package/dist/lib/stack-app/apps/implementations/client-app-impl.js +132 -22
  43. package/dist/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -1
  44. package/dist/lib/stack-app/apps/implementations/common.js +2 -1
  45. package/dist/lib/stack-app/apps/implementations/common.js.map +1 -1
  46. package/dist/lib/stack-app/apps/implementations/index.js.map +1 -1
  47. package/dist/lib/stack-app/apps/implementations/server-app-impl.js +29 -21
  48. package/dist/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -1
  49. package/dist/lib/stack-app/apps/index.js.map +1 -1
  50. package/dist/lib/stack-app/apps/interfaces/admin-app.js.map +1 -1
  51. package/dist/lib/stack-app/apps/interfaces/client-app.js.map +1 -1
  52. package/dist/lib/stack-app/apps/interfaces/server-app.js.map +1 -1
  53. package/dist/lib/stack-app/common.js.map +1 -1
  54. package/dist/lib/stack-app/connected-accounts/index.js.map +1 -1
  55. package/dist/lib/stack-app/contact-channels/index.js.map +1 -1
  56. package/dist/lib/stack-app/customers/index.js.map +1 -1
  57. package/dist/lib/stack-app/data-vault/index.js.map +1 -1
  58. package/dist/lib/stack-app/email/index.js.map +1 -1
  59. package/dist/lib/stack-app/email-templates/index.js.map +1 -1
  60. package/dist/lib/stack-app/index.js.map +1 -1
  61. package/dist/lib/stack-app/internal-api-keys/index.js.map +1 -1
  62. package/dist/lib/stack-app/notification-categories/index.js.map +1 -1
  63. package/dist/lib/stack-app/permissions/index.js.map +1 -1
  64. package/dist/lib/stack-app/project-configs/index.js.map +1 -1
  65. package/dist/lib/stack-app/projects/index.js +4 -0
  66. package/dist/lib/stack-app/projects/index.js.map +1 -1
  67. package/dist/lib/stack-app/teams/index.js.map +1 -1
  68. package/dist/lib/stack-app/users/index.js +15 -14
  69. package/dist/lib/stack-app/users/index.js.map +1 -1
  70. package/dist/utils/url.js.map +1 -1
  71. package/package.json +14 -13
  72. package/CHANGELOG.md +0 -2072
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nexport * from './lib/stack-app';\n\nexport { getConvexProvidersConfig } from \"./integrations/convex\";\n\n"],"mappings":";AAIA,cAAc;AAEd,SAAS,gCAAgC;","names":[]}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY, INSTEAD EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nexport * from './lib/stack-app';\n\nexport { getConvexProvidersConfig } from \"./integrations/convex\";\n\n"],"mappings":";AAIA,cAAc;AAEd,SAAS,gCAAgC;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/integrations/convex/component/convex.config.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { defineComponent } from \"convex/server\";\n\nconst component = defineComponent(\"stack_auth\");\n\nexport default component;\n"],"mappings":";AAIA,SAAS,uBAAuB;AAEhC,IAAM,YAAY,gBAAgB,YAAY;AAE9C,IAAO,wBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../../../../src/integrations/convex/component/convex.config.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY, INSTEAD EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { defineComponent } from \"convex/server\";\n\nconst component = defineComponent(\"stack_auth\");\n\nexport default component;\n"],"mappings":";AAIA,SAAS,uBAAuB;AAEhC,IAAM,YAAY,gBAAgB,YAAY;AAE9C,IAAO,wBAAQ;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/integrations/convex.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { urlString } from \"@stackframe/stack-shared/dist/utils/urls\";\nimport { defaultBaseUrl } from \"../lib/stack-app/apps/implementations/common\";\n\nexport function getConvexProvidersConfig(options: {\n baseUrl?: string,\n projectId: string,\n}) {\n const baseUrl = options.baseUrl || defaultBaseUrl;\n const projectId = options.projectId;\n return [\n {\n type: \"customJwt\",\n issuer: new URL(urlString`/api/v1/projects/${projectId}`, baseUrl),\n jwks: new URL(urlString`/api/v1/projects/${projectId}/.well-known/jwks.json`, baseUrl),\n algorithm: \"ES256\",\n },\n {\n type: \"customJwt\",\n issuer: new URL(urlString`/api/v1/projects-anonymous-users/${projectId}`, baseUrl),\n jwks: new URL(urlString`/api/v1/projects/${projectId}/.well-known/jwks.json?include_anonymous=true`, baseUrl),\n algorithm: \"ES256\",\n },\n ];\n}\n"],"mappings":";AAIA,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAExB,SAAS,yBAAyB,SAGtC;AACD,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,YAAY,QAAQ;AAC1B,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,QAAQ,IAAI,IAAI,6BAA6B,SAAS,IAAI,OAAO;AAAA,MACjE,MAAM,IAAI,IAAI,6BAA6B,SAAS,0BAA0B,OAAO;AAAA,MACrF,WAAW;AAAA,IACb;AAAA,IACA;AAAA,MACE,MAAM;AAAA,MACN,QAAQ,IAAI,IAAI,6CAA6C,SAAS,IAAI,OAAO;AAAA,MACjF,MAAM,IAAI,IAAI,6BAA6B,SAAS,iDAAiD,OAAO;AAAA,MAC5G,WAAW;AAAA,IACb;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/integrations/convex.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY, INSTEAD EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { urlString } from \"@stackframe/stack-shared/dist/utils/urls\";\nimport { defaultBaseUrl } from \"../lib/stack-app/apps/implementations/common\";\n\nexport function getConvexProvidersConfig(options: {\n baseUrl?: string,\n projectId: string,\n}) {\n const baseUrl = options.baseUrl || defaultBaseUrl;\n const projectId = options.projectId;\n return [\n {\n type: \"customJwt\",\n issuer: new URL(urlString`/api/v1/projects/${projectId}`, baseUrl),\n jwks: new URL(urlString`/api/v1/projects/${projectId}/.well-known/jwks.json`, baseUrl),\n algorithm: \"ES256\",\n },\n {\n type: \"customJwt\",\n issuer: new URL(urlString`/api/v1/projects-anonymous-users/${projectId}`, baseUrl),\n jwks: new URL(urlString`/api/v1/projects/${projectId}/.well-known/jwks.json?include_anonymous=true`, baseUrl),\n algorithm: \"ES256\",\n },\n ];\n}\n"],"mappings":";AAIA,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAExB,SAAS,yBAAyB,SAGtC;AACD,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,YAAY,QAAQ;AAC1B,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,QAAQ,IAAI,IAAI,6BAA6B,SAAS,IAAI,OAAO;AAAA,MACjE,MAAM,IAAI,IAAI,6BAA6B,SAAS,0BAA0B,OAAO;AAAA,MACrF,WAAW;AAAA,IACb;AAAA,IACA;AAAA,MACE,MAAM;AAAA,MACN,QAAQ,IAAI,IAAI,6CAA6C,SAAS,IAAI,OAAO;AAAA,MACjF,MAAM,IAAI,IAAI,6BAA6B,SAAS,iDAAiD,OAAO;AAAA,MAC5G,WAAW;AAAA,IACb;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/auth.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { KnownError, StackClientInterface } from \"@stackframe/stack-shared\";\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { StackAssertionError, throwErr } from \"@stackframe/stack-shared/dist/utils/errors\";\nimport { neverResolve } from \"@stackframe/stack-shared/dist/utils/promises\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { deindent } from \"@stackframe/stack-shared/dist/utils/strings\";\nimport { constructRedirectUrl } from \"../utils/url\";\nimport { consumeVerifierAndStateCookie, saveVerifierAndState } from \"./cookie\";\n\nexport async function signInWithOAuth(\n iface: StackClientInterface,\n options: {\n provider: string,\n redirectUrl: string,\n errorRedirectUrl: string,\n providerScope?: string,\n },\n session: InternalSession,\n) {\n const { codeChallenge, state } = await saveVerifierAndState();\n const location = await iface.getOAuthUrl({\n provider: options.provider,\n redirectUrl: constructRedirectUrl(options.redirectUrl, \"redirectUrl\"),\n errorRedirectUrl: constructRedirectUrl(options.errorRedirectUrl, \"errorRedirectUrl\"),\n codeChallenge,\n state,\n type: \"authenticate\",\n providerScope: options.providerScope,\n session,\n });\n window.location.assign(location);\n await neverResolve();\n}\n\nexport async function addNewOAuthProviderOrScope(\n iface: StackClientInterface,\n options: {\n provider: string,\n redirectUrl: string,\n errorRedirectUrl: string,\n providerScope?: string,\n },\n session: InternalSession,\n) {\n const { codeChallenge, state } = await saveVerifierAndState();\n const location = await iface.getOAuthUrl({\n provider: options.provider,\n redirectUrl: constructRedirectUrl(options.redirectUrl, \"redirectUrl\"),\n errorRedirectUrl: constructRedirectUrl(options.errorRedirectUrl, \"errorRedirectUrl\"),\n afterCallbackRedirectUrl: constructRedirectUrl(window.location.href, \"afterCallbackRedirectUrl\"),\n codeChallenge,\n state,\n type: \"link\",\n session,\n providerScope: options.providerScope,\n });\n window.location.assign(location);\n await neverResolve();\n}\n\n/**\n * Checks if the current URL has the query parameters for an OAuth callback, and if so, removes them.\n *\n * Must be synchronous for the logic in callOAuthCallback to work without race conditions.\n */\nfunction consumeOAuthCallbackQueryParams() {\n const requiredParams = [\"code\", \"state\"];\n const originalUrl = new URL(window.location.href);\n for (const param of requiredParams) {\n if (!originalUrl.searchParams.has(param)) {\n console.warn(new Error(`Missing required query parameter on OAuth callback: ${param}. Maybe you opened or reloaded the oauth-callback page from your history?`));\n return null;\n }\n }\n\n const expectedState = originalUrl.searchParams.get(\"state\") ?? throwErr(\"This should never happen; isn't state required above?\");\n const cookieResult = consumeVerifierAndStateCookie(expectedState);\n\n if (!cookieResult) {\n // If the state can't be found in the cookies, then the callback wasn't meant for us.\n // Maybe the website uses another OAuth library?\n console.warn(deindent`\n Stack found an outer OAuth callback state in the query parameters, but not in cookies.\n \n This could have multiple reasons:\n - The cookie expired, because the OAuth flow took too long.\n - The user's browser deleted the cookie, either manually or because of a very strict cookie policy.\n - The cookie was already consumed by this page, and the user already logged in.\n - You are using another OAuth client library with the same callback URL as Stack.\n - The user opened the OAuth callback page from their history.\n\n Either way, it is probably safe to ignore this warning unless you are debugging an OAuth issue.\n `);\n return null;\n }\n\n\n const newUrl = new URL(originalUrl);\n for (const param of requiredParams) {\n newUrl.searchParams.delete(param);\n }\n\n // let's get rid of the authorization code in the history as we\n // don't redirect to `redirectUrl` if there's a validation error\n // (as the redirectUrl might be malicious!).\n //\n // We use history.replaceState instead of location.assign(...) to\n // prevent an unnecessary reload\n window.history.replaceState({}, \"\", newUrl.toString());\n\n return {\n originalUrl,\n codeVerifier: cookieResult.codeVerifier,\n state: expectedState,\n };\n}\n\nexport async function callOAuthCallback(\n iface: StackClientInterface,\n redirectUrl: string,\n) {\n // note: this part of the function (until the return) needs\n // to be synchronous, to prevent race conditions when\n // callOAuthCallback is called multiple times in parallel\n const consumed = consumeOAuthCallbackQueryParams();\n if (!consumed) return Result.ok(undefined);\n\n // the rest can be asynchronous (we now know that we are the\n // intended recipient of the callback, and the only instance\n // of callOAuthCallback that's running)\n try {\n return Result.ok(await iface.callOAuthCallback({\n oauthParams: consumed.originalUrl.searchParams,\n redirectUri: constructRedirectUrl(redirectUrl, \"redirectUri\"),\n codeVerifier: consumed.codeVerifier,\n state: consumed.state,\n }));\n } catch (e) {\n if (KnownError.isKnownError(e)) {\n throw e;\n }\n throw new StackAssertionError(\"Error signing in during OAuth callback. Please try again.\", { cause: e });\n }\n}\n"],"mappings":";AAIA,SAAS,kBAAwC;AAEjD,SAAS,qBAAqB,gBAAgB;AAC9C,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,+BAA+B,4BAA4B;AAEpE,eAAsB,gBACpB,OACA,SAMA,SACA;AACA,QAAM,EAAE,eAAe,MAAM,IAAI,MAAM,qBAAqB;AAC5D,QAAM,WAAW,MAAM,MAAM,YAAY;AAAA,IACvC,UAAU,QAAQ;AAAA,IAClB,aAAa,qBAAqB,QAAQ,aAAa,aAAa;AAAA,IACpE,kBAAkB,qBAAqB,QAAQ,kBAAkB,kBAAkB;AAAA,IACnF;AAAA,IACA;AAAA,IACA,MAAM;AAAA,IACN,eAAe,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AACD,SAAO,SAAS,OAAO,QAAQ;AAC/B,QAAM,aAAa;AACrB;AAEA,eAAsB,2BACpB,OACA,SAMA,SACA;AACA,QAAM,EAAE,eAAe,MAAM,IAAI,MAAM,qBAAqB;AAC5D,QAAM,WAAW,MAAM,MAAM,YAAY;AAAA,IACv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AM,kBAAkB;AAAA,MAC7C,aAAa,SAAS,YAAY;AAAA,MAClC,aAAa,qBAAqB,aAAa,aAAa;AAAA,MAC5D,cAAc,SAAS;AAAA,MACvB,OAAO,SAAS;AAAA,IAClB,CAAC,CAAC;AAAA,EACJ,SAAS,GAAG;AACV,QAAI,WAAW,aAAa,CAAC,GAAG;AAC9B,YAAM;AAAA,IACR;AACA,UAAM,IAAI,oBAAoB,6DAA6D,EAAE,OAAO,EAAE,CAAC;AAAA,EACzG;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/auth.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY, INSTEAD EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { KnownError, StackClientInterface } from \"@stackframe/stack-shared\";\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { StackAssertionError, throwErr } from \"@stackframe/stack-shared/dist/utils/errors\";\nimport { neverResolve } from \"@stackframe/stack-shared/dist/utils/promises\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { deindent } from \"@stackframe/stack-shared/dist/utils/strings\";\nimport { constructRedirectUrl } from \"../utils/url\";\nimport { consumeVerifierAndStateCookie, saveVerifierAndState } from \"./cookie\";\n\nexport async function signInWithOAuth(\n iface: StackClientInterface,\n options: {\n provider: string,\n redirectUrl: string,\n errorRedirectUrl: string,\n providerScope?: string,\n },\n session: InternalSession,\n) {\n const { codeChallenge, state } = await saveVerifierAndState();\n const location = await iface.getOAuthUrl({\n provider: options.provider,\n redirectUrl: constructRedirectUrl(options.redirectUrl, \"redirectUrl\"),\n errorRedirectUrl: constructRedirectUrl(options.errorRedirectUrl, \"errorRedirectUrl\"),\n codeChallenge,\n state,\n type: \"authenticate\",\n providerScope: options.providerScope,\n session,\n });\n window.location.assign(location);\n await neverResolve();\n}\n\nexport async function addNewOAuthProviderOrScope(\n iface: StackClientInterface,\n options: {\n provider: string,\n redirectUrl: string,\n errorRedirectUrl: string,\n providerScope?: string,\n },\n session: InternalSession,\n) {\n const { codeChallenge, state } = await saveVerifierAndState();\n const location = await iface.getOAuthUrl({\n provider: options.provider,\n redirectUrl: constructRedirectUrl(options.redirectUrl, \"redirectUrl\"),\n errorRedirectUrl: constructRedirectUrl(options.errorRedirectUrl, \"errorRedirectUrl\"),\n afterCallbackRedirectUrl: constructRedirectUrl(window.location.href, \"afterCallbackRedirectUrl\"),\n codeChallenge,\n state,\n type: \"link\",\n session,\n providerScope: options.providerScope,\n });\n window.location.assign(location);\n await neverResolve();\n}\n\n/**\n * Checks if the current URL has the query parameters for an OAuth callback, and if so, removes them.\n *\n * Must be synchronous for the logic in callOAuthCallback to work without race conditions.\n */\nfunction consumeOAuthCallbackQueryParams() {\n const requiredParams = [\"code\", \"state\"];\n const originalUrl = new URL(window.location.href);\n for (const param of requiredParams) {\n if (!originalUrl.searchParams.has(param)) {\n console.warn(new Error(`Missing required query parameter on OAuth callback: ${param}. Maybe you opened or reloaded the oauth-callback page from your history?`));\n return null;\n }\n }\n\n const expectedState = originalUrl.searchParams.get(\"state\") ?? throwErr(\"This should never happen; isn't state required above?\");\n const cookieResult = consumeVerifierAndStateCookie(expectedState);\n\n if (!cookieResult) {\n // If the state can't be found in the cookies, then the callback wasn't meant for us.\n // Maybe the website uses another OAuth library?\n console.warn(deindent`\n Stack found an outer OAuth callback state in the query parameters, but not in cookies.\n \n This could have multiple reasons:\n - The cookie expired, because the OAuth flow took too long.\n - The user's browser deleted the cookie, either manually or because of a very strict cookie policy.\n - The cookie was already consumed by this page, and the user already logged in.\n - You are using another OAuth client library with the same callback URL as Stack.\n - The user opened the OAuth callback page from their history.\n\n Either way, it is probably safe to ignore this warning unless you are debugging an OAuth issue.\n `);\n return null;\n }\n\n\n const newUrl = new URL(originalUrl);\n for (const param of requiredParams) {\n newUrl.searchParams.delete(param);\n }\n\n // let's get rid of the authorization code in the history as we\n // don't redirect to `redirectUrl` if there's a validation error\n // (as the redirectUrl might be malicious!).\n //\n // We use history.replaceState instead of location.assign(...) to\n // prevent an unnecessary reload\n window.history.replaceState({}, \"\", newUrl.toString());\n\n return {\n originalUrl,\n codeVerifier: cookieResult.codeVerifier,\n state: expectedState,\n };\n}\n\nexport async function callOAuthCallback(\n iface: StackClientInterface,\n redirectUrl: string,\n) {\n // note: this part of the function (until the return) needs\n // to be synchronous, to prevent race conditions when\n // callOAuthCallback is called multiple times in parallel\n const consumed = consumeOAuthCallbackQueryParams();\n if (!consumed) return Result.ok(undefined);\n\n // the rest can be asynchronous (we now know that we are the\n // intended recipient of the callback, and the only instance\n // of callOAuthCallback that's running)\n try {\n return Result.ok(await iface.callOAuthCallback({\n oauthParams: consumed.originalUrl.searchParams,\n redirectUri: constructRedirectUrl(redirectUrl, \"redirectUri\"),\n codeVerifier: consumed.codeVerifier,\n state: consumed.state,\n }));\n } catch (e) {\n if (KnownError.isKnownError(e)) {\n throw e;\n }\n throw new StackAssertionError(\"Error signing in during OAuth callback. Please try again.\", { cause: e });\n }\n}\n"],"mappings":";AAIA,SAAS,kBAAwC;AAEjD,SAAS,qBAAqB,gBAAgB;AAC9C,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,+BAA+B,4BAA4B;AAEpE,eAAsB,gBACpB,OACA,SAMA,SACA;AACA,QAAM,EAAE,eAAe,MAAM,IAAI,MAAM,qBAAqB;AAC5D,QAAM,WAAW,MAAM,MAAM,YAAY;AAAA,IACvC,UAAU,QAAQ;AAAA,IAClB,aAAa,qBAAqB,QAAQ,aAAa,aAAa;AAAA,IACpE,kBAAkB,qBAAqB,QAAQ,kBAAkB,kBAAkB;AAAA,IACnF;AAAA,IACA;AAAA,IACA,MAAM;AAAA,IACN,eAAe,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AACD,SAAO,SAAS,OAAO,QAAQ;AAC/B,QAAM,aAAa;AACrB;AAEA,eAAs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A;AAIA,QAAM,WAAW,gCAAgC;AACjD,MAAI,CAAC,SAAU,QAAO,OAAO,GAAG,MAAS;AAKzC,MAAI;AACF,WAAO,OAAO,GAAG,MAAM,MAAM,kBAAkB;AAAA,MAC7C,aAAa,SAAS,YAAY;AAAA,MAClC,aAAa,qBAAqB,aAAa,aAAa;AAAA,MAC5D,cAAc,SAAS;AAAA,MACvB,OAAO,SAAS;AAAA,IAClB,CAAC,CAAC;AAAA,EACJ,SAAS,GAAG;AACV,QAAI,WAAW,aAAa,CAAC,GAAG;AAC9B,YAAM;AAAA,IACR;AACA,UAAM,IAAI,oBAAoB,6DAA6D,EAAE,OAAO,EAAE,CAAC;AAAA,EACzG;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/cookie.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { isBrowserLike } from '@stackframe/stack-shared/dist/utils/env';\nimport { StackAssertionError } from '@stackframe/stack-shared/dist/utils/errors';\nimport Cookies from \"js-cookie\";\nimport { calculatePKCECodeChallenge, generateRandomCodeVerifier, generateRandomState } from \"oauth4webapi\";\n\n\n// INFO: This file is used to manage cookies. It also sets some cookie flags automatically, see this description.\n//\n// It provides asynchronous setCookie, getCookie, deleteCookie, etc. functions that can be used in various environments\n// (browser + Next.js for now). Under the hood, they just get a CookieHelper object and then set the cookies there.\n//\n// The CookieHelper object is a simple object that lets you set, get and delete cookies synchronously. Acquiring one\n// is asynchronous (except for browser environments, where they can be acquired synchronously), but once you have it,\n// you can use it synchronously. This function is useful if you cannot await in the calling code, but otherwise you\n// should prefer to await the functions directly.\n//\n// Some cookie flags are set automatically by the CookieHelper (and hence also the <xyz>Cookie functions).\n// In particular:\n// - SameSite is set to `Lax` by default, which is already true in Chromium-based browsers, so this creates\n// compatibility with other browsers that use either Strict or None (particularly Safari and Firefox, and older\n// versions of Chrome). If Partitioned is automatically set (as described below), then this value is set to `None`\n// instead.\n// - Secure is set depending on whether we could successfully determine that the client is on HTTPS. For this, we use a\n// set of heuristics:\n// - In a browser environment, we check window.location.protocol which is always accurate\n// - In a Next.js server environment:\n// - First we check the `stack-is-https` cookie, which is set in various places on the\n// client with a Secure attribute. If that one is passed on to the server, we know that the client is on HTTPS\n// and we can set the Secure flag on the cookie. TODO: Should we also do this with a second cookie with a\n// __Host- prefix, so a malicious subdomain of the current domain cannot forcibly enable HTTPS mode and\n// therefore prevent new cookies from being set?\n// - Otherwise, we check the X-Forwarded-Proto header. If that one is `https`, we know that the client is\n// (pretending to be) on HTTPS and we can set the Secure flag on the cookie. Note that this header is\n// spoofable by malicious clients (so is the cookie actually), but since setting this value can only *increase*\n// security (and therefore prevent setting of a cookie), and requires a malicious client, this is still safe.\n// - If neither of the above is true, we don't set the Secure flag on the cookie.\n// - Partitioned is set depending on whether it is needed & supported. Unfortunately, the fact that Partitioned\n// cookies require SameSite=None, browsers that don't support it will still set them as normal third-party cookies,\n// which are fundamentally unsafe. Therefore, we need to take extra care that we only ever set Partitioned cookies\n// if we know for sure that the browser supports it.\n// - In a browser environment, we check:\n// - Whether `Secure` is set. If it's not, we don't set Partitioned.\n// - Whether we can set & retrieve cookies without Partitioned being set. If this is the case, we are likely in a\n// top-level context or a browser that partitions cookies by default (eg. Firefox). In this case, we don't need\n// Partitioned and can just proceed as normal.\n// - Whether CHIPS is supported. To prevent the case where CHIPS is not supported but third-party cookies are (in\n// which we would accidentally set SameSite=None without Partitioned as the latter requires the former), we\n// check this by running a simple test with document.cookie.\n// - Whether the browser supports Partitioned cookies. If yes, set Partitioned. Otherwise, don't set Partitioned.\n// Since there's no easy cross-compat way to do this (CookieStore and document.cookie do not return whether a\n// cookie is partitioned on some/all versions of Safari and Firefox), we use a heuristic; we run this test by\n// creating two cookies with the same name: One with Partitioned and one without. If there are two resulting\n// cookies, that means they were put into different jars, implying that the browser supports Partitioned cookies\n// (but doesn't partition cookies by default). If they result in just one cookie, that could mean that the\n// browser doesn't support Partitioned cookies, or that the browser doesn't put partitioned cookies into\n// different jars by default, in which case we still don't know. This heuristic works on Chrome, but may\n// incorrectly conclude that some other browsers don't support Partitioned. But from a security perspective,\n// that is better than accidentally setting SameSite=None without Partitioned. TODO: Find a better heuristic to\n// to determine whether the browser supports Partitioned cookies or not.\n// - In a Next.js server environment, right now we do nothing because of the complexity involved :( TODO: In the\n// future, we could improve this for example by setting hint cookies from the client, but we need to make sure that\n// no malicious actor (eg. on a malicious subdomain) can forcefully enable Partitioned cookies on a browser that\n// does not support it.\n\n\ntype SetCookieOptions = { maxAge: number | \"session\", noOpIfServerComponent?: boolean, domain?: string, secure?: boolean };\ntype DeleteCookieOptions = { noOpIfServerComponent?: boolean, domain?: string };\n\nfunction ensureClient() {\n if (!isBrowserLike()) {\n throw new Error(\"cookieClient functions can only be called in a browser environment, yet window is undefined\");\n }\n}\n\nexport type CookieHelper = {\n get: (name: string) => string | null,\n getAll: () => Record<string, string>,\n set: (name: string, value: string, options: SetCookieOptions) => void,\n setOrDelete: (name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) => void,\n delete: (name: string, options: DeleteCookieOptions) => void,\n};\n\nconst placeholderCookieHelperIdentity = { \"placeholder cookie helper identity\": true };\nexport async function createPlaceholderCookieHelper(): Promise<CookieHelper> {\n function throwError(): never {\n throw new StackAssertionError(\"Throwing cookie helper is just a placeholder. This should never be called\");\n }\n return {\n get: throwError,\n getAll: throwError,\n set: throwError,\n setOrDelete: throwError,\n delete: throwError,\n };\n}\n\nexport async function createCookieHelper(): Promise<CookieHelper> {\n if (isBrowserLike()) {\n return createBrowserCookieHelper();\n } else {\n return await createPlaceholderCookieHelper();\n }\n}\n\nexport function createBrowserCookieHelper(): CookieHelper {\n return {\n get: getCookieClient,\n getAll: getAllCookiesClient,\n set: setCookieClient,\n setOrDelete: setOrDeleteCookieClient,\n delete: deleteCookieClient,\n };\n}\n\nfunction handleCookieError(e: unknown, options: DeleteCookieOptions | SetCookieOptions) {\n if (e instanceof Error && e.message.includes(\"Cookies can only be modified in\")) {\n if (options.noOpIfServerComponent) {\n // ignore\n } else {\n throw new StackAssertionError(\"Attempted to set cookie in server component. Pass { noOpIfServerComponent: true } in the options of Stack's cookie functions if this is intentional and you want to ignore this error. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options\");\n }\n } else {\n throw e;\n }\n}\n\n\nexport function getCookieClient(name: string): string | null {\n const all = getAllCookiesClient();\n return all[name] ?? null;\n}\n\nexport function getAllCookiesClient(): Record<string, string> {\n ensureClient();\n // set a helper cookie, see comment in `NextCookieHelper.set` above\n Cookies.set(\"stack-is-https\", \"true\", { secure: true, expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365) });\n return Cookies.get();\n}\n\nexport async function getCookie(name: string): Promise<string | null> {\n const cookieHelper = await createCookieHelper();\n return cookieHelper.get(name);\n}\n\nexport async function isSecure(): Promise<boolean> {\n if (isBrowserLike()) {\n return determineSecureFromClientContext();\n }\n return false;\n}\n\nfunction determineSecureFromClientContext(): boolean {\n return typeof window !== \"undefined\" && window.location.protocol === \"https:\";\n}\n\n\nlet _shouldSetPartitionedClientCache: boolean | undefined = undefined;\nfunction shouldSetPartitionedClient() {\n return _shouldSetPartitionedClientCache ??= _internalShouldSetPartitionedClient();\n}\nfunction _internalShouldSetPartitionedClient() {\n ensureClient();\n\n if (!(determineSecureFromClientContext())) {\n return false;\n }\n\n // check whether we can set & retrieve normal cookies (either because we're on a top-level/same-origin context or the browser partitions cookies by default)\n const cookie1Name = \"__Host-stack-temporary-chips-test-\" + Math.random().toString(36).substring(2, 15);\n document.cookie = `${cookie1Name}=value1; Secure; path=/`;\n const cookies1 = document.cookie.split(\"; \");\n document.cookie = `${cookie1Name}=delete1; Secure; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;\n if (cookies1.some((c) => c.startsWith(cookie1Name + \"=\"))) {\n return false;\n }\n\n\n // check whether Partitioned cookies are supported by the browser\n // TODO: See comment at the top. Feels like we should find a better way to do this\n const cookie2Name = \"__Host-stack-temporary-chips-test-\" + Math.random().toString(36).substring(2, 15);\n\n // just to be safe, delete the cookie first to avoid weird RNG-prediction attacks\n // I don't know what they look like (since this is a host cookie) but better safe than sorry\n // (this function should be 100% bulletproof so we don't accidentally fall back to non-partitioned third party cookies on unsupported browsers)\n document.cookie = `${cookie2Name}=delete1; Secure; SameSite=None; Partitioned; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n document.cookie = `${cookie2Name}=delete2; Secure; SameSite=None; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n\n // set the cookie, once partitioned and once not partitioned\n document.cookie = `${cookie2Name}=set1; Secure; SameSite=None; Partitioned; path=/`;\n document.cookie = `${cookie2Name}=set2; Secure; SameSite=None; path=/`;\n\n // check if there are two cookies\n const cookies2 = document.cookie.split(\"; \");\n const numberOfCookiesWithThisName = cookies2.filter((c) => c.startsWith(cookie2Name + \"=\")).length;\n\n // clean up\n document.cookie = `${cookie2Name}=delete3; Secure; SameSite=None; Partitioned; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n document.cookie = `${cookie2Name}=delete4; Secure; SameSite=None; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n\n return numberOfCookiesWithThisName === 2;\n}\n\nfunction setCookieClientInternal(name: string, value: string, options: SetCookieOptions) {\n const secure = options.secure ?? determineSecureFromClientContext();\n const partitioned = shouldSetPartitionedClient();\n Cookies.set(name, value, {\n expires: options.maxAge === \"session\" ? undefined : new Date(Date.now() + (options.maxAge) * 1000),\n domain: options.domain,\n secure,\n sameSite: \"Lax\",\n ...(partitioned ? {\n partitioned,\n sameSite: \"None\",\n } : {}),\n });\n}\n\nfunction deleteCookieClientInternal(name: string, options: DeleteCookieOptions) {\n for (const partitioned of [true, false]) {\n if (options.domain !== undefined) {\n Cookies.remove(name, { domain: options.domain, secure: determineSecureFromClientContext(), partitioned });\n }\n Cookies.remove(name, { secure: determineSecureFromClientContext(), partitioned });\n }\n}\n\nexport function setOrDeleteCookieClient(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) {\n ensureClient();\n if (value === null) {\n deleteCookieClientInternal(name, options);\n } else {\n setCookieClientInternal(name, value, options);\n }\n}\n\nexport async function setOrDeleteCookie(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.setOrDelete(name, value, options);\n}\n\nexport function deleteCookieClient(name: string, options: DeleteCookieOptions) {\n ensureClient();\n deleteCookieClientInternal(name, options);\n}\n\nexport async function deleteCookie(name: string, options: DeleteCookieOptions) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.delete(name, options);\n}\n\nexport function setCookieClient(name: string, value: string, options: SetCookieOptions) {\n ensureClient();\n setCookieClientInternal(name, value, options);\n}\n\nexport async function setCookie(name: string, value: string, options: SetCookieOptions) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.set(name, value, options);\n}\n\nexport async function saveVerifierAndState() {\n const codeVerifier = generateRandomCodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n const state = generateRandomState();\n\n await setCookie(\"stack-oauth-outer-\" + state, codeVerifier, { maxAge: 60 * 60 });\n\n return {\n codeChallenge,\n state,\n };\n}\n\nexport function consumeVerifierAndStateCookie(state: string) {\n ensureClient();\n const cookieName = \"stack-oauth-outer-\" + state;\n const codeVerifier = getCookieClient(cookieName);\n if (!codeVerifier) {\n return null;\n }\n deleteCookieClient(cookieName, {});\n return {\n codeVerifier,\n };\n}\n"],"mappings":";AAIA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,OAAO,aAAa;AACpB,SAAS,4BAA4B,4BAA4B,2BAA2B;AAiE5F,SAAS,eAAe;AACtB,MAAI,CAAC,cAAc,GAAG;AACpB,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACF;AAWA,eAAsB,gCAAuD;AAC3E,WAAS,aAAoB;AAC3B,UAAM,IAAI,oBAAoB,2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AC;AAAA,EAClF;AACF;AAEO,SAAS,wBAAwB,MAAc,OAAsB,SAAiD;AAC3H,eAAa;AACb,MAAI,UAAU,MAAM;AAClB,+BAA2B,MAAM,OAAO;AAAA,EAC1C,OAAO;AACL,4BAAwB,MAAM,OAAO,OAAO;AAAA,EAC9C;AACF;AAEA,eAAsB,kBAAkB,MAAc,OAAsB,SAAiD;AAC3H,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,YAAY,MAAM,OAAO,OAAO;AAC/C;AAEO,SAAS,mBAAmB,MAAc,SAA8B;AAC7E,eAAa;AACb,6BAA2B,MAAM,OAAO;AAC1C;AAEA,eAAsB,aAAa,MAAc,SAA8B;AAC7E,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,OAAO,MAAM,OAAO;AACnC;AAEO,SAAS,gBAAgB,MAAc,OAAe,SAA2B;AACtF,eAAa;AACb,0BAAwB,MAAM,OAAO,OAAO;AAC9C;AAEA,eAAsB,UAAU,MAAc,OAAe,SAA2B;AACtF,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,IAAI,MAAM,OAAO,OAAO;AACvC;AAEA,eAAsB,uBAAuB;AAC3C,QAAM,eAAe,2BAA2B;AAChD,QAAM,gBAAgB,MAAM,2BAA2B,YAAY;AACnE,QAAM,QAAQ,oBAAoB;AAElC,QAAM,UAAU,uBAAuB,OAAO,cAAc,EAAE,QAAQ,KAAK,GAAG,CAAC;AAE/E,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,8BAA8B,OAAe;AAC3D,eAAa;AACb,QAAM,aAAa,uBAAuB;AAC1C,QAAM,eAAe,gBAAgB,UAAU;AAC/C,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AACA,qBAAmB,YAAY,CAAC,CAAC;AACjC,SAAO;AAAA,IACL;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/lib/cookie.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY, INSTEAD EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { isBrowserLike } from '@stackframe/stack-shared/dist/utils/env';\nimport { StackAssertionError } from '@stackframe/stack-shared/dist/utils/errors';\nimport Cookies from \"js-cookie\";\nimport { calculatePKCECodeChallenge, generateRandomCodeVerifier, generateRandomState } from \"oauth4webapi\";\n\n\n// INFO: This file is used to manage cookies. It also sets some cookie flags automatically, see this description.\n//\n// It provides asynchronous setCookie, getCookie, deleteCookie, etc. functions that can be used in various environments\n// (browser + Next.js for now). Under the hood, they just get a CookieHelper object and then set the cookies there.\n//\n// The CookieHelper object is a simple object that lets you set, get and delete cookies synchronously. Acquiring one\n// is asynchronous (except for browser environments, where they can be acquired synchronously), but once you have it,\n// you can use it synchronously. This function is useful if you cannot await in the calling code, but otherwise you\n// should prefer to await the functions directly.\n//\n// Some cookie flags are set automatically by the CookieHelper (and hence also the <xyz>Cookie functions).\n// In particular:\n// - SameSite is set to `Lax` by default, which is already true in Chromium-based browsers, so this creates\n// compatibility with other browsers that use either Strict or None (particularly Safari and Firefox, and older\n// versions of Chrome). If Partitioned is automatically set (as described below), then this value is set to `None`\n// instead.\n// - Secure is set depending on whether we could successfully determine that the client is on HTTPS. For this, we use a\n// set of heuristics:\n// - In a browser environment, we check window.location.protocol which is always accurate\n// - In a Next.js server environment:\n// - First we check the `stack-is-https` cookie, which is set in various places on the\n// client with a Secure attribute. If that one is passed on to the server, we know that the client is on HTTPS\n// and we can set the Secure flag on the cookie. TODO: Should we also do this with a second cookie with a\n// __Host- prefix, so a malicious subdomain of the current domain cannot forcibly enable HTTPS mode and\n// therefore prevent new cookies from being set?\n// - Otherwise, we check the X-Forwarded-Proto header. If that one is `https`, we know that the client is\n// (pretending to be) on HTTPS and we can set the Secure flag on the cookie. Note that this header is\n// spoofable by malicious clients (so is the cookie actually), but since setting this value can only *increase*\n// security (and therefore prevent setting of a cookie), and requires a malicious client, this is still safe.\n// - If neither of the above is true, we don't set the Secure flag on the cookie.\n// - Partitioned is set depending on whether it is needed & supported. Unfortunately, the fact that Partitioned\n// cookies require SameSite=None, browsers that don't support it will still set them as normal third-party cookies,\n// which are fundamentally unsafe. Therefore, we need to take extra care that we only ever set Partitioned cookies\n// if we know for sure that the browser supports it.\n// - In a browser environment, we check:\n// - Whether `Secure` is set. If it's not, we don't set Partitioned.\n// - Whether we can set & retrieve cookies without Partitioned being set. If this is the case, we are likely in a\n// top-level context or a browser that partitions cookies by default (eg. Firefox). In this case, we don't need\n// Partitioned and can just proceed as normal.\n// - Whether CHIPS is supported. To prevent the case where CHIPS is not supported but third-party cookies are (in\n// which we would accidentally set SameSite=None without Partitioned as the latter requires the former), we\n// check this by running a simple test with document.cookie.\n// - Whether the browser supports Partitioned cookies. If yes, set Partitioned. Otherwise, don't set Partitioned.\n// Since there's no easy cross-compat way to do this (CookieStore and document.cookie do not return whether a\n// cookie is partitioned on some/all versions of Safari and Firefox), we use a heuristic; we run this test by\n// creating two cookies with the same name: One with Partitioned and one without. If there are two resulting\n// cookies, that means they were put into different jars, implying that the browser supports Partitioned cookies\n// (but doesn't partition cookies by default). If they result in just one cookie, that could mean that the\n// browser doesn't support Partitioned cookies, or that the browser doesn't put partitioned cookies into\n// different jars by default, in which case we still don't know. This heuristic works on Chrome, but may\n// incorrectly conclude that some other browsers don't support Partitioned. But from a security perspective,\n// that is better than accidentally setting SameSite=None without Partitioned. TODO: Find a better heuristic to\n// to determine whether the browser supports Partitioned cookies or not.\n// - In a Next.js server environment, right now we do nothing because of the complexity involved :( TODO: In the\n// future, we could improve this for example by setting hint cookies from the client, but we need to make sure that\n// no malicious actor (eg. on a malicious subdomain) can forcefully enable Partitioned cookies on a browser that\n// does not support it.\n\n\ntype SetCookieOptions = { maxAge: number | \"session\", noOpIfServerComponent?: boolean, domain?: string, secure?: boolean };\ntype DeleteCookieOptions = { noOpIfServerComponent?: boolean, domain?: string };\n\nfunction ensureClient() {\n if (!isBrowserLike()) {\n throw new Error(\"cookieClient functions can only be called in a browser environment, yet window is undefined\");\n }\n}\n\nexport type CookieHelper = {\n get: (name: string) => string | null,\n getAll: () => Record<string, string>,\n set: (name: string, value: string, options: SetCookieOptions) => void,\n setOrDelete: (name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) => void,\n delete: (name: string, options: DeleteCookieOptions) => void,\n};\n\nconst placeholderCookieHelperIdentity = { \"placeholder cookie helper identity\": true };\nexport async function createPlaceholderCookieHelper(): Promise<CookieHelper> {\n function throwError(): never {\n throw new StackAssertionError(\"Throwing cookie helper is just a placeholder. This should never be called\");\n }\n return {\n get: throwError,\n getAll: throwError,\n set: throwError,\n setOrDelete: throwError,\n delete: throwError,\n };\n}\n\nexport async function createCookieHelper(): Promise<CookieHelper> {\n if (isBrowserLike()) {\n return createBrowserCookieHelper();\n } else {\n return await createPlaceholderCookieHelper();\n }\n}\n\nexport function createBrowserCookieHelper(): CookieHelper {\n return {\n get: getCookieClient,\n getAll: getAllCookiesClient,\n set: setCookieClient,\n setOrDelete: setOrDeleteCookieClient,\n delete: deleteCookieClient,\n };\n}\n\nfunction handleCookieError(e: unknown, options: DeleteCookieOptions | SetCookieOptions) {\n if (e instanceof Error && e.message.includes(\"Cookies can only be modified in\")) {\n if (options.noOpIfServerComponent) {\n // ignore\n } else {\n throw new StackAssertionError(\"Attempted to set cookie in server component. Pass { noOpIfServerComponent: true } in the options of Stack's cookie functions if this is intentional and you want to ignore this error. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options\");\n }\n } else {\n throw e;\n }\n}\n\n\nexport function getCookieClient(name: string): string | null {\n const all = getAllCookiesClient();\n return all[name] ?? null;\n}\n\nexport function getAllCookiesClient(): Record<string, string> {\n ensureClient();\n // set a helper cookie, see comment in `NextCookieHelper.set` above\n Cookies.set(\"stack-is-https\", \"true\", { secure: true, expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365) });\n return Cookies.get();\n}\n\nexport async function getCookie(name: string): Promise<string | null> {\n const cookieHelper = await createCookieHelper();\n return cookieHelper.get(name);\n}\n\nexport async function isSecure(): Promise<boolean> {\n if (isBrowserLike()) {\n return determineSecureFromClientContext();\n }\n return false;\n}\n\nfunction determineSecureFromClientContext(): boolean {\n return typeof window !== \"undefined\" && window.location.protocol === \"https:\";\n}\n\n\nlet _shouldSetPartitionedClientCache: boolean | undefined = undefined;\nfunction shouldSetPartitionedClient() {\n return _shouldSetPartitionedClientCache ??= _internalShouldSetPartitionedClient();\n}\nfunction _internalShouldSetPartitionedClient() {\n ensureClient();\n\n if (!(determineSecureFromClientContext())) {\n return false;\n }\n\n // check whether we can set & retrieve normal cookies (either because we're on a top-level/same-origin context or the browser partitions cookies by default)\n const cookie1Name = \"__Host-stack-temporary-chips-test-\" + Math.random().toString(36).substring(2, 15);\n document.cookie = `${cookie1Name}=value1; Secure; path=/`;\n const cookies1 = document.cookie.split(\"; \");\n document.cookie = `${cookie1Name}=delete1; Secure; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;\n if (cookies1.some((c) => c.startsWith(cookie1Name + \"=\"))) {\n return false;\n }\n\n\n // check whether Partitioned cookies are supported by the browser\n // TODO: See comment at the top. Feels like we should find a better way to do this\n const cookie2Name = \"__Host-stack-temporary-chips-test-\" + Math.random().toString(36).substring(2, 15);\n\n // just to be safe, delete the cookie first to avoid weird RNG-prediction attacks\n // I don't know what they look like (since this is a host cookie) but better safe than sorry\n // (this function should be 100% bulletproof so we don't accidentally fall back to non-partitioned third party cookies on unsupported browsers)\n document.cookie = `${cookie2Name}=delete1; Secure; SameSite=None; Partitioned; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n document.cookie = `${cookie2Name}=delete2; Secure; SameSite=None; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n\n // set the cookie, once partitioned and once not partitioned\n document.cookie = `${cookie2Name}=set1; Secure; SameSite=None; Partitioned; path=/`;\n document.cookie = `${cookie2Name}=set2; Secure; SameSite=None; path=/`;\n\n // check if there are two cookies\n const cookies2 = document.cookie.split(\"; \");\n const numberOfCookiesWithThisName = cookies2.filter((c) => c.startsWith(cookie2Name + \"=\")).length;\n\n // clean up\n document.cookie = `${cookie2Name}=delete3; Secure; SameSite=None; Partitioned; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n document.cookie = `${cookie2Name}=delete4; Secure; SameSite=None; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n\n return numberOfCookiesWithThisName === 2;\n}\n\nfunction setCookieClientInternal(name: string, value: string, options: SetCookieOptions) {\n const secure = options.secure ?? determineSecureFromClientContext();\n const partitioned = shouldSetPartitionedClient();\n Cookies.set(name, value, {\n expires: options.maxAge === \"session\" ? undefined : new Date(Date.now() + (options.maxAge) * 1000),\n domain: options.domain,\n secure,\n sameSite: \"Lax\",\n ...(partitioned ? {\n partitioned,\n sameSite: \"None\",\n } : {}),\n });\n}\n\nfunction deleteCookieClientInternal(name: string, options: DeleteCookieOptions) {\n for (const partitioned of [true, false]) {\n if (options.domain !== undefined) {\n Cookies.remove(name, { domain: options.domain, secure: determineSecureFromClientContext(), partitioned });\n }\n Cookies.remove(name, { secure: determineSecureFromClientContext(), partitioned });\n }\n}\n\nexport function setOrDeleteCookieClient(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) {\n ensureClient();\n if (value === null) {\n deleteCookieClientInternal(name, options);\n } else {\n setCookieClientInternal(name, value, options);\n }\n}\n\nexport async function setOrDeleteCookie(name: string, value: string | null, options: SetCookieOptions & DeleteCookieOptions) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.setOrDelete(name, value, options);\n}\n\nexport function deleteCookieClient(name: string, options: DeleteCookieOptions) {\n ensureClient();\n deleteCookieClientInternal(name, options);\n}\n\nexport async function deleteCookie(name: string, options: DeleteCookieOptions) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.delete(name, options);\n}\n\nexport function setCookieClient(name: string, value: string, options: SetCookieOptions) {\n ensureClient();\n setCookieClientInternal(name, value, options);\n}\n\nexport async function setCookie(name: string, value: string, options: SetCookieOptions) {\n const cookieHelper = await createCookieHelper();\n cookieHelper.set(name, value, options);\n}\n\nexport async function saveVerifierAndState() {\n const codeVerifier = generateRandomCodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n const state = generateRandomState();\n\n await setCookie(\"stack-oauth-outer-\" + state, codeVerifier, { maxAge: 60 * 60 });\n\n return {\n codeChallenge,\n state,\n };\n}\n\nexport function consumeVerifierAndStateCookie(state: string) {\n ensureClient();\n const cookieName = \"stack-oauth-outer-\" + state;\n const codeVerifier = getCookieClient(cookieName);\n if (!codeVerifier) {\n return null;\n }\n deleteCookieClient(cookieName, {});\n return {\n codeVerifier,\n };\n}\n"],"mappings":";AAIA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,OAAO,aAAa;AACpB,SAAS,4BAA4B,4BAA4B,2BAA2B;AAiE5F,SAAS,eAAe;AACtB,MAAI,CAAC,cAAc,GAAG;AACpB,UAAM,IAAI,MAAM,6FAA6F;AAAA,EAC/G;AACF;AAWA,eAAsB,gCAAuD;AAC3E,WAAS,aAAoB;AAC3B,UAAM,IAAI,oBAAoB,2EAA2E;AAAA,EAC3G;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAEA,eAAsB,qBAA4C;AAChE,MAAI,cAAc,GAAG;AACnB,WAAO,0BAA0B;AAAA,EACnC,OAAO;AACL,WAAO,MAAM,8BAA8B;AAAA,EAC7C;AACF;AAEO,SAAS,4BAA0C;AACxD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAeO,SAAS,gBAAgB,MAA6B;AAC3D,QAAM,MAAM,oBAAoB;AAChC,SAAO,IAAI,IAAI,KAAK;AACtB;A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;AACnC;AAEO,SAAS,gBAAgB,MAAc,OAAe,SAA2B;AACtF,eAAa;AACb,0BAAwB,MAAM,OAAO,OAAO;AAC9C;AAEA,eAAsB,UAAU,MAAc,OAAe,SAA2B;AACtF,QAAM,eAAe,MAAM,mBAAmB;AAC9C,eAAa,IAAI,MAAM,OAAO,OAAO;AACvC;AAEA,eAAsB,uBAAuB;AAC3C,QAAM,eAAe,2BAA2B;AAChD,QAAM,gBAAgB,MAAM,2BAA2B,YAAY;AACnE,QAAM,QAAQ,oBAAoB;AAElC,QAAM,UAAU,uBAAuB,OAAO,cAAc,EAAE,QAAQ,KAAK,GAAG,CAAC;AAE/E,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,8BAA8B,OAAe;AAC3D,eAAa;AACb,QAAM,aAAa,uBAAuB;AAC1C,QAAM,eAAe,gBAAgB,UAAU;AAC/C,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AACA,qBAAmB,YAAY,CAAC,CAAC;AACjC,SAAO;AAAA,IACL;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/lib/stack-app/api-keys/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { TeamApiKeysCrud, UserApiKeysCrud, teamApiKeysCreateInputSchema, userApiKeysCreateInputSchema } from \"@stackframe/stack-shared/dist/interface/crud/project-api-keys\";\nimport { filterUndefined } from \"@stackframe/stack-shared/dist/utils/objects\";\nimport { IfAndOnlyIf, PrettifyType } from \"@stackframe/stack-shared/dist/utils/types\";\nimport type * as yup from \"yup\";\n\nexport type ApiKeyType = \"user\" | \"team\";\n\nexport type ApiKey<Type extends ApiKeyType = ApiKeyType, IsFirstView extends boolean = false> =\n & {\n id: string,\n description: string,\n expiresAt?: Date,\n manuallyRevokedAt?: Date | null,\n createdAt: Date,\n value: IfAndOnlyIf<IsFirstView, true, string, { lastFour: string }>,\n update(options: ApiKeyUpdateOptions<Type>): Promise<void>,\n revoke: () => Promise<void>,\n isValid: () => boolean,\n whyInvalid: () => \"manually-revoked\" | \"expired\" | null,\n }\n & (\n | (\"user\" extends Type ? { type: \"user\", userId: string } : never)\n | (\"team\" extends Type ? { type: \"team\", teamId: string } : never)\n );\n\nexport type UserApiKeyFirstView = PrettifyType<ApiKey<\"user\", true>>;\nexport type UserApiKey = PrettifyType<ApiKey<\"user\", false>>;\n\nexport type TeamApiKeyFirstView = PrettifyType<ApiKey<\"team\", true>>;\nexport type TeamApiKey = PrettifyType<ApiKey<\"team\", false>>;\n\nexport type ApiKeyCreationOptions<Type extends ApiKeyType = ApiKeyType> =\n & {\n description: string,\n expiresAt: Date | null,\n /**\n * Whether the API key should be considered public. A public API key will not be detected by the secret scanner, which\n * automatically revokes API keys when it detects that they may have been exposed to the public.\n */\n isPublic?: boolean,\n };\nexport function apiKeyCreationOptionsToCrud(type: \"user\", userId: string, options: ApiKeyCreationOptions<\"user\">): Promise<yup.InferType<typeof userApiKeysCreateInputSchema>>;\nexport function apiKeyCreationOptionsToCrud(type: \"team\", teamId: string, options: ApiKeyCreationOptions<\"team\">): Promise<yup.InferType<typeof teamApiKeysCreateInputSchema>>;\nexport function apiKeyCreationOptionsToCrud(type: ApiKeyType, userIdOrTeamId: string, options: ApiKeyCreationOptions): Promise<yup.InferType<typeof userApiKeysCreateInputSchema> | yup.InferType<typeof teamApiKeysCreateInputSchema>>;\nexport async function apiKeyCreationOptionsToCrud(type: ApiKeyType, userIdOrTeamId: string, options: ApiKeyCreationOptions): Promise<yup.InferType<typeof userApiKeysCreateInputSchema> | yup.InferType<typeof teamApiKeysCreateInputSchema>> {\n return {\n description: options.description,\n expires_at_millis: options.expiresAt == null ? options.expiresAt : options.expiresAt.getTime(),\n is_public: options.isPublic,\n ...(type === \"user\" ? { user_id: userIdOrTeamId } : { team_id: userIdOrTeamId }),\n };\n}\n\n\nexport type ApiKeyUpdateOptions<Type extends ApiKeyType = ApiKeyType> = {\n description?: string,\n expiresAt?: Date | null,\n revoked?: boolean,\n};\nexport function apiKeyUpdateOptionsToCrud(type: \"user\", options: ApiKeyUpdateOptions<\"user\">): Promise<UserApiKeysCrud[\"Client\"][\"Update\"]>;\nexport function apiKeyUpdateOptionsToCrud(type: \"team\", options: ApiKeyUpdateOptions<\"team\">): Promise<TeamApiKeysCrud[\"Client\"][\"Update\"]>;\nexport function apiKeyUpdateOptionsToCrud(type: ApiKeyType, options: ApiKeyUpdateOptions): Promise<UserApiKeysCrud[\"Client\"][\"Update\"] | TeamApiKeysCrud[\"Client\"][\"Update\"]>;\nexport async function apiKeyUpdateOptionsToCrud(type: ApiKeyType, options: ApiKeyUpdateOptions): Promise<UserApiKeysCrud[\"Client\"][\"Update\"] | TeamApiKeysCrud[\"Client\"][\"Update\"]> {\n return filterUndefined({\n description: options.description,\n expires_at_millis: options.expiresAt == null ? options.expiresAt : options.expiresAt.getTime(),\n revoked: options.revoked,\n });\n}\n"],"mappings":";AAKA,SAAS,uBAAuB;AA2ChC,eAAsB,4BAA4B,MAAkB,gBAAwB,SAAkJ;AAC5O,SAAO;AAAA,IACL,aAAa,QAAQ;AAAA,IACrB,mBAAmB,QAAQ,aAAa,OAAO,QAAQ,YAAY,QAAQ,UAAU,QAAQ;AAAA,IAC7F,WAAW,QAAQ;AAAA,IACnB,GAAI,SAAS,SAAS,EAAE,SAAS,eAAe,IAAI,EAAE,SAAS,eAAe;AAAA,EAChF;AACF;AAWA,eAAsB,0BAA0B,MAAkB,SAAkH;AAClL,SAAO,gBAAgB;AAAA,IACrB,aAAa,QAAQ;AAAA,IACrB,mBAAmB,QAAQ,aAAa,OAAO,QAAQ,YAAY,QAAQ,UAAU,QAAQ;AAAA,IAC7F,SAAS,QAAQ;AAAA,EACnB,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../../../../src/lib/stack-app/api-keys/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY, INSTEAD EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { TeamApiKeysCrud, UserApiKeysCrud, teamApiKeysCreateInputSchema, userApiKeysCreateInputSchema } from \"@stackframe/stack-shared/dist/interface/crud/project-api-keys\";\nimport { filterUndefined } from \"@stackframe/stack-shared/dist/utils/objects\";\nimport { IfAndOnlyIf, PrettifyType } from \"@stackframe/stack-shared/dist/utils/types\";\nimport type * as yup from \"yup\";\n\nexport type ApiKeyType = \"user\" | \"team\";\n\nexport type ApiKey<Type extends ApiKeyType = ApiKeyType, IsFirstView extends boolean = false> =\n & {\n id: string,\n description: string,\n expiresAt?: Date,\n manuallyRevokedAt?: Date | null,\n createdAt: Date,\n value: IfAndOnlyIf<IsFirstView, true, string, { lastFour: string }>,\n update(options: ApiKeyUpdateOptions<Type>): Promise<void>,\n revoke: () => Promise<void>,\n isValid: () => boolean,\n whyInvalid: () => \"manually-revoked\" | \"expired\" | null,\n }\n & (\n | (\"user\" extends Type ? { type: \"user\", userId: string } : never)\n | (\"team\" extends Type ? { type: \"team\", teamId: string } : never)\n );\n\nexport type UserApiKeyFirstView = PrettifyType<ApiKey<\"user\", true>>;\nexport type UserApiKey = PrettifyType<ApiKey<\"user\", false>>;\n\nexport type TeamApiKeyFirstView = PrettifyType<ApiKey<\"team\", true>>;\nexport type TeamApiKey = PrettifyType<ApiKey<\"team\", false>>;\n\nexport type ApiKeyCreationOptions<Type extends ApiKeyType = ApiKeyType> =\n & {\n description: string,\n expiresAt: Date | null,\n /**\n * Whether the API key should be considered public. A public API key will not be detected by the secret scanner, which\n * automatically revokes API keys when it detects that they may have been exposed to the public.\n */\n isPublic?: boolean,\n };\nexport function apiKeyCreationOptionsToCrud(type: \"user\", userId: string, options: ApiKeyCreationOptions<\"user\">): Promise<yup.InferType<typeof userApiKeysCreateInputSchema>>;\nexport function apiKeyCreationOptionsToCrud(type: \"team\", teamId: string, options: ApiKeyCreationOptions<\"team\">): Promise<yup.InferType<typeof teamApiKeysCreateInputSchema>>;\nexport function apiKeyCreationOptionsToCrud(type: ApiKeyType, userIdOrTeamId: string, options: ApiKeyCreationOptions): Promise<yup.InferType<typeof userApiKeysCreateInputSchema> | yup.InferType<typeof teamApiKeysCreateInputSchema>>;\nexport async function apiKeyCreationOptionsToCrud(type: ApiKeyType, userIdOrTeamId: string, options: ApiKeyCreationOptions): Promise<yup.InferType<typeof userApiKeysCreateInputSchema> | yup.InferType<typeof teamApiKeysCreateInputSchema>> {\n return {\n description: options.description,\n expires_at_millis: options.expiresAt == null ? options.expiresAt : options.expiresAt.getTime(),\n is_public: options.isPublic,\n ...(type === \"user\" ? { user_id: userIdOrTeamId } : { team_id: userIdOrTeamId }),\n };\n}\n\n\nexport type ApiKeyUpdateOptions<Type extends ApiKeyType = ApiKeyType> = {\n description?: string,\n expiresAt?: Date | null,\n revoked?: boolean,\n};\nexport function apiKeyUpdateOptionsToCrud(type: \"user\", options: ApiKeyUpdateOptions<\"user\">): Promise<UserApiKeysCrud[\"Client\"][\"Update\"]>;\nexport function apiKeyUpdateOptionsToCrud(type: \"team\", options: ApiKeyUpdateOptions<\"team\">): Promise<TeamApiKeysCrud[\"Client\"][\"Update\"]>;\nexport function apiKeyUpdateOptionsToCrud(type: ApiKeyType, options: ApiKeyUpdateOptions): Promise<UserApiKeysCrud[\"Client\"][\"Update\"] | TeamApiKeysCrud[\"Client\"][\"Update\"]>;\nexport async function apiKeyUpdateOptionsToCrud(type: ApiKeyType, options: ApiKeyUpdateOptions): Promise<UserApiKeysCrud[\"Client\"][\"Update\"] | TeamApiKeysCrud[\"Client\"][\"Update\"]> {\n return filterUndefined({\n description: options.description,\n expires_at_millis: options.expiresAt == null ? options.expiresAt : options.expiresAt.getTime(),\n revoked: options.revoked,\n });\n}\n"],"mappings":";AAKA,SAAS,uBAAuB;AA2ChC,eAAsB,4BAA4B,MAAkB,gBAAwB,SAAkJ;AAC5O,SAAO;AAAA,IACL,aAAa,QAAQ;AAAA,IACrB,mBAAmB,QAAQ,aAAa,OAAO,QAAQ,YAAY,QAAQ,UAAU,QAAQ;AAAA,IAC7F,WAAW,QAAQ;AAAA,IACnB,GAAI,SAAS,SAAS,EAAE,SAAS,eAAe,IAAI,EAAE,SAAS,eAAe;AAAA,EAChF;AACF;AAWA,eAAsB,0BAA0B,MAAkB,SAAkH;AAClL,SAAO,gBAAgB;AAAA,IACrB,aAAa,QAAQ;AAAA,IACrB,mBAAmB,QAAQ,aAAa,OAAO,QAAQ,YAAY,QAAQ,UAAU,QAAQ;AAAA,IAC7F,SAAS,QAAQ;AAAA,EACnB,CAAC;AACH;","names":[]}
@@ -425,9 +425,244 @@ var _StackAdminAppImplIncomplete = class extends _StackServerAppImplIncomplete {
425
425
  const crud = Result.orThrow(await this._transactionsCache.getOrWait([params.cursor, params.limit, params.type, params.customerType], "write-only"));
426
426
  return crud;
427
427
  }
428
+ // Email Outbox methods
429
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Complex discriminated union conversion from API response
430
+ _emailOutboxCrudToAdmin(crud) {
431
+ const recipient = crud.to;
432
+ let to;
433
+ if (recipient.type === "user-primary-email") {
434
+ to = { type: "user-primary-email", userId: recipient.user_id };
435
+ } else if (recipient.type === "user-custom-emails") {
436
+ to = { type: "user-custom-emails", userId: recipient.user_id, emails: recipient.emails };
437
+ } else {
438
+ to = { type: "custom-emails", emails: recipient.emails };
439
+ }
440
+ const base = {
441
+ id: crud.id,
442
+ createdAt: new Date(crud.created_at_millis),
443
+ updatedAt: new Date(crud.updated_at_millis),
444
+ to,
445
+ scheduledAt: new Date(crud.scheduled_at_millis),
446
+ isPaused: false,
447
+ hasRendered: false,
448
+ hasDelivered: false
449
+ };
450
+ const rendered = crud.has_rendered ? {
451
+ ...base,
452
+ startedRenderingAt: new Date(crud.started_rendering_at_millis),
453
+ renderedAt: new Date(crud.rendered_at_millis),
454
+ subject: crud.subject,
455
+ html: crud.html,
456
+ text: crud.text,
457
+ isTransactional: crud.is_transactional,
458
+ isHighPriority: crud.is_high_priority,
459
+ notificationCategoryId: crud.notification_category_id,
460
+ hasRendered: true
461
+ } : null;
462
+ const startedSending = rendered && crud.started_sending_at_millis ? {
463
+ ...rendered,
464
+ startedSendingAt: new Date(crud.started_sending_at_millis)
465
+ } : null;
466
+ const finishedDelivering = startedSending && crud.has_delivered ? {
467
+ ...startedSending,
468
+ deliveredAt: new Date(crud.delivered_at_millis),
469
+ hasDelivered: true
470
+ } : null;
471
+ const result = (() => {
472
+ switch (crud.status) {
473
+ case "paused": {
474
+ return {
475
+ ...base,
476
+ status: "paused",
477
+ simpleStatus: "in-progress",
478
+ isPaused: true
479
+ };
480
+ }
481
+ case "preparing": {
482
+ return {
483
+ ...base,
484
+ status: "preparing",
485
+ simpleStatus: "in-progress"
486
+ };
487
+ }
488
+ case "rendering": {
489
+ return {
490
+ ...base,
491
+ status: "rendering",
492
+ simpleStatus: "in-progress",
493
+ startedRenderingAt: new Date(crud.started_rendering_at_millis)
494
+ };
495
+ }
496
+ case "render-error": {
497
+ return {
498
+ ...base,
499
+ status: "render-error",
500
+ simpleStatus: "error",
501
+ startedRenderingAt: new Date(crud.started_rendering_at_millis),
502
+ renderedAt: new Date(crud.rendered_at_millis),
503
+ renderError: crud.render_error
504
+ };
505
+ }
506
+ case "scheduled": {
507
+ return {
508
+ ...rendered,
509
+ status: "scheduled",
510
+ simpleStatus: "in-progress"
511
+ };
512
+ }
513
+ case "queued": {
514
+ return {
515
+ ...rendered,
516
+ status: "queued",
517
+ simpleStatus: "in-progress"
518
+ };
519
+ }
520
+ case "sending": {
521
+ return {
522
+ ...startedSending,
523
+ status: "sending",
524
+ simpleStatus: "in-progress"
525
+ };
526
+ }
527
+ case "server-error": {
528
+ return {
529
+ ...startedSending,
530
+ status: "server-error",
531
+ simpleStatus: "error",
532
+ errorAt: new Date(crud.error_at_millis),
533
+ serverError: crud.server_error
534
+ };
535
+ }
536
+ case "skipped": {
537
+ return {
538
+ ...base,
539
+ status: "skipped",
540
+ simpleStatus: "ok",
541
+ skippedAt: new Date(crud.skipped_at_millis),
542
+ skippedReason: crud.skipped_reason,
543
+ skippedDetails: crud.skipped_details ?? {},
544
+ hasRendered: crud.has_rendered,
545
+ // Optional fields
546
+ startedRenderingAt: crud.started_rendering_at_millis ? new Date(crud.started_rendering_at_millis) : void 0,
547
+ renderedAt: crud.rendered_at_millis ? new Date(crud.rendered_at_millis) : void 0,
548
+ subject: crud.subject,
549
+ html: crud.html,
550
+ text: crud.text,
551
+ isTransactional: crud.is_transactional,
552
+ isHighPriority: crud.is_high_priority,
553
+ notificationCategoryId: crud.notification_category_id,
554
+ startedSendingAt: crud.started_sending_at_millis ? new Date(crud.started_sending_at_millis) : void 0
555
+ };
556
+ }
557
+ case "bounced": {
558
+ return {
559
+ ...startedSending,
560
+ status: "bounced",
561
+ simpleStatus: "error",
562
+ bouncedAt: new Date(crud.bounced_at_millis)
563
+ };
564
+ }
565
+ case "delivery-delayed": {
566
+ return {
567
+ ...startedSending,
568
+ status: "delivery-delayed",
569
+ simpleStatus: "ok",
570
+ deliveryDelayedAt: new Date(crud.delivery_delayed_at_millis)
571
+ };
572
+ }
573
+ case "sent": {
574
+ return {
575
+ ...finishedDelivering,
576
+ status: "sent",
577
+ simpleStatus: "ok",
578
+ canHaveDeliveryInfo: crud.can_have_delivery_info
579
+ };
580
+ }
581
+ case "opened": {
582
+ return {
583
+ ...finishedDelivering,
584
+ status: "opened",
585
+ simpleStatus: "ok",
586
+ openedAt: new Date(crud.opened_at_millis),
587
+ canHaveDeliveryInfo: true
588
+ };
589
+ }
590
+ case "clicked": {
591
+ return {
592
+ ...finishedDelivering,
593
+ status: "clicked",
594
+ simpleStatus: "ok",
595
+ clickedAt: new Date(crud.clicked_at_millis),
596
+ canHaveDeliveryInfo: true
597
+ };
598
+ }
599
+ case "marked-as-spam": {
600
+ return {
601
+ ...finishedDelivering,
602
+ status: "marked-as-spam",
603
+ simpleStatus: "ok",
604
+ markedAsSpamAt: new Date(crud.marked_as_spam_at_millis),
605
+ canHaveDeliveryInfo: true
606
+ };
607
+ }
608
+ default: {
609
+ throw new StackAssertionError(`Unknown email outbox status: ${crud.status}`, { status: crud.status });
610
+ }
611
+ }
612
+ })();
613
+ return result;
614
+ }
615
+ async listOutboxEmails(options) {
616
+ const response = await this._interface.listOutboxEmails({
617
+ status: options?.status,
618
+ simple_status: options?.simpleStatus,
619
+ limit: options?.limit,
620
+ cursor: options?.cursor
621
+ });
622
+ return {
623
+ items: response.items.map((item) => this._emailOutboxCrudToAdmin(item)),
624
+ nextCursor: response.pagination?.next_cursor ?? null
625
+ };
626
+ }
627
+ async getOutboxEmail(id) {
628
+ const response = await this._interface.getOutboxEmail(id);
629
+ return this._emailOutboxCrudToAdmin(response);
630
+ }
631
+ async updateOutboxEmail(id, options) {
632
+ const response = await this._interface.updateOutboxEmail(id, {
633
+ is_paused: options.isPaused,
634
+ scheduled_at_millis: options.scheduledAtMillis,
635
+ cancel: options.cancel
636
+ });
637
+ return this._emailOutboxCrudToAdmin(response);
638
+ }
639
+ async pauseOutboxEmail(id) {
640
+ return await this.updateOutboxEmail(id, { isPaused: true });
641
+ }
642
+ async unpauseOutboxEmail(id) {
643
+ return await this.updateOutboxEmail(id, { isPaused: false });
644
+ }
645
+ async cancelOutboxEmail(id) {
646
+ return await this.updateOutboxEmail(id, { cancel: true });
647
+ }
428
648
  async getStripeAccountInfo() {
429
649
  return await this._interface.getStripeAccountInfo();
430
650
  }
651
+ async previewAffectedUsersByOnboardingChange(onboarding, limit) {
652
+ const result = await this._interface.previewAffectedUsersByOnboardingChange(
653
+ { require_email_verification: onboarding.requireEmailVerification },
654
+ limit
655
+ );
656
+ return {
657
+ affectedUsers: result.affected_users.map((u) => ({
658
+ id: u.id,
659
+ displayName: u.display_name,
660
+ primaryEmail: u.primary_email,
661
+ restrictedReason: u.restricted_reason
662
+ })),
663
+ totalAffectedCount: result.total_affected_count
664
+ };
665
+ }
431
666
  };
432
667
  export {
433
668
  _StackAdminAppImplIncomplete