Initial commit of eigent-main

This commit is contained in:
puzhen 2025-08-12 01:16:39 +02:00
commit 723df5a03e
1144 changed files with 103478 additions and 0 deletions

View file

@ -0,0 +1,22 @@
// src/lib/stack-app/api-keys/index.ts
import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects";
async function apiKeyCreationOptionsToCrud(type, userIdOrTeamId, options) {
return {
description: options.description,
expires_at_millis: options.expiresAt == null ? options.expiresAt : options.expiresAt.getTime(),
is_public: options.isPublic,
...type === "user" ? { user_id: userIdOrTeamId } : { team_id: userIdOrTeamId }
};
}
async function apiKeyUpdateOptionsToCrud(type, options) {
return filterUndefined({
description: options.description,
expires_at_millis: options.expiresAt == null ? options.expiresAt : options.expiresAt.getTime(),
revoked: options.revoked
});
}
export {
apiKeyCreationOptionsToCrud,
apiKeyUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +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":[]}

View file

@ -0,0 +1,331 @@
// src/lib/stack-app/apps/implementations/admin-app-impl.ts
import { StackAdminInterface } from "@stackframe/stack-shared";
import { getProductionModeErrors } from "@stackframe/stack-shared/dist/helpers/production-mode";
import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
import { pick } from "@stackframe/stack-shared/dist/utils/objects";
import { Result } from "@stackframe/stack-shared/dist/utils/results";
import { useMemo } from "react";
import { stackAppInternalsSymbol } from "../../common";
import { adminEmailTemplateUpdateOptionsToCrud } from "../../email-templates";
import { internalApiKeyCreateOptionsToCrud } from "../../internal-api-keys";
import { adminProjectPermissionDefinitionCreateOptionsToCrud, adminProjectPermissionDefinitionUpdateOptionsToCrud, adminTeamPermissionDefinitionCreateOptionsToCrud, adminTeamPermissionDefinitionUpdateOptionsToCrud } from "../../permissions";
import { adminProjectUpdateOptionsToCrud } from "../../projects";
import { clientVersion, createCache, getBaseUrl, getDefaultProjectId, getDefaultPublishableClientKey, getDefaultSecretServerKey, getDefaultSuperSecretAdminKey } from "./common";
import { _StackServerAppImplIncomplete } from "./server-app-impl";
import { useAsyncCache } from "./common";
var _StackAdminAppImplIncomplete = class extends _StackServerAppImplIncomplete {
constructor(options) {
super({
interface: new StackAdminInterface({
getBaseUrl: () => getBaseUrl(options.baseUrl),
projectId: options.projectId ?? getDefaultProjectId(),
extraRequestHeaders: options.extraRequestHeaders ?? {},
clientVersion,
..."projectOwnerSession" in options ? {
projectOwnerSession: options.projectOwnerSession
} : {
publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
superSecretAdminKey: options.superSecretAdminKey ?? getDefaultSuperSecretAdminKey()
}
}),
baseUrl: options.baseUrl,
extraRequestHeaders: options.extraRequestHeaders,
projectId: options.projectId,
tokenStore: options.tokenStore,
urls: options.urls,
oauthScopesOnSignIn: options.oauthScopesOnSignIn,
redirectMethod: options.redirectMethod
});
this._adminProjectCache = createCache(async () => {
return await this._interface.getProject();
});
this._internalApiKeysCache = createCache(async () => {
const res = await this._interface.listInternalApiKeys();
return res;
});
this._adminEmailTemplatesCache = createCache(async () => {
return await this._interface.listEmailTemplates();
});
this._adminTeamPermissionDefinitionsCache = createCache(async () => {
return await this._interface.listTeamPermissionDefinitions();
});
this._adminProjectPermissionDefinitionsCache = createCache(async () => {
return await this._interface.listProjectPermissionDefinitions();
});
this._svixTokenCache = createCache(async () => {
return await this._interface.getSvixToken();
});
this._metricsCache = createCache(async () => {
return await this._interface.getMetrics();
});
}
_adminOwnedProjectFromCrud(data, onRefresh) {
if (this._tokenStoreInit !== null) {
throw new StackAssertionError("Owned apps must always have tokenStore === null \u2014 did you not create this project with app._createOwnedApp()?");
}
return {
...this._adminProjectFromCrud(data, onRefresh),
app: this
};
}
_adminProjectFromCrud(data, onRefresh) {
if (data.id !== this.projectId) {
throw new StackAssertionError(`The project ID of the provided project JSON (${data.id}) does not match the project ID of the app (${this.projectId})!`);
}
const app = this;
return {
id: data.id,
displayName: data.display_name,
description: data.description,
createdAt: new Date(data.created_at_millis),
userCount: data.user_count,
isProductionMode: data.is_production_mode,
config: {
signUpEnabled: data.config.sign_up_enabled,
credentialEnabled: data.config.credential_enabled,
magicLinkEnabled: data.config.magic_link_enabled,
passkeyEnabled: data.config.passkey_enabled,
clientTeamCreationEnabled: data.config.client_team_creation_enabled,
clientUserDeletionEnabled: data.config.client_user_deletion_enabled,
allowLocalhost: data.config.allow_localhost,
oauthAccountMergeStrategy: data.config.oauth_account_merge_strategy,
allowUserApiKeys: data.config.allow_user_api_keys,
allowTeamApiKeys: data.config.allow_team_api_keys,
oauthProviders: data.config.oauth_providers.map((p) => p.type === "shared" ? {
id: p.id,
type: "shared"
} : {
id: p.id,
type: "standard",
clientId: p.client_id ?? throwErr("Client ID is missing"),
clientSecret: p.client_secret ?? throwErr("Client secret is missing"),
facebookConfigId: p.facebook_config_id,
microsoftTenantId: p.microsoft_tenant_id
}),
emailConfig: data.config.email_config.type === "shared" ? {
type: "shared"
} : {
type: "standard",
host: data.config.email_config.host ?? throwErr("Email host is missing"),
port: data.config.email_config.port ?? throwErr("Email port is missing"),
username: data.config.email_config.username ?? throwErr("Email username is missing"),
password: data.config.email_config.password ?? throwErr("Email password is missing"),
senderName: data.config.email_config.sender_name ?? throwErr("Email sender name is missing"),
senderEmail: data.config.email_config.sender_email ?? throwErr("Email sender email is missing")
},
domains: data.config.domains.map((d) => ({
domain: d.domain,
handlerPath: d.handler_path
})),
createTeamOnSignUp: data.config.create_team_on_sign_up,
teamCreatorDefaultPermissions: data.config.team_creator_default_permissions,
teamMemberDefaultPermissions: data.config.team_member_default_permissions,
userDefaultPermissions: data.config.user_default_permissions
},
async update(update) {
await app._interface.updateProject(adminProjectUpdateOptionsToCrud(update));
await onRefresh();
},
async delete() {
await app._interface.deleteProject();
},
async getProductionModeErrors() {
return getProductionModeErrors(data);
},
useProductionModeErrors() {
return getProductionModeErrors(data);
}
};
}
_adminEmailTemplateFromCrud(data) {
return {
type: data.type,
subject: data.subject,
content: data.content,
isDefault: data.is_default
};
}
async getProject() {
return this._adminProjectFromCrud(
Result.orThrow(await this._adminProjectCache.getOrWait([], "write-only")),
() => this._refreshProject()
);
}
useProject() {
const crud = useAsyncCache(this._adminProjectCache, [], "useProjectAdmin()");
return useMemo(() => this._adminProjectFromCrud(
crud,
() => this._refreshProject()
), [crud]);
}
_createInternalApiKeyBaseFromCrud(data) {
const app = this;
return {
id: data.id,
description: data.description,
expiresAt: new Date(data.expires_at_millis),
manuallyRevokedAt: data.manually_revoked_at_millis ? new Date(data.manually_revoked_at_millis) : null,
createdAt: new Date(data.created_at_millis),
isValid() {
return this.whyInvalid() === null;
},
whyInvalid() {
if (this.expiresAt.getTime() < Date.now()) return "expired";
if (this.manuallyRevokedAt) return "manually-revoked";
return null;
},
async revoke() {
const res = await app._interface.revokeInternalApiKeyById(data.id);
await app._refreshInternalApiKeys();
return res;
}
};
}
_createInternalApiKeyFromCrud(data) {
return {
...this._createInternalApiKeyBaseFromCrud(data),
publishableClientKey: data.publishable_client_key ? { lastFour: data.publishable_client_key.last_four } : null,
secretServerKey: data.secret_server_key ? { lastFour: data.secret_server_key.last_four } : null,
superSecretAdminKey: data.super_secret_admin_key ? { lastFour: data.super_secret_admin_key.last_four } : null
};
}
_createInternalApiKeyFirstViewFromCrud(data) {
return {
...this._createInternalApiKeyBaseFromCrud(data),
publishableClientKey: data.publishable_client_key,
secretServerKey: data.secret_server_key,
superSecretAdminKey: data.super_secret_admin_key
};
}
async listInternalApiKeys() {
const crud = Result.orThrow(await this._internalApiKeysCache.getOrWait([], "write-only"));
return crud.map((j) => this._createInternalApiKeyFromCrud(j));
}
useInternalApiKeys() {
const crud = useAsyncCache(this._internalApiKeysCache, [], "useInternalApiKeys()");
return useMemo(() => {
return crud.map((j) => this._createInternalApiKeyFromCrud(j));
}, [crud]);
}
async createInternalApiKey(options) {
const crud = await this._interface.createInternalApiKey(internalApiKeyCreateOptionsToCrud(options));
await this._refreshInternalApiKeys();
return this._createInternalApiKeyFirstViewFromCrud(crud);
}
useEmailTemplates() {
const crud = useAsyncCache(this._adminEmailTemplatesCache, [], "useEmailTemplates()");
return useMemo(() => {
return crud.map((j) => this._adminEmailTemplateFromCrud(j));
}, [crud]);
}
async listEmailTemplates() {
const crud = Result.orThrow(await this._adminEmailTemplatesCache.getOrWait([], "write-only"));
return crud.map((j) => this._adminEmailTemplateFromCrud(j));
}
async updateEmailTemplate(type, data) {
await this._interface.updateEmailTemplate(type, adminEmailTemplateUpdateOptionsToCrud(data));
await this._adminEmailTemplatesCache.refresh([]);
}
async resetEmailTemplate(type) {
await this._interface.resetEmailTemplate(type);
await this._adminEmailTemplatesCache.refresh([]);
}
async createTeamPermissionDefinition(data) {
const crud = await this._interface.createTeamPermissionDefinition(adminTeamPermissionDefinitionCreateOptionsToCrud(data));
await this._adminTeamPermissionDefinitionsCache.refresh([]);
return this._serverTeamPermissionDefinitionFromCrud(crud);
}
async updateTeamPermissionDefinition(permissionId, data) {
await this._interface.updateTeamPermissionDefinition(permissionId, adminTeamPermissionDefinitionUpdateOptionsToCrud(data));
await this._adminTeamPermissionDefinitionsCache.refresh([]);
}
async deleteTeamPermissionDefinition(permissionId) {
await this._interface.deleteTeamPermissionDefinition(permissionId);
await this._adminTeamPermissionDefinitionsCache.refresh([]);
}
async listTeamPermissionDefinitions() {
const crud = Result.orThrow(await this._adminTeamPermissionDefinitionsCache.getOrWait([], "write-only"));
return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
}
useTeamPermissionDefinitions() {
const crud = useAsyncCache(this._adminTeamPermissionDefinitionsCache, [], "usePermissions()");
return useMemo(() => {
return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
}, [crud]);
}
async createProjectPermissionDefinition(data) {
const crud = await this._interface.createProjectPermissionDefinition(adminProjectPermissionDefinitionCreateOptionsToCrud(data));
await this._adminProjectPermissionDefinitionsCache.refresh([]);
return this._serverProjectPermissionDefinitionFromCrud(crud);
}
async updateProjectPermissionDefinition(permissionId, data) {
await this._interface.updateProjectPermissionDefinition(permissionId, adminProjectPermissionDefinitionUpdateOptionsToCrud(data));
await this._adminProjectPermissionDefinitionsCache.refresh([]);
}
async deleteProjectPermissionDefinition(permissionId) {
await this._interface.deleteProjectPermissionDefinition(permissionId);
await this._adminProjectPermissionDefinitionsCache.refresh([]);
}
async listProjectPermissionDefinitions() {
const crud = Result.orThrow(await this._adminProjectPermissionDefinitionsCache.getOrWait([], "write-only"));
return crud.map((p) => this._serverProjectPermissionDefinitionFromCrud(p));
}
useProjectPermissionDefinitions() {
const crud = useAsyncCache(this._adminProjectPermissionDefinitionsCache, [], "useProjectPermissions()");
return useMemo(() => {
return crud.map((p) => this._serverProjectPermissionDefinitionFromCrud(p));
}, [crud]);
}
useSvixToken() {
const crud = useAsyncCache(this._svixTokenCache, [], "useSvixToken()");
return crud.token;
}
async _refreshProject() {
await Promise.all([
super._refreshProject(),
this._adminProjectCache.refresh([])
]);
}
async _refreshInternalApiKeys() {
await this._internalApiKeysCache.refresh([]);
}
get [stackAppInternalsSymbol]() {
return {
...super[stackAppInternalsSymbol],
useMetrics: () => {
return useAsyncCache(this._metricsCache, [], "useMetrics()");
}
};
}
async sendTestEmail(options) {
const response = await this._interface.sendTestEmail({
recipient_email: options.recipientEmail,
email_config: {
...pick(options.emailConfig, ["host", "port", "username", "password"]),
sender_email: options.emailConfig.senderEmail,
sender_name: options.emailConfig.senderName
}
});
if (response.success) {
return Result.ok(void 0);
} else {
return Result.error({ errorMessage: response.error_message ?? throwErr("Email test error not specified") });
}
}
async listSentEmails() {
const response = await this._interface.listSentEmails();
return response.items.map((email) => ({
id: email.id,
to: email.to ?? [],
subject: email.subject,
recipient: email.to?.[0] ?? "",
sentAt: new Date(email.sent_at_millis),
error: email.error
}));
}
};
export {
_StackAdminAppImplIncomplete
};
//# sourceMappingURL=admin-app-impl.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,147 @@
// src/lib/stack-app/apps/implementations/common.ts
import { AsyncCache } from "@stackframe/stack-shared/dist/utils/caches";
import { isBrowserLike } from "@stackframe/stack-shared/dist/utils/env";
import { StackAssertionError, concatStacktraces, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
import { filterUndefined } from "@stackframe/stack-shared/dist/utils/objects";
import { suspendIfSsr } from "@stackframe/stack-shared/dist/utils/react";
import { Result } from "@stackframe/stack-shared/dist/utils/results";
import { Store } from "@stackframe/stack-shared/dist/utils/stores";
import React, { useCallback } from "react";
var process = globalThis.process ?? { env: {} };
var clientVersion = "js @stackframe/react@2.8.12";
if (clientVersion.startsWith("STACK_COMPILE_TIME")) {
throw new StackAssertionError("Client version was not replaced. Something went wrong during build!");
}
var createCache = (fetcher) => {
return new AsyncCache(
async (dependencies) => await Result.fromThrowingAsync(async () => await fetcher(dependencies)),
{}
);
};
var createCacheBySession = (fetcher) => {
return new AsyncCache(
async ([session, ...extraDependencies]) => await Result.fromThrowingAsync(async () => await fetcher(session, extraDependencies)),
{
onSubscribe: ([session], refresh) => {
const handler = session.onInvalidate(() => refresh());
return () => handler.unsubscribe();
}
}
);
};
function getUrls(partial) {
const handler = partial.handler ?? "/handler";
const home = partial.home ?? "/";
const afterSignIn = partial.afterSignIn ?? home;
return {
handler,
signIn: `${handler}/sign-in`,
afterSignIn: home,
signUp: `${handler}/sign-up`,
afterSignUp: afterSignIn,
signOut: `${handler}/sign-out`,
afterSignOut: home,
emailVerification: `${handler}/email-verification`,
passwordReset: `${handler}/password-reset`,
forgotPassword: `${handler}/forgot-password`,
oauthCallback: `${handler}/oauth-callback`,
magicLinkCallback: `${handler}/magic-link-callback`,
home,
accountSettings: `${handler}/account-settings`,
error: `${handler}/error`,
teamInvitation: `${handler}/team-invitation`,
...filterUndefined(partial)
};
}
function getDefaultProjectId() {
return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || throwErr(new Error("Welcome to Stack Auth! It seems that you haven't provided a project ID. Please create a project on the Stack dashboard at https://app.stack-auth.com and put it in the NEXT_PUBLIC_STACK_PROJECT_ID environment variable."));
}
function getDefaultPublishableClientKey() {
return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || throwErr(new Error("Welcome to Stack Auth! It seems that you haven't provided a publishable client key. Please create an API key for your project on the Stack dashboard at https://app.stack-auth.com and copy your publishable client key into the NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY environment variable."));
}
function getDefaultSecretServerKey() {
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."));
}
function getDefaultSuperSecretAdminKey() {
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."));
}
function getDefaultExtraRequestHeaders() {
return JSON.parse(process.env.NEXT_PUBLIC_STACK_EXTRA_REQUEST_HEADERS || "{}");
}
function getBaseUrl(userSpecifiedBaseUrl) {
let url;
if (userSpecifiedBaseUrl) {
if (typeof userSpecifiedBaseUrl === "string") {
url = userSpecifiedBaseUrl;
} else {
if (isBrowserLike()) {
url = userSpecifiedBaseUrl.browser;
} else {
url = userSpecifiedBaseUrl.server;
}
}
} else {
if (isBrowserLike()) {
url = process.env.NEXT_PUBLIC_BROWSER_STACK_API_URL;
} else {
url = process.env.NEXT_PUBLIC_SERVER_STACK_API_URL;
}
url = url || process.env.NEXT_PUBLIC_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;
}
return url.endsWith("/") ? url.slice(0, -1) : url;
}
var defaultBaseUrl = "https://api.stack-auth.com";
function createEmptyTokenStore() {
return new Store({
refreshToken: null,
accessToken: null
});
}
var cachePromiseByHookId = /* @__PURE__ */ new Map();
function useAsyncCache(cache, dependencies, caller) {
suspendIfSsr(caller);
const id = React.useId();
const subscribe = useCallback((cb) => {
const { unsubscribe } = cache.onStateChange(dependencies, () => {
cachePromiseByHookId.delete(id);
cb();
});
return unsubscribe;
}, [cache, ...dependencies]);
const getSnapshot = useCallback(() => {
if (!cachePromiseByHookId.has(id)) {
cachePromiseByHookId.set(id, cache.getOrWait(dependencies, "read-write"));
}
return cachePromiseByHookId.get(id);
}, [cache, ...dependencies]);
const promise = React.useSyncExternalStore(
subscribe,
getSnapshot,
() => throwErr(new Error("getServerSnapshot should never be called in useAsyncCache because we restrict to CSR earlier"))
);
const result = React.use(promise);
if (result.status === "error") {
const error = result.error;
if (error instanceof Error && !error.__stackHasConcatenatedStacktraces) {
concatStacktraces(error, new Error());
error.__stackHasConcatenatedStacktraces = true;
}
throw error;
}
return result.data;
}
export {
clientVersion,
createCache,
createCacheBySession,
createEmptyTokenStore,
getBaseUrl,
getDefaultExtraRequestHeaders,
getDefaultProjectId,
getDefaultPublishableClientKey,
getDefaultSecretServerKey,
getDefaultSuperSecretAdminKey,
getUrls,
useAsyncCache
};
//# sourceMappingURL=common.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,24 @@
// src/lib/stack-app/apps/implementations/index.ts
import { scrambleDuringCompileTime } from "@stackframe/stack-shared/dist/utils/compile-time";
import { _StackAdminAppImplIncomplete } from "./admin-app-impl";
import { _StackClientAppImplIncomplete } from "./client-app-impl";
import { _StackServerAppImplIncomplete } from "./server-app-impl";
function complete() {
_StackClientAppImplIncomplete.LazyStackAdminAppImpl.value = _StackAdminAppImplIncomplete;
return {
_StackAdminAppImpl: scrambleDuringCompileTime(_StackAdminAppImplIncomplete),
_StackClientAppImpl: scrambleDuringCompileTime(_StackClientAppImplIncomplete),
_StackServerAppImpl: scrambleDuringCompileTime(_StackServerAppImplIncomplete)
};
}
var {
_StackAdminAppImpl,
_StackClientAppImpl,
_StackServerAppImpl
} = complete();
export {
_StackAdminAppImpl,
_StackClientAppImpl,
_StackServerAppImpl
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/lib/stack-app/apps/implementations/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\n\nimport { scrambleDuringCompileTime } from \"@stackframe/stack-shared/dist/utils/compile-time\";\nimport { _StackAdminAppImplIncomplete } from \"./admin-app-impl\";\nimport { _StackClientAppImplIncomplete } from \"./client-app-impl\";\nimport { _StackServerAppImplIncomplete } from \"./server-app-impl\";\n\n\n/**\n * Prevents a circular dependency between the client and admin apps. For more information, see the documentation comment\n * of `_StackClientAppImplIncomplete.LazyStackAdminAppImpl`.\n *\n * Note: This is an explicitly defined function that returns the new values (and not a barrel file with top-level side\n * effects) because we have `sideEffects: false` in the package.json, and so it would be tree-shaken away if we just\n * exported the values directly.\n */\nfunction complete() {\n _StackClientAppImplIncomplete.LazyStackAdminAppImpl.value = _StackAdminAppImplIncomplete;\n\n return {\n _StackAdminAppImpl: scrambleDuringCompileTime(_StackAdminAppImplIncomplete),\n _StackClientAppImpl: scrambleDuringCompileTime(_StackClientAppImplIncomplete),\n _StackServerAppImpl: scrambleDuringCompileTime(_StackServerAppImplIncomplete),\n };\n}\n\nexport const {\n _StackAdminAppImpl,\n _StackClientAppImpl,\n _StackServerAppImpl\n} = complete();\n\n"],"mappings":";AAKA,SAAS,iCAAiC;AAC1C,SAAS,oCAAoC;AAC7C,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAW9C,SAAS,WAAW;AAClB,gCAA8B,sBAAsB,QAAQ;AAE5D,SAAO;AAAA,IACL,oBAAoB,0BAA0B,4BAA4B;AAAA,IAC1E,qBAAqB,0BAA0B,6BAA6B;AAAA,IAC5E,qBAAqB,0BAA0B,6BAA6B;AAAA,EAC9E;AACF;AAEO,IAAM;AAAA,EACX;AAAA,EACA;AAAA,EACA;AACF,IAAI,SAAS;","names":[]}

View file

@ -0,0 +1,770 @@
// src/lib/stack-app/apps/implementations/server-app-impl.ts
import { KnownErrors, StackServerInterface } from "@stackframe/stack-shared";
import { StackAssertionError, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
import { runAsynchronously } from "@stackframe/stack-shared/dist/utils/promises";
import { suspend } from "@stackframe/stack-shared/dist/utils/react";
import { Result } from "@stackframe/stack-shared/dist/utils/results";
import { useMemo } from "react";
import { constructRedirectUrl } from "../../../../utils/url";
import { apiKeyCreationOptionsToCrud, apiKeyUpdateOptionsToCrud } from "../../api-keys";
import { serverContactChannelCreateOptionsToCrud, serverContactChannelUpdateOptionsToCrud } from "../../contact-channels";
import { serverTeamCreateOptionsToCrud, serverTeamUpdateOptionsToCrud } from "../../teams";
import { serverUserCreateOptionsToCrud, serverUserUpdateOptionsToCrud } from "../../users";
import { _StackClientAppImplIncomplete } from "./client-app-impl";
import { clientVersion, createCache, createCacheBySession, getBaseUrl, getDefaultProjectId, getDefaultPublishableClientKey, getDefaultSecretServerKey } from "./common";
import { useAsyncCache } from "./common";
var _StackServerAppImplIncomplete = class extends _StackClientAppImplIncomplete {
constructor(options) {
super("interface" in options ? {
interface: options.interface,
tokenStore: options.tokenStore,
urls: options.urls,
oauthScopesOnSignIn: options.oauthScopesOnSignIn
} : {
interface: new StackServerInterface({
getBaseUrl: () => getBaseUrl(options.baseUrl),
projectId: options.projectId ?? getDefaultProjectId(),
extraRequestHeaders: options.extraRequestHeaders ?? {},
clientVersion,
publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey()
}),
baseUrl: options.baseUrl,
extraRequestHeaders: options.extraRequestHeaders,
projectId: options.projectId,
publishableClientKey: options.publishableClientKey,
tokenStore: options.tokenStore,
urls: options.urls,
oauthScopesOnSignIn: options.oauthScopesOnSignIn,
redirectMethod: options.redirectMethod
});
// TODO override the client user cache to use the server user cache, so we save some requests
this._currentServerUserCache = createCacheBySession(async (session) => {
if (session.isKnownToBeInvalid()) {
return null;
}
return await this._interface.getServerUserByToken(session);
});
this._serverUsersCache = createCache(async ([cursor, limit, orderBy, desc, query]) => {
return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query });
});
this._serverUserCache = createCache(async ([userId]) => {
const user = await this._interface.getServerUserById(userId);
return Result.or(user, null);
});
this._serverTeamsCache = createCache(async ([userId]) => {
return await this._interface.listServerTeams({ userId });
});
this._serverTeamUserPermissionsCache = createCache(async ([teamId, userId, recursive]) => {
return await this._interface.listServerTeamPermissions({ teamId, userId, recursive }, null);
});
this._serverUserProjectPermissionsCache = createCache(async ([userId, recursive]) => {
return await this._interface.listServerProjectPermissions({ userId, recursive }, null);
});
this._serverUserOAuthConnectionAccessTokensCache = createCache(
async ([userId, providerId, scope]) => {
try {
const result = await this._interface.createServerProviderAccessToken(userId, providerId, scope || "");
return { accessToken: result.access_token };
} catch (err) {
if (!(KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(err) || KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(err))) {
throw err;
}
}
return null;
}
);
this._serverUserOAuthConnectionCache = createCache(
async ([userId, providerId, scope, redirect]) => {
return await this._getUserOAuthConnectionCacheFn({
getUser: async () => Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only")),
getOrWaitOAuthToken: async () => Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([userId, providerId, scope || ""], "write-only")),
useOAuthToken: () => useAsyncCache(this._serverUserOAuthConnectionAccessTokensCache, [userId, providerId, scope || ""], "user.useConnectedAccount()"),
providerId,
scope,
redirect,
session: null
});
}
);
this._serverTeamMemberProfilesCache = createCache(
async ([teamId]) => {
return await this._interface.listServerTeamMemberProfiles({ teamId });
}
);
this._serverTeamInvitationsCache = createCache(
async ([teamId]) => {
return await this._interface.listServerTeamInvitations({ teamId });
}
);
this._serverUserTeamProfileCache = createCache(
async ([teamId, userId]) => {
return await this._interface.getServerTeamMemberProfile({ teamId, userId });
}
);
this._serverContactChannelsCache = createCache(
async ([userId]) => {
return await this._interface.listServerContactChannels(userId);
}
);
this._serverUserApiKeysCache = createCache(
async ([userId]) => {
const result = await this._interface.listProjectApiKeys({
user_id: userId
}, null, "server");
return result;
}
);
this._serverTeamApiKeysCache = createCache(
async ([teamId]) => {
const result = await this._interface.listProjectApiKeys({
team_id: teamId
}, null, "server");
return result;
}
);
this._serverCheckApiKeyCache = createCache(async ([type, apiKey]) => {
const result = await this._interface.checkProjectApiKey(
type,
apiKey,
null,
"server"
);
return result;
});
}
async _updateServerUser(userId, update) {
const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));
await this._refreshUsers();
return result;
}
_serverEditableTeamProfileFromCrud(crud) {
const app = this;
return {
displayName: crud.display_name,
profileImageUrl: crud.profile_image_url,
async update(update) {
await app._interface.updateServerTeamMemberProfile({
teamId: crud.team_id,
userId: crud.user_id,
profile: {
display_name: update.displayName,
profile_image_url: update.profileImageUrl
}
});
await app._serverUserTeamProfileCache.refresh([crud.team_id, crud.user_id]);
}
};
}
_serverContactChannelFromCrud(userId, crud) {
const app = this;
return {
id: crud.id,
value: crud.value,
type: crud.type,
isVerified: crud.is_verified,
isPrimary: crud.is_primary,
usedForAuth: crud.used_for_auth,
async sendVerificationEmail(options) {
await app._interface.sendServerContactChannelVerificationEmail(userId, crud.id, options?.callbackUrl ?? constructRedirectUrl(app.urls.emailVerification, "callbackUrl"));
},
async update(data) {
await app._interface.updateServerContactChannel(userId, crud.id, serverContactChannelUpdateOptionsToCrud(data));
await Promise.all([
app._serverContactChannelsCache.refresh([userId]),
app._serverUserCache.refresh([userId])
]);
},
async delete() {
await app._interface.deleteServerContactChannel(userId, crud.id);
await Promise.all([
app._serverContactChannelsCache.refresh([userId]),
app._serverUserCache.refresh([userId])
]);
}
};
}
_serverApiKeyFromCrud(crud) {
return {
...this._baseApiKeyFromCrud(crud),
async revoke() {
await this.update({ revoked: true });
},
update: async (options) => {
await this._interface.updateProjectApiKey(
crud.type === "team" ? { team_id: crud.team_id } : { user_id: crud.user_id },
crud.id,
await apiKeyUpdateOptionsToCrud(crud.type, options),
null,
"server"
);
if (crud.type === "team") {
await this._serverTeamApiKeysCache.refresh([crud.team_id]);
} else {
await this._serverUserApiKeysCache.refresh([crud.user_id]);
}
}
};
}
_serverUserFromCrud(crud) {
const app = this;
async function getConnectedAccount(id, options) {
const scopeString = options?.scopes?.join(" ");
return Result.orThrow(await app._serverUserOAuthConnectionCache.getOrWait([crud.id, id, scopeString || "", options?.or === "redirect"], "write-only"));
}
function useConnectedAccount(id, options) {
const scopeString = options?.scopes?.join(" ");
return useAsyncCache(app._serverUserOAuthConnectionCache, [crud.id, id, scopeString || "", options?.or === "redirect"], "user.useConnectedAccount()");
}
return {
...super._createBaseUser(crud),
lastActiveAt: new Date(crud.last_active_at_millis),
serverMetadata: crud.server_metadata,
async setPrimaryEmail(email, options) {
await app._updateServerUser(crud.id, { primaryEmail: email, primaryEmailVerified: options?.verified });
},
async grantPermission(scopeOrPermissionId, permissionId) {
if (scopeOrPermissionId && typeof scopeOrPermissionId !== "string" && permissionId) {
const scope = scopeOrPermissionId;
await app._interface.grantServerTeamUserPermission(scope.id, crud.id, permissionId);
for (const recursive of [true, false]) {
await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
}
} else {
const pId = scopeOrPermissionId;
await app._interface.grantServerProjectPermission(crud.id, pId);
for (const recursive of [true, false]) {
await app._serverUserProjectPermissionsCache.refresh([crud.id, recursive]);
}
}
},
async revokePermission(scopeOrPermissionId, permissionId) {
if (scopeOrPermissionId && typeof scopeOrPermissionId !== "string" && permissionId) {
const scope = scopeOrPermissionId;
await app._interface.revokeServerTeamUserPermission(scope.id, crud.id, permissionId);
for (const recursive of [true, false]) {
await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
}
} else {
const pId = scopeOrPermissionId;
await app._interface.revokeServerProjectPermission(crud.id, pId);
for (const recursive of [true, false]) {
await app._serverUserProjectPermissionsCache.refresh([crud.id, recursive]);
}
}
},
async delete() {
const res = await app._interface.deleteServerUser(crud.id);
await app._refreshUsers();
return res;
},
async createSession(options) {
const tokens = await app._interface.createServerUserSession(crud.id, options.expiresInMillis ?? 1e3 * 60 * 60 * 24 * 365, options.isImpersonation ?? false);
return {
async getTokens() {
return tokens;
}
};
},
async getActiveSessions() {
const sessions = await app._interface.listServerSessions(crud.id);
return sessions.map((session) => app._clientSessionFromCrud(session));
},
async revokeSession(sessionId) {
await app._interface.deleteServerSession(sessionId);
},
async setDisplayName(displayName) {
return await this.update({ displayName });
},
async setClientMetadata(metadata) {
return await this.update({ clientMetadata: metadata });
},
async setClientReadOnlyMetadata(metadata) {
return await this.update({ clientReadOnlyMetadata: metadata });
},
async setServerMetadata(metadata) {
return await this.update({ serverMetadata: metadata });
},
async setSelectedTeam(team) {
return await this.update({ selectedTeamId: team?.id ?? null });
},
getConnectedAccount,
useConnectedAccount,
// THIS_LINE_PLATFORM react-like
selectedTeam: crud.selected_team ? app._serverTeamFromCrud(crud.selected_team) : null,
async getTeam(teamId) {
const teams = await this.listTeams();
return teams.find((t) => t.id === teamId) ?? null;
},
useTeam(teamId) {
const teams = this.useTeams();
return useMemo(() => {
return teams.find((t) => t.id === teamId) ?? null;
}, [teams, teamId]);
},
async listTeams() {
const teams = Result.orThrow(await app._serverTeamsCache.getOrWait([crud.id], "write-only"));
return teams.map((t) => app._serverTeamFromCrud(t));
},
useTeams() {
const teams = useAsyncCache(app._serverTeamsCache, [crud.id], "user.useTeams()");
return useMemo(() => teams.map((t) => app._serverTeamFromCrud(t)), [teams]);
},
createTeam: async (data) => {
const team = await app._interface.createServerTeam(serverTeamCreateOptionsToCrud({
creatorUserId: crud.id,
...data
}));
await app._serverTeamsCache.refresh([void 0]);
await app._updateServerUser(crud.id, { selectedTeamId: team.id });
return app._serverTeamFromCrud(team);
},
leaveTeam: async (team) => {
await app._interface.leaveServerTeam({ teamId: team.id, userId: crud.id });
},
async listPermissions(scopeOrOptions, options) {
if (scopeOrOptions && "id" in scopeOrOptions) {
const scope = scopeOrOptions;
const recursive = options?.recursive ?? true;
const permissions = Result.orThrow(await app._serverTeamUserPermissionsCache.getOrWait([scope.id, crud.id, recursive], "write-only"));
return permissions.map((crud2) => app._serverPermissionFromCrud(crud2));
} else {
const opts = scopeOrOptions;
const recursive = opts?.recursive ?? true;
const permissions = Result.orThrow(await app._serverUserProjectPermissionsCache.getOrWait([crud.id, recursive], "write-only"));
return permissions.map((crud2) => app._serverPermissionFromCrud(crud2));
}
},
usePermissions(scopeOrOptions, options) {
if (scopeOrOptions && "id" in scopeOrOptions) {
const scope = scopeOrOptions;
const recursive = options?.recursive ?? true;
const permissions = useAsyncCache(app._serverTeamUserPermissionsCache, [scope.id, crud.id, recursive], "user.usePermissions()");
return useMemo(() => permissions.map((crud2) => app._serverPermissionFromCrud(crud2)), [permissions]);
} else {
const opts = scopeOrOptions;
const recursive = opts?.recursive ?? true;
const permissions = useAsyncCache(app._serverUserProjectPermissionsCache, [crud.id, recursive], "user.usePermissions()");
return useMemo(() => permissions.map((crud2) => app._serverPermissionFromCrud(crud2)), [permissions]);
}
},
async getPermission(scopeOrPermissionId, permissionId) {
if (scopeOrPermissionId && typeof scopeOrPermissionId !== "string") {
const scope = scopeOrPermissionId;
const permissions = await this.listPermissions(scope);
return permissions.find((p) => p.id === permissionId) ?? null;
} else {
const pid = scopeOrPermissionId;
const permissions = await this.listPermissions();
return permissions.find((p) => p.id === pid) ?? null;
}
},
usePermission(scopeOrPermissionId, permissionId) {
if (scopeOrPermissionId && typeof scopeOrPermissionId !== "string") {
const scope = scopeOrPermissionId;
const permissions = this.usePermissions(scope);
return useMemo(() => permissions.find((p) => p.id === permissionId) ?? null, [permissions, permissionId]);
} else {
const pid = scopeOrPermissionId;
const permissions = this.usePermissions();
return useMemo(() => permissions.find((p) => p.id === pid) ?? null, [permissions, pid]);
}
},
async hasPermission(scopeOrPermissionId, permissionId) {
if (scopeOrPermissionId && typeof scopeOrPermissionId !== "string") {
const scope = scopeOrPermissionId;
return await this.getPermission(scope, permissionId) !== null;
} else {
const pid = scopeOrPermissionId;
return await this.getPermission(pid) !== null;
}
},
async update(update) {
await app._updateServerUser(crud.id, update);
},
async sendVerificationEmail() {
return await app._checkFeatureSupport("sendVerificationEmail() on ServerUser", {});
},
async updatePassword(options) {
const result = await app._interface.updatePassword(options);
await app._serverUserCache.refresh([crud.id]);
return result;
},
async setPassword(options) {
const result = await this.update(options);
await app._serverUserCache.refresh([crud.id]);
return result;
},
async getTeamProfile(team) {
const result = Result.orThrow(await app._serverUserTeamProfileCache.getOrWait([team.id, crud.id], "write-only"));
return app._serverEditableTeamProfileFromCrud(result);
},
useTeamProfile(team) {
const result = useAsyncCache(app._serverUserTeamProfileCache, [team.id, crud.id], "user.useTeamProfile()");
return useMemo(() => app._serverEditableTeamProfileFromCrud(result), [result]);
},
async listContactChannels() {
const result = Result.orThrow(await app._serverContactChannelsCache.getOrWait([crud.id], "write-only"));
return result.map((data) => app._serverContactChannelFromCrud(crud.id, data));
},
useContactChannels() {
const result = useAsyncCache(app._serverContactChannelsCache, [crud.id], "user.useContactChannels()");
return useMemo(() => result.map((data) => app._serverContactChannelFromCrud(crud.id, data)), [result]);
},
createContactChannel: async (data) => {
const contactChannel = await app._interface.createServerContactChannel(serverContactChannelCreateOptionsToCrud(crud.id, data));
await Promise.all([
app._serverContactChannelsCache.refresh([crud.id]),
app._serverUserCache.refresh([crud.id])
]);
return app._serverContactChannelFromCrud(crud.id, contactChannel);
},
useApiKeys() {
const result = useAsyncCache(app._serverUserApiKeysCache, [crud.id], "user.useApiKeys()");
return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));
},
async listApiKeys() {
const result = Result.orThrow(await app._serverUserApiKeysCache.getOrWait([crud.id], "write-only"));
return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));
},
async createApiKey(options) {
const result = await app._interface.createProjectApiKey(
await apiKeyCreationOptionsToCrud("user", crud.id, options),
null,
"server"
);
await app._serverUserApiKeysCache.refresh([crud.id]);
return app._serverApiKeyFromCrud(result);
}
};
}
_serverTeamUserFromCrud(crud) {
return {
...this._serverUserFromCrud(crud.user),
teamProfile: {
displayName: crud.display_name,
profileImageUrl: crud.profile_image_url
}
};
}
_serverTeamInvitationFromCrud(crud) {
return {
id: crud.id,
recipientEmail: crud.recipient_email,
expiresAt: new Date(crud.expires_at_millis),
revoke: async () => {
await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);
}
};
}
_currentUserFromCrud(crud, session) {
const app = this;
const currentUser = {
...this._serverUserFromCrud(crud),
...this._createAuth(session),
...this._isInternalProject() ? this._createInternalUserExtra(session) : {}
};
Object.freeze(currentUser);
return currentUser;
}
_serverTeamFromCrud(crud) {
const app = this;
return {
id: crud.id,
displayName: crud.display_name,
profileImageUrl: crud.profile_image_url,
createdAt: new Date(crud.created_at_millis),
clientMetadata: crud.client_metadata,
clientReadOnlyMetadata: crud.client_read_only_metadata,
serverMetadata: crud.server_metadata,
async update(update) {
await app._interface.updateServerTeam(crud.id, serverTeamUpdateOptionsToCrud(update));
await app._serverTeamsCache.refresh([void 0]);
},
async delete() {
await app._interface.deleteServerTeam(crud.id);
await app._serverTeamsCache.refresh([void 0]);
},
async listUsers() {
const result = Result.orThrow(await app._serverTeamMemberProfilesCache.getOrWait([crud.id], "write-only"));
return result.map((u) => app._serverTeamUserFromCrud(u));
},
useUsers() {
const result = useAsyncCache(app._serverTeamMemberProfilesCache, [crud.id], "team.useUsers()");
return useMemo(() => result.map((u) => app._serverTeamUserFromCrud(u)), [result]);
},
async addUser(userId) {
await app._interface.addServerUserToTeam({
teamId: crud.id,
userId
});
await app._serverTeamMemberProfilesCache.refresh([crud.id]);
},
async removeUser(userId) {
await app._interface.removeServerUserFromTeam({
teamId: crud.id,
userId
});
await app._serverTeamMemberProfilesCache.refresh([crud.id]);
},
async inviteUser(options) {
await app._interface.sendServerTeamInvitation({
teamId: crud.id,
email: options.email,
callbackUrl: options.callbackUrl ?? constructRedirectUrl(app.urls.teamInvitation, "callbackUrl")
});
await app._serverTeamInvitationsCache.refresh([crud.id]);
},
async listInvitations() {
const result = Result.orThrow(await app._serverTeamInvitationsCache.getOrWait([crud.id], "write-only"));
return result.map((crud2) => app._serverTeamInvitationFromCrud(crud2));
},
useInvitations() {
const result = useAsyncCache(app._serverTeamInvitationsCache, [crud.id], "team.useInvitations()");
return useMemo(() => result.map((crud2) => app._serverTeamInvitationFromCrud(crud2)), [result]);
},
useApiKeys() {
const result = useAsyncCache(app._serverTeamApiKeysCache, [crud.id], "team.useApiKeys()");
return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));
},
async listApiKeys() {
const result = Result.orThrow(await app._serverTeamApiKeysCache.getOrWait([crud.id], "write-only"));
return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));
},
async createApiKey(options) {
const result = await app._interface.createProjectApiKey(
await apiKeyCreationOptionsToCrud("team", crud.id, options),
null,
"server"
);
await app._serverTeamApiKeysCache.refresh([crud.id]);
return app._serverApiKeyFromCrud(result);
}
};
}
async _getUserApiKey(options) {
const crud = Result.orThrow(await this._serverCheckApiKeyCache.getOrWait(["user", options.apiKey], "write-only"));
return crud ? this._serverApiKeyFromCrud(crud) : null;
}
async _getTeamApiKey(options) {
const crud = Result.orThrow(await this._serverCheckApiKeyCache.getOrWait(["team", options.apiKey], "write-only"));
return crud ? this._serverApiKeyFromCrud(crud) : null;
}
_useUserApiKey(options) {
const crud = useAsyncCache(this._serverCheckApiKeyCache, ["user", options.apiKey], "useUserApiKey()");
return useMemo(() => crud ? this._serverApiKeyFromCrud(crud) : null, [crud]);
}
_useTeamApiKey(options) {
const crud = useAsyncCache(this._serverCheckApiKeyCache, ["team", options.apiKey], "useTeamApiKey()");
return useMemo(() => crud ? this._serverApiKeyFromCrud(crud) : null, [crud]);
}
async _getUserByApiKey(apiKey) {
const apiKeyObject = await this._getUserApiKey({ apiKey });
if (apiKeyObject === null) {
return null;
}
return await this.getServerUserById(apiKeyObject.userId);
}
_useUserByApiKey(apiKey) {
const apiKeyObject = this._useUserApiKey({ apiKey });
if (apiKeyObject === null) {
return null;
}
return this.useUserById(apiKeyObject.userId);
}
async _getTeamByApiKey(apiKey) {
const apiKeyObject = await this._getTeamApiKey({ apiKey });
if (apiKeyObject === null) {
return null;
}
return await this.getTeam(apiKeyObject.teamId);
}
_useTeamByApiKey(apiKey) {
const apiKeyObject = this._useTeamApiKey({ apiKey });
if (apiKeyObject === null) {
return null;
}
return this.useTeam(apiKeyObject.teamId);
}
async createUser(options) {
const crud = await this._interface.createServerUser(serverUserCreateOptionsToCrud(options));
await this._refreshUsers();
return this._serverUserFromCrud(crud);
}
async getUser(options) {
if (typeof options === "string") {
return await this.getServerUserById(options);
} else if (typeof options === "object" && "apiKey" in options) {
return await this._getUserByApiKey(options.apiKey);
} else {
this._ensurePersistentTokenStore(options?.tokenStore);
const session = await this._getSession(options?.tokenStore);
let crud = Result.orThrow(await this._currentServerUserCache.getOrWait([session], "write-only"));
if (crud?.is_anonymous && options?.or !== "anonymous" && options?.or !== "anonymous-if-exists") {
crud = null;
}
if (crud === null) {
switch (options?.or) {
case "redirect": {
await this.redirectToSignIn({ replace: true });
break;
}
case "throw": {
throw new Error("User is not signed in but getUser was called with { or: 'throw' }");
}
case "anonymous": {
const tokens = await this._signUpAnonymously();
return await this.getUser({ tokenStore: tokens, or: "anonymous-if-exists" }) ?? throwErr("Something went wrong while signing up anonymously");
}
case void 0:
case "anonymous-if-exists":
case "return-null": {
return null;
}
}
}
return crud && this._currentUserFromCrud(crud, session);
}
}
async getServerUser() {
console.warn("stackServerApp.getServerUser is deprecated; use stackServerApp.getUser instead");
return await this.getUser();
}
async getServerUserById(userId) {
const crud = Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only"));
return crud && this._serverUserFromCrud(crud);
}
useUser(options) {
if (typeof options === "string") {
return this.useUserById(options);
} else if (typeof options === "object" && "apiKey" in options) {
return this._useUserByApiKey(options.apiKey);
} else {
this._ensurePersistentTokenStore(options?.tokenStore);
const session = this._useSession(options?.tokenStore);
let crud = useAsyncCache(this._currentServerUserCache, [session], "useUser()");
if (crud?.is_anonymous && options?.or !== "anonymous" && options?.or !== "anonymous-if-exists") {
crud = null;
}
if (crud === null) {
switch (options?.or) {
case "redirect": {
runAsynchronously(this.redirectToSignIn({ replace: true }));
suspend();
throw new StackAssertionError("suspend should never return");
}
case "throw": {
throw new Error("User is not signed in but useUser was called with { or: 'throw' }");
}
case "anonymous": {
runAsynchronously(async () => {
await this._signUpAnonymously();
if (typeof window !== "undefined") {
window.location.reload();
}
});
suspend();
throw new StackAssertionError("suspend should never return");
}
case void 0:
case "anonymous-if-exists":
case "return-null": {
}
}
}
return useMemo(() => {
return crud && this._currentUserFromCrud(crud, session);
}, [crud, session, options?.or]);
}
}
useUserById(userId) {
const crud = useAsyncCache(this._serverUserCache, [userId], "useUserById()");
return useMemo(() => {
return crud && this._serverUserFromCrud(crud);
}, [crud]);
}
async listUsers(options) {
const crud = Result.orThrow(await this._serverUsersCache.getOrWait([options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "write-only"));
const result = crud.items.map((j) => this._serverUserFromCrud(j));
result.nextCursor = crud.pagination?.next_cursor ?? null;
return result;
}
useUsers(options) {
const crud = useAsyncCache(this._serverUsersCache, [options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "useServerUsers()");
const result = crud.items.map((j) => this._serverUserFromCrud(j));
result.nextCursor = crud.pagination?.next_cursor ?? null;
return result;
}
_serverPermissionFromCrud(crud) {
return {
id: crud.id
};
}
_serverTeamPermissionDefinitionFromCrud(crud) {
return {
id: crud.id,
description: crud.description,
containedPermissionIds: crud.contained_permission_ids
};
}
_serverProjectPermissionDefinitionFromCrud(crud) {
return {
id: crud.id,
description: crud.description,
containedPermissionIds: crud.contained_permission_ids
};
}
async listTeams() {
const teams = Result.orThrow(await this._serverTeamsCache.getOrWait([void 0], "write-only"));
return teams.map((t) => this._serverTeamFromCrud(t));
}
async createTeam(data) {
const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));
await this._serverTeamsCache.refresh([void 0]);
return this._serverTeamFromCrud(team);
}
useTeams() {
const teams = useAsyncCache(this._serverTeamsCache, [void 0], "useServerTeams()");
return useMemo(() => {
return teams.map((t) => this._serverTeamFromCrud(t));
}, [teams]);
}
async getTeam(options) {
if (typeof options === "object" && "apiKey" in options) {
return await this._getTeamByApiKey(options.apiKey);
} else {
const teamId = options;
const teams = await this.listTeams();
return teams.find((t) => t.id === teamId) ?? null;
}
}
useTeam(options) {
if (typeof options === "object" && "apiKey" in options) {
return this._useTeamByApiKey(options.apiKey);
} else {
const teamId = options;
const teams = this.useTeams();
return useMemo(() => {
return teams.find((t) => t.id === teamId) ?? null;
}, [teams, teamId]);
}
}
async _refreshSession(session) {
await Promise.all([
super._refreshUser(session),
this._currentServerUserCache.refresh([session])
]);
}
async _refreshUsers() {
await Promise.all([
super._refreshUsers(),
this._serverUserCache.refreshWhere(() => true),
this._serverUsersCache.refreshWhere(() => true),
this._serverContactChannelsCache.refreshWhere(() => true)
]);
}
};
export {
_StackServerAppImplIncomplete
};
//# sourceMappingURL=server-app-impl.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,16 @@
// src/lib/stack-app/apps/index.ts
import {
StackClientApp
} from "./interfaces/client-app";
import {
StackServerApp
} from "./interfaces/server-app";
import {
StackAdminApp
} from "./interfaces/admin-app";
export {
StackAdminApp,
StackClientApp,
StackServerApp
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/lib/stack-app/apps/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nexport {\n StackClientApp\n} from \"./interfaces/client-app\";\nexport type {\n StackClientAppConstructor,\n StackClientAppConstructorOptions,\n StackClientAppJson\n} from \"./interfaces/client-app\";\n\nexport {\n StackServerApp\n} from \"./interfaces/server-app\";\nexport type {\n StackServerAppConstructor,\n StackServerAppConstructorOptions\n} from \"./interfaces/server-app\";\n\nexport {\n StackAdminApp\n} from \"./interfaces/admin-app\";\nexport type {\n StackAdminAppConstructor,\n StackAdminAppConstructorOptions\n} from \"./interfaces/admin-app\";\n\n"],"mappings":";AAIA;AAAA,EACE;AAAA,OACK;AAOP;AAAA,EACE;AAAA,OACK;AAMP;AAAA,EACE;AAAA,OACK;","names":[]}

