import { assertNotCancelled, GuestError, GuestTransport } from './GuestContracts'; /** 请求与响应读取共用期限,取消后隔离迟到结果。 / One deadline covers fetch and response parsing; ignore late results after cancellation. */ export class GuestHttpClient implements GuestTransport { constructor(private readonly origin: string, private readonly timeoutMs: number, private readonly fetcher: typeof fetch) { if (!/^https:\/\/[^\s/@?#:\\]+(?::\d+)?$/.test(origin) || !Number.isFinite(timeoutMs) || timeoutMs <= 0) { throw new GuestError('configuration', 'Guest service configuration is unavailable.'); } } async post(path: string, body: object, headers: Record, signal?: AbortSignal): Promise> { assertNotCancelled(signal); const request = new AbortController(); let timer: ReturnType | undefined; let cancel = () => {}; const interruption = new Promise((_, reject) => { cancel = () => { reject(new GuestError('cancelled', 'Sign-in cancelled.')); request.abort(); }; signal?.addEventListener('abort', cancel, { once: true }); timer = setTimeout(() => { reject(new GuestError('timeout', 'Sign-in timed out. Please retry.')); request.abort(); }, this.timeoutMs); }); try { return await Promise.race([interruption, this.exchange(path, body, headers, request.signal)]); } catch (error) { if (error instanceof GuestError) throw error; throw new GuestError('network', 'Unable to connect. Please check your connection and retry.'); } finally { if (timer !== undefined) clearTimeout(timer); signal?.removeEventListener('abort', cancel); } } private async exchange(path: string, body: object, headers: Record, signal: AbortSignal): Promise> { const response = await this.fetcher(this.origin + path, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, credentials: 'omit', body: JSON.stringify(body), signal, }); if (!response.ok) throw new GuestError('network', 'Guest service is unavailable. Please retry.'); let data: unknown; try { data = await response.json(); } catch { throw new GuestError('response', 'Invalid sign-in response. Please retry.'); } if (!data || typeof data !== 'object' || Array.isArray(data)) throw new GuestError('response', 'Invalid sign-in response. Please retry.'); const result = data as Record; if (result.code !== 0) { if (result.code === 401 && typeof result.msg === 'string' && /\brequest_sign_invalid\b/.test(result.msg)) { throw new GuestError('verification', 'Sign-in verification failed. Check the device clock or signing configuration.'); } throw new GuestError('rejected', 'Guest sign-in was rejected. Please retry.'); } return result; } }