Compare commits
1 Commits
feat/front
...
bugfix/api
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8667f8b957 |
2
backend/Cargo.lock
generated
2
backend/Cargo.lock
generated
@@ -1470,7 +1470,7 @@ checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mangalord"
|
name = "mangalord"
|
||||||
version = "0.34.0"
|
version = "0.34.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"argon2",
|
"argon2",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mangalord"
|
name = "mangalord"
|
||||||
version = "0.35.0"
|
version = "0.34.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
default-run = "mangalord"
|
default-run = "mangalord"
|
||||||
|
|
||||||
|
|||||||
@@ -230,8 +230,24 @@ async fn create_token(
|
|||||||
Json(input): Json<CreateTokenInput>,
|
Json(input): Json<CreateTokenInput>,
|
||||||
) -> AppResult<impl IntoResponse> {
|
) -> AppResult<impl IntoResponse> {
|
||||||
let name = input.name.trim();
|
let name = input.name.trim();
|
||||||
|
// Both arms use `ValidationFailed` (422 with field details) to
|
||||||
|
// match the structured-error shape `attach_tag` returns for the
|
||||||
|
// same kind of free-form-identifier validation. The other
|
||||||
|
// /auth/* handlers in this file use `InvalidInput` (400); the
|
||||||
|
// divergence is pre-existing and would warrant a project-wide
|
||||||
|
// pass to flip them all if the client side wants uniform per-
|
||||||
|
// field error rendering.
|
||||||
if name.is_empty() {
|
if name.is_empty() {
|
||||||
return Err(AppError::InvalidInput("token name is required".into()));
|
return Err(AppError::ValidationFailed {
|
||||||
|
message: "token name is required".into(),
|
||||||
|
details: serde_json::json!({ "name": "required" }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if name.chars().count() > 64 {
|
||||||
|
return Err(AppError::ValidationFailed {
|
||||||
|
message: "token name too long".into(),
|
||||||
|
details: serde_json::json!({ "name": "max 64 characters" }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
let (raw, hash) = generate_token();
|
let (raw, hash) = generate_token();
|
||||||
let token = repo::api_token::create(&state.db, user.id, name, &hash).await?;
|
let token = repo::api_token::create(&state.db, user.id, name, &hash).await?;
|
||||||
|
|||||||
@@ -348,6 +348,7 @@ async fn attach_tag(
|
|||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
Json(body): Json<AttachTagBody>,
|
Json(body): Json<AttachTagBody>,
|
||||||
) -> AppResult<(StatusCode, Json<TagRef>)> {
|
) -> AppResult<(StatusCode, Json<TagRef>)> {
|
||||||
|
validate_tag_name(&body.name)?;
|
||||||
if !repo::manga::exists(&state.db, id).await? {
|
if !repo::manga::exists(&state.db, id).await? {
|
||||||
return Err(AppError::NotFound);
|
return Err(AppError::NotFound);
|
||||||
}
|
}
|
||||||
@@ -394,6 +395,27 @@ async fn detach_tag(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Request-side validation for `POST /mangas/:id/tags` body. Mirrors
|
||||||
|
/// the repo-level cap in `repo::tag::upsert_by_name` (max 64 chars
|
||||||
|
/// after trim) but surfaces the failure at the handler boundary with
|
||||||
|
/// the same envelope shape other validations use.
|
||||||
|
fn validate_tag_name(name: &str) -> AppResult<()> {
|
||||||
|
let trimmed = name.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Err(AppError::ValidationFailed {
|
||||||
|
message: "tag name cannot be empty".into(),
|
||||||
|
details: json!({ "name": "required" }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if trimmed.chars().count() > 64 {
|
||||||
|
return Err(AppError::ValidationFailed {
|
||||||
|
message: "tag name too long".into(),
|
||||||
|
details: json!({ "name": "max 64 characters" }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_new_manga(input: &NewManga) -> AppResult<()> {
|
fn validate_new_manga(input: &NewManga) -> AppResult<()> {
|
||||||
if input.title.trim().is_empty() {
|
if input.title.trim().is_empty() {
|
||||||
return Err(AppError::ValidationFailed {
|
return Err(AppError::ValidationFailed {
|
||||||
|
|||||||
@@ -16,6 +16,13 @@ impl LocalStorage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn resolve(&self, key: &str) -> Result<PathBuf, StorageError> {
|
fn resolve(&self, key: &str) -> Result<PathBuf, StorageError> {
|
||||||
|
// NUL bytes are rejected by the Linux syscall layer, but the
|
||||||
|
// error surfaces as an opaque IO failure rather than the
|
||||||
|
// explicit `BadKey` the rest of the contract uses. Catch it
|
||||||
|
// here so the error path is consistent.
|
||||||
|
if key.contains('\0') {
|
||||||
|
return Err(StorageError::BadKey);
|
||||||
|
}
|
||||||
let key = key.trim_start_matches('/');
|
let key = key.trim_start_matches('/');
|
||||||
if key.is_empty() {
|
if key.is_empty() {
|
||||||
return Err(StorageError::BadKey);
|
return Err(StorageError::BadKey);
|
||||||
@@ -114,6 +121,9 @@ mod tests {
|
|||||||
assert!(matches!(s.get(".").await, Err(StorageError::BadKey)));
|
assert!(matches!(s.get(".").await, Err(StorageError::BadKey)));
|
||||||
// Empty segment via doubled slash.
|
// Empty segment via doubled slash.
|
||||||
assert!(matches!(s.get("a//b").await, Err(StorageError::BadKey)));
|
assert!(matches!(s.get("a//b").await, Err(StorageError::BadKey)));
|
||||||
|
// NUL byte (rejected explicitly so callers see BadKey rather
|
||||||
|
// than an opaque IO error from the kernel).
|
||||||
|
assert!(matches!(s.put("a\0b", b"x").await, Err(StorageError::BadKey)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -581,3 +581,27 @@ async fn delete_unknown_token_is_404(pool: PgPool) {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Bot token names are user-supplied free-form strings; a 10 MB name
|
||||||
|
/// was accepted before. Cap at 64 chars to match the other free-form
|
||||||
|
/// identifier caps (tags, collection names). The response uses
|
||||||
|
/// `ValidationFailed` (422 with per-field details) so clients can
|
||||||
|
/// render the same shape they already handle for `attach_tag`.
|
||||||
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
|
async fn create_token_rejects_name_over_64_chars(pool: PgPool) {
|
||||||
|
let h = common::harness(pool);
|
||||||
|
let (_, cookie) = common::register_user(&h.app).await;
|
||||||
|
let resp = h
|
||||||
|
.app
|
||||||
|
.oneshot(common::post_json_with_cookie(
|
||||||
|
"/api/v1/auth/tokens",
|
||||||
|
json!({ "name": "x".repeat(65) }),
|
||||||
|
&cookie,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
let body = common::body_json(resp).await;
|
||||||
|
assert_eq!(body["error"]["code"], "validation_failed");
|
||||||
|
assert!(body["error"]["details"]["name"].is_string());
|
||||||
|
}
|
||||||
|
|||||||
@@ -59,6 +59,31 @@ async fn reattach_same_tag_is_idempotent_and_returns_200(pool: PgPool) {
|
|||||||
assert_eq!(second.status(), StatusCode::OK);
|
assert_eq!(second.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tag names over 64 chars are rejected at the handler boundary. The
|
||||||
|
/// repo enforces the same cap, but doing it at the handler keeps the
|
||||||
|
/// envelope consistent with the other validation paths
|
||||||
|
/// (username, collection name, etc.).
|
||||||
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
|
async fn attach_rejects_tag_name_over_64_chars(pool: PgPool) {
|
||||||
|
let h = common::harness(pool);
|
||||||
|
let (_, cookie) = common::register_user(&h.app).await;
|
||||||
|
let manga_id = common::seed_manga_via_api(&h.app, &cookie, "Berserk").await;
|
||||||
|
|
||||||
|
let long_name: String = "x".repeat(65);
|
||||||
|
let resp = h
|
||||||
|
.app
|
||||||
|
.oneshot(common::post_json_with_cookie(
|
||||||
|
&format!("/api/v1/mangas/{manga_id}/tags"),
|
||||||
|
json!({ "name": long_name }),
|
||||||
|
&cookie,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
let body = common::body_json(resp).await;
|
||||||
|
assert_eq!(body["error"]["code"], "validation_failed");
|
||||||
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn tag_names_dedup_case_insensitively(pool: PgPool) {
|
async fn tag_names_dedup_case_insensitively(pool: PgPool) {
|
||||||
let h = common::harness(pool);
|
let h = common::harness(pool);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "mangalord-frontend",
|
"name": "mangalord-frontend",
|
||||||
"version": "0.35.0",
|
"version": "0.34.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -94,6 +94,11 @@ describe('auth api client', () => {
|
|||||||
expect(url).toMatch(/\/v1\/auth\/logout$/);
|
expect(url).toMatch(/\/v1\/auth\/logout$/);
|
||||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||||
expect(init.method).toBe('POST');
|
expect(init.method).toBe('POST');
|
||||||
|
// Consistent content-type for all mutation requests, matching
|
||||||
|
// the rest of the module — axum doesn't require it but the
|
||||||
|
// header keeps the request style uniform.
|
||||||
|
const headers = new Headers(init.headers);
|
||||||
|
expect(headers.get('content-type')).toBe('application/json');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('me returns the user on 200', async () => {
|
it('me returns the user on 200', async () => {
|
||||||
|
|||||||
@@ -32,7 +32,14 @@ export async function login(creds: Credentials): Promise<User> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function logout(): Promise<void> {
|
export async function logout(): Promise<void> {
|
||||||
await request<void>('/v1/auth/logout', { method: 'POST' });
|
await request<void>('/v1/auth/logout', {
|
||||||
|
method: 'POST',
|
||||||
|
// Consistent with the other POST/PATCH helpers in this module.
|
||||||
|
// axum doesn't require it (no body), but keeping the header
|
||||||
|
// on every mutation request avoids the false-flag in logs and
|
||||||
|
// matches the project's style.
|
||||||
|
headers: { 'content-type': 'application/json' }
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ChangePassword = {
|
export type ChangePassword = {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
|
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
|
||||||
import { ApiError, request, setOn401Hook } from './client';
|
import { ApiError, request } from './client';
|
||||||
import { getManga } from './mangas';
|
import { getManga } from './mangas';
|
||||||
|
|
||||||
describe('request error envelope parsing', () => {
|
describe('request error envelope parsing', () => {
|
||||||
@@ -73,88 +73,3 @@ describe('request error envelope parsing', () => {
|
|||||||
expect(err.code).toBe('http_error');
|
expect(err.code).toBe('http_error');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('on401 hook', () => {
|
|
||||||
let fetchSpy: MockInstance<typeof globalThis.fetch>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
fetchSpy = vi.spyOn(globalThis, 'fetch');
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
// Critical: reset the module-level hook between tests so a
|
|
||||||
// hook installed by one test doesn't leak into the next.
|
|
||||||
setOn401Hook(null);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('invokes the hook exactly once on a 401 response and re-throws', async () => {
|
|
||||||
const hook = vi.fn();
|
|
||||||
setOn401Hook(hook);
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({ error: { code: 'unauthenticated', message: 'no auth' } }),
|
|
||||||
{ status: 401, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await expect(getManga('x')).rejects.toMatchObject({
|
|
||||||
status: 401,
|
|
||||||
code: 'unauthenticated'
|
|
||||||
});
|
|
||||||
expect(hook).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not invoke the hook on non-401 errors', async () => {
|
|
||||||
const hook = vi.fn();
|
|
||||||
setOn401Hook(hook);
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({ error: { code: 'not_found', message: 'no' } }),
|
|
||||||
{ status: 404, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await expect(getManga('x')).rejects.toMatchObject({ status: 404 });
|
|
||||||
expect(hook).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not invoke the hook on successful responses', async () => {
|
|
||||||
const hook = vi.fn();
|
|
||||||
setOn401Hook(hook);
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
id: 'm1',
|
|
||||||
title: 't',
|
|
||||||
status: 'ongoing',
|
|
||||||
alt_titles: [],
|
|
||||||
description: null,
|
|
||||||
cover_image_path: null,
|
|
||||||
created_at: '2026-01-01T00:00:00Z',
|
|
||||||
updated_at: '2026-01-01T00:00:00Z',
|
|
||||||
authors: [],
|
|
||||||
genres: [],
|
|
||||||
tags: []
|
|
||||||
}),
|
|
||||||
{ status: 200, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await getManga('m1');
|
|
||||||
expect(hook).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('swallows hook exceptions so the original ApiError still propagates', async () => {
|
|
||||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
||||||
setOn401Hook(() => {
|
|
||||||
throw new Error('hook boom');
|
|
||||||
});
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({ error: { code: 'unauthenticated', message: 'x' } }),
|
|
||||||
{ status: 401, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await expect(getManga('x')).rejects.toMatchObject({ status: 401 });
|
|
||||||
// The original ApiError won — the hook's panic was logged but
|
|
||||||
// didn't replace the API error.
|
|
||||||
expect(consoleSpy).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -25,21 +25,6 @@ export class ApiError extends Error {
|
|||||||
|
|
||||||
type ErrorEnvelope = { error?: { code?: unknown; message?: unknown } };
|
type ErrorEnvelope = { error?: { code?: unknown; message?: unknown } };
|
||||||
|
|
||||||
/**
|
|
||||||
* Optional hook fired the first moment `request()` observes a 401 on
|
|
||||||
* any endpoint. Used by the session store to clear the cached user
|
|
||||||
* when the server reports the session is no longer valid (expired
|
|
||||||
* cookie, rotated server-side, password changed on another device).
|
|
||||||
*
|
|
||||||
* Set to `null` (or `undefined`) to disable. Tests that don't want
|
|
||||||
* the side effect should leave it unset.
|
|
||||||
*/
|
|
||||||
let on401Hook: (() => void) | null = null;
|
|
||||||
|
|
||||||
export function setOn401Hook(handler: (() => void) | null): void {
|
|
||||||
on401Hook = handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
// Forward credentials (session cookie) explicitly so cross-origin
|
// Forward credentials (session cookie) explicitly so cross-origin
|
||||||
// deployments — those configured via CORS_ALLOWED_ORIGINS — keep
|
// deployments — those configured via CORS_ALLOWED_ORIGINS — keep
|
||||||
@@ -69,16 +54,6 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
} catch {
|
} catch {
|
||||||
// Body wasn't parseable; keep the http_error fallback.
|
// Body wasn't parseable; keep the http_error fallback.
|
||||||
}
|
}
|
||||||
if (res.status === 401 && on401Hook) {
|
|
||||||
// Fire before throwing so the session store updates even
|
|
||||||
// if the caller swallows the ApiError (e.g. the *OrEmpty
|
|
||||||
// wrappers used by guest-rendering pages).
|
|
||||||
try {
|
|
||||||
on401Hook();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('on401 hook threw:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new ApiError(res.status, code, message);
|
throw new ApiError(res.status, code, message);
|
||||||
}
|
}
|
||||||
// Any empty body (not just 204) returns undefined — the manga-add
|
// Any empty body (not just 204) returns undefined — the manga-add
|
||||||
|
|||||||
@@ -3,17 +3,7 @@
|
|||||||
// Only mutated client-side (onMount / form submits) so the module-level
|
// Only mutated client-side (onMount / form submits) so the module-level
|
||||||
// instance can't leak across SSR requests — SSR always renders the
|
// instance can't leak across SSR requests — SSR always renders the
|
||||||
// `loaded === false` state, and the client refreshes after hydration.
|
// `loaded === false` state, and the client refreshes after hydration.
|
||||||
//
|
|
||||||
// IMPORTANT: do not call any `api/*` helper from `+page.server.ts` /
|
|
||||||
// `+layout.server.ts`. The `setOn401Hook` below is registered at
|
|
||||||
// module load (gated on `browser`, so it only fires in the client
|
|
||||||
// bundle), so a 401 from a server-side fetch would mutate this
|
|
||||||
// module-level `session.user` across SvelteKit requests — a real
|
|
||||||
// cross-request state leak. The `if (browser)` guard makes that
|
|
||||||
// failure mode mechanical rather than convention-based.
|
|
||||||
|
|
||||||
import { browser } from '$app/environment';
|
|
||||||
import { setOn401Hook } from './api/client';
|
|
||||||
import { me, type User } from './api/auth';
|
import { me, type User } from './api/auth';
|
||||||
|
|
||||||
class SessionStore {
|
class SessionStore {
|
||||||
@@ -41,16 +31,3 @@ class SessionStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const session = new SessionStore();
|
export const session = new SessionStore();
|
||||||
|
|
||||||
// When any backend call returns 401, drop the cached user. Before this
|
|
||||||
// hook, the `*OrEmpty` wrappers silently returned empty pages on 401
|
|
||||||
// — so a mid-session expiry left the UI rendering as "logged in but
|
|
||||||
// no bookmarks/collections/etc." until the user manually reloaded.
|
|
||||||
// With the hook the session.user reactive store flips to null on the
|
|
||||||
// first 401, so the layout re-renders the login affordance.
|
|
||||||
//
|
|
||||||
// Gated on `browser` so it's only installed in the client bundle.
|
|
||||||
// See the module-level comment above for the SSR rationale.
|
|
||||||
if (browser) {
|
|
||||||
setOn401Hook(() => session.setUser(null));
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -350,54 +350,48 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `fetch()` initiated during `pagehide` / `beforeunload` is
|
* Flush read-progress as the tab is closing. A plain `fetch()`
|
||||||
* cancelled by every browser by default. `sendBeacon` is the
|
* during `pagehide` / `beforeunload` is cancelled by every
|
||||||
* supported way to ship a small payload during unload — it's
|
* browser; `fetch(..., { keepalive: true })` is the supported
|
||||||
* guaranteed to survive even if the tab is closing. Failure here
|
* escape hatch and survives the close.
|
||||||
* is silent because the API is fire-and-forget.
|
*
|
||||||
|
* `sendBeacon` would be the textbook alternative, but it's
|
||||||
|
* POST-only and `/me/read-progress` takes PUT — so a beacon
|
||||||
|
* always 405s, adds server-log noise, then falls through to this
|
||||||
|
* same keepalive path anyway. The beacon was dropped; the
|
||||||
|
* keepalive fetch is the only path.
|
||||||
*/
|
*/
|
||||||
function beaconFinalProgress() {
|
function flushFinalProgress() {
|
||||||
if (!session.user) return;
|
if (!session.user) return;
|
||||||
const body = JSON.stringify({
|
const body = JSON.stringify({
|
||||||
manga_id: manga.id,
|
manga_id: manga.id,
|
||||||
chapter_id: chapter.id,
|
chapter_id: chapter.id,
|
||||||
page: progressPage
|
page: progressPage
|
||||||
});
|
});
|
||||||
const blob = new Blob([body], { type: 'application/json' });
|
|
||||||
// sendBeacon only supports POST — the server's PUT route is
|
|
||||||
// strict on method. The dedicated POST alias is omitted; in
|
|
||||||
// practice the in-app navigation path (back-link, chapter
|
|
||||||
// links) already covers the common-case unmount via the
|
|
||||||
// onDestroy fetch. Fall through to fetch+keepalive for browser
|
|
||||||
// implementations that don't honor sendBeacon for this endpoint.
|
|
||||||
try {
|
try {
|
||||||
const ok = navigator.sendBeacon('/api/v1/me/read-progress', blob);
|
void fetch('/api/v1/me/read-progress', {
|
||||||
if (!ok) throw new Error('sendBeacon rejected');
|
method: 'PUT',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body,
|
||||||
|
keepalive: true,
|
||||||
|
credentials: 'include'
|
||||||
|
});
|
||||||
} catch {
|
} catch {
|
||||||
try {
|
// keepalive fetch was rejected (very old Firefox etc.);
|
||||||
void fetch('/api/v1/me/read-progress', {
|
// the in-app onDestroy flush below catches the SPA-
|
||||||
method: 'PUT',
|
// navigation case, which is the common one anyway.
|
||||||
headers: { 'content-type': 'application/json' },
|
|
||||||
body,
|
|
||||||
keepalive: true,
|
|
||||||
credentials: 'include'
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Final fallback failed; the in-app onDestroy flush
|
|
||||||
// below catches the SPA-navigation case.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
window.addEventListener('pagehide', beaconFinalProgress);
|
window.addEventListener('pagehide', flushFinalProgress);
|
||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
observer?.disconnect();
|
observer?.disconnect();
|
||||||
if (progressTimer) clearTimeout(progressTimer);
|
if (progressTimer) clearTimeout(progressTimer);
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
window.removeEventListener('pagehide', beaconFinalProgress);
|
window.removeEventListener('pagehide', flushFinalProgress);
|
||||||
}
|
}
|
||||||
// Don't let the fullscreen flag leak to non-reader pages —
|
// Don't let the fullscreen flag leak to non-reader pages —
|
||||||
// otherwise the layout header would stay slid-off on /upload
|
// otherwise the layout header would stay slid-off on /upload
|
||||||
|
|||||||
Reference in New Issue
Block a user