@sweidos/eidos 1.0.20 → 1.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/action.js +103 -0
- package/dist/action.js.map +1 -0
- package/dist/eidos.cjs.js +2 -2
- package/dist/eidos.cjs.js.map +1 -1
- package/dist/idb.js +87 -0
- package/dist/idb.js.map +1 -0
- package/dist/index.js +36 -0
- package/dist/index.js.map +1 -0
- package/dist/react/Provider.js +12 -0
- package/dist/react/Provider.js.map +1 -0
- package/dist/react/hooks.js +42 -0
- package/dist/react/hooks.js.map +1 -0
- package/dist/resource.js +200 -0
- package/dist/resource.js.map +1 -0
- package/dist/runtime.js +34 -0
- package/dist/runtime.js.map +1 -0
- package/dist/store.js +55 -0
- package/dist/store.js.map +1 -0
- package/dist/stores.js +36 -0
- package/dist/stores.js.map +1 -0
- package/dist/sw-bridge.js +105 -0
- package/dist/sw-bridge.js.map +1 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/package.json +4 -4
- package/dist/eidos.es.js +0 -621
- package/dist/eidos.es.js.map +0 -1
package/dist/idb.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const w = "eidos";
|
|
2
|
+
const o = "action-queue";
|
|
3
|
+
let m = null;
|
|
4
|
+
function d() {
|
|
5
|
+
return m ? Promise.resolve(m) : new Promise((r, s) => {
|
|
6
|
+
const t = indexedDB.open(w, 1);
|
|
7
|
+
t.onupgradeneeded = (n) => {
|
|
8
|
+
const e = n.target.result;
|
|
9
|
+
if (!e.objectStoreNames.contains(o)) {
|
|
10
|
+
const c = e.createObjectStore(o, { keyPath: "id" });
|
|
11
|
+
c.createIndex("status", "status", { unique: !1 }), c.createIndex("actionId", "actionId", { unique: !1 });
|
|
12
|
+
}
|
|
13
|
+
}, t.onsuccess = () => {
|
|
14
|
+
m = t.result, r(t.result);
|
|
15
|
+
}, t.onerror = () => s(t.error);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
async function p(r) {
|
|
19
|
+
const s = await d();
|
|
20
|
+
return new Promise((t, n) => {
|
|
21
|
+
const e = s.transaction(o, "readwrite");
|
|
22
|
+
e.objectStore(o).add(r), e.oncomplete = () => t(), e.onerror = () => n(e.error);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
async function x() {
|
|
26
|
+
const r = await d();
|
|
27
|
+
return new Promise((s, t) => {
|
|
28
|
+
const e = r.transaction(o, "readonly").objectStore(o).getAll();
|
|
29
|
+
e.onsuccess = () => s(e.result), e.onerror = () => t(e.error);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async function y(r, s) {
|
|
33
|
+
const t = await d();
|
|
34
|
+
return new Promise((n, e) => {
|
|
35
|
+
const c = t.transaction(o, "readwrite"), l = c.objectStore(o), i = l.get(r);
|
|
36
|
+
i.onsuccess = () => {
|
|
37
|
+
i.result && l.put({ ...i.result, ...s });
|
|
38
|
+
}, c.oncomplete = () => n(), c.onerror = () => e(c.error);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async function g(r) {
|
|
42
|
+
const s = await d();
|
|
43
|
+
return new Promise((t, n) => {
|
|
44
|
+
const e = s.transaction(o, "readwrite");
|
|
45
|
+
e.objectStore(o).delete(r), e.oncomplete = () => t(), e.onerror = () => n(e.error);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
async function S() {
|
|
49
|
+
const r = await d();
|
|
50
|
+
return new Promise((s, t) => {
|
|
51
|
+
const e = r.transaction(o, "readonly").objectStore(o).index("status"), c = [];
|
|
52
|
+
let l = 0;
|
|
53
|
+
function i(u) {
|
|
54
|
+
if (u) {
|
|
55
|
+
t(u);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
++l === 2 && s(c);
|
|
59
|
+
}
|
|
60
|
+
const b = e.openCursor(IDBKeyRange.only("pending"));
|
|
61
|
+
b.onsuccess = (u) => {
|
|
62
|
+
const a = u.target.result;
|
|
63
|
+
a ? (c.push(a.value), a.continue()) : i();
|
|
64
|
+
}, b.onerror = () => i(b.error);
|
|
65
|
+
const f = e.openCursor(IDBKeyRange.only("failed"));
|
|
66
|
+
f.onsuccess = (u) => {
|
|
67
|
+
const a = u.target.result;
|
|
68
|
+
a ? (c.push(a.value), a.continue()) : i();
|
|
69
|
+
}, f.onerror = () => i(f.error);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async function I() {
|
|
73
|
+
const r = await d();
|
|
74
|
+
return new Promise((s, t) => {
|
|
75
|
+
const n = r.transaction(o, "readwrite");
|
|
76
|
+
n.objectStore(o).clear(), n.oncomplete = () => s(), n.onerror = () => t(n.error);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
export {
|
|
80
|
+
p as idbAddToQueue,
|
|
81
|
+
I as idbClearQueue,
|
|
82
|
+
S as idbGetPendingItems,
|
|
83
|
+
x as idbGetQueue,
|
|
84
|
+
g as idbRemoveFromQueue,
|
|
85
|
+
y as idbUpdateQueueItem
|
|
86
|
+
};
|
|
87
|
+
//# sourceMappingURL=idb.js.map
|
package/dist/idb.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idb.js","sources":["../src/idb.ts"],"sourcesContent":["import type { ActionQueueItem } from './types'\n\nconst DB_NAME = 'eidos'\nconst DB_VERSION = 1\nconst QUEUE_STORE = 'action-queue'\n\nlet _db: IDBDatabase | null = null\n\nfunction openDB(): Promise<IDBDatabase> {\n if (_db) return Promise.resolve(_db)\n\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION)\n\n req.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result\n if (!db.objectStoreNames.contains(QUEUE_STORE)) {\n const store = db.createObjectStore(QUEUE_STORE, { keyPath: 'id' })\n store.createIndex('status', 'status', { unique: false })\n store.createIndex('actionId', 'actionId', { unique: false })\n }\n }\n\n req.onsuccess = () => {\n _db = req.result\n resolve(req.result)\n }\n\n req.onerror = () => reject(req.error)\n })\n}\n\nexport async function idbAddToQueue(item: ActionQueueItem): Promise<void> {\n const db = await openDB()\n return new Promise((resolve, reject) => {\n const tx = db.transaction(QUEUE_STORE, 'readwrite')\n tx.objectStore(QUEUE_STORE).add(item)\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n })\n}\n\nexport async function idbGetQueue(): Promise<ActionQueueItem[]> {\n const db = await openDB()\n return new Promise((resolve, reject) => {\n const tx = db.transaction(QUEUE_STORE, 'readonly')\n const req = tx.objectStore(QUEUE_STORE).getAll()\n req.onsuccess = () => resolve(req.result as ActionQueueItem[])\n req.onerror = () => reject(req.error)\n })\n}\n\nexport async function idbUpdateQueueItem(\n id: string,\n update: Partial<ActionQueueItem>,\n): Promise<void> {\n const db = await openDB()\n return new Promise((resolve, reject) => {\n const tx = db.transaction(QUEUE_STORE, 'readwrite')\n const store = tx.objectStore(QUEUE_STORE)\n const get = store.get(id)\n get.onsuccess = () => {\n if (get.result) {\n store.put({ ...get.result, ...update })\n } else if (import.meta.env.DEV) {\n console.warn(`[eidos] idbUpdateQueueItem: item \"${id}\" not found — store/IDB may have diverged`)\n }\n }\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n })\n}\n\nexport async function idbRemoveFromQueue(id: string): Promise<void> {\n const db = await openDB()\n return new Promise((resolve, reject) => {\n const tx = db.transaction(QUEUE_STORE, 'readwrite')\n tx.objectStore(QUEUE_STORE).delete(id)\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n })\n}\n\n// Uses the status index to fetch only pending/failed items — avoids a full\n// table scan when the queue has many succeeded/replaying entries.\nexport async function idbGetPendingItems(): Promise<ActionQueueItem[]> {\n const db = await openDB()\n return new Promise((resolve, reject) => {\n const tx = db.transaction(QUEUE_STORE, 'readonly')\n const index = tx.objectStore(QUEUE_STORE).index('status')\n const results: ActionQueueItem[] = []\n\n let done = 0\n function finish(err?: DOMException | null) {\n if (err) { reject(err); return }\n if (++done === 2) resolve(results)\n }\n\n const pendingReq = index.openCursor(IDBKeyRange.only('pending'))\n pendingReq.onsuccess = (e) => {\n const cursor = (e.target as IDBRequest<IDBCursorWithValue>).result\n if (cursor) { results.push(cursor.value as ActionQueueItem); cursor.continue() }\n else finish()\n }\n pendingReq.onerror = () => finish(pendingReq.error)\n\n const failedReq = index.openCursor(IDBKeyRange.only('failed'))\n failedReq.onsuccess = (e) => {\n const cursor = (e.target as IDBRequest<IDBCursorWithValue>).result\n if (cursor) { results.push(cursor.value as ActionQueueItem); cursor.continue() }\n else finish()\n }\n failedReq.onerror = () => finish(failedReq.error)\n })\n}\n\nexport async function idbClearQueue(): Promise<void> {\n const db = await openDB()\n return new Promise((resolve, reject) => {\n const tx = db.transaction(QUEUE_STORE, 'readwrite')\n tx.objectStore(QUEUE_STORE).clear()\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n })\n}\n"],"names":["DB_NAME","QUEUE_STORE","_db","openDB","resolve","reject","req","event","db","store","idbAddToQueue","item","tx","idbGetQueue","idbUpdateQueueItem","id","update","get","idbRemoveFromQueue","idbGetPendingItems","index","results","done","finish","err","pendingReq","e","cursor","failedReq","idbClearQueue"],"mappings":"AAEA,MAAMA,IAAU;AAEhB,MAAMC,IAAc;AAEpB,IAAIC,IAA0B;AAE9B,SAASC,IAA+B;AACtC,SAAID,IAAY,QAAQ,QAAQA,CAAG,IAE5B,IAAI,QAAQ,CAACE,GAASC,MAAW;AACtC,UAAMC,IAAM,UAAU,KAAKN,GAAS,CAAU;AAE9C,IAAAM,EAAI,kBAAkB,CAACC,MAAU;AAC/B,YAAMC,IAAMD,EAAM,OAA4B;AAC9C,UAAI,CAACC,EAAG,iBAAiB,SAASP,CAAW,GAAG;AAC9C,cAAMQ,IAAQD,EAAG,kBAAkBP,GAAa,EAAE,SAAS,MAAM;AACjE,QAAAQ,EAAM,YAAY,UAAU,UAAU,EAAE,QAAQ,IAAO,GACvDA,EAAM,YAAY,Y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AML,EAAOK,EAAU,KAAK;AAAA,EAClD,CAAC;AACH;AAEA,eAAsBC,IAA+B;AACnD,QAAMrB,IAAK,MAAML,EAAA;AACjB,SAAO,IAAI,QAAQ,CAACC,GAASC,MAAW;AACtC,UAAMO,IAAKJ,EAAG,YAAYP,GAAa,WAAW;AAClD,IAAAW,EAAG,YAAYX,CAAW,EAAE,MAAA,GAC5BW,EAAG,aAAa,MAAMR,EAAA,GACtBQ,EAAG,UAAU,MAAMP,EAAOO,EAAG,KAAK;AAAA,EACpC,CAAC;AACH;"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { resource as s, setQueryInvalidator as r } from "./resource.js";
|
|
2
|
+
import { action as t, clearQueue as u, replayQueue as d } from "./action.js";
|
|
3
|
+
import { initEidos as a } from "./runtime.js";
|
|
4
|
+
import { EidosProvider as E } from "./react/Provider.js";
|
|
5
|
+
import { useEidos as n, useEidosAction as S, useEidosOnDrain as x, useEidosQueue as c, useEidosQueueStats as Q, useEidosResource as l, useEidosStatus as y } from "./react/hooks.js";
|
|
6
|
+
import { VERSION as R } from "./version.js";
|
|
7
|
+
import { isBgSyncSupported as A, setOfflineSimulation as I } from "./sw-bridge.js";
|
|
8
|
+
import { useEidosStore as B } from "./store.js";
|
|
9
|
+
import { eidosAction as N, eidosQueue as P, eidosQueueStats as V, eidosResource as b, eidosStatus as h, eidosStore as j } from "./stores.js";
|
|
10
|
+
export {
|
|
11
|
+
E as EidosProvider,
|
|
12
|
+
R as VERSION,
|
|
13
|
+
t as action,
|
|
14
|
+
u as clearQueue,
|
|
15
|
+
N as eidosAction,
|
|
16
|
+
P as eidosQueue,
|
|
17
|
+
V as eidosQueueStats,
|
|
18
|
+
b as eidosResource,
|
|
19
|
+
h as eidosStatus,
|
|
20
|
+
j as eidosStore,
|
|
21
|
+
a as initEidos,
|
|
22
|
+
A as isBgSyncSupported,
|
|
23
|
+
d as replayQueue,
|
|
24
|
+
s as resource,
|
|
25
|
+
I as setOfflineSimulation,
|
|
26
|
+
r as setQueryInvalidator,
|
|
27
|
+
n as useEidos,
|
|
28
|
+
S as useEidosAction,
|
|
29
|
+
x as useEidosOnDrain,
|
|
30
|
+
c as useEidosQueue,
|
|
31
|
+
Q as useEidosQueueStats,
|
|
32
|
+
l as useEidosResource,
|
|
33
|
+
y as useEidosStatus,
|
|
34
|
+
B as useEidosStore
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { jsx as t, Fragment as m } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect as e } from "react";
|
|
3
|
+
import { initEidos as f } from "../runtime.js";
|
|
4
|
+
function d({ children: r, swPath: o, autoReplay: i }) {
|
|
5
|
+
return e(() => {
|
|
6
|
+
f({ swPath: o, autoReplay: i });
|
|
7
|
+
}, []), /* @__PURE__ */ t(m, { children: r });
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
d as EidosProvider
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=Provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Provider.js","sources":["../../src/react/Provider.tsx"],"sourcesContent":["import { useEffect, type ReactNode } from 'react'\nimport { initEidos, type EidosConfig } from '../runtime'\n\ninterface EidosProviderProps extends EidosConfig {\n children: ReactNode\n}\n\n/**\n * Mount once at the root of your application.\n * Registers the service worker and initialises the Eidos runtime.\n *\n * @example\n * <EidosProvider swPath=\"/eidos-sw.js\">\n * <App />\n * </EidosProvider>\n */\nexport function EidosProvider({ children, swPath, autoReplay }: EidosProviderProps) {\n useEffect(() => {\n initEidos({ swPath, autoReplay })\n // Run once on mount only\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n return <>{children}</>\n}\n"],"names":["EidosProvider","children","swPath","autoReplay","useEffect","initEidos"],"mappings":";;;AAgBO,SAASA,EAAc,EAAE,UAAAC,GAAU,QAAAC,GAAQ,YAAAC,KAAkC;AAClF,SAAAC,EAAU,MAAM;AACd,IAAAC,EAAU,EAAE,QAAAH,GAAQ,YAAAC,GAAY;AAAA,EAGlC,GAAG,CAAA,CAAE,0BAEK,UAAAF,GAAS;AACrB;"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { useRef as i, useEffect as f, useSyncExternalStore as l } from "react";
|
|
2
|
+
import { useEidosStore as c } from "../store.js";
|
|
3
|
+
function n(e) {
|
|
4
|
+
const t = e ?? ((u) => u);
|
|
5
|
+
return l(c.subscribe, () => t(c.getState()));
|
|
6
|
+
}
|
|
7
|
+
function E() {
|
|
8
|
+
return n();
|
|
9
|
+
}
|
|
10
|
+
function g(e) {
|
|
11
|
+
return n((t) => t.resources[e]);
|
|
12
|
+
}
|
|
13
|
+
function S() {
|
|
14
|
+
return n((e) => e.queue);
|
|
15
|
+
}
|
|
16
|
+
function p(e) {
|
|
17
|
+
return n((t) => t.queue.find((u) => u.id === e));
|
|
18
|
+
}
|
|
19
|
+
function q() {
|
|
20
|
+
const e = n((s) => s.isOnline), t = n((s) => s.swStatus), u = n((s) => s.swError);
|
|
21
|
+
return { isOnline: e, swStatus: t, swError: u };
|
|
22
|
+
}
|
|
23
|
+
function h() {
|
|
24
|
+
const e = n((r) => r.queue.filter((o) => o.status === "pending").length), t = n((r) => r.queue.filter((o) => o.status === "failed").length), u = n((r) => r.queue.filter((o) => o.status === "replaying").length), s = n((r) => r.queue.length);
|
|
25
|
+
return { pending: e, failed: t, replaying: u, total: s };
|
|
26
|
+
}
|
|
27
|
+
function m(e) {
|
|
28
|
+
const t = n((r) => r.queue.length), u = i(0), s = i(e);
|
|
29
|
+
s.current = e, f(() => {
|
|
30
|
+
u.current > 0 && t === 0 && s.current(), u.current = t;
|
|
31
|
+
}, [t]);
|
|
32
|
+
}
|
|
33
|
+
export {
|
|
34
|
+
E as useEidos,
|
|
35
|
+
p as useEidosAction,
|
|
36
|
+
m as useEidosOnDrain,
|
|
37
|
+
S as useEidosQueue,
|
|
38
|
+
h as useEidosQueueStats,
|
|
39
|
+
g as useEidosResource,
|
|
40
|
+
q as useEidosStatus
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.js","sources":["../../src/react/hooks.ts"],"sourcesContent":["import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { useEidosStore } from '../store'\nimport type { EidosStore } from '../store'\n\nfunction useStore(): EidosStore\nfunction useStore<T>(selector: (state: EidosStore) => T): T\nfunction useStore<T = EidosStore>(selector?: (state: EidosStore) => T): T {\n const fn = selector ?? ((s: EidosStore) => s as unknown as T)\n return useSyncExternalStore(useEidosStore.subscribe, () => fn(useEidosStore.getState()))\n}\n\n/** Full Eidos store — prefer the narrower hooks below for performance. */\nexport function useEidos() {\n return useStore()\n}\n\n/** Live state for a single registered resource URL. */\nexport function useEidosResource(url: string) {\n return useStore((s) => s.resources[url])\n}\n\n/** The current action queue. */\nexport function useEidosQueue() {\n return useStore((s) => s.queue)\n}\n\n/**\n * Live state for a single queue item by ID. Only re-renders when that specific\n * item changes — cheaper than `useEidosQueue().find(id)` which re-renders on\n * any queue mutation.\n */\nexport function useEidosAction(id: string) {\n return useStore((s) => s.queue.find((item) => item.id === id))\n}\n\n/**\n * Online + SW status — cheap subscription, safe to use in header components.\n * Three separate primitive selectors so each only triggers a re-render when\n * its own value changes (no object-reference churn from a combined selector).\n */\nexport function useEidosStatus() {\n const isOnline = useStore((s) => s.isOnline)\n const swStatus = useStore((s) => s.swStatus)\n const swError = useStore((s) => s.swError)\n return { isOnline, swStatus, swError }\n}\n\n/**\n * Queue counts — four independent primitive selectors. Re-renders only when a\n * count changes, not on every queue mutation. Use for badges and status bars\n * instead of `useEidosQueue()` when you only need numbers, not full items.\n */\nexport function useEidosQueueStats() {\n const pending = useStore((s) => s.queue.filter((q) => q.status === 'pending').length)\n const failed = useStore((s) => s.queue.filter((q) => q.status === 'failed').length)\n const replaying = useStore((s) => s.queue.filter((q) => q.status === 'replaying').length)\n const total = useStore((s) => s.queue.length)\n return { pending, failed, replaying, total }\n}\n\n/**\n * Calls `callback` once each time the action queue drains from non-empty → 0.\n * Stable callback reference not required — always calls the latest version.\n * Use for \"all offline actions synced!\" toasts.\n *\n * @example\n * useEidosOnDrain(() => toast.success('All offline actions synced!'))\n */\nexport function useEidosOnDrain(callback: () => void) {\n const total = useStore((s) => s.queue.length)\n const prevRef = useRef(0)\n const callbackRef = useRef(callback)\n callbackRef.current = callback\n\n useEffect(() => {\n if (prevRef.current > 0 && total === 0) {\n callbackRef.current()\n }\n prevRef.current = total\n }, [total])\n}\n"],"names":["useStore","selector","fn","s","useSyncExternalStore","useEidosStore","useEidos","useEidosResource","url","useEidosQueue","useEidosAction","id","item","useEidosStatus","isOnline","swStatus","swError","useEidosQueueStats","pending","q","failed","replaying","total","useEidosOnDrain","callback","prevRef","useRef","callbackRef","useEffect"],"mappings":";;AAMA,SAASA,EAAyBC,GAAwC;AACxE,QAAMC,IAAKD,MAAa,CAACE,MAAkBA;AAC3C,SAAOC,EAAqBC,EAAc,WAAW,MAAMH,EAAGG,EAAc,SAAA,CAAU,CAAC;AACzF;AAGO,SAASC,IAAW;AACzB,SAAON,EAAA;AACT;AAGO,SAASO,EAAiBC,GAAa;AAC5C,SAAOR,EAAS,CAACG,MAAMA,EAAE,UAAUK,CAAG,CAAC;AACzC;AAGO,SAASC,IAAgB;AAC9B,SAAOT,EAAS,CAACG,MAAMA,EAAE,KAAK;AAChC;AAOO,SAASO,EAAeC,GAAY;AACzC,SAAOX,EAAS,CAACG,MAAMA,EAAE,MAAM,KAAK,CAACS,MAASA,EAAK,OAAOD,CAAE,CAAC;AAC/D;AAOO,SAASE,IAAiB;AAC/B,QAAMC,IAAWd,EAAS,CAAC,MAAM,EAAE,QAAQ,GACrCe,IAAWf,EAAS,CAAC,MAAM,EAAE,QAAQ,GACrCgB,IAAUhB,EAAS,CAAC,MAAM,EAAE,OAAO;AACzC,SAAO,EAAE,UAAAc,GAAU,UAAAC,GAAU,SAAAC,EAAA;AAC/B;AAOO,SAASC,IAAqB;AACnC,QAAMC,IAAYlB,EAAS,CAACG,MAAMA,EAAE,MAAM,OAAO,CAACgB,MAAMA,EAAE,WAAW,SAAS,EAAE,MAAM,GAChFC,IAAYpB,EAAS,CAACG,MAAMA,EAAE,MAAM,OAAO,CAACgB,MAAMA,EAAE,WAAW,QAAQ,EAAE,MAAM,GAC/EE,IAAYrB,EAAS,CAACG,MAAMA,EAAE,MAAM,OAAO,CAACgB,MAAMA,EAAE,WAAW,WAAW,EAAE,MAAM,GAClFG,IAAYtB,EAAS,CAACG,MAAMA,EAAE,MAAM,MAAM;AAChD,SAAO,EAAE,SAAAe,GAAS,QAAAE,GAAQ,WAAAC,GAAW,OAAAC,EAAA;AACvC;AAUO,SAASC,EAAgBC,GAAsB;AACpD,QAAMF,IAAWtB,EAAS,CAACG,MAAMA,EAAE,MAAM,MAAM,GACzCsB,IAAWC,EAAO,CAAC,GACnBC,IAAcD,EAAOF,CAAQ;AACnC,EAAAG,EAAY,UAAUH,GAEtBI,EAAU,MAAM;AACd,IAAIH,EAAQ,UAAU,KAAKH,MAAU,KACnCK,EAAY,QAAA,GAEdF,EAAQ,UAAUH;AAAA,EACpB,GAAG,CAACA,CAAK,CAAC;AACZ;"}
|
package/dist/resource.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { useEidosStore as h } from "./store.js";
|
|
2
|
+
import { sendToWorker as g } from "./sw-bridge.js";
|
|
3
|
+
const p = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map();
|
|
4
|
+
let m = null;
|
|
5
|
+
function N(e) {
|
|
6
|
+
m = e;
|
|
7
|
+
}
|
|
8
|
+
function u(e) {
|
|
9
|
+
return e.includes("*") || /:[^/]+/.test(e);
|
|
10
|
+
}
|
|
11
|
+
function k(e) {
|
|
12
|
+
return "^" + e.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".+").replace(/\*/g, "[^/]+").replace(/:[^/]+/g, "[^/]+") + "$";
|
|
13
|
+
}
|
|
14
|
+
function w(e, t) {
|
|
15
|
+
return new Error(
|
|
16
|
+
`[eidos] resource('${e}') is a URL pattern — ${t}() is not supported on pattern handles. The SW intercepts matching requests automatically; call fetch(specificUrl) directly in your app code.`
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
function q(e, t) {
|
|
20
|
+
if (p.has(e))
|
|
21
|
+
return p.get(e);
|
|
22
|
+
const a = S(e, t), n = u(e) ? k(e) : void 0, o = {
|
|
23
|
+
url: e,
|
|
24
|
+
config: t,
|
|
25
|
+
strategy: a,
|
|
26
|
+
status: "idle",
|
|
27
|
+
cacheHits: 0,
|
|
28
|
+
cacheMisses: 0
|
|
29
|
+
};
|
|
30
|
+
h.getState().registerResource(e, o), g({
|
|
31
|
+
type: "EIDOS_REGISTER_RESOURCE",
|
|
32
|
+
url: e,
|
|
33
|
+
strategy: a.swStrategy,
|
|
34
|
+
cacheName: a.cacheName,
|
|
35
|
+
...n !== void 0 && { pattern: n }
|
|
36
|
+
});
|
|
37
|
+
const s = {
|
|
38
|
+
url: e,
|
|
39
|
+
config: t,
|
|
40
|
+
strategy: a,
|
|
41
|
+
fetch: async () => {
|
|
42
|
+
if (u(e)) throw w(e, "fetch");
|
|
43
|
+
const r = y.get(e);
|
|
44
|
+
if (r) return r.then((c) => c.clone());
|
|
45
|
+
const i = E(e, t, a);
|
|
46
|
+
return y.set(e, i), i.finally(() => y.delete(e)), i.then((c) => c.clone());
|
|
47
|
+
},
|
|
48
|
+
json: async () => {
|
|
49
|
+
if (u(e)) throw w(e, "json");
|
|
50
|
+
return (await s.fetch()).json();
|
|
51
|
+
},
|
|
52
|
+
query: () => {
|
|
53
|
+
if (u(e)) throw w(e, "query");
|
|
54
|
+
return {
|
|
55
|
+
queryKey: ["eidos", e],
|
|
56
|
+
queryFn: () => s.json()
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
prefetch: async () => {
|
|
60
|
+
if (u(e)) throw w(e, "prefetch");
|
|
61
|
+
await s.fetch();
|
|
62
|
+
},
|
|
63
|
+
invalidate: async () => {
|
|
64
|
+
g({ type: "EIDOS_CLEAR_CACHE", url: e });
|
|
65
|
+
const r = await caches.open(a.cacheName).catch(() => null);
|
|
66
|
+
if (r) {
|
|
67
|
+
const i = await r.keys(), c = n ? new RegExp(n) : null, l = e.startsWith("http");
|
|
68
|
+
await Promise.all(
|
|
69
|
+
i.filter((f) => {
|
|
70
|
+
const d = f.url, v = new URL(d).pathname;
|
|
71
|
+
return c ? c.test(l ? d : v) : l ? d === e : d === e || v === e;
|
|
72
|
+
}).map((f) => r.delete(f))
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
u(e) || h.getState().updateResource(e, {
|
|
76
|
+
status: "stale",
|
|
77
|
+
cachedAt: void 0,
|
|
78
|
+
lastEvent: "cache-cleared",
|
|
79
|
+
cacheHits: 0,
|
|
80
|
+
cacheMisses: 0
|
|
81
|
+
}), m == null || m(["eidos", e]);
|
|
82
|
+
},
|
|
83
|
+
unregister: () => {
|
|
84
|
+
p.delete(e), g({ type: "EIDOS_UNREGISTER_RESOURCE", url: e }), h.getState().unregisterResource(e);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
return p.set(e, s), s;
|
|
88
|
+
}
|
|
89
|
+
async function E(e, t, a) {
|
|
90
|
+
const n = h.getState();
|
|
91
|
+
n.updateResource(e, { status: "fetching", fetchedAt: Date.now() });
|
|
92
|
+
const o = await caches.open(a.cacheName).catch(() => null);
|
|
93
|
+
try {
|
|
94
|
+
if (a.swStrategy !== "network-first") {
|
|
95
|
+
const i = o ? await o.match(e).catch(() => null) : null, c = h.getState().resources[e], l = t.maxAge !== void 0 && (c == null ? void 0 : c.cachedAt) !== void 0 && Date.now() - c.cachedAt > t.maxAge;
|
|
96
|
+
if (i && !l)
|
|
97
|
+
return n.updateResource(e, {
|
|
98
|
+
status: "fresh",
|
|
99
|
+
lastEvent: "cache-hit",
|
|
100
|
+
cacheHits: ((c == null ? void 0 : c.cacheHits) ?? 0) + 1
|
|
101
|
+
}), a.swStrategy === "stale-while-revalidate" && fetch(e).then(async (d) => {
|
|
102
|
+
d.ok && o && (await o.put(e, d.clone()), h.getState().updateResource(e, {
|
|
103
|
+
cachedAt: Date.now(),
|
|
104
|
+
lastEvent: "cache-updated"
|
|
105
|
+
}));
|
|
106
|
+
}).catch(() => {
|
|
107
|
+
}), i;
|
|
108
|
+
const f = h.getState().resources[e];
|
|
109
|
+
n.updateResource(e, {
|
|
110
|
+
cacheMisses: ((f == null ? void 0 : f.cacheMisses) ?? 0) + 1
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
const s = await fetch(e);
|
|
114
|
+
if (s.ok)
|
|
115
|
+
return o && await o.put(e, s.clone()), n.updateResource(e, {
|
|
116
|
+
status: "fresh",
|
|
117
|
+
cachedAt: Date.now(),
|
|
118
|
+
lastEvent: "cache-updated"
|
|
119
|
+
}), s;
|
|
120
|
+
n.updateResource(e, { status: s.status === 503 ? "offline" : "error" });
|
|
121
|
+
const r = s.headers.get("X-Eidos-Offline") === "true";
|
|
122
|
+
throw new Error(
|
|
123
|
+
r ? `offline: no cached response for ${e}` : `${s.status} ${s.statusText}`
|
|
124
|
+
);
|
|
125
|
+
} catch (s) {
|
|
126
|
+
const r = o ? await o.match(e).catch(() => null) : null;
|
|
127
|
+
if (r) {
|
|
128
|
+
const i = h.getState().resources[e];
|
|
129
|
+
return n.updateResource(e, {
|
|
130
|
+
status: "fresh",
|
|
131
|
+
lastEvent: "cache-hit",
|
|
132
|
+
cacheHits: ((i == null ? void 0 : i.cacheHits) ?? 0) + 1
|
|
133
|
+
}), r;
|
|
134
|
+
}
|
|
135
|
+
throw n.updateResource(e, { status: "error" }), s;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function S(e, t) {
|
|
139
|
+
const a = t.strategy;
|
|
140
|
+
return t.offline ? R(a ?? "stale-while-revalidate", e, t.cacheName) : R(a ?? "network-first", e, t.cacheName);
|
|
141
|
+
}
|
|
142
|
+
const x = {
|
|
143
|
+
"stale-while-revalidate": {
|
|
144
|
+
name: "StaleWhileRevalidate",
|
|
145
|
+
reasoning: "offline: true signals resilience. SWR returns cached data instantly while revalidating in the background — the best tradeoff between speed and freshness for offline-capable resources.",
|
|
146
|
+
behavior: [
|
|
147
|
+
"Cache hit → return immediately, kick off background revalidation",
|
|
148
|
+
"Cache miss → fetch from network, cache the response, return it",
|
|
149
|
+
"Offline → return cached version if available, 503 if not",
|
|
150
|
+
"Reconnect → next request triggers a background refresh"
|
|
151
|
+
],
|
|
152
|
+
equivalentCode: `// Workbox equivalent
|
|
153
|
+
new StaleWhileRevalidate({
|
|
154
|
+
cacheName: 'eidos-resources-v1',
|
|
155
|
+
plugins: [new ExpirationPlugin({ maxEntries: 60 })],
|
|
156
|
+
})`
|
|
157
|
+
},
|
|
158
|
+
"cache-first": {
|
|
159
|
+
name: "CacheFirst",
|
|
160
|
+
reasoning: "cache-first maximises speed and offline availability. Network is consulted only on cache miss. Best for static or infrequently-updated data.",
|
|
161
|
+
behavior: [
|
|
162
|
+
"Cache hit → return immediately, no network request made",
|
|
163
|
+
"Cache miss → fetch from network, cache the response, return it",
|
|
164
|
+
"Offline → return cached version, 503 if cache is empty",
|
|
165
|
+
"Cache never expires unless explicitly invalidated"
|
|
166
|
+
],
|
|
167
|
+
equivalentCode: `// Workbox equivalent
|
|
168
|
+
new CacheFirst({
|
|
169
|
+
cacheName: 'eidos-resources-v1',
|
|
170
|
+
plugins: [new ExpirationPlugin({ maxEntries: 60 })],
|
|
171
|
+
})`
|
|
172
|
+
},
|
|
173
|
+
"network-first": {
|
|
174
|
+
name: "NetworkFirst",
|
|
175
|
+
reasoning: "network-first prioritises fresh data. Cache acts as a safety net when offline. Best for frequently-updated resources where stale data causes problems.",
|
|
176
|
+
behavior: [
|
|
177
|
+
"Always try network first",
|
|
178
|
+
"Network success → update cache, return fresh response",
|
|
179
|
+
"Network failure → fall back to cached version",
|
|
180
|
+
"Offline with empty cache → return 503 error response"
|
|
181
|
+
],
|
|
182
|
+
equivalentCode: `// Workbox equivalent
|
|
183
|
+
new NetworkFirst({
|
|
184
|
+
cacheName: 'eidos-resources-v1',
|
|
185
|
+
networkTimeoutSeconds: 3,
|
|
186
|
+
})`
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
function R(e, t, a) {
|
|
190
|
+
return {
|
|
191
|
+
...x[e],
|
|
192
|
+
swStrategy: e,
|
|
193
|
+
cacheName: a ?? "eidos-resources-v1"
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
export {
|
|
197
|
+
q as resource,
|
|
198
|
+
N as setQueryInvalidator
|
|
199
|
+
};
|
|
200
|
+
//# sourceMappingURL=resource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource.js","sources":["../src/resource.ts"],"sourcesContent":["import { useEidosStore } from './store'\nimport { sendToWorker } from './sw-bridge'\nimport type {\n ResourceConfig,\n ResourceHandle,\n ResourceEntry,\n GeneratedStrategy,\n CacheStrategy,\n} from './types'\n\nconst _registry = new Map<string, ResourceHandle>()\n\n// ── Request deduplication ─────────────────────────────────────────────────────\n// If multiple callers invoke handle.fetch() simultaneously for the same URL,\n// only one network request is made. Each caller gets its own cloned Response.\n// Keyed by URL; entry is deleted when the request settles.\nconst _inflightRequests = /* @__PURE__ */ new Map<string, Promise<Response>>()\n\n// ── TanStack Query bridge (optional) ─────────────────────────────────────────\n// Set by @sweidos/eidos/query when withEidosQueryClient() is called.\n// Lets handle.invalidate() also invalidate the matching TQ cache entry.\ntype QueryInvalidator = (queryKey: [string, string]) => void\nlet _queryInvalidator: QueryInvalidator | null = null\n\n/** @internal Called by @sweidos/eidos/query. */\nexport function setQueryInvalidator(fn: QueryInvalidator): void {\n _queryInvalidator = fn\n}\n\n// ── URL pattern helpers ───────────────────────────────────────────────────────\n\n/** Returns true if `url` contains wildcard or :param segments. */\nfunction isPattern(url: string): boolean {\n return url.includes('*') || /:[^/]+/.test(url)\n}\n\n/**\n * Converts a URL pattern to a regex source string for SW fetch matching.\n * `**` → multi-segment wildcard (`.+`)\n * `*` → single-segment wildcard (`[^/]+`)\n * `:param` → named single segment (`[^/]+`)\n *\n * Special regex characters in the pattern (e.g. `.`) are escaped first so\n * they match literally.\n *\n * @example\n * patternToRegexStr('/api/products/*') // '^/api/products/[^/]+$'\n * patternToRegexStr('/api/products/**') // '^/api/products/.+$'\n * patternToRegexStr('/api/users/:id') // '^/api/users/[^/]+$'\n */\nfunction patternToRegexStr(pattern: string): string {\n // Escape all regex-special chars except `*`, `/`, `:` (handled below)\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return (\n '^' +\n escaped\n .replace(/\\*\\*/g, '.+') // ** → multi-segment wildcard\n .replace(/\\*/g, '[^/]+') // * → single-segment wildcard\n .replace(/:[^/]+/g, '[^/]+') // :param → single-segment wildcard\n + '$'\n )\n}\n\nfunction _patternError(url: string, method: string): Error {\n return new Error(\n `[eidos] resource('${url}') is a URL pattern — ${method}() is not supported on pattern handles. ` +\n `The SW intercepts matching requests automatically; call fetch(specificUrl) directly in your app code.`,\n )\n}\n\n// ── resource() ────────────────────────────────────────────────────────────────\n\nexport function resource<T = unknown>(\n url: string,\n config: ResourceConfig,\n): ResourceHandle<T> {\n if (_registry.has(url)) {\n if (import.meta.env.DEV) {\n const existing = _registry.get(url)!\n const existingCfg = existing.config\n if (\n existingCfg.offline !== config.offline ||\n existingCfg.strategy !== config.strategy ||\n existingCfg.cacheName !== config.cacheName\n ) {\n console.warn(\n `[eidos] resource('${url}') already registered with a different config — returning cached handle. Call resource.unregister() first to re-register.`,\n { registered: existingCfg, ignored: config },\n )\n }\n }\n return _registry.get(url) as ResourceHandle<T>\n }\n\n const strategy = deriveStrategy(url, config)\n const regexStr = isPattern(url) ? patternToRegexStr(url) : undefined\n\n const entry: ResourceEntry = {\n url,\n config,\n strategy,\n status: 'idle',\n cacheHits: 0,\n cacheMisses: 0,\n }\n\n useEidosStore.getState().registerResource(url, entry)\n\n sendToWorker({\n type: 'EIDOS_REGISTER_RESOURCE',\n url,\n strategy: strategy.swStrategy,\n cacheName: strategy.cacheName,\n ...(regexStr !== undefined && { pattern: regexStr }),\n })\n\n const handle: ResourceHandle<T> = {\n url,\n config,\n strategy,\n\n fetch: async () => {\n if (isPattern(url)) throw _patternError(url, 'fetch')\n\n // ── Deduplication: coalesce concurrent fetches for the same URL ─────\n // If a request is already in-flight, piggyback on it and return a clone\n // so each caller gets an independent readable Response body.\n const existing = _inflightRequests.get(url)\n if (existing) return existing.then((r) => r.clone())\n\n // Store the raw-response promise. All callers (including the primary)\n // receive a clone — the raw response stays unconsumed in the map so\n // any caller arriving while the promise is still pending can clone it.\n const task = _fetchResource(url, config, strategy)\n _inflightRequests.set(url, task)\n task.finally(() => _inflightRequests.delete(url))\n return task.then((r) => r.clone())\n },\n\n json: async () => {\n if (isPattern(url)) throw _patternError(url, 'json')\n const res = await handle.fetch()\n return res.json() as Promise<T>\n },\n\n query: () => {\n if (isPattern(url)) throw _patternError(url, 'query')\n return {\n queryKey: ['eidos', url] as [string, string],\n queryFn: () => handle.json(),\n }\n },\n\n prefetch: async () => {\n if (isPattern(url)) throw _patternError(url, 'prefetch')\n await handle.fetch()\n },\n\n invalidate: async () => {\n sendToWorker({ type: 'EIDOS_CLEAR_CACHE', url })\n const cache = await caches.open(strategy.cacheName).catch(() => null)\n if (cache) {\n const keys = await cache.keys()\n const patternRe = regexStr ? new RegExp(regexStr) : null\n const isCrossOrigin = url.startsWith('http')\n await Promise.all(\n keys\n .filter((r) => {\n const rUrl = r.url\n const p = new URL(rUrl).pathname\n if (patternRe) {\n // Cross-origin patterns were compiled from absolute URLs; test full URL.\n return patternRe.test(isCrossOrigin ? rUrl : p)\n }\n return isCrossOrigin ? rUrl === url : (rUrl === url || p === url)\n })\n .map((r) => cache.delete(r)),\n )\n }\n // For exact-URL resources update the store entry; patterns don't have a\n // single entry to update (individual URLs are not tracked per-pattern).\n if (!isPattern(url)) {\n useEidosStore.getState().updateResource(url, {\n status: 'stale',\n cachedAt: undefined,\n lastEvent: 'cache-cleared',\n cacheHits: 0,\n cacheMisses: 0,\n })\n }\n // Notify TanStack Query bridge if registered.\n _queryInvalidator?.(['eidos', url])\n },\n\n unregister: () => {\n _registry.delete(url)\n sendToWorker({ type: 'EIDOS_UNREGISTER_RESOURCE', url })\n useEidosStore.getState().unregisterResource(url)\n },\n }\n\n _registry.set(url, handle)\n return handle\n}\n\n// ── _fetchResource ─────────────────────────────────────────────────────────────\n// The actual network/cache implementation. Separated from handle.fetch() so the\n// deduplication wrapper can store the Promise and share it across concurrent callers.\n// Returns the raw (unconsumed) Response — callers MUST .clone() before reading body.\nasync function _fetchResource(\n url: string,\n config: ResourceConfig,\n strategy: GeneratedStrategy,\n): Promise<Response> {\n const store = useEidosStore.getState()\n store.updateResource(url, { status: 'fetching', fetchedAt: Date.now() })\n\n // Open cache once and reuse across try/catch — avoids a redundant\n // caches.open() call in the error fallback path.\n const cache = await caches.open(strategy.cacheName).catch(() => null)\n\n try {\n // ── network-first: skip cache check, go straight to network ─────────\n // For cache-first / SWR the cache check below is correct. For\n // network-first, reading cache first and returning early would\n // contradict the strategy — fresh data is the priority.\n if (strategy.swStrategy !== 'network-first') {\n // ── Direct Cache API check ─────────────────────────────────────────\n // We read the cache in the main thread rather than waiting for\n // an async SW postMessage. This gives instant, reliable status\n // updates regardless of SW message timing.\n const cached = cache ? await cache.match(url).catch(() => null) : null\n\n // Treat cache as miss if maxAge exceeded\n const current = useEidosStore.getState().resources[url]\n const expired =\n config.maxAge !== undefined &&\n current?.cachedAt !== undefined &&\n Date.now() - current.cachedAt > config.maxAge\n\n if (cached && !expired) {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n\n // Background revalidation for SWR (stale-while-revalidate)\n if (strategy.swStrategy === 'stale-while-revalidate') {\n fetch(url)\n .then(async (resp) => {\n if (resp.ok && cache) {\n await cache.put(url, resp.clone())\n useEidosStore.getState().updateResource(url, {\n cachedAt: Date.now(),\n lastEvent: 'cache-updated',\n })\n }\n })\n .catch(() => {\n /* offline — cached version stays valid */\n })\n }\n\n return cached\n }\n\n // Cache miss (or expired)\n const storeEntry = useEidosStore.getState().resources[url]\n store.updateResource(url, {\n cacheMisses: (storeEntry?.cacheMisses ?? 0) + 1,\n })\n }\n\n const response = await fetch(url)\n\n if (response.ok) {\n if (cache) await cache.put(url, response.clone())\n store.updateResource(url, {\n status: 'fresh',\n cachedAt: Date.now(),\n lastEvent: 'cache-updated',\n })\n return response\n }\n\n // Non-2xx response (e.g. 503 from offline SW) — update status and throw\n // so callers get a proper error instead of a plain-object body they can't use.\n store.updateResource(url, { status: response.status === 503 ? 'offline' : 'error' })\n\n // Check if the SW tagged this as an offline response\n const isOffline = response.headers.get('X-Eidos-Offline') === 'true'\n throw new Error(\n isOffline ? `offline: no cached response for ${url}` : `${response.status} ${response.statusText}`,\n )\n } catch (err) {\n // Network failure — try cache one more time as fallback\n const fallback = cache ? await cache.match(url).catch(() => null) : null\n\n if (fallback) {\n const current = useEidosStore.getState().resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n return fallback\n }\n\n store.updateResource(url, { status: 'error' })\n throw err\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Strategy derivation — intent → deterministic caching strategy\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction deriveStrategy(url: string, config: ResourceConfig): GeneratedStrategy {\n const explicit = config.strategy\n if (config.offline) return buildStrategy(explicit ?? 'stale-while-revalidate', url, config.cacheName)\n return buildStrategy(explicit ?? 'network-first', url, config.cacheName)\n}\n\nconst STRATEGY_META: Record<CacheStrategy, Omit<GeneratedStrategy, 'swStrategy' | 'cacheName'>> = {\n 'stale-while-revalidate': {\n name: 'StaleWhileRevalidate',\n reasoning:\n 'offline: true signals resilience. SWR returns cached data instantly while revalidating in the background — the best tradeoff between speed and freshness for offline-capable resources.',\n behavior: [\n 'Cache hit → return immediately, kick off background revalidation',\n 'Cache miss → fetch from network, cache the response, return it',\n 'Offline → return cached version if available, 503 if not',\n 'Reconnect → next request triggers a background refresh',\n ],\n equivalentCode: `// Workbox equivalent\nnew StaleWhileRevalidate({\n cacheName: 'eidos-resources-v1',\n plugins: [new ExpirationPlugin({ maxEntries: 60 })],\n})`,\n },\n 'cache-first': {\n name: 'CacheFirst',\n reasoning:\n 'cache-first maximises speed and offline availability. Network is consulted only on cache miss. Best for static or infrequently-updated data.',\n behavior: [\n 'Cache hit → return immediately, no network request made',\n 'Cache miss → fetch from network, cache the response, return it',\n 'Offline → return cached version, 503 if cache is empty',\n 'Cache never expires unless explicitly invalidated',\n ],\n equivalentCode: `// Workbox equivalent\nnew CacheFirst({\n cacheName: 'eidos-resources-v1',\n plugins: [new ExpirationPlugin({ maxEntries: 60 })],\n})`,\n },\n 'network-first': {\n name: 'NetworkFirst',\n reasoning:\n 'network-first prioritises fresh data. Cache acts as a safety net when offline. Best for frequently-updated resources where stale data causes problems.',\n behavior: [\n 'Always try network first',\n 'Network success → update cache, return fresh response',\n 'Network failure → fall back to cached version',\n 'Offline with empty cache → return 503 error response',\n ],\n equivalentCode: `// Workbox equivalent\nnew NetworkFirst({\n cacheName: 'eidos-resources-v1',\n networkTimeoutSeconds: 3,\n})`,\n },\n}\n\nfunction buildStrategy(swStrategy: CacheStrategy, _url: string, cacheName?: string): GeneratedStrategy {\n return {\n ...STRATEGY_META[swStrategy],\n swStrategy,\n cacheName: cacheName ?? 'eidos-resources-v1',\n }\n}\n"],"names":["_registry","_inflightRequests","_queryInvalidator","setQueryInvalidator","fn","isPattern","url","patternToRegexStr","pattern","_patternError","method","resource","config","strategy","deriveStrategy","regexStr","entry","useEidosStore","sendToWorker","handle","existing","r","task","_fetchResource","cache","keys","patternRe","isCrossOrigin","rUrl","p","store","cached","current","expired","resp","storeEntry","response","isOffline","err","fallback","explicit","buildStrategy","STRATEGY_META","swStrategy","_url","cacheName"],"mappings":";;AAUA,MAAMA,wBAAgB,IAAA,GAMhBC,wBAAwC,IAAA;AAM9C,IAAIC,IAA6C;AAG1C,SAASC,EAAoBC,GAA4B;AAC9D,EAAAF,IAAoBE;AACtB;AAKA,SAASC,EAAUC,GAAsB;AACvC,SAAOA,EAAI,SAAS,GAAG,KAAK,SAAS,KAAKA,CAAG;AAC/C;AAgBA,SAASC,EAAkBC,GAAyB;AAGlD,SACE,MAFcA,EAAQ,QAAQ,sBAAsB,MAAM,EAIvD,QAAQ,SAAS,IAAI,EACrB,QAAQ,OAAO,OAAO,EACtB,QAAQ,WAAW,OAAO,IAC3B;AAEN;AAEA,SAASC,EAAcH,GAAaI,GAAuB;AACzD,SAAO,IAAI;AAAA,IACT,qBAAqBJ,CAAG,yBAAyBI,CAAM;AAAA,EAAA;AAG3D;AAIO,SAASC,EACdL,GACAM,GACmB;AACnB,MAAIZ,EAAU,IAAIM,CAAG;AAenB,WAAON,EAAU,IAAIM,CAAG;AAG1B,QAAMO,IAAWC,EAAeR,GAAKM,CAAM,GACrCG,IAAWV,EAAUC,CAAG,IAAIC,EAAkBD,CAAG,IAAI,QAErDU,IAAuB;AAAA,IAC3B,KAAAV;AAAA,IACA,QAAAM;AAAA,IACA,UAAAC;AAAA,IACA,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,aAAa;AAAA,EAAA;AAGf,EAAAI,EAAc,SAAA,EAAW,iBAAiBX,GAAKU,CAAK,GAEpDE,EAAa;AAAA,IACX,MAAM;AAAA,IACN,KAAAZ;AAAA,IACA,UAAUO,EAAS;AAAA,IACnB,WAAWA,EAAS;AAAA,IACpB,GAAIE,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rG,SAAO;AAAA,IACL,GAAGH,EAAcC,CAAU;AAAA,IAC3B,YAAAA;AAAA,IACA,WAAWE,KAAa;AAAA,EAAA;AAE5B;"}
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { registerServiceWorker as m, registerBgSyncHandler as f } from "./sw-bridge.js";
|
|
2
|
+
import { replayQueue as s } from "./action.js";
|
|
3
|
+
import { useEidosStore as e } from "./store.js";
|
|
4
|
+
import { idbGetQueue as d } from "./idb.js";
|
|
5
|
+
let a = !1;
|
|
6
|
+
async function h(n = {}) {
|
|
7
|
+
if (a) return;
|
|
8
|
+
a = !0;
|
|
9
|
+
const o = n.swPath ?? "/eidos-sw.js", u = n.autoReplay ?? !0;
|
|
10
|
+
try {
|
|
11
|
+
const t = await d();
|
|
12
|
+
t.length > 0 && e.getState().hydrateQueue(t);
|
|
13
|
+
} catch {
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
await m(o);
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
if (f(() => {
|
|
20
|
+
e.getState().isOnline && setTimeout(s, 200);
|
|
21
|
+
}), u) {
|
|
22
|
+
let t = e.getState().isOnline;
|
|
23
|
+
e.subscribe(() => {
|
|
24
|
+
const { isOnline: i } = e.getState(), c = i && !t;
|
|
25
|
+
t = i, c && setTimeout(s, 600);
|
|
26
|
+
});
|
|
27
|
+
const r = e.getState(), l = r.queue.some((i) => i.status === "pending" || i.status === "failed");
|
|
28
|
+
r.isOnline && l && setTimeout(s, 1200);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export {
|
|
32
|
+
h as initEidos
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sources":["../src/runtime.ts"],"sourcesContent":["import { registerServiceWorker, registerBgSyncHandler } from './sw-bridge'\nimport { replayQueue } from './action'\nimport { useEidosStore } from './store'\nimport { idbGetQueue } from './idb'\n\nexport interface EidosConfig {\n /** Path to the eidos service worker. Defaults to '/eidos-sw.js'. */\n swPath?: string\n /** Automatically replay the action queue on reconnect. Default: true. */\n autoReplay?: boolean\n}\n\nlet _initialized = false\nlet _unsubscribe: (() => void) | null = null\n\nexport async function initEidos(config: EidosConfig = {}): Promise<void> {\n if (_initialized) return\n _initialized = true\n\n const swPath = config.swPath ?? '/eidos-sw.js'\n const autoReplay = config.autoReplay ?? true\n\n // Restore persisted queue from IndexedDB on startup\n try {\n const persisted = await idbGetQueue()\n if (persisted.length > 0) {\n useEidosStore.getState().hydrateQueue(persisted)\n }\n } catch {\n // IndexedDB unavailable (Firefox private browsing) — silent fallback\n }\n\n try {\n await registerServiceWorker(swPath)\n } catch {\n // SW registration failed; app continues without offline support\n }\n\n // When the SW fires the Background Sync tag, replay the queue in the main thread.\n // This path runs even if the user briefly navigated away and back — the browser\n // triggers the sync event on the SW, which wakes up all open clients.\n registerBgSyncHandler(() => {\n if (useEidosStore.getState().isOnline) {\n setTimeout(replayQueue, 200)\n }\n })\n\n if (autoReplay) {\n // ── Subscribe to the store instead of window.addEventListener('online')\n //\n // WHY: setOfflineSimulation() updates the store directly but never fires a\n // real browser `online` event. Watching the store catches both:\n // • Real network reconnects (sw-bridge updates store on window.online)\n // • Simulation toggled off (setOfflineSimulation(false) → store.setOnline(true))\n //\n let prevIsOnline = useEidosStore.getState().isOnline\n\n _unsubscribe = useEidosStore.subscribe(() => {\n const { isOnline } = useEidosStore.getState()\n const justCameOnline = isOnline && !prevIsOnline\n prevIsOnline = isOnline\n\n if (justCameOnline) {\n // Small delay so the connection (or simulation reset) settles first\n setTimeout(replayQueue, 600)\n }\n })\n\n // Replay any pending items that survived a page reload\n const store = useEidosStore.getState()\n const hasPending = store.queue.some((q) => q.status === 'pending' || q.status === 'failed')\n if (store.isOnline && hasPending) {\n setTimeout(replayQueue, 1200)\n }\n }\n\n if (import.meta.env.DEV) {\n const store = useEidosStore.getState()\n console.groupCollapsed('%c⚡ Eidos', 'color:#38bdf8;font-weight:bold')\n console.log('SW path :', swPath)\n console.log('Auto-replay:', autoReplay)\n console.log('SW status :', store.swStatus)\n console.groupEnd()\n }\n}\n\nexport function _resetEidos() {\n _unsubscribe?.()\n _unsubscribe = null\n _initialized = false\n}\n"],"names":["_initialized","initEidos","config","swPath","autoReplay","persisted","idbGetQueue","useEidosStore","registerServiceWorker","registerBgSyncHandler","replayQueue","prevIsOnline","isOnline","justCameOnline","store","hasPending","q"],"mappings":";;;;AAYA,IAAIA,IAAe;AAGnB,eAAsBC,EAAUC,IAAsB,IAAmB;AACvE,MAAIF,EAAc;AAClB,EAAAA,IAAe;AAEf,QAAMG,IAASD,EAAO,UAAU,gBAC1BE,IAAaF,EAAO,cAAc;AAGxC,MAAI;AACF,UAAMG,IAAY,MAAMC,EAAA;AACxB,IAAID,EAAU,SAAS,KACrBE,EAAc,SAAA,EAAW,aAAaF,CAAS;AAAA,EAEnD,QAAQ;AAAA,EAER;AAEA,MAAI;AACF,UAAMG,EAAsBL,CAAM;AAAA,EACpC,QAAQ;AAAA,EAER;AAWA,MANAM,EAAsB,MAAM;AAC1B,IAAIF,EAAc,SAAA,EAAW,YAC3B,WAAWG,GAAa,GAAG;AAAA,EAE/B,CAAC,GAEGN,GAAY;AAQd,QAAIO,IAAeJ,EAAc,SAAA,EAAW;AAE7B,IAAAA,EAAc,UAAU,MAAM;AAC3C,YAAM,EAAE,UAAAK,EAAA,IAAaL,EAAc,SAAA,GAC7BM,IAAiBD,KAAY,CAACD;AACpC,MAAAA,IAAeC,GAEXC,KAEF,WAAWH,GAAa,GAAG;AAAA,IAE/B,CAAC;AAGD,UAAMI,IAAQP,EAAc,SAAA,GACtBQ,IAAaD,EAAM,MAAM,KAAK,CAACE,MAAMA,EAAE,WAAW,aAAaA,EAAE,WAAW,QAAQ;AAC1F,IAAIF,EAAM,YAAYC,KACpB,WAAWL,GAAa,IAAI;AAAA,EAEhC;AAUF;"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
let s;
|
|
2
|
+
const n = /* @__PURE__ */ new Set();
|
|
3
|
+
function c() {
|
|
4
|
+
n.forEach((e) => e());
|
|
5
|
+
}
|
|
6
|
+
function r(e) {
|
|
7
|
+
s = { ...s, ...e(s) }, c();
|
|
8
|
+
}
|
|
9
|
+
s = {
|
|
10
|
+
isOnline: typeof navigator < "u" ? navigator.onLine : !0,
|
|
11
|
+
swStatus: "idle",
|
|
12
|
+
swError: void 0,
|
|
13
|
+
resources: {},
|
|
14
|
+
queue: [],
|
|
15
|
+
setOnline: (e) => r(() => ({ isOnline: e })),
|
|
16
|
+
setSwStatus: (e, u) => r(() => ({ swStatus: e, swError: u })),
|
|
17
|
+
registerResource: (e, u) => r((t) => ({ resources: { ...t.resources, [e]: u } })),
|
|
18
|
+
updateResource: (e, u) => r((t) => ({
|
|
19
|
+
resources: {
|
|
20
|
+
...t.resources,
|
|
21
|
+
[e]: t.resources[e] ? { ...t.resources[e], ...u } : t.resources[e]
|
|
22
|
+
}
|
|
23
|
+
})),
|
|
24
|
+
unregisterResource: (e) => r((u) => {
|
|
25
|
+
const { [e]: t, ...o } = u.resources;
|
|
26
|
+
return { resources: o };
|
|
27
|
+
}),
|
|
28
|
+
addQueueItem: (e) => r((u) => ({ queue: [...u.queue, e] })),
|
|
29
|
+
updateQueueItem: (e, u) => r((t) => ({
|
|
30
|
+
queue: t.queue.map((o) => o.id === e ? { ...o, ...u } : o)
|
|
31
|
+
})),
|
|
32
|
+
removeQueueItem: (e) => r((u) => ({ queue: u.queue.filter((t) => t.id !== e) })),
|
|
33
|
+
hydrateQueue: (e) => r(() => ({ queue: e }))
|
|
34
|
+
};
|
|
35
|
+
function i() {
|
|
36
|
+
return s;
|
|
37
|
+
}
|
|
38
|
+
function d(e) {
|
|
39
|
+
return n.add(e), () => {
|
|
40
|
+
n.delete(e);
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const a = {
|
|
44
|
+
getState: i,
|
|
45
|
+
subscribe: d,
|
|
46
|
+
// Test/devtools helper — merges partial state, preserves action methods.
|
|
47
|
+
setState: (e) => {
|
|
48
|
+
const u = typeof e == "function" ? e(s) : e;
|
|
49
|
+
s = { ...s, ...u }, c();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
export {
|
|
53
|
+
a as useEidosStore
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sources":["../src/store.ts"],"sourcesContent":["import type { EidosState, ResourceEntry, ActionQueueItem } from './types'\n\nexport interface EidosStore extends EidosState {\n // Online\n setOnline: (online: boolean) => void\n // SW\n setSwStatus: (status: EidosState['swStatus'], error?: string) => void\n // Resources\n registerResource: (url: string, entry: ResourceEntry) => void\n updateResource: (url: string, update: Partial<ResourceEntry>) => void\n unregisterResource: (url: string) => void\n // Queue\n addQueueItem: (item: ActionQueueItem) => void\n updateQueueItem: (id: string, update: Partial<ActionQueueItem>) => void\n removeQueueItem: (id: string) => void\n hydrateQueue: (items: ActionQueueItem[]) => void\n}\n\ntype Listener = () => void\n\nlet _state: EidosStore\nconst _listeners = new Set<Listener>()\n\nfunction _notify() {\n _listeners.forEach((fn) => fn())\n}\n\nfunction _set(updater: (prev: EidosStore) => Partial<EidosStore>) {\n _state = { ..._state, ...updater(_state) }\n _notify()\n}\n\n_state = {\n isOnline: typeof navigator !== 'undefined' ? navigator.onLine : true,\n swStatus: 'idle',\n swError: undefined,\n resources: {},\n queue: [],\n\n setOnline: (isOnline) => _set(() => ({ isOnline })),\n\n setSwStatus: (swStatus, swError) => _set(() => ({ swStatus, swError })),\n\n registerResource: (url, entry) =>\n _set((s) => ({ resources: { ...s.resources, [url]: entry } })),\n\n updateResource: (url, update) =>\n _set((s) => ({\n resources: {\n ...s.resources,\n [url]: s.resources[url] ? { ...s.resources[url], ...update } : s.resources[url],\n },\n })),\n\n unregisterResource: (url) =>\n _set((s) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { [url]: _removed, ...rest } = s.resources\n return { resources: rest }\n }),\n\n addQueueItem: (item) => _set((s) => ({ queue: [...s.queue, item] })),\n\n updateQueueItem: (id, update) =>\n _set((s) => ({\n queue: s.queue.map((item) => (item.id === id ? { ...item, ...update } : item)),\n })),\n\n removeQueueItem: (id) => _set((s) => ({ queue: s.queue.filter((item) => item.id !== id) })),\n\n hydrateQueue: (items) => _set(() => ({ queue: items })),\n}\n\nfunction _getState() {\n return _state\n}\n\nfunction _subscribe(listener: Listener) {\n _listeners.add(listener)\n return () => { _listeners.delete(listener) }\n}\n\nexport const useEidosStore = {\n getState: _getState,\n subscribe: _subscribe,\n // Test/devtools helper — merges partial state, preserves action methods.\n setState: (partial: Partial<EidosStore> | ((s: EidosStore) => Partial<EidosStore>)) => {\n const update = typeof partial === 'function' ? partial(_state) : partial\n _state = { ..._state, ...update }\n _notify()\n },\n}\n"],"names":["_state","_listeners","_notify","fn","_set","updater","isOnline","swStatus","swError","url","entry","s","update","_removed","rest","item","id","items","_getState","_subscribe","listener","useEidosStore","partial"],"mappings":"AAoBA,IAAIA;AACJ,MAAMC,wBAAiB,IAAA;AAEvB,SAASC,IAAU;AACjB,EAAAD,EAAW,QAAQ,CAACE,MAAOA,EAAA,CAAI;AACjC;AAEA,SAASC,EAAKC,GAAoD;AAChE,EAAAL,IAAS,EAAE,GAAGA,GAAQ,GAAGK,EAAQL,CAAM,EAAA,GACvCE,EAAA;AACF;AAEAF,IAAS;AAAA,EACP,UAAU,OAAO,YAAc,MAAc,UAAU,SAAS;AAAA,EAChE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAA;AAAA,EACX,OAAO,CAAA;AAAA,EAEP,WAAW,CAACM,MAAaF,EAAK,OAAO,EAAE,UAAAE,IAAW;AAAA,EAElD,aAAa,CAACC,GAAUC,MAAYJ,EAAK,OAAO,EAAE,UAAAG,GAAU,SAAAC,EAAA,EAA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B;AAAA,EAC3B,UAAUH;AAAA,EACV,WAAWC;AAAA;AAAA,EAEX,UAAU,CAACG,MAA4E;AACrF,UAAMV,IAAS,OAAOU,KAAY,aAAaA,EAAQtB,CAAM,IAAIsB;AACjE,IAAAtB,IAAS,EAAE,GAAGA,GAAQ,GAAGY,EAAA,GACzBV,EAAA;AAAA,EACF;AACF;"}
|
package/dist/stores.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { useEidosStore as i } from "./store.js";
|
|
2
|
+
function s(e) {
|
|
3
|
+
return {
|
|
4
|
+
subscribe(t) {
|
|
5
|
+
return t(e(i.getState())), i.subscribe(() => t(e(i.getState())));
|
|
6
|
+
},
|
|
7
|
+
getState() {
|
|
8
|
+
return e(i.getState());
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
const a = s((e) => e), d = s((e) => e.queue), f = s((e) => ({
|
|
13
|
+
isOnline: e.isOnline,
|
|
14
|
+
swStatus: e.swStatus,
|
|
15
|
+
swError: e.swError
|
|
16
|
+
})), c = s((e) => {
|
|
17
|
+
let t = 0, u = 0, r = 0;
|
|
18
|
+
for (const n of e.queue)
|
|
19
|
+
n.status === "pending" ? t++ : n.status === "failed" ? u++ : n.status === "replaying" && r++;
|
|
20
|
+
return { pending: t, failed: u, replaying: r, total: e.queue.length };
|
|
21
|
+
});
|
|
22
|
+
function l(e) {
|
|
23
|
+
return s((t) => t.resources[e]);
|
|
24
|
+
}
|
|
25
|
+
function S(e) {
|
|
26
|
+
return s((t) => t.queue.find((u) => u.id === e));
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
S as eidosAction,
|
|
30
|
+
d as eidosQueue,
|
|
31
|
+
c as eidosQueueStats,
|
|
32
|
+
l as eidosResource,
|
|
33
|
+
f as eidosStatus,
|
|
34
|
+
a as eidosStore
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=stores.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stores.js","sources":["../src/stores.ts"],"sourcesContent":["/**\n * Framework-agnostic reactive stores — compatible with Svelte's store protocol,\n * Vue's watchEffect, RxJS, and vanilla JS. Zero framework dependencies.\n *\n * Svelte: use the `$` prefix — `$eidosQueue`, `$eidosStatus`, etc.\n * Vue: call `.subscribe()` inside a composable with `onUnmounted` cleanup.\n * Vanilla: call `.subscribe(run)` directly; the return value unsubscribes.\n *\n * Each store calls its subscriber whenever any part of the Eidos state changes.\n * For fine-grained subscriptions, use `.getState()` to read the current snapshot\n * and compare manually in the subscriber callback.\n */\n\nimport { useEidosStore } from './store'\nimport type { EidosStore } from './store'\nimport type { ActionQueueItem, ResourceEntry } from './types'\n\n// ── Readable<T> — compatible with Svelte's Readable interface ─────────────────\n\nexport interface EidosReadable<T> {\n /** Subscribe to value changes. Returns an unsubscribe function. */\n subscribe(run: (value: T) => void): () => void\n /** Read the current value synchronously without subscribing. */\n getState(): T\n}\n\nfunction readable<T>(selector: (s: EidosStore) => T): EidosReadable<T> {\n return {\n subscribe(run) {\n // Emit current value immediately (Svelte store contract)\n run(selector(useEidosStore.getState()))\n return useEidosStore.subscribe(() => run(selector(useEidosStore.getState())))\n },\n getState() {\n return selector(useEidosStore.getState())\n },\n }\n}\n\n// ── Static stores (created once at module scope) ──────────────────────────────\n\n/** Full Eidos state snapshot. Prefer the narrower stores below. */\nexport const eidosStore: EidosReadable<EidosStore> = readable((s) => s)\n\n/** The action queue. Re-notifies on every queue mutation. */\nexport const eidosQueue: EidosReadable<ActionQueueItem[]> = readable((s) => s.queue)\n\n/**\n * Online status + SW lifecycle.\n * Object identity changes on every notification — destructure or compare fields\n * in the subscriber if you need to avoid unnecessary work.\n */\nexport const eidosStatus: EidosReadable<{\n isOnline: boolean\n swStatus: EidosStore['swStatus']\n swError: string | undefined\n}> = readable((s) => ({\n isOnline: s.isOnline,\n swStatus: s.swStatus,\n swError: s.swError,\n}))\n\n/**\n * Queue counts. Re-notifies on any queue mutation — compare values inside the\n * subscriber callback to skip work when counts haven't changed.\n */\nexport const eidosQueueStats: EidosReadable<{\n pending: number\n failed: number\n replaying: number\n total: number\n}> = readable((s) => {\n // Single pass over the queue — avoids three separate .filter() calls.\n let pending = 0, failed = 0, replaying = 0\n for (const q of s.queue) {\n if (q.status === 'pending') pending++\n else if (q.status === 'failed') failed++\n else if (q.status === 'replaying') replaying++\n }\n return { pending, failed, replaying, total: s.queue.length }\n})\n\n// ── Dynamic stores (created per URL / ID) ─────────────────────────────────────\n\n/**\n * Live cache state for a single registered resource URL.\n * @example\n * // Svelte\n * const entry = eidosResource('/api/products')\n * $: hits = $entry?.cacheHits ?? 0\n */\nexport function eidosResource(url: string): EidosReadable<ResourceEntry | undefined> {\n return readable((s) => s.resources[url])\n}\n\n/**\n * Live state for a single queue item by ID. Returns `undefined` once the item\n * is removed from the queue (after a successful replay or `clearQueue()`).\n * @example\n * // Svelte\n * const item = eidosAction(queuedResult.id)\n * $: status = $item?.status // 'pending' | 'replaying' | 'succeeded' | 'failed' | undefined\n */\nexport function eidosAction(id: string): EidosReadable<ActionQueueItem | undefined> {\n return readable((s) => s.queue.find((item) => item.id === id))\n}\n"],"names":["readable","selector","run","useEidosStore","eidosStore","s","eidosQueue","eidosStatus","eidosQueueStats","pending","failed","replaying","q","eidosResource","url","eidosAction","id","item"],"mappings":";AA0BA,SAASA,EAAYC,GAAkD;AACrE,SAAO;AAAA,IACL,UAAUC,GAAK;AAEb,aAAAA,EAAID,EAASE,EAAc,SAAA,CAAU,CAAC,GAC/BA,EAAc,UAAU,MAAMD,EAAID,EAASE,EAAc,SAAA,CAAU,CAAC,CAAC;AAAA,IAC9E;AAAA,IACA,WAAW;AACT,aAAOF,EAASE,EAAc,UAAU;AAAA,IAC1C;AAAA,EAAA;AAEJ;AAKO,MAAMC,IAAwCJ,EAAS,CAACK,MAAMA,CAAC,GAGzDC,IAA+CN,EAAS,CAACK,MAAMA,EAAE,KAAK,GAOtEE,IAIRP,EAAS,CAACK,OAAO;AAAA,EACpB,UAAUA,EAAE;AAAA,EACZ,UAAUA,EAAE;AAAA,EACZ,SAASA,EAAE;AACb,EAAE,GAMWG,IAKRR,EAAS,CAACK,MAAM;AAEnB,MAAII,IAAU,GAAGC,IAAS,GAAGC,IAAY;AACzC,aAAWC,KAAKP,EAAE;AAChB,IAAIO,EAAE,WAAW,YAAWH,MACnBG,EAAE,WAAW,WAAUF,MACvBE,EAAE,WAAW,eAAaD;AAErC,SAAO,EAAE,SAAAF,GAAS,QAAAC,GAAQ,WAAAC,GAAW,OAAON,EAAE,MAAM,OAAA;AACtD,CAAC;AAWM,SAASQ,EAAcC,GAAuD;AACnF,SAAOd,EAAS,CAACK,MAAMA,EAAE,UAAUS,CAAG,CAAC;AACzC;AAUO,SAASC,EAAYC,GAAwD;AAClF,SAAOhB,EAAS,CAACK,MAAMA,EAAE,MAAM,KAAK,CAACY,MAASA,EAAK,OAAOD,CAAE,CAAC;AAC/D;"}
|