Files
gpx.studio/website/src/lib/storage/cached-fetch.ts
T
vcoppeandvcoppe 8fe7d8d64d Migration to new Rust-based engine (#401)
* wasm first steps

* parsing start

* parsing continued

* progress

* progress

* progress

* progress

* progress

* progress

* progress

* progress

* fixes

* reorganize

* change type

* fix

* progress

* refactoring

* progress

* progress

* progress

* keep style info

* progress

* progress

* remove (copy) in name

* progress

* merge methods into 1

* splice

* progress

* progress

* progress

* cleaning

* progress

* progress

* progress

* visibility

* progress

* progress

* progress

* progress

* progress

* fixes

* progress

* fix markers

* fix

* progress

* progress

* progress

* progress

* progress

* progress

* small fix

* use engine info

* fix popups

* small fix

* progress

* progress

* progress

* clean tool

* handle self closing elements

* reduce data exchanges across boundary

* copy on wasm side to avoid any data corruption

* speed fix

* routing

* refactoring

* reverse

* reverse

* crop

* split

* merge

* progress

* time tool

* fix bounds for waypoints

* reduce

* fix reactivity

* handle corrupt time data

* export

* progress

* remove gpx js package

* remove todo

* update readme

* cleaning

* progress

* fix link fields

* remove unused fields

* refactoring and tests

* import and export of routes, ref #192

* per-chunk categories storage

* cross-tab sync

* outdated state

* refactoring

* reorder methods

* refactoring

* fix

* improve flow

* renaming

* progress

* progress

* fix

* progress

* per file history

* keep original flag

* use history variant

* fix

* progress

* file explorer

* progress

* fix

* sticky folders

* improved sticky folders

* fix sortable

* fix sortable

* fix

* fix tab size

* no file delete on desktop

* fix routing on other file

* fix sorting

* remember language

* open links in browser

* commit missing changes

* avoid selecting on resize

* clarify filename

* explorer actions

* fix folder styling

* drop anywhere in folder

* cleaning

* fixes

* remove focus-ring

* full screen

* small fix

* consistent highlight color

* improved preview

* performance improvements

* sparser data transfers

* sparser data transfers

* show popup once data is loaded

* fix routing control size

* fix

* sparse desktop build

* remove custom ign styles

* use new endpoint for openhikingmap

* strip native menu

* reorder context menu items

* route full support

* route - track conversion

* create route file action

* route export, filter out anchors at high zoom level

* clarify name handling

* move hide & center to view

* routes continued

* update docs

* fix power format, closes #378

* lint fixes

* fix display of additional data with gaps, closes #361

* fix linting issues

* fix import modules

* fix multidrag

* change base to resolve

* fix type errors

* fix layer typings

* fix last type error

* each keys

* improve typings

* deploy to cloudflare

---------

Co-authored-by: vcoppe <vcoppe@hexaly.com>
2026-10-31 18:08:22 +01:00

90 lines
2.8 KiB
TypeScript

/**
* `fetch` that keeps the responses in the Cache API, which the browser does whatever the headers
* of the server are: the HTTP cache needs them to keep a response (and `cache: 'force-cache'`
* can only use what it kept). A kept response is used until it is older than `maxAge`.
*
* It works without the Cache API (insecure pages, private windows, blocked storage): the
* responses are then just not kept.
*/
export type CachedFetchOptions = {
/** Name of the cache the responses are kept in. */
name: string;
/** How long a kept response is used, in milliseconds. */
maxAge: number;
};
/** When a response was kept (ms since the epoch): the server's date can be wrong or missing. */
const KEPT_AT = 'x-kept-at';
/** The caches that were cleaned of their old responses in this session. */
const pruned = new Set<string>();
async function openCache(name: string): Promise<Cache | undefined> {
try {
return typeof caches === 'undefined' ? undefined : await caches.open(name);
} catch {
return undefined;
}
}
function age(response: Response): number {
const keptAt = Number(response.headers.get(KEPT_AT));
return keptAt > 0 ? Date.now() - keptAt : Infinity;
}
/** Deletes the responses that are too old to be used. */
export async function pruneCache({ name, maxAge }: CachedFetchOptions) {
const cache = await openCache(name);
if (!cache) {
return;
}
try {
for (const request of await cache.keys()) {
const response = await cache.match(request);
if (!response || !(age(response) < maxAge)) {
await cache.delete(request);
}
}
} catch {
// what is left is cleaned another time
}
}
/**
* The response for `url`: the kept one if there is one that is not too old, otherwise the one of
* the network, which is kept if it is successful.
*/
export async function cachedFetch(url: string, options: CachedFetchOptions): Promise<Response> {
const cache = await openCache(options.name);
if (cache && !pruned.has(options.name)) {
pruned.add(options.name);
void pruneCache(options);
}
try {
const kept = await cache?.match(url);
if (kept && age(kept) < options.maxAge) {
return kept;
}
} catch {
// as if there was nothing
}
const response = await fetch(url);
if (!response.ok || !cache) {
return response;
}
const headers = new Headers(response.headers);
headers.set(KEPT_AT, String(Date.now()));
const stamped = new Response(await response.arrayBuffer(), {
status: response.status,
statusText: response.statusText,
headers,
});
// best effort: the storage can be full
cache.put(url, stamped.clone()).catch(() => undefined);
return stamped;
}