Download apps/web/src/lib/api.ts from aliroya/contiai: direct link, hf CLI and curl.
- Browser
- Download file 30.8 kB
-
https://huggingface.co/spaces/aliroya/contiai/resolve/main/apps/web/src/lib/api.ts
- Command line
-
hf download hf://spaces/aliroya/contiai/apps/web/src/lib/api.ts
-
curl -L -o api.ts https://huggingface.co/spaces/aliroya/contiai/resolve/main/apps/web/src/lib/api.ts
30.8 kB
| import { supabase } from "./supabase"; | |
| import type { | |
| BookCatalog, | |
| BookDesignResult, | |
| AdminAnnouncement, | |
| AdminUserRow, | |
| Reconciliation, | |
| TaskTypeSpend, | |
| UsageMatrix, | |
| UserDetail, | |
| AdminOverview, | |
| AdminRunDetail, | |
| AnnouncementItem, | |
| AuditEntry, | |
| CatalogueEntry, | |
| DesignResult, | |
| SlideDesignResult, | |
| SlideImages, | |
| DesignableRun, | |
| DesignTemplate, | |
| JsonSchema, | |
| LibraryItem, | |
| ProfileInput, | |
| SavedProfile, | |
| TaskType, | |
| UsageSummary, | |
| AdminRun, | |
| ArtifactMeta, | |
| UploadMeta, | |
| ModelBreakdown, | |
| PipelineBreakdown, | |
| PipelineDef, | |
| Profile, | |
| Project, | |
| ReviewPayload, | |
| Run, | |
| RunDetail, | |
| SeriesPoint, | |
| UserUsage, | |
| SavedImages, | |
| ImageModelTier, | |
| } from "./types"; | |
| export const API_URL = import.meta.env.VITE_API_URL ?? "http://127.0.0.1:8000"; | |
| export class ApiError extends Error { | |
| constructor( | |
| readonly status: number, | |
| message: string, | |
| /* a form's refusal field by field: `{field, detail}` (routes._check_brief) */ | |
| readonly errors: { field?: string; detail?: string }[] = [], | |
| ) { | |
| super(message); | |
| } | |
| } | |
| /* ยซtoken expiredยป while editing a chapter of a novel's plan (2026-11-16): | |
| a tab left in the background stops the session's refresh timer, and the | |
| hour-long token ran out under the page. The token is renewed before a | |
| request when it has under two minutes left, and once more when the server | |
| still says it expired - the request is then sent again, and the person | |
| never sees it. */ | |
| const RENEW_MS = 120_000; | |
| async function authHeader(force = false): Promise<Record<string, string>> { | |
| let { data } = await supabase.auth.getSession(); | |
| const ends = (data.session?.expires_at ?? 0) * 1000; | |
| if (data.session && (force || ends - Date.now() < RENEW_MS)) { | |
| const renewed = await supabase.auth.refreshSession(); | |
| if (renewed.data.session) data = { session: renewed.data.session }; | |
| } | |
| const token = data.session?.access_token; | |
| return token ? { Authorization: `Bearer ${token}` } : {}; | |
| } | |
| async function send(path: string, init: RequestInit, force = false): Promise<Response> { | |
| return fetch(`${API_URL}${path}`, { | |
| ...init, | |
| headers: { | |
| "Content-Type": "application/json", | |
| ...(await authHeader(force)), | |
| ...(init.headers ?? {}), | |
| }, | |
| }); | |
| } | |
| async function request<T>(path: string, init: RequestInit = {}): Promise<T> { | |
| let res = await send(path, init); | |
| if (res.status === 401) { | |
| // the session ran out under the page: renewed, and the request sent again | |
| const said = await res.clone().text().catch(() => ""); | |
| if (/expired|missing Authorization/i.test(said)) { | |
| res = await send(path, init, true); | |
| if (res.status === 401) { | |
| throw new ApiError(401, "ุงูุชูุช ุฌูุณุชู - ุณุฌูู ุงูุฏุฎูู ู ู ุฌุฏูุฏ. ู ุง ูุชุจุชู ูู ุงูุตูุญุฉ ุจุงูู ูููุง."); | |
| } | |
| } | |
| } | |
| if (!res.ok) { | |
| // FastAPI puts the human-readable reason in `detail`; surface that rather | |
| // than a bare status code, because these strings are written to be shown. | |
| let message = `ุงูุทูุจ ูุดู (${res.status})`; | |
| let errors: { field?: string; detail?: string }[] = []; | |
| try { | |
| const body = await res.json(); | |
| if (typeof body?.detail === "string") message = body.detail; | |
| else if (Array.isArray(body?.detail)) { | |
| message = body.detail.map((d: { msg: string }) => d.msg).join("ุ "); | |
| } else if (body?.detail && typeof body.detail === "object") { | |
| // ยซุงูุทูุจ ูุดู (422)ยป hid which field the server named (2026-11-15) | |
| errors = Array.isArray(body.detail.errors) ? body.detail.errors : []; | |
| const named = errors.map((e) => `${e.field ?? ""}: ${e.detail ?? ""}`).join("ุ "); | |
| message = [body.detail.message, named].filter(Boolean).join(" โ ") || message; | |
| } | |
| } catch { | |
| /* keep the fallback */ | |
| } | |
| throw new ApiError(res.status, message, errors); | |
| } | |
| if (res.status === 204) return undefined as T; | |
| return res.json() as Promise<T>; | |
| } | |
| /* ยซูุฑุฃูุง ุชุตูุฑู ูุฏูยป: a supplied design read before the run (api/v1/blueprint_read). */ | |
| export type BlueprintReading = { | |
| reading: Record<string, unknown>; | |
| reading_digest: string; | |
| notes: string[]; | |
| summary: { | |
| kind: "book" | "bag"; | |
| chapters: number; | |
| items: number; | |
| days?: number; | |
| rows: { title: string; children: string[]; points: number }[]; | |
| }; | |
| }; | |
| export const api = { | |
| // profile | |
| me: () => request<Profile>("/v1/me"), | |
| updateMe: (body: { full_name?: string }) => | |
| request<Profile>("/v1/me", { method: "PATCH", body: JSON.stringify(body) }), | |
| // the founder's bag designer (the API answers 404 to everyone else) | |
| designTemplates: () => | |
| request<{ | |
| templates: DesignTemplate[]; | |
| max_colors: number; | |
| fonts?: { key: string; label: string; default: boolean }[]; | |
| image_models?: Record<string, ImageModelTier>; | |
| infographic_models?: ImageModelTier; | |
| images_available?: boolean; | |
| pdf_available: boolean; | |
| }>( | |
| "/v1/design/templates", | |
| ), | |
| designSlideTemplates: () => | |
| request<{ | |
| templates: DesignTemplate[]; | |
| max_colors: number; | |
| fonts: string[]; | |
| image_models: Record<string, ImageModelTier>; | |
| infographic_models?: ImageModelTier; | |
| images_available: boolean; | |
| pdf_available: boolean; | |
| }>("/v1/design/slide-templates"), | |
| designSlideImages: (runId: string) => | |
| request<SlideImages>(`/v1/runs/${runId}/design-slides/images`), | |
| designBookTemplates: () => request<BookCatalog>("/v1/design/book-templates"), | |
| designBookImages: (runId: string) => | |
| request<{ saved: SavedImages | null }>(`/v1/runs/${runId}/design-book/images`), | |
| /* What this account chose the last time it designed this run. */ | |
| designPrefs: (runId: string) => | |
| request<{ designer?: string; colors?: string[]; author?: string; org_name?: string; | |
| font?: string }>(`/v1/runs/${runId}/design/prefs`), | |
| designImages: (runId: string) => | |
| request<{ | |
| saved: SavedImages | null; | |
| infographics?: SavedImages | null; | |
| infographic_candidates?: number; | |
| infographic_limit?: number; | |
| }>(`/v1/runs/${runId}/design/images`), | |
| designRuns: (q = "") => | |
| request<{ items: DesignableRun[] }>(`/v1/design/runs?q=${encodeURIComponent(q)}`), | |
| // pipelines | |
| pipelines: () => request<{ items: PipelineDef[] }>("/v1/pipelines"), | |
| readBlueprint: (body: { pipeline_key: string; text: string; upload_ids: string[] }) => | |
| request<BlueprintReading>("/v1/blueprint/read", { method: "POST", body: JSON.stringify(body) }), | |
| // projects | |
| projects: (params: { kind?: string; archived?: boolean } = {}) => { | |
| const q = new URLSearchParams(); | |
| if (params.kind) q.set("kind", params.kind); | |
| if (params.archived !== undefined) q.set("archived", String(params.archived)); | |
| return request<{ items: Project[]; total: number }>(`/v1/projects?${q}`); | |
| }, | |
| project: (id: string) => request<Project>(`/v1/projects/${id}`), | |
| createProject: (body: { | |
| kind: string; | |
| title: string; | |
| description?: string; | |
| language?: string; | |
| }) => request<Project>("/v1/projects", { method: "POST", body: JSON.stringify(body) }), | |
| updateProject: (id: string, body: Record<string, unknown>) => | |
| request<Project>(`/v1/projects/${id}`, { method: "PATCH", body: JSON.stringify(body) }), | |
| deleteProject: (id: string) => request<void>(`/v1/projects/${id}`, { method: "DELETE" }), | |
| // runs | |
| runs: (projectId: string) => | |
| request<{ items: Run[]; total: number }>(`/v1/projects/${projectId}/runs`), | |
| run: (id: string) => request<RunDetail>(`/v1/runs/${id}`), | |
| startRun: ( | |
| projectId: string, | |
| body: { | |
| params: Record<string, unknown>; | |
| skip_steps?: string[]; | |
| profile_id?: string | null; | |
| }, | |
| ) => | |
| request<Run>(`/v1/projects/${projectId}/runs`, { | |
| method: "POST", | |
| body: JSON.stringify(body), | |
| }), | |
| // The blueprint gate. Saving and approving are separate so a long edit is | |
| // never lost, but approve also accepts the edit so the screen can do both in | |
| // one call rather than leaving a window between them. | |
| review: (id: string) => request<ReviewPayload>(`/v1/runs/${id}/review`), | |
| saveReview: (id: string, blueprint: Record<string, unknown>) => | |
| request<{ saved: boolean }>(`/v1/runs/${id}/review`, { | |
| method: "PATCH", | |
| body: JSON.stringify({ blueprint }), | |
| }), | |
| approveReview: (id: string, blueprint?: Record<string, unknown>) => | |
| request<Run>(`/v1/runs/${id}/approve`, { | |
| method: "POST", | |
| body: JSON.stringify(blueprint ? { blueprint } : {}), | |
| }), | |
| // ยซุงุณุชูุฏูู ุงูุฑูุงูุฉยป - the novel's studio (api/v1/novel.py) | |
| novelCatalog: () => request<NovelCatalog>("/v1/novel/catalog"), | |
| novelOutlineCheck: (plan: Record<string, unknown>) => | |
| request<OutlineReport>("/v1/novel/outline-check", { method: "POST", body: JSON.stringify({ plan }) }), | |
| novelRegenerate: (id: string, n: number, plan: Record<string, unknown>, note = "") => | |
| request<{ chapter: Record<string, unknown>; effects: string[]; check: OutlineReport }>( | |
| `/v1/runs/${id}/novel/chapters/${n}/regenerate`, | |
| { method: "POST", body: JSON.stringify({ plan, note }) }), | |
| novelWorkspace: (id: string) => request<NovelWorkspace>(`/v1/runs/${id}/novel/workspace`), | |
| novelAction: (id: string, n: number, action: string, note = "", confirm = false) => | |
| request<NovelWorkspace & { affected?: number[] }>(`/v1/runs/${id}/novel/chapters/${n}/action`, { | |
| method: "POST", body: JSON.stringify({ action, note, confirm }), | |
| }), | |
| novelCheck: (id: string, n: number) => | |
| request<NovelWorkspace & { findings: string[] }>(`/v1/runs/${id}/novel/chapters/${n}/check`, { method: "POST" }), | |
| novelApprove: (id: string, n: number) => | |
| request<NovelWorkspace>(`/v1/runs/${id}/novel/chapters/${n}/approve`, { method: "POST" }), | |
| novelRestore: (id: string, n: number, version: number, confirm = false) => | |
| request<NovelWorkspace>(`/v1/runs/${id}/novel/chapters/${n}/restore`, { | |
| method: "POST", body: JSON.stringify({ version, confirm }), | |
| }), | |
| novelQuality: (id: string) => request<NovelWorkspace>(`/v1/runs/${id}/novel/quality`, { method: "POST" }), | |
| novelExport: (id: string) => | |
| request<{ files: { id: string; kind: string; format: string }[]; pdf: boolean; note: string }>( | |
| `/v1/runs/${id}/novel/export`, { method: "POST" }), | |
| /** The run's own record, from `offset` bytes on. The caller passes back the | |
| offset it was handed, so each poll carries only what is new. */ | |
| runLog: (id: string, offset: number) => | |
| request<{ text: string; offset: number }>(`/v1/runs/${id}/log?offset=${offset}`), | |
| resumeRun: (id: string) => request<Run>(`/v1/runs/${id}/resume`, { method: "POST" }), | |
| cancelRun: (id: string) => request<Run>(`/v1/runs/${id}/cancel`, { method: "POST" }), | |
| stepOutput: (runId: string, stepKey: string) => | |
| request<{ step_key: string; status: string; output: unknown }>( | |
| `/v1/runs/${runId}/steps/${stepKey}/output`, | |
| ), | |
| // artifacts | |
| artifacts: (projectId: string) => | |
| request<{ items: ArtifactMeta[] }>(`/v1/projects/${projectId}/artifacts`), | |
| /** The raw URL. Only useful with an Authorization header - see | |
| * downloadArtifact / viewArtifact below, which is how the UI reaches it. */ | |
| artifactUrl: (id: string) => `${API_URL}/v1/artifacts/${id}`, | |
| // uploads | |
| uploads: (projectId: string) => | |
| request<{ items: UploadMeta[] }>(`/v1/projects/${projectId}/uploads`), | |
| deleteUpload: (id: string) => request<void>(`/v1/uploads/${id}`, { method: "DELETE" }), | |
| /** how the file was read, and the start of its text */ | |
| upload: (id: string, preview = 0) => | |
| request<UploadMeta>(`/v1/uploads/${id}?preview=${preview}`), | |
| /** read the file again, every page by OCR */ | |
| rereadUpload: (id: string) => | |
| request<UploadMeta>(`/v1/uploads/${id}/read?force_ocr=true`, { method: "POST" }), | |
| // task types (the spec's name for a pipeline) | |
| taskTypes: () => request<{ items: TaskType[] }>("/v1/task-types"), | |
| taskType: (id: string) => request<TaskType>(`/v1/task-types/${id}`), | |
| // profiles - saved context | |
| profileSchema: () => request<JsonSchema>("/v1/profiles/schema"), | |
| profiles: () => request<{ items: SavedProfile[] }>("/v1/profiles"), | |
| createProfile: (body: ProfileInput) => | |
| request<SavedProfile>("/v1/profiles", { method: "POST", body: JSON.stringify(body) }), | |
| updateProfile: (id: string, body: ProfileInput) => | |
| request<SavedProfile>(`/v1/profiles/${id}`, { method: "PATCH", body: JSON.stringify(body) }), | |
| deleteProfile: (id: string) => | |
| request<{ archived: boolean; usedByRuns: number }>(`/v1/profiles/${id}`, { method: "DELETE" }), | |
| // library and usage | |
| library: (params: Record<string, string> = {}) => | |
| request<{ items: LibraryItem[]; total: number }>( | |
| `/v1/library?${new URLSearchParams(params)}`, | |
| ), | |
| usage: () => request<UsageSummary>("/v1/usage"), | |
| announcements: () => request<{ items: AnnouncementItem[] }>("/v1/announcements"), | |
| // admin | |
| // user administration | |
| /* The public catalogue. Slim on purpose: `/v1/pipelines` carries a JSON | |
| Schema for every step and runs to 108 KB, which the wizard needs and the | |
| front page does not. */ | |
| catalogue: () => request<{ items: CatalogueEntry[] }>("/v1/catalogue"), | |
| adminPendingUsers: () => request<AdminUserRow[]>("/v1/admin/users/pending"), | |
| approveUser: ( | |
| id: string, | |
| body: { | |
| allowed_task_types: string[]; | |
| department?: string | null; | |
| make_admin?: boolean; | |
| design_access?: string[]; | |
| }, | |
| ) => | |
| request<Profile>(`/v1/admin/users/${id}/approve`, { | |
| method: "POST", | |
| body: JSON.stringify(body), | |
| }), | |
| deleteUser: (id: string) => | |
| request<void>(`/v1/admin/users/${id}`, { method: "DELETE" }), | |
| /* The founder's alone: which designers an account may use. */ | |
| setDesignAccess: (id: string, designs: string[]) => | |
| request<{ design_access: string[] }>(`/v1/admin/users/${id}/design-access`, { | |
| method: "PUT", | |
| body: JSON.stringify({ design_access: designs }), | |
| }), | |
| /* Generated and handed over, never mailed - see the endpoint's own note. */ | |
| userResetLink: (id: string) => | |
| request<{ email: string; link: string; expires_in_minutes: number }>( | |
| `/v1/admin/users/${id}/reset-link`, | |
| { method: "POST" }, | |
| ), | |
| patchUser: ( | |
| id: string, | |
| body: { | |
| status?: string; | |
| role?: string; | |
| department?: string; | |
| allowed_task_types?: string[]; | |
| monthly_cost_limit_usd?: number | null; | |
| }, | |
| ) => | |
| request<Profile>(`/v1/admin/users/${id}`, { | |
| method: "PATCH", | |
| body: JSON.stringify(body), | |
| }), | |
| /** One person, whole: totals, tools, and the named list of what they made. */ | |
| userDetail: (id: string, days: number) => | |
| request<UserDetail>(`/v1/admin/users/${id}/detail?days=${days}`), | |
| userByTaskType: (id: string, days: number) => | |
| request<TaskTypeSpend[]>(`/v1/admin/users/${id}/by-task-type?days=${days}`), | |
| usageMatrix: (days: number) => | |
| request<UsageMatrix>(`/v1/admin/usage/matrix?days=${days}`), | |
| adminTaskTypes: () => request<{ items: TaskType[] }>("/v1/admin/task-types"), | |
| adminPatchTaskType: (id: string, body: Record<string, unknown>) => | |
| request<TaskType>(`/v1/admin/task-types/${id}`, { method: "PATCH", body: JSON.stringify(body) }), | |
| adminAnnouncements: () => request<{ items: AdminAnnouncement[] }>("/v1/admin/announcements"), | |
| adminCreateAnnouncement: (body: Record<string, unknown>) => | |
| request<{ id: string }>("/v1/admin/announcements", { method: "POST", body: JSON.stringify(body) }), | |
| adminPatchAnnouncement: (id: string, body: { published?: boolean; body?: string }) => | |
| request<{ id: string; published: boolean }>(`/v1/admin/announcements/${id}`, { | |
| method: "PATCH", | |
| body: JSON.stringify(body), | |
| }), | |
| adminDeleteAnnouncement: (id: string) => | |
| request<void>(`/v1/admin/announcements/${id}`, { method: "DELETE" }), | |
| adminAudit: (params: Record<string, string> = {}) => | |
| request<{ items: AuditEntry[] }>(`/v1/admin/audit?${new URLSearchParams(params)}`), | |
| adminRunDetail: (id: string) => request<AdminRunDetail>(`/v1/admin/runs/${id}`), | |
| adminRetryRun: (id: string) => | |
| request<{ status: string }>(`/v1/admin/runs/${id}/retry`, { method: "POST" }), | |
| adminImpersonate: (id: string) => | |
| request<{ userId: string; email: string; note: string }>( | |
| `/v1/admin/users/${id}/impersonate`, { method: "POST" }, | |
| ), | |
| adminOverview: () => request<AdminOverview>("/v1/admin/overview"), | |
| /* Our ledger beside the provider's, so a gap is visible rather than | |
| assumed. The dashboard cannot otherwise tell you it under-counted. */ | |
| adminReconciliation: () => request<Reconciliation>("/v1/admin/reconciliation"), | |
| // 500, the endpoint's ceiling: the users screen groups and ranks everyone. | |
| adminUsers: (sort = "cost", limit = 500) => | |
| request<UserUsage[]>(`/v1/admin/users?sort=${sort}&limit=${limit}`), | |
| adminPatchUser: (id: string, body: Record<string, unknown>) => | |
| request<Profile>(`/v1/admin/users/${id}`, { method: "PATCH", body: JSON.stringify(body) }), | |
| adminSeries: (days = 30) => request<SeriesPoint[]>(`/v1/admin/usage/series?days=${days}`), | |
| adminByModel: (days = 30) => request<ModelBreakdown[]>(`/v1/admin/usage/by-model?days=${days}`), | |
| adminByPipeline: (days = 30) => | |
| request<PipelineBreakdown[]>(`/v1/admin/usage/by-pipeline?days=${days}`), | |
| adminRuns: (status?: string) => | |
| request<{ items: AdminRun[] }>(`/v1/admin/runs${status ? `?status=${status}` : ""}`), | |
| adminFailures: (days = 30) => | |
| request<{ | |
| runs_total: number; | |
| runs_succeeded: number; | |
| runs_failed: number; | |
| success_rate: number | null; | |
| by_step: { step_key: string; failures: number }[]; | |
| }>(`/v1/admin/runs/failures?days=${days}`), | |
| }; | |
| /** Live run progress over SSE. | |
| * | |
| * EventSource cannot send an Authorization header, so this uses fetch with a | |
| * reader instead. Returns a function that stops the stream. | |
| */ | |
| export function streamRun( | |
| runId: string, | |
| onEvent: (event: string, data: unknown) => void, | |
| ): () => void { | |
| const controller = new AbortController(); | |
| (async () => { | |
| const res = await fetch(`${API_URL}/v1/runs/${runId}/events`, { | |
| headers: { ...(await authHeader()) }, | |
| signal: controller.signal, | |
| }); | |
| if (!res.body) return; | |
| const reader = res.body.getReader(); | |
| const decoder = new TextDecoder(); | |
| let buffer = ""; | |
| while (true) { | |
| const { done, value } = await reader.read(); | |
| if (done) break; | |
| buffer += decoder.decode(value, { stream: true }); | |
| // SSE frames are separated by a blank line. | |
| const frames = buffer.split("\n\n"); | |
| buffer = frames.pop() ?? ""; | |
| for (const frame of frames) { | |
| let event = "message"; | |
| let data = ""; | |
| for (const line of frame.split("\n")) { | |
| if (line.startsWith("event:")) event = line.slice(6).trim(); | |
| else if (line.startsWith("data:")) data += line.slice(5).trim(); | |
| } | |
| if (!data) continue; | |
| try { | |
| onEvent(event, JSON.parse(data)); | |
| } catch { | |
| onEvent(event, data); | |
| } | |
| } | |
| } | |
| })().catch((e) => { | |
| if ((e as Error).name !== "AbortError") console.warn("run stream ended", e); | |
| }); | |
| return () => controller.abort(); | |
| } | |
| /** Upload a source file. Uses FormData, so the JSON content-type must not be | |
| * set - the browser has to write its own multipart boundary. */ | |
| export async function uploadSource(projectId: string, file: File, read = true): Promise<UploadMeta> { | |
| const body = new FormData(); | |
| body.append("file", file); | |
| const res = await fetch(`${API_URL}/v1/projects/${projectId}/uploads${read ? "" : "?read=false"}`, { | |
| method: "POST", | |
| headers: await authHeader(), | |
| body, | |
| }); | |
| if (!res.ok) { | |
| let message = `ุชุนุฐูุฑ ุฑูุน ุงูู ูู (${res.status})`; | |
| try { | |
| const payload = await res.json(); | |
| if (typeof payload?.detail === "string") message = payload.detail; | |
| } catch { | |
| /* keep the fallback */ | |
| } | |
| throw new ApiError(res.status, message); | |
| } | |
| return res.json() as Promise<UploadMeta>; | |
| } | |
| /** Design a finished Arabic bag: template, up to four colours, a logo. | |
| * Multipart, so the JSON content-type is left for the browser to set. */ | |
| export async function designRun( | |
| runId: string, | |
| form: { | |
| template: string; | |
| colors: string[]; | |
| author: string; | |
| orgName: string; | |
| showImageSlots: boolean; | |
| font: string; | |
| images: "none" | "saved" | "generate"; | |
| imageStyle?: "vector" | "natural"; | |
| models: Record<string, string>; | |
| infographics?: "none" | "saved" | "generate"; | |
| infographicCount?: number; | |
| infographicModel?: string; | |
| logo: File | null; | |
| }, | |
| ): Promise<DesignResult> { | |
| const body = new FormData(); | |
| body.append("template", form.template); | |
| body.append("colors", JSON.stringify(form.colors)); | |
| body.append("author", form.author); | |
| body.append("org_name", form.orgName); | |
| body.append("show_image_slots", String(form.showImageSlots)); | |
| body.append("font", form.font); | |
| body.append("images", form.images); | |
| body.append("image_style", form.imageStyle ?? "vector"); | |
| for (const [tier, key] of Object.entries(form.models)) body.append(`model_${tier}`, key); | |
| body.append("infographics", form.infographics ?? "none"); | |
| body.append("infographic_count", String(form.infographicCount ?? 0)); | |
| if (form.infographicModel) body.append("model_infographic", form.infographicModel); | |
| if (form.logo) body.append("logo", form.logo); | |
| const res = await fetch(`${API_URL}/v1/runs/${runId}/design`, { | |
| method: "POST", | |
| headers: await authHeader(), | |
| body, | |
| }); | |
| if (!res.ok) { | |
| let message = `ุชุนุฐูุฑ ุชุตู ูู ุงูุญููุจุฉ (${res.status})`; | |
| try { | |
| const payload = await res.json(); | |
| if (typeof payload?.detail === "string") message = payload.detail; | |
| } catch { | |
| /* keep the fallback */ | |
| } | |
| throw new ApiError(res.status, message); | |
| } | |
| return res.json() as Promise<DesignResult>; | |
| } | |
| /** Design a run's slides - a bag's deck or a standalone deck - as PowerPoint. */ | |
| export async function designSlides( | |
| runId: string, | |
| form: { | |
| template: string; | |
| colors: string[]; | |
| author: string; | |
| orgName: string; | |
| font: string; | |
| logo: File | null; | |
| images?: "none" | "saved" | "bag" | "generate"; | |
| scope?: "main" | "all"; | |
| models?: Record<string, string>; | |
| infographics?: "none" | "saved" | "generate"; | |
| infographicCount?: number; | |
| infographicModel?: string; | |
| activityPictures?: boolean; | |
| still?: boolean; | |
| imageTreatment?: "grayscale" | "duotone" | "color"; | |
| }, | |
| ): Promise<SlideDesignResult> { | |
| const body = new FormData(); | |
| body.append("template", form.template); | |
| body.append("colors", JSON.stringify(form.colors)); | |
| body.append("author", form.author); | |
| body.append("org_name", form.orgName); | |
| body.append("font", form.font); | |
| body.append("images", form.images ?? "none"); | |
| body.append("scope", form.scope ?? "all"); | |
| body.append("infographics", form.infographics ?? "none"); | |
| body.append("infographic_count", String(form.infographicCount ?? 0)); | |
| if (form.infographicModel) body.append("model_infographic", form.infographicModel); | |
| for (const [tier, key] of Object.entries(form.models ?? {})) body.append(`model_${tier}`, key); | |
| body.append("activity_pictures", String(Boolean(form.activityPictures))); | |
| body.append("still", String(Boolean(form.still))); | |
| if (form.imageTreatment) body.append("image_treatment", form.imageTreatment); | |
| if (form.logo) body.append("logo", form.logo); | |
| const res = await fetch(`${API_URL}/v1/runs/${runId}/design-slides`, { | |
| method: "POST", | |
| headers: await authHeader(), | |
| body, | |
| }); | |
| if (!res.ok) { | |
| let message = `ุชุนุฐูุฑ ุชุตู ูู ุงูุนุฑุถ (${res.status})`; | |
| try { | |
| const payload = await res.json(); | |
| if (typeof payload?.detail === "string") message = payload.detail; | |
| } catch { | |
| /* keep the fallback */ | |
| } | |
| throw new ApiError(res.status, message); | |
| } | |
| return res.json() as Promise<SlideDesignResult>; | |
| } | |
| /* Artifacts need the Authorization header, which a plain <a href> cannot send. | |
| Linking straight at the endpoint therefore produced a 401 page instead of a | |
| file. These fetch it properly and hand the browser a blob. */ | |
| async function fetchArtifact(id: string): Promise<Blob> { | |
| const res = await fetch(`${API_URL}/v1/artifacts/${id}`, { | |
| headers: await authHeader(), | |
| }); | |
| if (!res.ok) { | |
| throw new ApiError(res.status, `ุชุนุฐูุฑ ุฌูุจ ุงูู ูู (${res.status})`); | |
| } | |
| return res.blob(); | |
| } | |
| function safeName(title: string, format: string): string { | |
| const base = (title || "ู ุฎุฑุฌ").replace(/[/:*?"<>|]/g, "-").slice(0, 80); | |
| return `${base}.${format.toLowerCase()}`; | |
| } | |
| /** Save the artifact to disk under a readable name. */ | |
| export async function downloadArtifact( | |
| id: string, | |
| title: string, | |
| format: string, | |
| ): Promise<void> { | |
| const blob = await fetchArtifact(id); | |
| const url = URL.createObjectURL(blob); | |
| const link = document.createElement("a"); | |
| link.href = url; | |
| link.download = safeName(title, format); | |
| document.body.appendChild(link); | |
| link.click(); | |
| link.remove(); | |
| // Revoked on the next tick: Firefox cancels the download if it goes early. | |
| setTimeout(() => URL.revokeObjectURL(url), 10_000); | |
| } | |
| /** The file name the server gave the gate's Word file (RFC 5987 `filename*`), | |
| * or ยซุงูุชุตูุฑ ุงูููู.docxยป when it gave none. */ | |
| export function reviewFileName(disposition: string | null): string { | |
| const m = /filename\*=UTF-8''([^;]+)/i.exec(disposition || ""); | |
| if (m) { | |
| try { | |
| const name = decodeURIComponent(m[1].trim()); | |
| if (name.toLowerCase().endsWith(".docx")) return safeName(name.slice(0, -5), "docx"); | |
| } catch { | |
| /* a malformed header falls back to the plain name */ | |
| } | |
| } | |
| return safeName("ุงูุชุตูุฑ ุงูููู", "docx"); | |
| } | |
| /** Save the blueprint waiting at the gate as a Word file. | |
| The reviewer is being asked whether the structure holds together, and a form | |
| is the wrong shape for that question: it shows one field at a time and never | |
| the whole thing in order. Rendered server-side from what the run is holding, | |
| so a saved edit is already in it. */ | |
| export async function downloadBlueprint(runId: string): Promise<void> { | |
| const res = await fetch(`${API_URL}/v1/runs/${runId}/review.docx`, { | |
| headers: await authHeader(), | |
| }); | |
| if (!res.ok) { | |
| throw new ApiError(res.status, `ุชุนุฐูุฑ ุชุฌููุฒ ุงูู ูู (${res.status})`); | |
| } | |
| const url = URL.createObjectURL(await res.blob()); | |
| const link = document.createElement("a"); | |
| link.href = url; | |
| // named after the book or bag it holds (the server says so), not | |
| // ยซุงูุชุตูุฑ ุงููููยป again for the browser to number ยซ(9)ยป | |
| link.download = reviewFileName(res.headers.get("Content-Disposition")); | |
| document.body.appendChild(link); | |
| link.click(); | |
| link.remove(); | |
| setTimeout(() => URL.revokeObjectURL(url), 10_000); | |
| } | |
| /** Open an HTML report in a new tab. */ | |
| /** A fixed example of a book template and weight, opened in a new tab - | |
| * drawn from the demo book on the server, no model called. */ | |
| export async function viewBookExample(template: string, tier: string, trim: string): Promise<void> { | |
| const tab = window.open("", "_blank"); | |
| try { | |
| const q = new URLSearchParams({ template, tier, trim }); | |
| const res = await fetch(`${API_URL}/v1/design/book-example?${q}`, { headers: await authHeader() }); | |
| if (!res.ok) throw new ApiError(res.status, `ุชุนุฐูุฑ ูุชุญ ุงููู ูุฐุฌ (${res.status})`); | |
| const url = URL.createObjectURL(await res.blob()); | |
| if (tab) tab.location.href = url; | |
| else window.location.href = url; | |
| setTimeout(() => URL.revokeObjectURL(url), 60_000); | |
| } catch (e) { | |
| tab?.close(); | |
| throw e; | |
| } | |
| } | |
| /** Design a finished book: the sample for the client, or the whole book. */ | |
| export async function designBook( | |
| runId: string, | |
| form: Record<string, string | boolean | string[]>, | |
| logo: File | null, | |
| ): Promise<BookDesignResult> { | |
| const body = new FormData(); | |
| for (const [k, v] of Object.entries(form)) { | |
| body.append(k, Array.isArray(v) ? JSON.stringify(v) : String(v)); | |
| } | |
| if (logo) body.append("logo", logo); | |
| const res = await fetch(`${API_URL}/v1/runs/${runId}/design-book`, { | |
| method: "POST", | |
| headers: await authHeader(), | |
| body, | |
| }); | |
| if (!res.ok) { | |
| let message = `ุชุนุฐูุฑ ุชุตู ูู ุงููุชุงุจ (${res.status})`; | |
| try { | |
| const payload = await res.json(); | |
| if (typeof payload?.detail === "string") message = payload.detail; | |
| } catch { | |
| /* keep the fallback */ | |
| } | |
| throw new ApiError(res.status, message); | |
| } | |
| return res.json(); | |
| } | |
| export async function viewArtifact(id: string): Promise<void> { | |
| // The tab is opened synchronously, before the await, or the pop-up blocker | |
| // treats it as unrelated to the click that caused it. | |
| const tab = window.open("", "_blank"); | |
| try { | |
| const blob = await fetchArtifact(id); | |
| const url = URL.createObjectURL(blob); | |
| if (tab) { | |
| tab.location.href = url; | |
| } else { | |
| window.location.href = url; | |
| } | |
| setTimeout(() => URL.revokeObjectURL(url), 60_000); | |
| } catch (e) { | |
| tab?.close(); | |
| throw e; | |
| } | |
| } | |
| // โโ ยซุงุณุชูุฏูู ุงูุฑูุงูุฉยป types โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| export type NovelCatalog = Record<string, Record<string, [string, string]>>; | |
| export type OutlineItem = { key: string; question: string; ok: boolean; note: string }; | |
| export type OutlineReport = { | |
| items: OutlineItem[]; passed: number; total: number; | |
| cards: { chapter: number; missing: string[] }[]; events_missing: string[]; | |
| acts: Record<string, number[]>; | |
| }; | |
| export type NovelChapter = { | |
| number: number; title: string; status: string; status_ar: string; | |
| card: Record<string, unknown>; text: string; summary: string; words: number; current: number; | |
| attention: string[]; check: string[]; | |
| versions: { index: number; source: string; at: string; words: number }[]; | |
| }; | |
| export type NovelQualityRow = { | |
| key: string; name: string; weight: number; core: boolean; score: number | null; reason: string; | |
| strengths: string[]; weaknesses: string[]; recommendations: string[]; chapters: number[]; | |
| }; | |
| export type NovelWorkspace = { | |
| title: string; author: string; chapters: NovelChapter[]; memory: Record<string, unknown>; | |
| quality: null | { verdict?: string; quality?: { total: number | null; level: string; warning: string; | |
| criteria: NovelQualityRow[]; revisit: number[]; metrics: Record<string, number> } }; | |
| counts: Record<string, number>; actions: Record<string, string>; | |
| history: { chapter: number; event: string; at: string }[]; | |
| }; | |