chore: consolidate platform split checks
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
import type { ApiSettings } from "../types";
|
||||
|
||||
const STORAGE_KEY = "multimailer.apiSettings";
|
||||
const LEGACY_STORAGE_KEYS = ["i18n:govoplan-core.multimailer_apisettings.1d1601d4"];
|
||||
const SESSION_STORAGE_KEY = "multimailer.session";
|
||||
const CSRF_COOKIE_NAME = import.meta.env.VITE_CSRF_COOKIE_NAME ?? "msm_csrf";
|
||||
const RECENT_SAFE_REQUEST_TTL_MS = 750;
|
||||
const MAX_RECENT_SAFE_REQUESTS = 100;
|
||||
const MAX_CONDITIONAL_SAFE_REQUESTS = 200;
|
||||
|
||||
export const AUTH_REQUIRED_EVENT = "govoplan:auth-required";
|
||||
|
||||
@@ -19,8 +21,14 @@ type RecentSafeRequest = {
|
||||
expiresAt: number;
|
||||
};
|
||||
|
||||
type ConditionalSafeRequest = {
|
||||
value: unknown;
|
||||
etag: string;
|
||||
};
|
||||
|
||||
const inFlightSafeRequests = new Map<string, Promise<unknown>>();
|
||||
const recentSafeRequests = new Map<string, RecentSafeRequest>();
|
||||
const conditionalSafeRequests = new Map<string, ConditionalSafeRequest>();
|
||||
let safeRequestGeneration = 0;
|
||||
|
||||
export class ApiError extends Error {
|
||||
@@ -47,8 +55,20 @@ export function isApiError(error: unknown, ...statuses: number[]): error is ApiE
|
||||
* API prefix so old localStorage settings cannot produce /api/v1/api/v1 URLs.
|
||||
*/
|
||||
export function normalizeApiBaseUrl(value: string): string {
|
||||
const withoutTrailingSlash = value.trim().replace(/\/+$/, "");
|
||||
return withoutTrailingSlash.replace(/\/api(?:\/v1)?$/i, "");
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || trimmed === "." || trimmed === "./") return "";
|
||||
|
||||
const withoutTrailingSlash = trimmed.replace(/\/+$/, "");
|
||||
const withoutApiPrefix = withoutTrailingSlash.replace(/\/api(?:\/v1)?$/i, "");
|
||||
|
||||
// API base is an origin, not a frontend route prefix. Path-only values such
|
||||
// as /a or . are stale/invalid local settings and would bypass Vite's /api
|
||||
// proxy by producing /a/api/v1/... requests.
|
||||
if (withoutApiPrefix.startsWith("/") && !withoutApiPrefix.startsWith("//")) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return withoutApiPrefix;
|
||||
}
|
||||
|
||||
export function apiUrl(settings: ApiSettings, path: string): string {
|
||||
@@ -58,7 +78,8 @@ export function apiUrl(settings: ApiSettings, path: string): string {
|
||||
}
|
||||
|
||||
export function loadApiSettings(): ApiSettings {
|
||||
const storedBaseUrl = localStorage.getItem(`${STORAGE_KEY}.baseUrl`);
|
||||
const storedBaseUrl = loadStoredSetting("baseUrl");
|
||||
const storedApiKey = loadStoredSetting("apiKey");
|
||||
const configuredBaseUrl = storedBaseUrl !== null ? storedBaseUrl : import.meta.env.VITE_API_BASE_URL ?? "";
|
||||
const apiBaseUrl = normalizeApiBaseUrl(configuredBaseUrl);
|
||||
|
||||
@@ -66,6 +87,11 @@ export function loadApiSettings(): ApiSettings {
|
||||
if (storedBaseUrl !== null && storedBaseUrl !== apiBaseUrl) {
|
||||
localStorage.setItem(`${STORAGE_KEY}.baseUrl`, apiBaseUrl);
|
||||
}
|
||||
if (storedApiKey !== null) {
|
||||
localStorage.setItem(`${STORAGE_KEY}.apiKey`, storedApiKey);
|
||||
}
|
||||
clearLegacyStoredSetting("baseUrl");
|
||||
clearLegacyStoredSetting("apiKey");
|
||||
|
||||
localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
|
||||
sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);
|
||||
@@ -73,7 +99,7 @@ export function loadApiSettings(): ApiSettings {
|
||||
return {
|
||||
// Empty base URL means "same origin". In Vite dev, /api is proxied to FastAPI.
|
||||
apiBaseUrl,
|
||||
apiKey: localStorage.getItem(`${STORAGE_KEY}.apiKey`) || "",
|
||||
apiKey: storedApiKey || "",
|
||||
accessToken: ""
|
||||
};
|
||||
}
|
||||
@@ -81,6 +107,8 @@ export function loadApiSettings(): ApiSettings {
|
||||
export function saveApiSettings(settings: ApiSettings): void {
|
||||
localStorage.setItem(`${STORAGE_KEY}.baseUrl`, normalizeApiBaseUrl(settings.apiBaseUrl));
|
||||
localStorage.setItem(`${STORAGE_KEY}.apiKey`, settings.apiKey);
|
||||
clearLegacyStoredSetting("baseUrl");
|
||||
clearLegacyStoredSetting("apiKey");
|
||||
localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
|
||||
sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);
|
||||
}
|
||||
@@ -90,14 +118,29 @@ export function clearAccessToken(): void {
|
||||
localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
|
||||
}
|
||||
|
||||
function loadStoredSetting(name: string): string | null {
|
||||
const keys = [STORAGE_KEY, ...LEGACY_STORAGE_KEYS];
|
||||
for (const key of keys) {
|
||||
const value = localStorage.getItem(`${key}.${name}`);
|
||||
if (value !== null) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function clearLegacyStoredSetting(name: string): void {
|
||||
for (const key of LEGACY_STORAGE_KEYS) {
|
||||
localStorage.removeItem(`${key}.${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function readCookie(name: string): string {
|
||||
const prefix = `${encodeURIComponent(name)}=`;
|
||||
return document.cookie
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part.startsWith(prefix))
|
||||
?.slice(prefix.length) ?? "";
|
||||
return document.cookie.
|
||||
split(";").
|
||||
map((part) => part.trim()).
|
||||
find((part) => part.startsWith(prefix))?.
|
||||
slice(prefix.length) ?? "";
|
||||
}
|
||||
|
||||
export function csrfToken(): string {
|
||||
@@ -111,29 +154,29 @@ function isUnsafeMethod(method?: string): boolean {
|
||||
}
|
||||
|
||||
function canReuseSafeRequest(method: string, init?: RequestInit): boolean {
|
||||
return (method === "GET" || method === "HEAD")
|
||||
&& !init?.body
|
||||
&& !init?.signal
|
||||
&& init?.cache !== "no-store"
|
||||
&& init?.cache !== "reload";
|
||||
return (method === "GET" || method === "HEAD") &&
|
||||
!init?.body &&
|
||||
!init?.signal &&
|
||||
init?.cache !== "no-store" &&
|
||||
init?.cache !== "reload";
|
||||
}
|
||||
|
||||
function requestHeadersKey(headers: Headers): string {
|
||||
return [...headers.entries()]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, value]) => `${key}:${value}`)
|
||||
.join("\n");
|
||||
return [...headers.entries()].
|
||||
sort(([left], [right]) => left.localeCompare(right)).
|
||||
map(([key, value]) => `${key}:${value}`).
|
||||
join("\n");
|
||||
}
|
||||
|
||||
function safeRequestKey(url: string, method: string, headers: Headers, init?: RequestInit): string {
|
||||
return [
|
||||
method,
|
||||
url,
|
||||
init?.credentials ?? "include",
|
||||
init?.mode ?? "",
|
||||
init?.redirect ?? "",
|
||||
requestHeadersKey(headers),
|
||||
].join("\n\n");
|
||||
method,
|
||||
url,
|
||||
init?.credentials ?? "include",
|
||||
init?.mode ?? "",
|
||||
init?.redirect ?? "",
|
||||
requestHeadersKey(headers)].
|
||||
join("\n\n");
|
||||
}
|
||||
|
||||
function pruneRecentSafeRequests(now = Date.now()): void {
|
||||
@@ -167,6 +210,31 @@ function rememberSafeResponse(key: string, value: unknown): void {
|
||||
pruneRecentSafeRequests(now);
|
||||
}
|
||||
|
||||
function conditionalSafeResponse(key: string): ConditionalSafeRequest | undefined {
|
||||
const cached = conditionalSafeRequests.get(key);
|
||||
if (!cached) return undefined;
|
||||
conditionalSafeRequests.delete(key);
|
||||
conditionalSafeRequests.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
function rememberConditionalSafeResponse(key: string, etag: string, value: unknown): void {
|
||||
conditionalSafeRequests.delete(key);
|
||||
conditionalSafeRequests.set(key, { etag, value });
|
||||
while (conditionalSafeRequests.size > MAX_CONDITIONAL_SAFE_REQUESTS) {
|
||||
const oldestKey = conditionalSafeRequests.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
conditionalSafeRequests.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
function clearSafeRequestCaches(): void {
|
||||
safeRequestGeneration += 1;
|
||||
inFlightSafeRequests.clear();
|
||||
recentSafeRequests.clear();
|
||||
conditionalSafeRequests.clear();
|
||||
}
|
||||
|
||||
export function authHeaders(settings: ApiSettings): Headers {
|
||||
const headers = new Headers();
|
||||
if (settings.accessToken) {
|
||||
@@ -187,13 +255,13 @@ function notifyAuthRequired(path: string): void {
|
||||
const detail: AuthRequiredEventDetail = {
|
||||
path,
|
||||
status: 401,
|
||||
message: "Your session has expired. Sign in again to continue."
|
||||
message: "i18n:govoplan-core.your_session_has_expired_sign_in_again_to_contin.4cc6a1b3"
|
||||
};
|
||||
window.dispatchEvent(new CustomEvent<AuthRequiredEventDetail>(AUTH_REQUIRED_EVENT, { detail }));
|
||||
}
|
||||
|
||||
function authExpiredError(statusText: string): ApiError {
|
||||
return new ApiError(401, statusText || "Unauthorized", "Your session has expired. Sign in again to continue.");
|
||||
return new ApiError(401, statusText || "i18n:govoplan-core.unauthorized.740b8315", "i18n:govoplan-core.your_session_has_expired_sign_in_again_to_contin.4cc6a1b3");
|
||||
}
|
||||
|
||||
export async function apiFetch<T>(settings: ApiSettings, path: string, init?: RequestInit): Promise<T> {
|
||||
@@ -214,17 +282,27 @@ export async function apiFetch<T>(settings: ApiSettings, path: string, init?: Re
|
||||
}
|
||||
|
||||
if (isUnsafeMethod(method)) {
|
||||
safeRequestGeneration += 1;
|
||||
inFlightSafeRequests.clear();
|
||||
recentSafeRequests.clear();
|
||||
clearSafeRequestCaches();
|
||||
}
|
||||
|
||||
const url = apiUrl(settings, path);
|
||||
const fetchInit = { ...init, headers, credentials: init?.credentials ?? "include" };
|
||||
const reusableSafeRequest = canReuseSafeRequest(method, init);
|
||||
const cacheKey = reusableSafeRequest ? safeRequestKey(url, method, headers, init) : null;
|
||||
|
||||
async function runFetch(): Promise<T> {
|
||||
const fetchHeaders = new Headers(headers);
|
||||
const conditional = cacheKey ? conditionalSafeResponse(cacheKey) : undefined;
|
||||
if (conditional && !fetchHeaders.has("If-None-Match")) {
|
||||
fetchHeaders.set("If-None-Match", conditional.etag);
|
||||
}
|
||||
const fetchInit = { ...init, headers: fetchHeaders, credentials: init?.credentials ?? "include" };
|
||||
const response = await fetch(url, fetchInit);
|
||||
|
||||
if (response.status === 304 && cacheKey && conditional) {
|
||||
rememberSafeResponse(cacheKey, conditional.value);
|
||||
return conditional.value as T;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
if (response.status === 401 && shouldNotifyAuthRequired(path)) {
|
||||
@@ -235,22 +313,31 @@ export async function apiFetch<T>(settings: ApiSettings, path: string, init?: Re
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
if (cacheKey) conditionalSafeRequests.delete(cacheKey);
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
let value: T;
|
||||
if (!contentType.includes("application/json")) {
|
||||
return (await response.text()) as T;
|
||||
value = (await response.text()) as T;
|
||||
} else {
|
||||
value = (await response.json()) as T;
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
const etag = response.headers.get("etag");
|
||||
if (cacheKey && etag) {
|
||||
rememberConditionalSafeResponse(cacheKey, etag, value);
|
||||
} else if (cacheKey) {
|
||||
conditionalSafeRequests.delete(cacheKey);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
if (!canReuseSafeRequest(method, init)) {
|
||||
if (!reusableSafeRequest || !cacheKey) {
|
||||
return runFetch();
|
||||
}
|
||||
|
||||
const cacheKey = safeRequestKey(url, method, headers, init);
|
||||
const requestGeneration = safeRequestGeneration;
|
||||
const recent = recentSafeResponse(cacheKey);
|
||||
if (recent !== undefined) {
|
||||
@@ -262,18 +349,18 @@ export async function apiFetch<T>(settings: ApiSettings, path: string, init?: Re
|
||||
return existing as Promise<T>;
|
||||
}
|
||||
|
||||
const request = runFetch()
|
||||
.then((value) => {
|
||||
if (requestGeneration === safeRequestGeneration) {
|
||||
rememberSafeResponse(cacheKey, value);
|
||||
}
|
||||
return value;
|
||||
})
|
||||
.finally(() => {
|
||||
if (inFlightSafeRequests.get(cacheKey) === request) {
|
||||
inFlightSafeRequests.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
const request = runFetch().
|
||||
then((value) => {
|
||||
if (requestGeneration === safeRequestGeneration) {
|
||||
rememberSafeResponse(cacheKey, value);
|
||||
}
|
||||
return value;
|
||||
}).
|
||||
finally(() => {
|
||||
if (inFlightSafeRequests.get(cacheKey) === request) {
|
||||
inFlightSafeRequests.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
inFlightSafeRequests.set(cacheKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user