{"version":3,"file":"user.mjs","names":[],"sources":["../../../src/getIntlayerAPI/user.ts"],"sourcesContent":["import type { RouteEndpoints } from '@intlayer/backend-contract/defineRoute';\nimport { buildRouteURL } from '@intlayer/backend-contract/defineRoute';\nimport type { ResponseData } from '@intlayer/backend-contract/responseData';\nimport type {\n  CreateUserBody,\n  CreateUserResult,\n  GetUserByEmailParams,\n  GetUserByEmailResult,\n  GetUserByIdParams,\n  GetUserByIdResult,\n  GetUsersParams,\n  GetUsersResult,\n  UpdateUserBody,\n  UpdateUserResult,\n  UploadUserAvatarResult,\n  UserAPI,\n  UserRoutes,\n  userContract,\n} from '@intlayer/backend-contract/user';\nimport { editor } from '@intlayer/config/built';\nimport { BACKEND_URL } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport type GetUserByAccountParams = {\n  providerAccountId: string;\n  provider: string;\n};\nexport type GetUserByAccountResult = ResponseData<UserAPI>;\n\n/** Prefix of the routes, checked against the backend contract. */\nconst userGroup = {\n  prefix: '/api/user',\n} as const satisfies Pick<typeof userContract, 'prefix'>;\n\n/**\n * Method and path of every route, checked against the backend contract at\n * compile time (the contract's zod schemas are never loaded).\n */\nconst userEndpoints = {\n  getSetupStatus: { method: 'GET', path: '/setup' },\n  getUsers: { method: 'GET', path: '/' },\n  updateUser: { method: 'PUT', path: '/' },\n  createUser: { method: 'POST', path: '/' },\n  getUserById: { method: 'GET', path: '/:userId' },\n  getUserByEmail: { method: 'GET', path: '/email/:email' },\n  deleteUser: { method: 'DELETE', path: '/:userId' },\n  verifyEmailStatusSSE: { method: 'GET', path: '/verify-email-status/:userId' },\n  uploadAvatar: { method: 'POST', path: '/avatar' },\n} as const satisfies RouteEndpoints<UserRoutes>;\n\nexport const getUserAPI = (\n  authAPIOptions: FetcherOptions = {},\n  intlayerConfig?: IntlayerConfig\n) => {\n  const backendURL =\n    intlayerConfig?.editor?.backendURL ?? editor.backendURL ?? BACKEND_URL;\n\n  /**\n   * Retrieves a list of users based on filters and pagination.\n   * @param filters - Filters and pagination options.\n   * @returns List of users.\n   */\n  const getUsers = async (\n    filters?: GetUsersParams,\n    otherOptions: FetcherOptions = {}\n  ) =>\n    await fetcher<GetUsersResult>(\n      buildRouteURL(backendURL, userGroup, userEndpoints.getUsers),\n      authAPIOptions,\n      otherOptions,\n      {\n        cache: 'no-store',\n        // @ts-ignore Number of parameter will be stringified by the fetcher\n        params: filters,\n      }\n    );\n\n  /**\n   * Retrieves a user by ID.\n   * @param userId - User ID.\n   * @returns User object.\n   */\n  const getUserById = async (\n    userId: GetUserByIdParams['userId'],\n    otherOptions: FetcherOptions = {}\n  ) =>\n    await fetcher<GetUserByIdResult>(\n      buildRouteURL(backendURL, userGroup, userEndpoints.getUserById, {\n        userId: String(userId),\n      }),\n      authAPIOptions,\n      otherOptions,\n      {\n        cache: 'no-store',\n      }\n    );\n\n  /**\n   * Retrieves a user by email.\n   * @param email - User email.\n   * @returns User object.\n   */\n  const getUserByEmail = async (\n    email: GetUserByEmailParams['email'],\n    otherOptions: FetcherOptions = {}\n  ) =>\n    await fetcher<GetUserByEmailResult>(\n      buildRouteURL(backendURL, userGroup, userEndpoints.getUserByEmail, {\n        email,\n      }),\n      authAPIOptions,\n      otherOptions,\n      {\n        cache: 'no-store',\n      }\n    );\n\n  /**\n   * Retrieves a user by account.\n   * @param providerAccountId - The provider account ID.\n   * @param provider - The provider of the account.\n   */\n  /**\n   * Creates a new user.\n   * @param user - User credentials.\n   * @returns User object.\n   */\n  const createUser = async (\n    user: CreateUserBody,\n    otherOptions: FetcherOptions = {}\n  ) =>\n    await fetcher<CreateUserResult>(\n      buildRouteURL(backendURL, userGroup, userEndpoints.createUser),\n      authAPIOptions,\n      otherOptions,\n      {\n        method: userEndpoints.createUser.method,\n        body: user,\n      }\n    );\n\n  /**\n   * Updates the user with the provided data.\n   * @param user - Updated user data.\n   * @returns User object.\n   */\n  const updateUser = async (\n    user: UpdateUserBody,\n    otherOptions: FetcherOptions = {}\n  ) =>\n    await fetcher<UpdateUserResult>(\n      buildRouteURL(backendURL, userGroup, userEndpoints.updateUser),\n      authAPIOptions,\n      otherOptions,\n      {\n        method: userEndpoints.updateUser.method,\n        body: user,\n      }\n    );\n\n  /**\n   * Deletes a user with the provided ID.\n   * @param userId - User ID.\n   * @returns User object.\n   */\n  const deleteUser = async (\n    userId: string,\n    otherOptions: FetcherOptions = {}\n  ) =>\n    await fetcher<UpdateUserResult>(\n      buildRouteURL(backendURL, userGroup, userEndpoints.deleteUser, {\n        userId: String(userId),\n      }),\n      authAPIOptions,\n      otherOptions,\n      {\n        method: userEndpoints.deleteUser.method,\n      }\n    );\n\n  /**\n   * Uploads a new avatar for the authenticated user.\n   * @param file - The image File object to upload.\n   * @returns Updated user object.\n   */\n  const uploadAvatar = async (\n    file: File,\n    otherOptions: FetcherOptions = {}\n  ) => {\n    const buffer = await file.arrayBuffer();\n\n    const baseHeaders: Record<string, string> = {\n      'Content-Type': file.type || 'image/jpeg',\n    };\n\n    // Forward auth cookies / credentials from authAPIOptions headers\n    const authHeaders =\n      (authAPIOptions.headers as Record<string, string> | undefined) ?? {};\n\n    const response = await fetch(\n      buildRouteURL(backendURL, userGroup, userEndpoints.uploadAvatar),\n      {\n        method: userEndpoints.uploadAvatar.method,\n        credentials: 'include',\n        headers: { ...authHeaders, ...baseHeaders },\n        body: buffer,\n        signal: otherOptions.signal as AbortSignal | undefined,\n      }\n    );\n\n    if (!response.ok) {\n      const result = await response.json();\n      throw new Error(JSON.stringify(result.error) ?? 'Avatar upload failed');\n    }\n\n    return (await response.json()) as UploadUserAvatarResult;\n  };\n\n  /**\n   * Gets the verify email status URL to use in the SSE.\n   * @param userId - User ID.\n   * @returns The verify email status URL.\n   */\n  const getVerifyEmailStatusURL = (userId: string | UserAPI['id']) =>\n    buildRouteURL(backendURL, userGroup, userEndpoints.verifyEmailStatusSSE, {\n      userId: String(userId),\n    });\n\n  return {\n    createUser,\n    getUsers,\n    getUserById,\n    getUserByEmail,\n    updateUser,\n    deleteUser,\n    uploadAvatar,\n    getVerifyEmailStatusURL,\n  };\n};\n\n/**\n * Authenticated `user` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const userEndpoint = createEndpoint(getUserAPI);\n"],"mappings":";;;;;;;;AAgCA,MAAM,YAAY,EAChB,QAAQ,YACV;;;;;AAMA,MAAM,gBAAgB;CACpB,gBAAgB;EAAE,QAAQ;EAAO,MAAM;CAAS;CAChD,UAAU;EAAE,QAAQ;EAAO,MAAM;CAAI;CACrC,YAAY;EAAE,QAAQ;EAAO,MAAM;CAAI;CACvC,YAAY;EAAE,QAAQ;EAAQ,MAAM;CAAI;CACxC,aAAa;EAAE,QAAQ;EAAO,MAAM;CAAW;CAC/C,gBAAgB;EAAE,QAAQ;EAAO,MAAM;CAAgB;CACvD,YAAY;EAAE,QAAQ;EAAU,MAAM;CAAW;CACjD,sBAAsB;EAAE,QAAQ;EAAO,MAAM;CAA+B;CAC5E,cAAc;EAAE,QAAQ;EAAQ,MAAM;CAAU;AAClD;AAEA,MAAa,cACX,iBAAiC,CAAC,GAClC,mBACG;CACH,MAAM,aACJ,gBAAgB,QAAQ,cAAc,OAAO,cAAc;;;;;;CAO7D,MAAM,WAAW,OACf,SACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,cAAc,YAAY,WAAW,cAAc,QAAQ,GAC3D,gBACA,cACA;EACE,OAAO;EAEP,QAAQ;CACV,CACF;;;;;;CAOF,MAAM,cAAc,OAClB,QACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,cAAc,YAAY,WAAW,cAAc,aAAa,EAC9D,QAAQ,OAAO,MAAM,EACvB,CAAC,GACD,gBACA,cACA,EACE,OAAO,WACT,CACF;;;;;;CAOF,MAAM,iBAAiB,OACrB,OACA,eAA+B,CAAC,MA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