/* Use with the existing VoiceClient behind a same-origin /api proxy. */ export class DocumentClient { constructor(voiceClient) { this.voice = voiceClient; } async request(path, method = 'GET', body, key) { const headers = {}; if (method !== 'GET') headers['X-CSRF-Token'] = this.voice.csrf; if (key) headers['Idempotency-Key'] = key; const multipart = body instanceof FormData; if (body !== undefined && !multipart) headers['Content-Type'] = 'application/json'; const response = await fetch('/api/v1' + path, { method, credentials: 'same-origin', headers, ...(body === undefined ? {} : {body: multipart ? body : JSON.stringify(body)}) }); const result = await response.json(); if (!response.ok) throw Object.assign(new Error(result.error?.code || 'REQUEST_FAILED'), { status: response.status, requestID: result.error?.request_id, details: result.error?.details }); return result; } upload(file, title, key) { // Caller retains this key AND the exact file/title until replay is resolved. const body = new FormData(); body.append('file', file); if (title !== undefined) body.append('title', title); return this.request('/documents', 'POST', body, key); } list(query = '') { return this.request('/documents' + (query ? '?' + query : '')); } poll(id) { return this.request('/documents/' + encodeURIComponent(id)); } review(id, cursor) { return this.request('/documents/' + encodeURIComponent(id) + '/extraction-review' + (cursor ? '?cursor=' + encodeURIComponent(cursor) : '')); } decide(id, decision, key) { return this.request('/documents/' + encodeURIComponent(id) + '/extraction-review/decisions', 'POST', decision, key); } retry(id, key) { return this.request('/documents/' + encodeURIComponent(id) + '/retry', 'POST', undefined, key); } selection() { return this.request('/knowledge-selection'); } replace(revision, ids) { return this.request('/knowledge-selection', 'PATCH', {expected_revision: revision, document_ids: ids}); } configuration() { return this.request('/configuration'); } }