import {isSearchRequest,normalizeSearchQuery} from './search-query.ts'; export type Environment = 'dev' | 'prod'; // Do not let a pasted server address redirect credentials to an Internet host. export function internalUrl(value: string, allowLoopback = false): string { const url = new URL(value); const parts = url.hostname.split('.').map(Number); const ipv4 = parts.length === 4 && parts.every(p => Number.isInteger(p) && p >= 0 && p <= 255); const privateIp = ipv4 && (parts[0] === 10 || (parts[0] === 192 && parts[1] === 168) || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31)); const local = allowLoopback && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || !(privateIp || local)) throw new Error('请配置公司内网地址,不包含账号、密码或查询参数。'); return url.toString().replace(/\/$/, ''); } export type Json = Record; export class ApiError extends Error { code: number; constructor(message: string, code: number) { super(message); this.code = code; } } export class ApiClient { private token = ''; private generation = 0; readonly baseUrl: string; private expired: () => void; private transport: typeof fetch; constructor(baseUrl: string, expired: () => void, transport: typeof fetch = (input, init) => globalThis.fetch(input, init)) { this.baseUrl = baseUrl; this.expired = expired; this.transport = transport; } authenticate(token: string) { this.generation++; this.token = token; } clear() { this.generation++; this.token = ''; } async request(path: string, options: { method?: string; body?: unknown; query?: Record; anonymous?: boolean; timeout?: number; signal?: AbortSignal; responseType?: 'image'; } = {}): Promise { if (!/^\/[a-zA-Z]/.test(path) || path.includes('://') || path.includes('..')) throw new Error('无效的接口地址'); const url = new URL(this.baseUrl + path); const query=isSearchRequest(path,options.method)?normalizeSearchQuery(options.query||{}) as Record:options.query||{}; const requestBody=isSearchRequest(path,options.method)&&options.method?.toUpperCase()==='POST'?normalizeSearchQuery(options.body):options.body; for (const [key, value] of Object.entries(query)) { if (value !== '' && value != null) url.searchParams.set(key, String(value)); } const epoch = this.generation; const controller = new AbortController(); const abort = () => controller.abort(); options.signal?.addEventListener('abort', abort, { once: true }); if (options.signal?.aborted) controller.abort(); const timer = setTimeout(abort, options.timeout || 30000); try { const multipart = typeof FormData !== 'undefined' && requestBody instanceof FormData; const response = await this.transport(url.toString(), { method: options.method || 'GET', redirect: 'error', signal: controller.signal, headers: { Accept: 'application/json', ...(!multipart ? { 'Content-Type': 'application/json' } : {}), ...(!options.anonymous && this.token ? { Authorization: `Bearer ${this.token}` } : {}) }, body: requestBody === undefined ? undefined : multipart ? requestBody as FormData : JSON.stringify(requestBody) }); if(options.responseType==='image'&&response.ok&&/^image\/(png|jpeg|webp)$/.test(response.headers.get('content-type')?.split(';')[0]||'')){ if(Number(response.headers.get('content-length')||0)>6*1024*1024)throw new ApiError('图片较大,请在电脑端查看。',413); const bytes=new Uint8Array(await response.arrayBuffer()); if(epoch!==this.generation)throw new ApiError('会话已切换,请重新查询。',409); if(bytes.length>6*1024*1024)throw new ApiError('图片较大,请在电脑端查看。',413); return `data:${response.headers.get('content-type')?.split(';')[0]};base64,${base64(bytes)}` as T; } const data = await response.json(); if (epoch !== this.generation) throw new ApiError('会话已切换,请重新查询。', 409); const code = Number(data.code ?? response.status); if (code === 401 || response.status === 401) { if (!options.anonymous) { this.clear(); this.expired(); } throw new ApiError(options.anonymous ? data.msg || '账号或密码未通过校验,请重新核对。' : '登录已过期,请重新登录。', 401); } if (code === 403 || response.status === 403) throw new ApiError('这项业务可请管理员协助办理或确认开通范围。', 403); if (!response.ok || code !== 200) throw new ApiError(data.msg || '处理未完成,请核对后重试。', code); return data as T; } catch (error) { if (error instanceof ApiError) throw error; if (options.signal?.aborted) throw new ApiError('请求已取消。', 499); if (typeof __DEV__ !== 'undefined' && __DEV__) console.warn('Internal API transport failure:', error instanceof Error ? error.message : 'unknown'); throw new ApiError('暂时连接不上内网服务,请检查公司网络后重试。', 503); } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', abort); } } } export function base64(bytes:Uint8Array){ const alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';const parts:string[]=[];let chunk=''; for(let i=0;i>>18)&63]+alphabet[(n>>>12)&63]+(i+1>>6)&63]:'=')+(i+2=16384){parts.push(chunk);chunk='';}} parts.push(chunk); return parts.join(''); } export function allows(permissions: string[], ...groups: string[][]) { return permissions.includes('*:*:*') || groups.every(group => group.some(p => permissions.includes(p))); }