View file

@ -0,0 +1,7 @@
// src/lib/stack-app/apps/interfaces/admin-app.ts
import { _StackAdminAppImpl } from "../implementations";
var StackAdminApp = _StackAdminAppImpl;
export {
StackAdminApp
};
//# sourceMappingURL=admin-app.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/lib/stack-app/apps/interfaces/admin-app.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { EmailTemplateType } from \"@stackframe/stack-shared/dist/interface/crud/email-templates\";\nimport { InternalSession } from \"@stackframe/stack-shared/dist/sessions\";\nimport { Result } from \"@stackframe/stack-shared/dist/utils/results\";\nimport { AsyncStoreProperty, EmailConfig } from \"../../common\";\nimport { AdminSentEmail } from \"../../email\";\nimport { AdminEmailTemplate, AdminEmailTemplateUpdateOptions } from \"../../email-templates\";\nimport { InternalApiKey, InternalApiKeyCreateOptions, InternalApiKeyFirstView } from \"../../internal-api-keys\";\nimport { AdminProjectPermission, AdminProjectPermissionDefinition, AdminProjectPermissionDefinitionCreateOptions, AdminProjectPermissionDefinitionUpdateOptions, AdminTeamPermission, AdminTeamPermissionDefinition, AdminTeamPermissionDefinitionCreateOptions, AdminTeamPermissionDefinitionUpdateOptions } from \"../../permissions\";\nimport { AdminProject } from \"../../projects\";\nimport { _StackAdminAppImpl } from \"../implementations\";\nimport { StackServerApp, StackServerAppConstructorOptions } from \"./server-app\";\n\n\nexport type StackAdminAppConstructorOptions<HasTokenStore extends boolean, ProjectId extends string> = (\n | (\n & StackServerAppConstructorOptions<HasTokenStore, ProjectId>\n & {\n superSecretAdminKey?: string,\n }\n )\n | (\n & Omit<StackServerAppConstructorOptions<HasTokenStore, ProjectId>, \"publishableClientKey\" | \"secretServerKey\">\n & {\n projectOwnerSession: InternalSession,\n }\n )\n);\n\n\nexport type StackAdminApp<HasTokenStore extends boolean = boolean, ProjectId extends string = string> = (\n & AsyncStoreProperty<\"project\", [], AdminProject, false>\n & AsyncStoreProperty<\"internalApiKeys\", [], InternalApiKey[], true>\n & AsyncStoreProperty<\"teamPermissionDefinitions\", [], AdminTeamPermissionDefinition[], true>\n & AsyncStoreProperty<\"projectPermissionDefinitions\", [], AdminProjectPermissionDefinition[], true>\n & {\n useEmailTemplates(): AdminEmailTemplate[], // THIS_LINE_PLATFORM react-like\n listEmailTemplates(): Promise<AdminEmailTemplate[]>,\n updateEmailTemplate(type: EmailTemplateType, data: AdminEmailTemplateUpdateOptions): Promise<void>,\n resetEmailTemplate(type: EmailTemplateType): Promise<void>,\n\n createInternalApiKey(options: InternalApiKeyCreateOptions): Promise<InternalApiKeyFirstView>,\n\n createTeamPermissionDefinition(data: AdminTeamPermissionDefinitionCreateOptions): Promise<AdminTeamPermission>,\n updateTeamPermissionDefinition(permissionId: string, data: AdminTeamPermissionDefinitionUpdateOptions): Promise<void>,\n deleteTeamPermissionDefinition(permissionId: string): Promise<void>,\n\n createProjectPermissionDefinition(data: AdminProjectPermissionDefinitionCreateOptions): Promise<AdminProjectPermission>,\n updateProjectPermissionDefinition(permissionId: string, data: AdminProjectPermissionDefinitionUpdateOptions): Promise<void>,\n deleteProjectPermissionDefinition(permissionId: string): Promise<void>,\n\n useSvixToken(): string, // THIS_LINE_PLATFORM react-like\n\n sendTestEmail(options: {\n recipientEmail: string,\n emailConfig: EmailConfig,\n }): Promise<Result<undefined, { errorMessage: string }>>,\n\n listSentEmails(): Promise<AdminSentEmail[]>,\n }\n & StackServerApp<HasTokenStore, ProjectId>\n);\nexport type StackAdminAppConstructor = {\n new <\n HasTokenStore extends boolean,\n ProjectId extends string\n >(options: StackAdminAppConstructorOptions<HasTokenStore, ProjectId>): StackAdminApp<HasTokenStore, ProjectId>,\n new (options: StackAdminAppConstructorOptions<boolean, string>): StackAdminApp<boolean, string>,\n};\nexport const StackAdminApp: StackAdminAppConstructor = _StackAdminAppImpl;\n"],"mappings":";AAaA,SAAS,0BAA0B;AA2D5B,IAAM,gBAA0C;","names":[]}

