import { ErrorShowType } from '../constants/index.js'; import { a as AsyncEncryptionStrategy } from '../types-CaC11eNm.js'; import { A as ApiResponse, P as PaginatedData } from '../api-DFOs5fnc.js'; /** * 请求相关常量 */ /** API 成功状态码 */ declare const API_SUCCESS_CODE = "200"; /** HTTP 状态码 */ declare const HTTP_STATUS: { readonly OK: 200; readonly UNAUTHORIZED: 401; readonly FORBIDDEN: 403; readonly NOT_FOUND: 404; readonly INTERNAL_ERROR: 500; }; /** 默认请求超时时间 (毫秒) */ declare const DEFAULT_TIMEOUT = 10000; /** 默认加密请求头名称 */ declare const DEFAULT_ENCRYPT_HEADER = "X-Encrypted"; declare const DEFAULT_TIMESTAMP_HEADER = "X-Timestamp"; declare const DEFAULT_SIGNATURE_HEADER = "X-Signature"; /** 默认未授权状态码 */ declare const DEFAULT_UNAUTHORIZED_CODES: readonly [401, 403]; /** * 判断业务状态码是否为未授权 * * @param code - 业务状态码 * @returns 是否为未授权状态码 (401 / 403) */ declare function isUnauthorizedCode(code: string | number | undefined): boolean; /** * 创建未授权状态码检测器 * * @param customCodes - 业务自定义未授权码 * @param includeDefault - 是否包含默认 401/403 */ declare function createUnauthorizedCodeChecker(customCodes?: Array, includeDefault?: boolean): (code: string | number | undefined) => boolean; /** * 请求层类型定义 * */ /** UmiJS 请求拦截器 */ type RequestInterceptor = (url: string, options: Record) => { url: string; options: Record; } | Promise<{ url: string; options: Record; }>; /** UmiJS 响应拦截器 */ type ResponseInterceptor = (response: Record) => Record | Promise>; /** * 标准响应结构 (Pro/UmiJS 风格) */ interface ResponseStructure { success?: boolean; data?: unknown; errorCode?: string | number; errorMessage?: string; showType?: ErrorShowType; } /** * 业务错误 */ interface BizError extends Error { name: 'BizError'; info: ResponseStructure; } /** * 请求错误 (含 HTTP 信息) */ interface RequestError extends Error { name: string; info?: ResponseStructure; response?: { status: number; data?: unknown; }; request?: unknown; } /** * Auth 拦截器配置 */ interface AuthInterceptorConfig { /** localStorage 中存储 token 的 key */ tokenKey: string; /** 请求头名称,如 'Authorization' 或 'X-Session-Id' */ headerName: string; /** 请求头前缀,如 'Bearer ' (注意尾部空格) */ headerPrefix?: string; /** 不需要添加 token 的路径列表 */ excludePaths?: string[]; /** 额外的请求头 */ extraHeaders?: Record; } /** * 加密拦截器配置 */ interface EncryptInterceptorConfig { /** 是否启用加密 */ enabled: boolean; /** AES-256-CBC + HMAC-SHA256 加密策略实例 */ strategy: AsyncEncryptionStrategy; /** 不加密的路径列表 (支持通配符) */ excludePaths?: string[]; /** 需要加密请求体的 HTTP 方法,默认 ['POST', 'PUT'] */ methods?: string[]; /** * 允许通过 X-HTTP-Method-Override 转为 POST 的方法,默认 ['GET', 'DELETE'] * * 当这些方法携带 params 时,加密拦截器会自动将其转为 POST+data, * 并添加 X-HTTP-Method-Override 头,后端解密后还原为原始方法。 */ overridableMethods?: string[]; /** 加密标识请求头名称,默认 'X-Encrypted' */ encryptHeader?: string; /** 时间戳请求头名称,默认 'X-Timestamp' */ timestampHeader?: string; /** 签名请求头名称,默认 'X-Signature' */ signatureHeader?: string; /** * 加密请求体封装函数 * 默认: 直接使用加密字符串 */ wrapEncryptedBody?: (encrypted: string) => unknown; /** * 解密前解包响应数据函数 * 默认: 直接使用响应体字符串 */ unwrapEncryptedResponse?: (data: unknown) => string; } /** * 错误处理配置 */ interface ErrorHandlerConfig { /** 401/403 未授权回调 */ onUnauthorized: () => void; /** 业务自定义未授权状态码(如 20001 / 20002) */ unauthorizedCodes?: Array; /** 是否包含默认未授权码 401/403(默认 true) */ includeDefaultUnauthorizedCodes?: boolean; /** 通用错误回调 */ onError?: (message: string, showType?: ErrorShowType) => void; /** 业务错误回调 (更细粒度控制) */ onBizError?: (error: ResponseStructure) => void; /** 成功状态码,默认 '200' */ successCode?: string | number; } /** * createRequestConfig 完整配置 */ interface RequestConfigOptions { /** 基础 URL */ baseURL?: string; /** 超时时间 (毫秒),默认 10000 */ timeout?: number; /** 响应类型,默认 'json' */ responseType?: string; /** 认证拦截器配置 */ auth: AuthInterceptorConfig; /** 加密拦截器配置 (可选) */ encryption?: EncryptInterceptorConfig; /** 自定义请求拦截器 */ requestInterceptors?: RequestInterceptor[]; /** 自定义响应拦截器(在 decrypt 后、未授权检查前执行) */ responseInterceptors?: ResponseInterceptor[]; /** 错误处理配置 */ errorConfig: ErrorHandlerConfig; } /** * 一站式请求配置工厂 * * 将 auth、encrypt、error handling 整合为一个配置对象, * 直接用于 UmiJS request 插件。 */ /** * 创建完整的 UmiJS RequestConfig * * 一站式配置认证、加密、错误处理,直接导出给 UmiJS 使用。 * * @param options - 配置选项 * @returns UmiJS RequestConfig 对象 * * @example * ```ts * // keel-cloud-web (无加密) * export const request = createRequestConfig({ * timeout: 10000, * auth: { * tokenKey: 'kc_auth_token', * headerName: 'Authorization', * headerPrefix: 'Bearer ', * }, * errorConfig: { * onUnauthorized: () => history.push('/login'), * onError: (msg) => message.error(msg), * }, * }); * ``` */ declare function createRequestConfig(options: RequestConfigOptions): Record; /** * CRUD Service 工厂 * * 基于 @umijs/max 的 request 函数,为业务实体生成标准的 * list / detail / create / update / delete / toggleStatus 请求方法, * 消除大量手写重复 service 的问题。 */ /** * 请求方法 */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; /** * 单个操作的自定义配置 */ interface OperationConfig { /** HTTP 方法 */ method?: HttpMethod; /** 路径后缀 (支持 :id 占位符) */ path?: string; /** 额外请求配置 (如 skipEncrypt) */ requestOptions?: Record; } /** * CRUD Service 工厂配置 */ interface CrudServiceConfig { /** 分页列表 — 默认 POST /page + { pageNo, pageSize, ... } */ list?: OperationConfig | false; /** 查询详情 — 默认 GET /:id */ detail?: OperationConfig | false; /** 创建 — 默认 POST / */ create?: OperationConfig | false; /** 更新 — 默认 PUT / */ update?: OperationConfig | false; /** 删除 — 默认 DELETE /:id */ delete?: OperationConfig | false; /** 切换状态 — 默认 PUT /:id/status */ toggleStatus?: OperationConfig | false; /** id 字段名,默认 'id' */ idField?: string; /** * request 函数,来自 @umijs/max 的 request。 * 不在此包中直接 import,由调用方注入以保持零依赖。 */ request: (url: string, options?: Record) => Promise; } /** * CRUD Service 返回类型 — 按配置动态生成 */ interface CrudServiceMethods, CreateDTO = Partial, UpdateDTO = Partial, ListParams = Record> { /** 分页列表 */ list: (params: ListParams) => Promise>>; /** 查询详情 */ detail: (id: string | number) => Promise>; /** 创建 */ create: (data: CreateDTO) => Promise>; /** 更新 */ update: (data: UpdateDTO) => Promise>; /** 删除 */ remove: (id: string | number) => Promise>; /** 切换状态 */ toggleStatus: (id: string | number, status: string | number | boolean) => Promise>; /** 保存 (create if no id, update if has id; 可通过 isNew 显式指定) */ save: (data: CreateDTO | UpdateDTO, isNew?: boolean) => Promise>; } /** * 创建 CRUD Service * * @param basePath - API 基础路径,如 '/kc-api/users' * @param config - 配置项 * @returns CRUD 方法集合 * * @example * ```ts * import { request } from '@umijs/max'; * * const userService = createCrudService('/kc-api/users', { * request, * list: { method: 'POST', path: '/page' }, * detail: { method: 'GET', path: '/:id' }, * create: { method: 'POST' }, * update: { method: 'PUT' }, * delete: { method: 'DELETE', path: '/:id' }, * }); * * // 使用 * const res = await userService.list({ pageNo: 1, pageSize: 10 }); * const user = await userService.detail(1); * await userService.create({ name: 'test' }); * await userService.save({ id: 1, name: 'updated' }); // 自动选择 update * await userService.remove(1); * ``` * * @example * ```ts * // 禁用不需要的操作 * const readonlyService = createCrudService
('/api/articles', { * request, * create: false, * update: false, * delete: false, * toggleStatus: false, * }); * ``` */ declare function createCrudService, CreateDTO = Partial, UpdateDTO = Partial, ListParams = Record>(basePath: string, config: CrudServiceConfig): CrudServiceMethods; /** * 快速创建标准 CRUD Service 的简化版本 * * 适用于完全遵循标准 RESTful 约定的场景。 * * @example * ```ts * const userService = createStandardCrudService(request, '/kc-api/users'); * const articleService = createStandardCrudService
(request, '/api/articles', { * list: { path: '/page' }, * }); * ``` */ declare function createStandardCrudService>(requestFn: (url: string, options?: Record) => Promise, basePath: string, overrides?: Partial>): CrudServiceMethods, Partial, Record>; /** * 错误处理器工厂 * */ /** * 创建错误抛出器 (errorThrower) * * 用于 UmiJS request 插件的 errorConfig.errorThrower。 * 当 API 返回非成功状态码时,将响应转换为可识别的业务错误抛出。 * * @param successCode - 成功状态码,默认 '200' * @returns errorThrower 函数 */ declare function createErrorThrower(successCode?: string | number): (res: Record) => void; /** * 创建错误处理器 (errorHandler) * * 用于 UmiJS request 插件的 errorConfig.errorHandler。 * * @param config - 错误处理配置 * @returns errorHandler 函数 */ declare function createErrorHandler(config: ErrorHandlerConfig): (error: RequestError & { _unauthorizedHandled?: boolean; }, opts?: { skipErrorHandler?: boolean; }) => void; /** * 文件服务工厂 * * 为文件上传/下载/删除生成标准化的服务方法。 * */ /** * 上传参数 */ interface UploadParams { /** 文件 */ file: File; /** 文件模块/业务类型 */ moduleType?: string; /** 业务 ID */ businessId?: string | number; /** 文件类型标识 */ fileType?: string; /** 自定义路径 */ customPath?: string; /** 额外参数 */ extra?: Record; } /** * 上传结果 */ interface UploadResult { /** 文件访问 URL */ url: string; /** 文件名 */ name?: string; /** 文件大小 (bytes) */ size?: number; /** 文件类型 */ type?: string; /** 服务器返回的文件 ID */ fileId?: string | number; /** 原始响应数据 */ [key: string]: unknown; } /** * 文件服务配置 */ interface FileServiceConfig { /** * request 函数,来自 @umijs/max */ request: (url: string, options?: Record) => Promise; /** 上传配置 */ upload?: { /** 上传路径, 默认 '/upload' */ path?: string; /** HTTP 方法, 默认 'POST' */ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; /** 额外请求配置 (如 skipEncrypt: true) */ requestOptions?: Record; }; /** 删除配置 */ delete?: { /** 删除路径, 默认 '/' */ path?: string; /** HTTP 方法, 默认 'DELETE' */ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; /** 删除参数名 (放在 query 中), 默认 'fileUrl' */ paramName?: string; /** 额外请求配置 (如 skipEncrypt: true) */ requestOptions?: Record; }; /** 下载配置 */ download?: { /** 下载路径 (支持 :id 占位符), 默认 '/download/:id' */ path?: string; /** HTTP 方法, 默认 'GET' */ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; /** 额外请求配置 (如 headers) */ requestOptions?: Record; }; } /** * 文件服务方法 */ interface FileServiceMethods { /** 上传文件 */ upload: (params: UploadParams) => Promise>; /** 删除文件 */ remove: (fileUrl: string) => Promise>; /** 下载文件 (返回 Blob) */ download: (fileId: string | number) => Promise; } /** * 创建文件服务 * * @param basePath - 文件 API 基础路径, 如 '/api/files' * @param config - 配置项 * @returns 文件服务方法 * * @example * ```ts * import { request } from '@umijs/max'; * * const fileService = createFileService('/api/files', { * request, * upload: { path: '/upload', requestOptions: { skipEncrypt: true } }, * delete: { path: '/', paramName: 'fileUrl' }, * download: { path: '/download/:id' }, * }); * * // 上传 * const res = await fileService.upload({ * file: selectedFile, * moduleType: 'avatar', * businessId: userId, * }); * * // 删除 * await fileService.remove('https://cdn.example.com/files/abc.jpg'); * * // 下载 * const blob = await fileService.download('file-123'); * ``` */ declare function createFileService(basePath: string, config: FileServiceConfig): FileServiceMethods; /** * 请求/响应拦截器工厂 */ /** * 创建认证请求拦截器 * * 自动为请求添加认证 token 和额外的 headers。 * * @param config - 认证配置 * @returns UmiJS 请求拦截器函数 */ declare function createAuthInterceptor(config: AuthInterceptorConfig): (url: string, options: Record) => { url: string; options: { headers: Record; }; }; /** * 创建加密请求拦截器 * * 自动加密请求体,添加加密标识、时间戳和 HMAC 签名请求头。 * * @param config - 加密配置 * @returns UmiJS 请求拦截器函数(异步) */ declare function createEncryptRequestInterceptor(config: EncryptInterceptorConfig): (url: string, options: Record) => Promise<{ url: string; options: Record; }>; /** * 创建解密响应拦截器 * * 加密启用时 responseType:'text',所有响应均为字符串: * - X-Encrypted: true → 解密 * - 其他 → JSON.parse 还原 */ declare function createDecryptResponseInterceptor(config: EncryptInterceptorConfig): (response: Record) => Promise>; export { API_SUCCESS_CODE, type AuthInterceptorConfig, type BizError, type CrudServiceConfig, type CrudServiceMethods, DEFAULT_ENCRYPT_HEADER, DEFAULT_SIGNATURE_HEADER, DEFAULT_TIMEOUT, DEFAULT_TIMESTAMP_HEADER, DEFAULT_UNAUTHORIZED_CODES, type EncryptInterceptorConfig, type ErrorHandlerConfig, ErrorShowType, type FileServiceConfig, type FileServiceMethods, HTTP_STATUS, type OperationConfig, type RequestConfigOptions, type RequestError, type RequestInterceptor, type ResponseInterceptor, type ResponseStructure, type UploadParams, type UploadResult, createAuthInterceptor, createCrudService, createDecryptResponseInterceptor, createEncryptRequestInterceptor, createErrorHandler, createErrorThrower, createFileService, createRequestConfig, createStandardCrudService, createUnauthorizedCodeChecker, isUnauthorizedCode };