sokko-g/website/src/features/toolboxes/sharing/sharesApi.js
Shinuwa aa8bb1ebaa Split dailyShare.js and document the shared exported functions with JSDoc
dailyShare.js held fillTemplate and formatCountdown, used across the whole TCG,
under a Daily Card name. They now live in textFormat.js at the root, and the
Daily Card helpers in daily/dailyFormat.js.

173 exported functions that other files call now explain what they return and
how they treat missing values: the server game rules, the toolbox storage chain,
the shared hooks and utilities, and the TCG display helpers. website/AGENTS.md
asks the same of new shared functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:32:20 +01:00

80 lines
3.4 KiB
JavaScript

/**
* @file Centralise les appels à l'API d'envoi de toolbox et rend leurs erreurs lisibles.
*/
const FALLBACK_ERROR = "Le service d'envoi est indisponible. Réessayez plus tard.";
function apiError(status, payload, fallback = FALLBACK_ERROR) {
return Object.assign(new Error(payload?.error?.message || fallback), { status, code: payload?.error?.code || "" });
}
async function failedResponse(response) {
return apiError(response.status, await response.json().catch(() => null));
}
/** Réglages publics des partages : `enabled`, taille maximale (`maxBytes`) et durée de vie (`ttlMs`). */
export async function loadSharesConfig() {
const response = await fetch("/api/shares/config", { headers: { Accept: "application/json" } });
if (!response.ok) throw await failedResponse(response);
return response.json();
}
/** XMLHttpRequest reste nécessaire pour suivre la progression d'un envoi : fetch ne l'expose pas. */
export function uploadShare(bytes, { singleUse = true, onProgress } = {}) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("POST", "/api/shares");
request.setRequestHeader("Content-Type", "application/octet-stream");
request.setRequestHeader("X-Sokkog-Share", "1");
if (singleUse) request.setRequestHeader("X-Share-Single-Use", "1");
request.responseType = "json";
request.upload.onprogress = (event) => {
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
};
request.onload = () => {
if (request.status === 201 && request.response?.id) resolve(request.response);
else reject(apiError(request.status, request.response));
};
request.onerror = () => reject(apiError(0, null));
request.send(bytes);
});
}
/** Taille et date d'expiration d'un partage, sans le télécharger. */
export async function loadShareMeta(id) {
const response = await fetch(`/api/shares/${encodeURIComponent(id)}/meta`, { headers: { Accept: "application/json" } });
if (!response.ok) throw await failedResponse(response);
return response.json();
}
/** Télécharge le contenu chiffré d'un partage ; `onProgress` reçoit l'avancement. Un partage à usage unique n'est plus lisible ensuite. */
export async function downloadShare(id, { onProgress } = {}) {
const response = await fetch(`/api/shares/${encodeURIComponent(id)}`);
if (!response.ok) throw await failedResponse(response);
const total = Number(response.headers.get("Content-Length")) || 0;
if (!response.body) return new Uint8Array(await response.arrayBuffer());
const reader = response.body.getReader();
const chunks = [];
let received = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
if (total) onProgress?.(received / total);
}
const bytes = new Uint8Array(received);
let offset = 0;
chunks.forEach((chunk) => {
bytes.set(chunk, offset);
offset += chunk.length;
});
return bytes;
}
/** Un lien déjà expiré ou utilisé n'existe plus : la révocation est alors considérée comme faite. */
export async function revokeShare(id, deleteToken) {
const response = await fetch(`/api/shares/${encodeURIComponent(id)}`, { method: "DELETE", headers: { "X-Share-Delete-Token": deleteToken } });
if (response.ok || response.status === 404) return true;
throw await failedResponse(response);
}