View file

@ -0,0 +1,7 @@
// src/lib/stack-app/apps/interfaces/client-app.ts
import { _StackClientAppImpl } from "../implementations";
var StackClientApp = _StackClientAppImpl;
export {
StackClientApp
};
//# sourceMappingURL=client-app.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,7 @@
// src/lib/stack-app/apps/interfaces/server-app.ts
import { _StackServerAppImpl } from "../implementations";
var StackServerApp = _StackServerAppImpl;
export {
StackServerApp
};
//# sourceMappingURL=server-app.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/lib/stack-app/apps/interfaces/server-app.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { AsyncStoreProperty, GetUserOptions } from \"../../common\";\nimport { ServerListUsersOptions, ServerTeam, ServerTeamCreateOptions } from \"../../teams\";\nimport { ProjectCurrentServerUser, ServerUser, ServerUserCreateOptions } from \"../../users\";\nimport { _StackServerAppImpl } from \"../implementations\";\nimport { StackClientApp, StackClientAppConstructorOptions } from \"./client-app\";\n\n\nexport type StackServerAppConstructorOptions<HasTokenStore extends boolean, ProjectId extends string> = StackClientAppConstructorOptions<HasTokenStore, ProjectId> & {\n secretServerKey?: string,\n};\n\nexport type StackServerApp<HasTokenStore extends boolean = boolean, ProjectId extends string = string> = (\n & {\n createTeam(data: ServerTeamCreateOptions): Promise<ServerTeam>,\n /**\n * @deprecated use `getUser()` instead\n */\n getServerUser(): Promise<ProjectCurrentServerUser<ProjectId> | null>,\n\n createUser(options: ServerUserCreateOptions): Promise<ServerUser>,\n\n useUser(options: GetUserOptions<HasTokenStore> & { or: 'redirect' }): ProjectCurrentServerUser<ProjectId>,\n useUser(options: GetUserOptions<HasTokenStore> & { or: 'throw' }): ProjectCurrentServerUser<ProjectId>,\n useUser(options: GetUserOptions<HasTokenStore> & { or: 'anonymous' }): ProjectCurrentServerUser<ProjectId>,\n useUser(options?: GetUserOptions<HasTokenStore>): ProjectCurrentServerUser<ProjectId> | null,\n useUser(id: string): ServerUser | null,\n useUser(options: { apiKey: string }): ServerUser | null,\n\n getUser(options: GetUserOptions<HasTokenStore> & { or: 'redirect' }): Promise<ProjectCurrentServerUser<ProjectId>>,\n getUser(options: GetUserOptions<HasTokenStore> & { or: 'throw' }): Promise<ProjectCurrentServerUser<ProjectId>>,\n getUser(options: GetUserOptions<HasTokenStore> & { or: 'anonymous' }): Promise<ProjectCurrentServerUser<ProjectId>>,\n getUser(options?: GetUserOptions<HasTokenStore>): Promise<ProjectCurrentServerUser<ProjectId> | null>,\n getUser(id: string): Promise<ServerUser | null>,\n getUser(options: { apiKey: string }): Promise<ServerUser | null>,\n\n useTeam(id: string): ServerTeam | null,\n useTeam(options: { apiKey: string }): ServerTeam | null,\n\n getTeam(id: string): Promise<ServerTeam | null>,\n getTeam(options: { apiKey: string }): Promise<ServerTeam | null>,\n\n\n useUsers(options?: ServerListUsersOptions): ServerUser[] & { nextCursor: string | null }, // THIS_LINE_PLATFORM react-like\n listUsers(options?: ServerListUsersOptions): Promise<ServerUser[] & { nextCursor: string | null }>,\n }\n & AsyncStoreProperty<\"user\", [id: string], ServerUser | null, false>\n & Omit<AsyncStoreProperty<\"users\", [], ServerUser[], true>, \"listUsers\" | \"useUsers\">\n & AsyncStoreProperty<\"teams\", [], ServerTeam[], true>\n & StackClientApp<HasTokenStore, ProjectId>\n);\nexport type StackServerAppConstructor = {\n new <\n TokenStoreType extends string,\n HasTokenStore extends (TokenStoreType extends {} ? true : boolean),\n ProjectId extends string\n >(options: StackServerAppConstructorOptions<HasTokenStore, ProjectId>): StackServerApp<HasTokenStore, ProjectId>,\n new (options: StackServerAppConstructorOptions<boolean, string>): StackServerApp<boolean, string>,\n};\nexport const StackServerApp: StackServerAppConstructor = _StackServerAppImpl;\n"],"mappings":";AAOA,SAAS,2BAA2B;AAuD7B,IAAM,iBAA4C;","names":[]}

