Add the V2 web app: design system, shell, study flows, AI, settings, sharing
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
eae109c166
commit
74a98ac1f1
52 changed files with 11976 additions and 1 deletions
147
web/src/lib/api.ts
Normal file
147
web/src/lib/api.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
/** Thin client for the Study Desk API: JSON in, JSON out, typed errors, CSRF header on every call. */
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code: string;
|
||||
details?: unknown;
|
||||
constructor(status: number, code: string, message: string, details?: unknown) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
/** Set by the app shell: called when any request comes back 401 so the login screen can appear. */
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
export function setUnauthorizedHandler(fn: (() => void) | null): void {
|
||||
onUnauthorized = fn;
|
||||
}
|
||||
|
||||
const BASE_HEADERS = { 'X-Requested-With': 'studydesk' };
|
||||
|
||||
async function toError(res: Response): Promise<ApiError> {
|
||||
let code = 'http_error';
|
||||
let message = res.status >= 500 ? 'The server ran into a problem. Try again in a moment.' : `Request failed (${res.status})`;
|
||||
let details: unknown;
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body?.error) {
|
||||
code = body.error.code ?? code;
|
||||
message = body.error.message ?? message;
|
||||
details = body.error.details;
|
||||
}
|
||||
} catch {
|
||||
/* not JSON */
|
||||
}
|
||||
return new ApiError(res.status, code, message, details);
|
||||
}
|
||||
|
||||
export async function request<T>(method: string, url: string, body?: unknown, init: { signal?: AbortSignal; publicCall?: boolean } = {}): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
signal: init.signal,
|
||||
headers: body instanceof FormData ? BASE_HEADERS : body !== undefined ? { ...BASE_HEADERS, 'Content-Type': 'application/json' } : BASE_HEADERS,
|
||||
body: body instanceof FormData ? body : body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
if ((e as Error)?.name === 'AbortError') throw e;
|
||||
throw new ApiError(0, 'network', 'Could not reach the server. Check your connection and try again.');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const err = await toError(res);
|
||||
if (res.status === 401 && !init.publicCall && err.code === 'unauthorized') onUnauthorized?.();
|
||||
throw err;
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal }),
|
||||
post: <T>(url: string, body?: unknown) => request<T>('POST', url, body ?? {}),
|
||||
put: <T>(url: string, body?: unknown) => request<T>('PUT', url, body ?? {}),
|
||||
patch: <T>(url: string, body?: unknown) => request<T>('PATCH', url, body ?? {}),
|
||||
del: <T>(url: string) => request<T>('DELETE', url),
|
||||
upload: <T>(url: string, form: FormData) => request<T>('POST', url, form),
|
||||
/** Public (share-link) calls never trigger the login screen. */
|
||||
pub: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal, publicCall: true }),
|
||||
};
|
||||
|
||||
export function errorMessage(e: unknown, fallback = 'Something went wrong.'): string {
|
||||
if (e instanceof ApiError) return e.message;
|
||||
if (e instanceof Error && e.message) return e.message;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Uploads with progress (fetch cannot report upload progress). */
|
||||
export function uploadWithProgress<T>(url: string, form: FormData, onProgress: (fraction: number) => void): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', url);
|
||||
xhr.setRequestHeader('X-Requested-With', 'studydesk');
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress(e.loaded / e.total);
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError(0, 'network', 'The upload was interrupted. Check your connection and try again.'));
|
||||
xhr.onload = () => {
|
||||
let body: any = null;
|
||||
try {
|
||||
body = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve(body as T);
|
||||
else {
|
||||
if (xhr.status === 401) onUnauthorized?.();
|
||||
reject(new ApiError(xhr.status, body?.error?.code ?? 'http_error', body?.error?.message ?? `Upload failed (${xhr.status})`, body?.error?.details));
|
||||
}
|
||||
};
|
||||
xhr.send(form);
|
||||
});
|
||||
}
|
||||
|
||||
/** POSTs JSON and reads a server-sent event stream of JSON objects. */
|
||||
export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
if (!res.ok || !res.body) {
|
||||
const err = await toError(res);
|
||||
if (res.status === 401) onUnauthorized?.();
|
||||
throw err;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let idx: number;
|
||||
while ((idx = buffer.search(/\r?\n\r?\n/)) >= 0) {
|
||||
const block = buffer.slice(0, idx);
|
||||
buffer = buffer.slice(idx).replace(/^\r?\n\r?\n/, '');
|
||||
const data = block
|
||||
.split(/\r?\n/)
|
||||
.filter((l) => l.startsWith('data:'))
|
||||
.map((l) => l.slice(5).trimStart())
|
||||
.join('\n');
|
||||
if (!data) continue;
|
||||
try {
|
||||
const event = JSON.parse(data) as T;
|
||||
if (event.type !== 'ping') onEvent(event);
|
||||
} catch {
|
||||
/* skip malformed event */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue