import type { Locale } from "@/i18n/messages"; export class ApiError extends Error { readonly status: number; readonly retryAfter: number | null; /** Set when the school has this route's module switched off (`403 {error, module}`). */ readonly module: string | null; /** Machine refusal code (`{error, code}`), sent only where a route documents one. */ readonly code: string | null; constructor( status: number, message: string, retryAfter: number | null = null, module: string | null = null, code: string | null = null, ) { super(message); this.name = "ApiError"; this.status = status; this.retryAfter = retryAfter; this.module = module; this.code = code; } } /** True for a refusal because the school's module is off, not a role or record problem. */ export function isModuleDisabledError(err: unknown): err is ApiError & { module: string } { return err instanceof ApiError && err.status === 403 && err.module != null; } // A builder can switch a module off mid-session; the backend then answers // `403 {error, module}` on every route of it. Listeners (the modules context) // hear about it on the first such refusal and refetch the enabled set, so the // nav and route gate catch up without a reload. const moduleDisabledListeners = new Set<(module: string) => void>(); export function onModuleDisabled(listener: (module: string) => void): () => void { moduleDisabledListeners.add(listener); return () => moduleDisabledListeners.delete(listener); } function disabledModuleOf(status: number, data: unknown): string | null { if (status !== 403 || !data || typeof data !== "object") return null; const module = (data as { module?: unknown }).module; if (typeof module !== "string" || !module) return null; for (const listener of moduleDisabledListeners) listener(module); return module; } type RequestOptions = { method?: "GET" | "POST" | "PATCH" | "DELETE"; body?: unknown; signal?: AbortSignal; cache?: RequestCache; }; const API_PREFIX = "/api"; // Deadline for a JSON request. Generous enough for the slowest real call // (login's Argon2 hash under load), short enough that a hung socket surfaces // as an error instead of a permanently disabled button. const REQUEST_TIMEOUT_MS = 20_000; const API_ERROR_MESSAGES: Record> = { // Settings lists reject two entries that fold to the same word — İZİN/izin, // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed. "exam_kinds: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": { en: "Two exam kinds are the same word apart from upper/lower case or Turkish letters. Keep only one of them.", tr: "İki sınav türü, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.", }, "attendance_statuses: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": { en: "Two attendance statuses are the same word apart from upper/lower case or Turkish letters. Keep only one of them.", tr: "İki yoklama durumu, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.", }, "request failed": { en: "Request failed.", tr: "İşlem tamamlanamadı.", }, "unauthorized": { en: "Sign in to continue.", tr: "Devam etmek için giriş yap.", }, "forbidden": { en: "You do not have permission for this action.", tr: "Bu işlem için yetkin yok.", }, "not found": { en: "The requested record was not found.", tr: "İstenen kayıt bulunamadı.", }, "invalid credentials": { en: "Username or password is incorrect.", tr: "Kullanıcı adı veya şifre hatalı.", }, "username already exists": { en: "This username is already in use.", tr: "Bu kullanıcı adı zaten kullanılıyor.", }, "file too large": { en: "This file is larger than the allowed upload limit.", tr: "Bu dosya izin verilen yükleme sınırından büyük.", }, "payload too large": { en: "This upload is too large. Choose a smaller file and try again.", tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", }, "request entity too large": { en: "This upload is too large. Choose a smaller file and try again.", tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", }, "unsupported file type": { en: "This file type is not supported.", tr: "Bu dosya türü desteklenmiyor.", }, "unsupported image type": { en: "This image type is not supported. Use PNG, JPEG, WebP, or GIF.", tr: "Bu görsel türü desteklenmiyor. PNG, JPEG, WebP veya GIF kullan.", }, "invalid image": { en: "The image could not be read. Choose another image and try again.", tr: "Görsel okunamadı. Başka bir görsel seçip tekrar dene.", }, "too many files": { en: "This note already has the maximum number of files.", tr: "Bu notta en fazla dosya sayısına ulaşılmış.", }, "note file limit reached": { en: "This note already has the maximum number of files.", tr: "Bu notta en fazla dosya sayısına ulaşılmış.", }, "this time overlaps a slot you have already published": { en: "This time overlaps a slot you already published.", tr: "Bu zaman aralığı, daha önce yayınladığın bir müsaitlikle çakışıyor.", }, "a repeated slot overlaps one you have already published": { en: "One of the repeated slots overlaps a slot you already published.", tr: "Tekrarlanan müsaitliklerden biri, daha önce yayınladığın bir müsaitlikle çakışıyor.", }, "the repeated slots overlap each other": { en: "The repeated slots overlap each other.", tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.", }, // Builder surface (web/builder.rs, tenant.rs) — byte-exact. "that account is not an admin of this school": { en: "That account exists but is not an admin of this school.", tr: "Bu hesap var ama bu okulun yöneticisi değil.", }, "school is suspended": { en: "This school is suspended.", tr: "Bu okul askıya alınmış.", }, // Booking/decision conflicts from domain/appointment.rs — byte-exact. "the slot is already booked": { en: "Someone else booked this time first.", tr: "Bu saati senden önce başkası aldı.", }, "the slot has already started": { en: "This time has already started, so it can no longer be booked.", tr: "Bu saat başladığı için artık randevu alınamaz.", }, "you already have an appointment at that time": { en: "You already have an appointment at that time.", tr: "O saatte zaten bir randevun var.", }, "the appointment is already settled": { en: "This appointment is already settled.", tr: "Bu randevu zaten sonuçlanmış.", }, "the appointment has already started": { en: "This appointment has already started.", tr: "Bu randevu çoktan başladı.", }, "that time has already started": { en: "That time has already started. Pick a later one.", tr: "O saat çoktan başladı. Daha ileri bir saat seç.", }, "no time has been proposed": { en: "No time has been proposed for this appointment yet.", tr: "Bu randevu için henüz bir saat önerilmedi.", }, "the appointment is no longer pending": { en: "This appointment is no longer waiting for an answer.", tr: "Bu randevu artık yanıt bekliyor değil.", }, "question: this question did not come from a bank template": { en: "This question was not copied from a bank template, so there is nothing to refresh it from.", tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.", }, "request timed out": { en: "The server did not respond in time. Check your connection and try again.", tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.", }, "only the template's owner or an admin can change it": { en: "Only the teacher who created this template (or an admin) can change it.", tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", }, "only the course creator, an assigned teacher, or a manager/admin can author questions": { en: "Only this course's teachers or a manager can add questions to this exam.", tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.", }, "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": { en: "Only this course's teachers or a manager can save this question to the bank.", tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.", }, "cannot change questions after attempts have started": { en: "Students have already started this exam, so its questions can no longer change.", tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", }, "bank questions still reference this subject — re-tag or delete them first": { en: "Question bank templates still use this subject. Re-tag or delete them first.", tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.", }, "the term is archived — past years are read-only": { en: "This term is archived. Past years are read-only.", tr: "Bu dönem arşivli. Geçmiş dönemler salt okunur.", }, "this course's term is archived — past years are read-only": { en: "This course's term is archived. Past years are read-only.", tr: "Bu dersin dönemi arşivli. Geçmiş dönemler salt okunur.", }, "module disabled": { en: "This feature is not enabled for your school.", tr: "Bu özellik okulunuz için etkin değil.", }, "course not found": { en: "Course not found.", tr: "Ders bulunamadı.", }, "exam not found": { en: "Exam not found.", tr: "Sınav bulunamadı.", }, "not enrolled in this exam's course": { en: "You are not enrolled in this exam's course.", tr: "Bu sınavın dersine kayıtlı değilsin.", }, "you are not enrolled in this exam's course": { en: "You are not enrolled in this exam's course.", tr: "Bu sınavın dersine kayıtlı değilsin.", }, "exam is not scheduled": { en: "This exam is not scheduled for online sitting.", tr: "Bu sınav çevrim içi oturum için zamanlanmamış.", }, "attempt not found": { en: "Start the exam before opening the exam room.", tr: "Sınav odasını açmadan önce sınavı başlat.", }, "attempt is closed": { en: "This attempt is closed. Answers are read-only.", tr: "Bu oturum kapalı. Cevaplar salt okunur.", }, "exam has not started": { en: "This exam has not started yet.", tr: "Bu sınav henüz başlamadı.", }, "exam has ended": { en: "This exam has ended.", tr: "Bu sınav sona erdi.", }, "no attempts left": { en: "No attempts left for this exam.", tr: "Bu sınav için deneme hakkı kalmadı.", }, "answer is required": { en: "Enter an answer before saving.", tr: "Kaydetmeden önce cevap gir.", }, "only students can sit exams": { en: "Only students can take exams.", tr: "Sınava yalnızca öğrenciler girebilir.", }, "user_id: only students can be enrolled in a course": { en: "Only students can be enrolled in a course.", tr: "Derse yalnızca öğrenciler kaydedilebilir.", }, "user_id: only students can be graded": { en: "Only students can be graded.", tr: "Yalnızca öğrencilere not verilebilir.", }, "user_id: only students can be marked present in a lesson": { en: "Only students can be marked on a lesson roll call.", tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.", }, "event is full": { en: "This event is full.", tr: "Bu etkinlik dolu.", }, "registration is closed": { en: "Registration is closed for this event.", tr: "Bu etkinlik için kayıt kapalı.", }, "already registered": { en: "This student is already registered.", tr: "Bu öğrenci zaten kayıtlı.", }, "already enrolled": { en: "This student is already enrolled.", tr: "Bu öğrenci zaten kayıtlı.", }, "active pomodoro session already exists": { en: "You already have a focus session running.", tr: "Zaten devam eden bir odak oturumun var.", }, "no active pomodoro session": { en: "There is no active focus session to finish.", tr: "Bitirilecek aktif odak oturumu yok.", }, }; type LocalizedMessage = Record; const ARCHIVED_YEAR: LocalizedMessage = { en: "This academic year is archived. Past years are read-only, so records in it can no longer change.", tr: "Bu eğitim yılı arşivlendi. Geçmiş yıllar salt okunur, bu yüzden içindeki kayıtlar artık değiştirilemez.", }; const STUDENT_NUMBER_TAKEN: LocalizedMessage = { en: "Another student already has this student number. Enter a different number.", tr: "Bu öğrenci numarası başka bir öğrencide kayıtlı. Farklı bir numara gir.", }; const STALE_RECORD: LocalizedMessage = { en: "This record changed while you were editing it. Reload the page and try again.", tr: "Bu kayıt sen düzenlerken değişti. Sayfayı yenileyip tekrar dene.", }; /** * Machine refusal codes (`{error, code}`). The backend sends one only where a * route documents its vocabulary (class attach/add-member, podcast, insight * report, student numbers), so these win over the prose whenever present. * `duplicate` is left out on purpose: it means a course on one route and a * student on another, so the prose patterns below tell them apart. */ const API_ERROR_CODE_MESSAGES: Record = { academic_year_archived: ARCHIVED_YEAR, class_at_course_ceiling: { en: "This class already has the maximum number of courses. Remove a course from it before adding another.", tr: "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.", }, class_roster_too_large: { en: "This class has too many students to enroll in a course in one step. Contact your system administrator.", tr: "Bu şubede bir derse tek seferde kaydedilemeyecek kadar çok öğrenci var. Sistem yöneticine başvur.", }, class_at_roster_ceiling: { en: "This class is full. Remove a student from it before adding another.", tr: "Bu şube dolu. Yeni öğrenci eklemeden önce şubeden bir öğrenci çıkar.", }, class_course_list_too_large: { en: "This class has too many courses to enroll a student in one step. Contact your system administrator.", tr: "Bu şubede bir öğrenciyi tek seferde kaydetmek için çok fazla ders var. Sistem yöneticine başvur.", }, linked_course_missing: { en: "One of this class's courses was removed while the student was being added. Reload the page and try again.", tr: "Öğrenci eklenirken şubenin derslerinden biri kaldırıldı. Sayfayı yenileyip tekrar dene.", }, student_number_taken: STUDENT_NUMBER_TAKEN, session_time_taken: { en: "Another lesson of this section already starts at this time. Pick a different start time.", tr: "Bu şubenin başka bir dersi zaten bu saatte başlıyor. Farklı bir başlangıç saati seç.", }, offering_exists: { en: "This course already has a template for this grade. Edit the existing template instead.", tr: "Bu dersin bu seviye için zaten bir şablonu var. Bunun yerine mevcut şablonu düzenle.", }, offering_in_use: { en: "Classes still teach from this template. Detach the course from those classes first.", tr: "Bu şablondan hâlâ ders işleyen şubeler var. Önce dersi o şubelerden çıkar.", }, slot_overlap: { en: "Another slot on this day overlaps this time window. Pick a different time.", tr: "Bu gündeki başka bir ders saati bu zaman aralığıyla çakışıyor. Farklı bir saat seç.", }, slot_cap: { en: "This weekly plan already holds the maximum number of slots. Remove one before adding another.", tr: "Bu haftalık plan en fazla ders saati sayısına ulaştı. Yenisini eklemeden önce birini kaldır.", }, unknown_exam_kind: { en: "This exam kind is not one the school uses. Pick a kind from the school settings.", tr: "Bu sınav türü okulun kullandığı türlerden biri değil. Okul ayarlarındaki türlerden birini seç.", }, instance_has_no_weekly_plan: { en: "This section has no weekly plan yet. Add slots before generating lessons.", tr: "Bu şubenin henüz haftalık planı yok. Ders üretmeden önce ders saati ekle.", }, instance_has_no_teacher: { en: "No teacher is assigned to this section. Assign a teacher before generating lessons.", tr: "Bu şubeye atanmış öğretmen yok. Ders üretmeden önce bir öğretmen ata.", }, not_ready: { en: "This audio is not ready yet. Wait for it to finish and try again.", tr: "Bu ses kaydı henüz hazır değil. Tamamlanmasını bekleyip tekrar dene.", }, audio_missing: { en: "This audio file could not be found on the server. Generate the episode again.", tr: "Bu ses dosyası sunucuda bulunamadı. Bölümü yeniden oluştur.", }, source_missing: { en: "This note has no PDF to narrate. Attach a PDF to the note and try again.", tr: "Bu notta seslendirilecek bir PDF yok. Nota bir PDF ekleyip tekrar dene.", }, report_missing: { en: "No report has been generated for this day yet.", tr: "Bu gün için henüz rapor oluşturulmadı.", }, report_empty: { en: "There is no data for this day to build a report from.", tr: "Bu gün için rapor oluşturacak veri yok.", }, report_refused: { en: "The AI service declined to write this report. Try again later.", tr: "Yapay zekâ servisi bu raporu hazırlamayı reddetti. Daha sonra tekrar dene.", }, }; /** * Backend refusals that carry no code, matched on the stable part of their * prose (the nouns and the "still linked / in use / already" verb) rather than * byte-exact, so a reworded tail or a different em dash still lands. Checked * in order after the exact table; keep each pattern specific enough that it * cannot swallow an unrelated reason. */ const API_ERROR_PATTERNS: ReadonlyArray = [ [ /\b(classes|terms)\b.*\bstill linked to this (academic )?year\b/, { en: "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.", tr: "Bu eğitim yılına bağlı şubeler ve dönemler var. Silmeden önce onları başka bir yıla taşı veya sil.", }, ], [/\bacademic year is archived\b|\bin an archived academic year\b/, ARCHIVED_YEAR], [ /\btarget year already (holds|has) classes\b/, { en: "The target year already has classes. Choose an empty year to carry the classes into.", tr: "Hedef eğitim yılında zaten şubeler var. Şubeleri aktarmak için boş bir yıl seç.", }, ], [ /\b(academic )?year (with|named) (that|this) name already exists\b|\bacademic year .*already exists\b/, { en: "An academic year with this name already exists. Choose a different name.", tr: "Bu adla bir eğitim yılı zaten var. Farklı bir ad seç.", }, ], [ /\b(students|instances|courses)\b.*\bstill (on|in|attached to) this class\b/, { en: "This class still has students or courses. Remove its students and detach its courses before deleting it.", tr: "Bu şubede hâlâ öğrenci veya ders var. Silmeden önce öğrencileri şubeden çıkar ve dersleri şubeden kaldır.", }, ], [ /\bclass(es)? still teach(es)? this course\b|\bstudents still hold an individual membership\b/, { en: "A class still teaches this course, or students are still enrolled in it directly. Detach it from its classes and remove those students before deleting it.", tr: "Bu ders hâlâ bir şubede okutuluyor ya da derse doğrudan kayıtlı öğrenciler var. Silmeden önce dersi şubelerden çıkar ve bu öğrencileri dersten kaldır.", }, ], [ /\b(exams|karnes?)\b.*\bstill belong to this term\b/, { en: "Exams or finalized report cards still belong to this term, so it cannot be deleted. Archive it instead.", tr: "Bu döneme bağlı sınavlar veya kesinleşmiş karneler var, bu yüzden dönem silinemez. Bunun yerine dönemi arşivle.", }, ], [ /\b(exam questions|questions|homework)\b.*\bstill reference this subject\b/, { en: "Exam questions or homework still use this subject. Move them to another subject or delete them first.", tr: "Sınav soruları veya ödevler hâlâ bu konuyu kullanıyor. Önce onları başka bir konuya taşı veya sil.", }, ], [ /\bmenu still has (live |active )?bookings\b/, { en: "This menu still has bookings. Cancel them before deleting the menu.", tr: "Bu menüde hâlâ rezervasyonlar var. Menüyü silmeden önce rezervasyonları iptal et.", }, ], [ /\b(slot|occurrence) has an? (pending or approved )?(booking|appointment)\b/, { en: "This time already has a pending or approved appointment. Cancel or decline it before removing the time.", tr: "Bu saatte bekleyen veya onaylanmış bir randevu var. Saati kaldırmadan önce randevuyu iptal et ya da reddet.", }, ], [ /\bplan is already assigned\b/, { en: "This payment plan is already assigned to a student, so it can no longer be changed or deleted.", tr: "Bu ödeme planı bir öğrenciye atanmış, bu yüzden artık değiştirilemez veya silinemez.", }, ], [ /\bschool's last admin\b|\blast admin (of|in) (this|the) school\b/, { en: "This account is the school's last admin. Make someone else an admin before changing its role.", tr: "Bu hesap okulun son yöneticisi. Rolünü değiştirmeden önce başka birini yönetici yap.", }, ], [ /\bblueprint already exists\b/, { en: "A template already exists for this grade. Edit the existing template instead.", tr: "Bu seviye için zaten bir şablon var. Bunun yerine mevcut şablonu düzenle.", }, ], [ /\bmenu already exists\b/, { en: "A menu already exists for this date and meal. Edit the existing menu instead.", tr: "Bu tarih ve öğün için zaten bir menü var. Bunun yerine mevcut menüyü düzenle.", }, ], [/\bstudent number is already taken\b|\bstudent number already (exists|taken|in use)\b/, STUDENT_NUMBER_TAKEN], [ /\balready attached\b/, { en: "This course is already attached to this class.", tr: "Bu ders bu şubeye zaten eklenmiş.", }, ], [ /\balready in this class\b/, { en: "This student is already in this class.", tr: "Bu öğrenci zaten bu şubede.", }, ], [ /\bhomework (has been|is) graded\b/, { en: "This homework has been graded, so the submission is locked until the grade is removed.", tr: "Bu ödev notlandırıldı. Not kaldırılana kadar teslim değiştirilemez.", }, ], [ /\bquestion is approved\b/, { en: "This question is approved, so its content can no longer change.", tr: "Bu soru onaylandığı için içeriği artık değiştirilemez.", }, ], [ /\battempts have started\b/, { en: "Students have already started this exam, so its questions can no longer change.", tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", }, ], [ /\bremoved exam kind still has\b/, { en: "An exam kind you removed still has graded exams. Keep it in the list, or move those exams to another kind first.", tr: "Kaldırdığın sınav türüne ait notlandırılmış sınavlar var. Türü listede bırak ya da önce bu sınavları başka bir türe taşı.", }, ], [ /\bremoved meal slot still has\b/, { en: "A meal you removed still has published menus. Keep it in the list, or delete those menus first.", tr: "Kaldırdığın öğüne ait yayınlanmış menüler var. Öğünü listede bırak ya da önce bu menüleri sil.", }, ], [ /\bmaximum number of boards\b/, { en: "You already have the maximum number of boards. Delete one before creating another.", tr: "En fazla tahta sayısına ulaştın. Yenisini oluşturmadan önce birini sil.", }, ], [/\bre-read (it )?and retry\b|\bunder concurrent edits\b|\bkept changing\b/, STALE_RECORD], ]; /** A specific wording for this backend refusal, or null when only the generic fallback fits. */ function knownApiErrorMessage(message: string, code: string | null, locale: Locale): string | null { const normalized = normalizeApiMessage(message); const exact = API_ERROR_MESSAGES[normalized]?.[locale]; if (exact) return exact; const byCode = code ? API_ERROR_CODE_MESSAGES[code]?.[locale] : undefined; if (byCode) return byCode; for (const [pattern, messages] of API_ERROR_PATTERNS) { if (pattern.test(normalized)) return messages[locale]; } return null; } const FIELD_LABELS: Record> = { content: { en: "Content", tr: "İçerik" }, description: { en: "Description", tr: "Açıklama" }, password: { en: "Password", tr: "Şifre" }, title: { en: "Title", tr: "Başlık" }, username: { en: "Username", tr: "Kullanıcı adı" }, }; export function currentLocale(): Locale { if (typeof window === "undefined") return "en"; try { const saved = window.localStorage.getItem("hezarfen.locale"); if (saved === "en" || saved === "tr") return saved; return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en"; } catch { return "en"; } } function normalizeApiMessage(message: string): string { return message .trim() .replace(/[’‘]/g, "'") .replace(/\s+/g, " ") .replace(/[.!?]+$/, "") .toLowerCase(); } function sentenceCase(message: string): string { const trimmed = message.trim(); if (!trimmed) return trimmed; return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1); } function formatRuntimeErrorMessage(message: string, locale: Locale): string | null { const normalized = normalizeApiMessage(message); if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) { return locale === "tr" ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene." : "Could not reach the server. Check your connection and try again."; } if ( /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) || /^use\w+ must be used within \w+provider/.test(normalized) ) { return locale === "tr" ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." : "Something went wrong while loading the page. Reload the page and try again."; } return null; } function formatNumber(value: string, locale: Locale): string { return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value)); } function fieldLabel(field: string, locale: Locale): string { const normalized = field.trim().toLowerCase().replace(/[_.-]+/g, " "); const known = FIELD_LABELS[normalized]?.[locale]; if (known) return known; return sentenceCase(normalized); } function formatValidationMessage(message: string, locale: Locale): string | null { const lengthMatch = message.match(/^([\w .-]+) must be at most (\d+) characters \(got (\d+)\)$/i); if (!lengthMatch) return null; const label = fieldLabel(lengthMatch[1], locale); const max = formatNumber(lengthMatch[2], locale); const got = formatNumber(lengthMatch[3], locale); if (locale === "tr") return `${label} en fazla ${max} karakter olmalı. Şu an ${got} karakter.`; return `${label} must be at most ${max} characters. Currently ${got} characters.`; } function errorCodeFromPayload(data: unknown): string | null { if (!data || typeof data !== "object") return null; const code = (data as { code?: unknown }).code; return typeof code === "string" && code ? code : null; } function errorMessageFromPayload(data: unknown, fallback: string): string { if (!data || typeof data !== "object") return fallback; const record = data as Record; if (typeof record.error === "string") return record.error; if (typeof record.message === "string") return record.message; const detail = record.detail; if (typeof detail === "string") return detail; if (Array.isArray(detail)) { return detail .map((item) => { if (!item || typeof item !== "object") return ""; const row = item as Record; const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : ""; const msg = typeof row.msg === "string" ? row.msg : ""; return loc && msg ? `${loc}: ${msg}` : msg; }) .filter(Boolean) .join("; ") || fallback; } return fallback; } const pendingGets = new Map>(); async function request(path: string, options: RequestOptions = {}): Promise { const headers: Record = {}; let body: string | undefined; if (options.body !== undefined) { headers["Content-Type"] = "application/json"; body = JSON.stringify(options.body); } // JSON calls only — uploads (formClient) and downloads (blobClient) stay // untimed. Without this a dead connection leaves callers (exam-room REST // autosave) stuck on "saving…" until the browser gives up. const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS); // Caller-initiated aborts keep their original AbortError so cancellation // handling upstream is untouched; only our own deadline becomes an ApiError. const asDeadlineError = (err: unknown) => timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err; let res: Response; try { res = await fetch(`${API_PREFIX}${path}`, { method: options.method ?? "GET", headers, body, credentials: "same-origin", signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout, cache: options.cache, }); } catch (err) { throw asDeadlineError(err); } if (res.status === 204) { return undefined as T; } // The deadline aborts the body stream too, so headers can arrive in time and // res.text() still blow up mid-download on a multi-MB response. let text: string; try { text = await res.text(); } catch (err) { throw asDeadlineError(err); } let data: unknown = null; if (text) { try { data = JSON.parse(text); } catch { data = { error: text }; } } if (!res.ok) { const message = errorMessageFromPayload(data, res.statusText || "Request failed"); let retryAfter: number | null = null; if (res.status === 429 || res.status === 503) { const raw = res.headers.get("Retry-After"); if (raw) { const n = Number(raw); retryAfter = Number.isFinite(n) ? n : null; } } throw new ApiError(res.status, message, retryAfter, disabledModuleOf(res.status, data), errorCodeFromPayload(data)); } return data as T; } /** * Coalesce only overlapping, non-cancellable GETs. This is deliberately not a * cache: once settled the entry disappears, so every later resource refetch * still reaches the backend and mutation consistency stays unchanged. */ export function client(path: string, options: RequestOptions = {}): Promise { const method = options.method ?? "GET"; if (method !== "GET" || options.body !== undefined || options.signal || options.cache === "no-store") { return request(path, options); } const key = `${path}\u0000${options.cache ?? "default"}`; const pending = pendingGets.get(key); if (pending) return pending as Promise; const next = request(path, options).finally(() => pendingGets.delete(key)); pendingGets.set(key, next); return next; } export async function formClient(path: string, body: FormData, signal?: AbortSignal): Promise { const res = await fetch(`${API_PREFIX}${path}`, { method: "POST", body, credentials: "same-origin", signal, }); const text = await res.text(); let data: unknown = null; if (text) { try { data = JSON.parse(text); } catch { data = { error: text }; } } if (!res.ok) { const message = errorMessageFromPayload(data, res.statusText || "Request failed"); throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data), errorCodeFromPayload(data)); } return data as T; } export async function blobClient(path: string, signal?: AbortSignal): Promise { const res = await fetch(`${API_PREFIX}${path}`, { credentials: "same-origin", signal, }); if (!res.ok) { const text = await res.text(); let message = res.statusText || "Request failed"; let payload: unknown = null; if (text) { try { payload = JSON.parse(text); message = errorMessageFromPayload(payload, message); } catch { message = text; } } throw new ApiError(res.status, message, null, disabledModuleOf(res.status, payload), errorCodeFromPayload(payload)); } return res.blob(); } /** * A request body the backend could not read (its JSON extractor, serde). The * text names the field and what was wrong with it, which is exactly what a * reader needs to fix the form — so it is translated instead of hidden. */ function formatDecodeMessage(message: string, locale: Locale): string | null { const tr = locale === "tr"; const missing = message.match(/missing field `([^`]+)`/i); if (missing) { const label = fieldLabel(missing[1], locale); return tr ? `“${label}” alanı eksik. Doldurup tekrar dene.` : `The “${label}” field is missing. Fill it in and try again.`; } const variant = message.match(/unknown variant `([^`]*)`, expected (.+?)(?: at line \d+.*)?$/i); if (variant) { return tr ? `“${variant[1]}” geçerli bir seçenek değil. Geçerli değerler: ${variant[2].replace(/`/g, "")}.` : `“${variant[1]}” is not a valid option. Valid values: ${variant[2].replace(/`/g, "")}.`; } const field = message.match(/([\w.[\]]+): invalid (?:type|value|length)/i)?.[1]; const typed = message.match(/invalid (?:type|value): (.+?), expected (.+?)(?: at line \d+.*)?$/i); if (typed) { const where = field ? (tr ? `“${fieldLabel(field, locale)}” alanının` : `The “${fieldLabel(field, locale)}” field has the`) : tr ? "Bir alanın" : "A field has the"; return tr ? `${where} biçimi hatalı: ${typed[2]} bekleniyordu, ${typed[1]} geldi.` : `${where} wrong format: expected ${typed[2]}, got ${typed[1]}.`; } if (/failed to (parse|deserialize) the (request )?(json )?body|expected value at line|eof while parsing/i.test(message)) { return tr ? "Gönderilen veri okunamadı (biçim hatası). Alanları kontrol edip tekrar dene." : "The data sent could not be read (format error). Check the fields and try again."; } return null; } /** What kind of failure a status is, for when the backend's words are not mapped. */ function statusLead(status: number | null, locale: Locale): string { const tr = locale === "tr"; if (status === 400) return tr ? "Sunucu isteği geçersiz buldu." : "The server rejected the request as invalid."; if (status === 408) return tr ? "Sunucu zamanında yanıt vermedi." : "The server did not answer in time."; if (status === 409) return tr ? "İşlem kaydın şu anki durumuyla çakışıyor." : "The action conflicts with the record's current state."; if (status === 422) return tr ? "Gönderilen bilgilerde eksik ya da hatalı bir alan var." : "A field is missing or has the wrong format."; return tr ? "İşlem tamamlanamadı." : "The action could not be completed."; } /** * The last resort: say what kind of failure it was and quote the backend's * own reason, so the reader (and whoever they ask) can tell a format problem * from a conflict. Raw text is labelled as the server's, not passed off as ours. */ function formatFallbackMessage(message: string, status: number | null, locale: Locale): string { const lead = statusLead(status, locale); const detail = message.trim().replace(/[.\s]+$/, ""); const generic = !detail || /^(request failed|bad request|unprocessable entity|conflict|error)$/i.test(detail); if (generic) return `${lead} ${locale === "tr" ? "Bilgileri kontrol edip tekrar dene." : "Check your input and try again."}`; return `${lead} ${locale === "tr" ? "Sunucu yanıtı" : "Server said"}: “${detail}”.`; } export function formatApiErrorMessage(message: string, locale: Locale = currentLocale(), status: number | null = null): string { const known = knownApiErrorMessage(message, null, locale); if (known) return known; const runtime = formatRuntimeErrorMessage(message, locale); if (runtime) return runtime; const validation = formatValidationMessage(message, locale); if (validation) return validation; const decode = formatDecodeMessage(message, locale); if (decode) return decode; // Unmapped backend text: name the kind of failure and quote the server's // reason instead of a bare "something went wrong" that hides it. Add a // mapping in API_ERROR_MESSAGES (exact), API_ERROR_CODE_MESSAGES or // API_ERROR_PATTERNS when a message deserves its own wording. return formatFallbackMessage(message, status, locale); } export function formatApiError(err: unknown, locale: Locale = currentLocale()): string { if (err instanceof ApiError) { if ((err.status === 429 || err.status === 503) && err.retryAfter != null) { return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`; } // The specific backend message wins over the per-status generic one — // otherwise every 401/403/404/413/5xx entry in the table is dead code. // Ahead of the message table: the backend's text for a switched-off // module may be a generic "forbidden", which reads as a permissions fault. if (err.module != null && err.status === 403) { return locale === "tr" ? "Bu özellik okulunuzda şu an kapalı." : "This feature is currently switched off for your school."; } const known = knownApiErrorMessage(err.message, err.code, locale); if (known) return known; if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale]; if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale]; if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale]; if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; return formatApiErrorMessage(err.message, locale, err.status); } if (err instanceof TypeError) { return formatRuntimeErrorMessage(err.message, locale) ?? (locale === "tr" ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." : "Something went wrong while loading the page. Reload the page and try again."); } if (err instanceof Error) return formatApiErrorMessage(err.message, locale); return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong."; }