View file

@ -0,0 +1,6 @@
// src/lib/stack-app/common.ts
var stackAppInternalsSymbol = Symbol.for("StackAuth--DO-NOT-USE-OR-YOU-WILL-BE-FIRED--StackAppInternals");
export {
stackAppInternalsSymbol
};
//# sourceMappingURL=common.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/stack-app/common.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { ProviderType } from \"@stackframe/stack-shared/dist/utils/oauth\";\n\nexport type RedirectToOptions = {\n replace?: boolean,\n noRedirectBack?: boolean,\n};\n\nexport type AsyncStoreProperty<Name extends string, Args extends any[], Value, IsMultiple extends boolean> =\n & { [key in `${IsMultiple extends true ? \"list\" : \"get\"}${Capitalize<Name>}`]: (...args: Args) => Promise<Value> }\n & { [key in `use${Capitalize<Name>}`]: (...args: Args) => Value } // THIS_LINE_PLATFORM react-like\n\nexport type EmailConfig = {\n host: string,\n port: number,\n username: string,\n password: string,\n senderEmail: string,\n senderName: string,\n}\n\nexport type RedirectMethod = \"window\"\n | \"none\"\n | {\n useNavigate: () => (to: string) => void,\n navigate?: (to: string) => void,\n }\n\n\nexport type GetUserOptions<HasTokenStore> =\n & {\n or?: 'redirect' | 'throw' | 'return-null' | 'anonymous' | 'anonymous-if-exists',\n tokenStore?: TokenStoreInit,\n }\n & (HasTokenStore extends false ? {\n tokenStore: TokenStoreInit,\n } : {});\n\nexport type RequestLike = {\n headers: {\n get: (name: string) => string | null,\n },\n};\n\nexport type TokenStoreInit<HasTokenStore extends boolean = boolean> =\n HasTokenStore extends true ? (\n | \"cookie\"\n | \"nextjs-cookie\"\n | \"memory\"\n | RequestLike\n | { accessToken: string, refreshToken: string }\n )\n : HasTokenStore extends false ? null\n : TokenStoreInit<true> | TokenStoreInit<false>;\n\nexport type HandlerUrls = {\n handler: string,\n signIn: string,\n signUp: string,\n afterSignIn: string,\n afterSignUp: string,\n signOut: string,\n afterSignOut: string,\n emailVerification: string,\n passwordReset: string,\n forgotPassword: string,\n home: string,\n oauthCallback: string,\n magicLinkCallback: string,\n accountSettings: string,\n teamInvitation: string,\n error: string,\n}\n\nexport type OAuthScopesOnSignIn = {\n [key in ProviderType]: string[];\n};\n\n/** @internal */\nexport const stackAppInternalsSymbol = Symbol.for(\"StackAuth--DO-NOT-USE-OR-YOU-WILL-BE-FIRED--StackAppInternals\");\n"],"mappings":";AAkFO,IAAM,0BAA0B,OAAO,IAAI,+DAA+D;","names":[]}

View file

@ -0,0 +1 @@
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View file

@ -0,0 +1,42 @@
// src/lib/stack-app/contact-channels/index.ts
function contactChannelCreateOptionsToCrud(userId, options) {
return {
value: options.value,
type: options.type,
used_for_auth: options.usedForAuth,
is_primary: options.isPrimary,
user_id: userId
};
}
function contactChannelUpdateOptionsToCrud(options) {
return {
value: options.value,
used_for_auth: options.usedForAuth,
is_primary: options.isPrimary
};
}
function serverContactChannelUpdateOptionsToCrud(options) {
return {
value: options.value,
is_verified: options.isVerified,
used_for_auth: options.usedForAuth,
is_primary: options.isPrimary
};
}
function serverContactChannelCreateOptionsToCrud(userId, options) {
return {
type: options.type,
value: options.value,
is_verified: options.isVerified,
user_id: userId,
used_for_auth: options.usedForAuth,
is_primary: options.isPrimary
};
}
export {
contactChannelCreateOptionsToCrud,
contactChannelUpdateOptionsToCrud,
serverContactChannelCreateOptionsToCrud,
serverContactChannelUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/lib/stack-app/contact-channels/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { ContactChannelsCrud } from \"@stackframe/stack-shared/dist/interface/crud/contact-channels\";\n\n\nexport type ContactChannel = {\n id: string,\n value: string,\n type: 'email',\n isPrimary: boolean,\n isVerified: boolean,\n usedForAuth: boolean,\n\n sendVerificationEmail(): Promise<void>,\n update(data: ContactChannelUpdateOptions): Promise<void>,\n delete(): Promise<void>,\n}\n\nexport type ContactChannelCreateOptions = {\n value: string,\n type: 'email',\n usedForAuth: boolean,\n isPrimary?: boolean,\n}\n\nexport function contactChannelCreateOptionsToCrud(userId: string, options: ContactChannelCreateOptions): ContactChannelsCrud[\"Client\"][\"Create\"] {\n return {\n value: options.value,\n type: options.type,\n used_for_auth: options.usedForAuth,\n is_primary: options.isPrimary,\n user_id: userId,\n };\n}\n\nexport type ContactChannelUpdateOptions = {\n usedForAuth?: boolean,\n value?: string,\n isPrimary?: boolean,\n}\n\nexport function contactChannelUpdateOptionsToCrud(options: ContactChannelUpdateOptions): ContactChannelsCrud[\"Client\"][\"Update\"] {\n return {\n value: options.value,\n used_for_auth: options.usedForAuth,\n is_primary: options.isPrimary,\n };\n}\n\nexport type ServerContactChannel = ContactChannel & {\n update(data: ServerContactChannelUpdateOptions): Promise<void>,\n}\nexport type ServerContactChannelUpdateOptions = ContactChannelUpdateOptions & {\n isVerified?: boolean,\n}\n\nexport function serverContactChannelUpdateOptionsToCrud(options: ServerContactChannelUpdateOptions): ContactChannelsCrud[\"Server\"][\"Update\"] {\n return {\n value: options.value,\n is_verified: options.isVerified,\n used_for_auth: options.usedForAuth,\n is_primary: options.isPrimary,\n };\n}\n\nexport type ServerContactChannelCreateOptions = ContactChannelCreateOptions & {\n isVerified?: boolean,\n}\nexport function serverContactChannelCreateOptionsToCrud(userId: string, options: ServerContactChannelCreateOptions): ContactChannelsCrud[\"Server\"][\"Create\"] {\n return {\n type: options.type,\n value: options.value,\n is_verified: options.isVerified,\n user_id: userId,\n used_for_auth: options.usedForAuth,\n is_primary: options.isPrimary,\n };\n}\n"],"mappings":";AA2BO,SAAS,kCAAkC,QAAgB,SAA+E;AAC/I,SAAO;AAAA,IACL,OAAO,QAAQ;AAAA,IACf,MAAM,QAAQ;AAAA,IACd,eAAe,QAAQ;AAAA,IACvB,YAAY,QAAQ;AAAA,IACpB,SAAS;AAAA,EACX;AACF;AAQO,SAAS,kCAAkC,SAA+E;AAC/H,SAAO;AAAA,IACL,OAAO,QAAQ;AAAA,IACf,eAAe,QAAQ;AAAA,IACvB,YAAY,QAAQ;AAAA,EACtB;AACF;AASO,SAAS,wCAAwC,SAAqF;AAC3I,SAAO;AAAA,IACL,OAAO,QAAQ;AAAA,IACf,aAAa,QAAQ;AAAA,IACrB,eAAe,QAAQ;AAAA,IACvB,YAAY,QAAQ;AAAA,EACtB;AACF;AAKO,SAAS,wCAAwC,QAAgB,SAAqF;AAC3J,SAAO;AAAA,IACL,MAAM,QAAQ;AAAA,IACd,OAAO,QAAQ;AAAA,IACf,aAAa,QAAQ;AAAA,IACrB,SAAS;AAAA,IACT,eAAe,QAAQ;AAAA,IACvB,YAAY,QAAQ;AAAA,EACtB;AACF;","names":[]}

View file

@ -0,0 +1,11 @@
// src/lib/stack-app/email-templates/index.ts
function adminEmailTemplateUpdateOptionsToCrud(options) {
return {
subject: options.subject,
content: options.content
};
}
export {
adminEmailTemplateUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/lib/stack-app/email-templates/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { EmailTemplateCrud, EmailTemplateType } from \"@stackframe/stack-shared/dist/interface/crud/email-templates\";\n\n\nexport type AdminEmailTemplate = {\n type: EmailTemplateType,\n subject: string,\n content: any,\n isDefault: boolean,\n}\n\nexport type AdminEmailTemplateUpdateOptions = {\n subject?: string,\n content?: any,\n};\nexport function adminEmailTemplateUpdateOptionsToCrud(options: AdminEmailTemplateUpdateOptions): EmailTemplateCrud['Admin']['Update'] {\n return {\n subject: options.subject,\n content: options.content,\n };\n}\n"],"mappings":";AAkBO,SAAS,sCAAsC,SAAgF;AACpI,SAAO;AAAA,IACL,SAAS,QAAQ;AAAA,IACjB,SAAS,QAAQ;AAAA,EACnB;AACF;","names":[]}

View file

@ -0,0 +1 @@
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View file

@ -0,0 +1,16 @@
// src/lib/stack-app/index.ts
import {
StackAdminApp,
StackClientApp,
StackServerApp
} from "./apps";
import {
stackAppInternalsSymbol
} from "./common";
export {
StackAdminApp,
StackClientApp,
StackServerApp,
stackAppInternalsSymbol
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/stack-app/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nexport {\n StackAdminApp, StackClientApp,\n StackServerApp\n} from \"./apps\";\nexport type {\n StackAdminAppConstructor,\n StackAdminAppConstructorOptions,\n StackClientAppConstructor,\n StackClientAppConstructorOptions,\n StackClientAppJson,\n StackServerAppConstructor,\n StackServerAppConstructorOptions\n} from \"./apps\";\n\nexport type {\n ProjectConfig\n} from \"./project-configs\";\n\nexport type {\n InternalApiKey,\n InternalApiKeyBase,\n InternalApiKeyBaseCrudRead,\n InternalApiKeyCreateOptions,\n InternalApiKeyFirstView\n} from \"./internal-api-keys\";\n\nexport {\n stackAppInternalsSymbol\n} from \"./common\";\nexport type {\n GetUserOptions,\n HandlerUrls,\n OAuthScopesOnSignIn\n} from \"./common\";\n\nexport type {\n Connection,\n OAuthConnection\n} from \"./connected-accounts\";\n\nexport type {\n ContactChannel,\n ServerContactChannel\n} from \"./contact-channels\";\n\nexport type {\n AdminSentEmail\n} from \"./email\";\n\nexport type {\n AdminTeamPermission,\n AdminTeamPermissionDefinition,\n AdminTeamPermissionDefinitionCreateOptions,\n AdminTeamPermissionDefinitionUpdateOptions,\n AdminProjectPermission,\n AdminProjectPermissionDefinition,\n AdminProjectPermissionDefinitionCreateOptions,\n AdminProjectPermissionDefinitionUpdateOptions,\n} from \"./permissions\";\n\nexport type {\n AdminDomainConfig,\n AdminEmailConfig,\n AdminOAuthProviderConfig,\n AdminProjectConfig,\n AdminProjectConfigUpdateOptions,\n OAuthProviderConfig\n} from \"./project-configs\";\n\nexport type {\n AdminOwnedProject,\n AdminProject,\n AdminProjectCreateOptions,\n AdminProjectUpdateOptions,\n Project\n} from \"./projects\";\n\nexport type {\n EditableTeamMemberProfile,\n ServerListUsersOptions,\n ServerTeam,\n ServerTeamCreateOptions,\n ServerTeamMemberProfile,\n ServerTeamUpdateOptions,\n ServerTeamUser,\n Team,\n TeamCreateOptions,\n TeamInvitation,\n TeamMemberProfile,\n TeamUpdateOptions,\n TeamUser\n} from \"./teams\";\n\nexport type {\n Auth,\n CurrentInternalServerUser,\n CurrentInternalUser,\n CurrentServerUser,\n CurrentUser,\n ServerUser,\n Session,\n User\n} from \"./users\";\n\n"],"mappings":";AAIA;AAAA,EACE;AAAA,EAAe;AAAA,EACf;AAAA,OACK;AAuBP;AAAA,EACE;AAAA,OACK;","names":[]}

View file

@ -0,0 +1,14 @@
// src/lib/stack-app/internal-api-keys/index.ts
function internalApiKeyCreateOptionsToCrud(options) {
return {
description: options.description,
expires_at_millis: options.expiresAt.getTime(),
has_publishable_client_key: options.hasPublishableClientKey,
has_secret_server_key: options.hasSecretServerKey,
has_super_secret_admin_key: options.hasSuperSecretAdminKey
};
}
export {
internalApiKeyCreateOptionsToCrud
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/lib/stack-app/internal-api-keys/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { InternalApiKeyCreateCrudRequest } from \"@stackframe/stack-shared/dist/interface/adminInterface\";\nimport { InternalApiKeysCrud } from \"@stackframe/stack-shared/dist/interface/crud/internal-api-keys\";\n\nexport type InternalApiKeyBase = {\n id: string,\n description: string,\n expiresAt: Date,\n manuallyRevokedAt: Date | null,\n createdAt: Date,\n isValid(): boolean,\n whyInvalid(): \"expired\" | \"manually-revoked\" | null,\n revoke(): Promise<void>,\n};\n\nexport type InternalApiKeyBaseCrudRead = Pick<InternalApiKeysCrud[\"Admin\"][\"Read\"], \"id\" | \"created_at_millis\" | \"description\" | \"expires_at_millis\" | \"manually_revoked_at_millis\">;\n\nexport type InternalApiKeyFirstView = {\n publishableClientKey?: string,\n secretServerKey?: string,\n superSecretAdminKey?: string,\n} & InternalApiKeyBase;\n\nexport type InternalApiKey = {\n publishableClientKey: null | {\n lastFour: string,\n },\n secretServerKey: null | {\n lastFour: string,\n },\n superSecretAdminKey: null | {\n lastFour: string,\n },\n} & InternalApiKeyBase;\n\nexport type InternalApiKeyCreateOptions = {\n description: string,\n expiresAt: Date,\n hasPublishableClientKey: boolean,\n hasSecretServerKey: boolean,\n hasSuperSecretAdminKey: boolean,\n};\nexport function internalApiKeyCreateOptionsToCrud(options: InternalApiKeyCreateOptions): InternalApiKeyCreateCrudRequest {\n return {\n description: options.description,\n expires_at_millis: options.expiresAt.getTime(),\n has_publishable_client_key: options.hasPublishableClientKey,\n has_secret_server_key: options.hasSecretServerKey,\n has_super_secret_admin_key: options.hasSuperSecretAdminKey,\n };\n}\n"],"mappings":";AA6CO,SAAS,kCAAkC,SAAuE;AACvH,SAAO;AAAA,IACL,aAAa,QAAQ;AAAA,IACrB,mBAAmB,QAAQ,UAAU,QAAQ;AAAA,IAC7C,4BAA4B,QAAQ;AAAA,IACpC,uBAAuB,QAAQ;AAAA,IAC/B,4BAA4B,QAAQ;AAAA,EACtC;AACF;","names":[]}

View file

@ -0,0 +1,34 @@
// src/lib/stack-app/permissions/index.ts
function adminTeamPermissionDefinitionCreateOptionsToCrud(options) {
return {
id: options.id,
description: options.description,
contained_permission_ids: options.containedPermissionIds
};
}
function adminTeamPermissionDefinitionUpdateOptionsToCrud(options) {
return {
description: options.description,
contained_permission_ids: options.containedPermissionIds
};
}
function adminProjectPermissionDefinitionCreateOptionsToCrud(options) {
return {
id: options.id,
description: options.description,
contained_permission_ids: options.containedPermissionIds
};
}
function adminProjectPermissionDefinitionUpdateOptionsToCrud(options) {
return {
description: options.description,
contained_permission_ids: options.containedPermissionIds
};
}
export {
adminProjectPermissionDefinitionCreateOptionsToCrud,
adminProjectPermissionDefinitionUpdateOptionsToCrud,
adminTeamPermissionDefinitionCreateOptionsToCrud,
adminTeamPermissionDefinitionUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/lib/stack-app/permissions/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { ProjectPermissionDefinitionsCrud } from \"@stackframe/stack-shared/dist/interface/crud/project-permissions\";\nimport { TeamPermissionDefinitionsCrud } from \"@stackframe/stack-shared/dist/interface/crud/team-permissions\";\n\n\nexport type TeamPermission = {\n id: string,\n};\n\nexport type AdminTeamPermission = TeamPermission;\n\nexport type AdminTeamPermissionDefinition = {\n id: string,\n description?: string,\n containedPermissionIds: string[],\n isDefaultUserPermission?: boolean,\n};\n\nexport type AdminTeamPermissionDefinitionCreateOptions = {\n id: string,\n description?: string,\n containedPermissionIds: string[],\n isDefaultUserPermission?: boolean,\n};\nexport function adminTeamPermissionDefinitionCreateOptionsToCrud(options: AdminTeamPermissionDefinitionCreateOptions): TeamPermissionDefinitionsCrud[\"Admin\"][\"Create\"] {\n return {\n id: options.id,\n description: options.description,\n contained_permission_ids: options.containedPermissionIds,\n };\n}\n\nexport type AdminTeamPermissionDefinitionUpdateOptions = Pick<Partial<AdminTeamPermissionDefinitionCreateOptions>, \"description\" | \"containedPermissionIds\">;\nexport function adminTeamPermissionDefinitionUpdateOptionsToCrud(options: AdminTeamPermissionDefinitionUpdateOptions): TeamPermissionDefinitionsCrud[\"Admin\"][\"Update\"] {\n return {\n description: options.description,\n contained_permission_ids: options.containedPermissionIds,\n };\n}\n\nexport type ProjectPermission = {\n id: string,\n};\n\nexport type AdminProjectPermission = ProjectPermission;\n\nexport type AdminProjectPermissionDefinition = {\n id: string,\n description?: string,\n containedPermissionIds: string[],\n};\n\nexport type AdminProjectPermissionDefinitionCreateOptions = {\n id: string,\n description?: string,\n containedPermissionIds: string[],\n};\nexport function adminProjectPermissionDefinitionCreateOptionsToCrud(options: AdminProjectPermissionDefinitionCreateOptions): ProjectPermissionDefinitionsCrud[\"Admin\"][\"Create\"] {\n return {\n id: options.id,\n description: options.description,\n contained_permission_ids: options.containedPermissionIds,\n };\n}\n\nexport type AdminProjectPermissionDefinitionUpdateOptions = Pick<Partial<AdminProjectPermissionDefinitionCreateOptions>, \"description\" | \"containedPermissionIds\">;\nexport function adminProjectPermissionDefinitionUpdateOptionsToCrud(options: AdminProjectPermissionDefinitionUpdateOptions): ProjectPermissionDefinitionsCrud[\"Admin\"][\"Update\"] {\n return {\n description: options.description,\n contained_permission_ids: options.containedPermissionIds,\n };\n}\n"],"mappings":";AA2BO,SAAS,iDAAiD,SAAuG;AACtK,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,aAAa,QAAQ;AAAA,IACrB,0BAA0B,QAAQ;AAAA,EACpC;AACF;AAGO,SAAS,iDAAiD,SAAuG;AACtK,SAAO;AAAA,IACL,aAAa,QAAQ;AAAA,IACrB,0BAA0B,QAAQ;AAAA,EACpC;AACF;AAmBO,SAAS,oDAAoD,SAA6G;AAC/K,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,aAAa,QAAQ;AAAA,IACrB,0BAA0B,QAAQ;AAAA,EACpC;AACF;AAGO,SAAS,oDAAoD,SAA6G;AAC/K,SAAO;AAAA,IACL,aAAa,QAAQ;AAAA,IACrB,0BAA0B,QAAQ;AAAA,EACpC;AACF;","names":[]}

View file

@ -0,0 +1 @@
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View file

@ -0,0 +1,60 @@
// src/lib/stack-app/projects/index.ts
function adminProjectUpdateOptionsToCrud(options) {
return {
display_name: options.displayName,
description: options.description,
is_production_mode: options.isProductionMode,
config: {
domains: options.config?.domains?.map((d) => ({
domain: d.domain,
handler_path: d.handlerPath
})),
oauth_providers: options.config?.oauthProviders?.map((p) => ({
id: p.id,
type: p.type,
...p.type === "standard" && {
client_id: p.clientId,
client_secret: p.clientSecret,
facebook_config_id: p.facebookConfigId,
microsoft_tenant_id: p.microsoftTenantId
}
})),
email_config: options.config?.emailConfig && (options.config.emailConfig.type === "shared" ? {
type: "shared"
} : {
type: "standard",
host: options.config.emailConfig.host,
port: options.config.emailConfig.port,
username: options.config.emailConfig.username,
password: options.config.emailConfig.password,
sender_name: options.config.emailConfig.senderName,
sender_email: options.config.emailConfig.senderEmail
}),
sign_up_enabled: options.config?.signUpEnabled,
credential_enabled: options.config?.credentialEnabled,
magic_link_enabled: options.config?.magicLinkEnabled,
passkey_enabled: options.config?.passkeyEnabled,
allow_localhost: options.config?.allowLocalhost,
create_team_on_sign_up: options.config?.createTeamOnSignUp,
client_team_creation_enabled: options.config?.clientTeamCreationEnabled,
client_user_deletion_enabled: options.config?.clientUserDeletionEnabled,
team_creator_default_permissions: options.config?.teamCreatorDefaultPermissions,
team_member_default_permissions: options.config?.teamMemberDefaultPermissions,
user_default_permissions: options.config?.userDefaultPermissions,
oauth_account_merge_strategy: options.config?.oauthAccountMergeStrategy,
allow_user_api_keys: options.config?.allowUserApiKeys,
allow_team_api_keys: options.config?.allowTeamApiKeys
}
};
}
function adminProjectCreateOptionsToCrud(options) {
return {
...adminProjectUpdateOptionsToCrud(options),
display_name: options.displayName
};
}
export {
adminProjectCreateOptionsToCrud,
adminProjectUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,38 @@
// src/lib/stack-app/teams/index.ts
function teamUpdateOptionsToCrud(options) {
return {
display_name: options.displayName,
profile_image_url: options.profileImageUrl,
client_metadata: options.clientMetadata
};
}
function teamCreateOptionsToCrud(options, creatorUserId) {
return {
display_name: options.displayName,
profile_image_url: options.profileImageUrl,
creator_user_id: creatorUserId
};
}
function serverTeamCreateOptionsToCrud(options) {
return {
display_name: options.displayName,
profile_image_url: options.profileImageUrl,
creator_user_id: options.creatorUserId
};
}
function serverTeamUpdateOptionsToCrud(options) {
return {
display_name: options.displayName,
profile_image_url: options.profileImageUrl,
client_metadata: options.clientMetadata,
client_read_only_metadata: options.clientReadOnlyMetadata,
server_metadata: options.serverMetadata
};
}
export {
serverTeamCreateOptionsToCrud,
serverTeamUpdateOptionsToCrud,
teamCreateOptionsToCrud,
teamUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/lib/stack-app/teams/index.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY\n//===========================================\nimport { TeamsCrud } from \"@stackframe/stack-shared/dist/interface/crud/teams\";\nimport { ReadonlyJson } from \"@stackframe/stack-shared/dist/utils/json\";\n\nimport { ApiKeyCreationOptions, TeamApiKey, TeamApiKeyFirstView } from \"../api-keys\";\nimport { AsyncStoreProperty } from \"../common\";\nimport { ServerUser } from \"../users\";\n\n\nexport type TeamMemberProfile = {\n displayName: string | null,\n profileImageUrl: string | null,\n}\n\nexport type TeamMemberProfileUpdateOptions = {\n displayName?: string,\n profileImageUrl?: string | null,\n};\n\nexport type EditableTeamMemberProfile = TeamMemberProfile & {\n update(update: TeamMemberProfileUpdateOptions): Promise<void>,\n}\n\nexport type TeamUser = {\n id: string,\n teamProfile: TeamMemberProfile,\n}\n\nexport type TeamInvitation = {\n id: string,\n recipientEmail: string | null,\n expiresAt: Date,\n revoke(): Promise<void>,\n}\n\nexport type Team = {\n id: string,\n displayName: string,\n profileImageUrl: string | null,\n clientMetadata: any,\n clientReadOnlyMetadata: any,\n inviteUser(options: { email: string, callbackUrl?: string }): Promise<void>,\n listUsers(): Promise<TeamUser[]>,\n useUsers(): TeamUser[], // THIS_LINE_PLATFORM react-like\n listInvitations(): Promise<TeamInvitation[]>,\n useInvitations(): TeamInvitation[], // THIS_LINE_PLATFORM react-like\n update(update: TeamUpdateOptions): Promise<void>,\n delete(): Promise<void>,\n createApiKey(options: ApiKeyCreationOptions<\"team\">): Promise<TeamApiKeyFirstView>,\n} & AsyncStoreProperty<\"apiKeys\", [], TeamApiKey[], true>;\n\nexport type TeamUpdateOptions = {\n displayName?: string,\n profileImageUrl?: string | null,\n clientMetadata?: ReadonlyJson,\n};\nexport function teamUpdateOptionsToCrud(options: TeamUpdateOptions): TeamsCrud[\"Client\"][\"Update\"] {\n return {\n display_name: options.displayName,\n profile_image_url: options.profileImageUrl,\n client_metadata: options.clientMetadata,\n };\n}\n\nexport type TeamCreateOptions = {\n displayName: string,\n profileImageUrl?: string,\n}\nexport function teamCreateOptionsToCrud(options: TeamCreateOptions, creatorUserId: string): TeamsCrud[\"Client\"][\"Create\"] {\n return {\n display_name: options.displayName,\n profile_image_url: options.profileImageUrl,\n creator_user_id: creatorUserId,\n };\n}\n\n\nexport type ServerTeamMemberProfile = TeamMemberProfile;\n\nexport type ServerTeamUser = ServerUser & {\n teamProfile: ServerTeamMemberProfile,\n}\n\nexport type ServerTeam = {\n createdAt: Date,\n serverMetadata: any,\n listUsers(): Promise<ServerTeamUser[]>,\n useUsers(): ServerUser[], // THIS_LINE_PLATFORM react-like\n update(update: ServerTeamUpdateOptions): Promise<void>,\n delete(): Promise<void>,\n addUser(userId: string): Promise<void>,\n inviteUser(options: { email: string, callbackUrl?: string }): Promise<void>,\n removeUser(userId: string): Promise<void>,\n} & Team;\n\nexport type ServerListUsersOptions = {\n cursor?: string,\n limit?: number,\n orderBy?: 'signedUpAt',\n desc?: boolean,\n query?: string,\n};\n\nexport type ServerTeamCreateOptions = TeamCreateOptions & {\n creatorUserId?: string,\n};\nexport function serverTeamCreateOptionsToCrud(options: ServerTeamCreateOptions): TeamsCrud[\"Server\"][\"Create\"] {\n return {\n display_name: options.displayName,\n profile_image_url: options.profileImageUrl,\n creator_user_id: options.creatorUserId,\n };\n}\n\nexport type ServerTeamUpdateOptions = TeamUpdateOptions & {\n clientReadOnlyMetadata?: ReadonlyJson,\n serverMetadata?: ReadonlyJson,\n};\nexport function serverTeamUpdateOptionsToCrud(options: ServerTeamUpdateOptions): TeamsCrud[\"Server\"][\"Update\"] {\n return {\n display_name: options.displayName,\n profile_image_url: options.profileImageUrl,\n client_metadata: options.clientMetadata,\n client_read_only_metadata: options.clientReadOnlyMetadata,\n server_metadata: options.serverMetadata,\n };\n}\n"],"mappings":";AA2DO,SAAS,wBAAwB,SAA2D;AACjG,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,mBAAmB,QAAQ;AAAA,IAC3B,iBAAiB,QAAQ;AAAA,EAC3B;AACF;AAMO,SAAS,wBAAwB,SAA4B,eAAsD;AACxH,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,mBAAmB,QAAQ;AAAA,IAC3B,iBAAiB;AAAA,EACnB;AACF;AAgCO,SAAS,8BAA8B,SAAiE;AAC7G,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,mBAAmB,QAAQ;AAAA,IAC3B,iBAAiB,QAAQ;AAAA,EAC3B;AACF;AAMO,SAAS,8BAA8B,SAAiE;AAC7G,SAAO;AAAA,IACL,cAAc,QAAQ;AAAA,IACtB,mBAAmB,QAAQ;AAAA,IAC3B,iBAAiB,QAAQ;AAAA,IACzB,2BAA2B,QAAQ;AAAA,IACnC,iBAAiB,QAAQ;AAAA,EAC3B;AACF;","names":[]}

View file

@ -0,0 +1,47 @@
// src/lib/stack-app/users/index.ts
import { encodeBase64 } from "@stackframe/stack-shared/dist/utils/bytes";
function userUpdateOptionsToCrud(options) {
return {
display_name: options.displayName,
client_metadata: options.clientMetadata,
selected_team_id: options.selectedTeamId,
totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,
profile_image_url: options.profileImageUrl,
otp_auth_enabled: options.otpAuthEnabled,
passkey_auth_enabled: options.passkeyAuthEnabled
};
}
function serverUserUpdateOptionsToCrud(options) {
return {
display_name: options.displayName,
primary_email: options.primaryEmail,
client_metadata: options.clientMetadata,
client_read_only_metadata: options.clientReadOnlyMetadata,
server_metadata: options.serverMetadata,
selected_team_id: options.selectedTeamId,
primary_email_auth_enabled: options.primaryEmailAuthEnabled,
primary_email_verified: options.primaryEmailVerified,
password: options.password,
profile_image_url: options.profileImageUrl,
totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret
};
}
function serverUserCreateOptionsToCrud(options) {
return {
primary_email: options.primaryEmail,
password: options.password,
otp_auth_enabled: options.otpAuthEnabled,
primary_email_auth_enabled: options.primaryEmailAuthEnabled,
display_name: options.displayName,
primary_email_verified: options.primaryEmailVerified,
client_metadata: options.clientMetadata,
client_read_only_metadata: options.clientReadOnlyMetadata,
server_metadata: options.serverMetadata
};
}
export {
serverUserCreateOptionsToCrud,
serverUserUpdateOptionsToCrud,
userUpdateOptionsToCrud
};
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long