@sweidos/eidos 2.1.0 → 2.2.0
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 +43 -14
- package/dist/action.js +47 -47
- package/dist/action.js.map +1 -1
- package/dist/devtools.js +169 -20
- package/dist/eidos.cjs +2 -2
- package/dist/eidos.cjs.map +1 -1
- package/dist/index.d.ts +74 -13
- package/dist/index.js +36 -33
- package/dist/react/hooks.js +30 -27
- package/dist/react/hooks.js.map +1 -1
- package/dist/runtime.js +29 -24
- package/dist/runtime.js.map +1 -1
- package/dist/store-slices.js +31 -20
- package/dist/store-slices.js.map +1 -1
- package/dist/store.js +22 -19
- package/dist/store.js.map +1 -1
- package/dist/stores.js +31 -22
- package/dist/stores.js.map +1 -1
- package/dist/testing.cjs +3 -2
- package/dist/testing.js +3 -2
- package/dist/types.js +19 -8
- package/dist/types.js.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +3 -3
package/dist/store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["import type { EidosState } from './types';\nimport { createResourceActions
|
|
1
|
+
{"version":3,"file":"store.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["import type { EidosState } from './types';\nimport { emptyReliabilityStats } from './types';\nimport {\n createResourceActions,\n createQueueActions,\n createReliabilityActions,\n} from './store-slices';\nimport type { ResourceActions, QueueActions, ReliabilityActions } from './store-slices';\n\nexport interface EidosStore extends EidosState, ResourceActions, QueueActions, ReliabilityActions {\n // Online\n setOnline: (online: boolean) => void;\n // SW\n setSwStatus: (status: EidosState['swStatus'], error?: string) => 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 // navigator.onLine is undefined in React Native — default to true unless explicitly false\n isOnline: typeof navigator === 'undefined' || navigator.onLine !== false,\n swStatus: 'idle',\n swError: undefined,\n resources: {},\n queue: [],\n reliability: emptyReliabilityStats(),\n\n setOnline: (isOnline) => _set(() => ({ isOnline })),\n\n setSwStatus: (swStatus, swError) => _set(() => ({ swStatus, swError })),\n\n ...createResourceActions(_set),\n ...createQueueActions(_set),\n ...createReliabilityActions(_set),\n};\n\nfunction _getState() {\n return _state;\n}\n\nfunction _subscribe(listener: Listener) {\n _listeners.add(listener);\n return () => {\n _listeners.delete(listener);\n };\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"],"mappings":";;AAkBA,IAAI,GACE,IAAa,oBAAI,IAAc;AAErC,SAAS,IAAU;AACjB,EAAA,EAAW,QAAA,CAAS,MAAO,EAAG,CAAC;AACjC;AAEA,SAAS,EAAK,GAAoD;AAChE,EAAA,IAAS;AAAA,IAAE,GAAG;AAAA,IAAQ,GAAG,EAAQ,CAAM;AAAA,EAAE,GACzC,EAAQ;AACV;AAEA,IAAS;AAAA,EAEP,UAAU,OAAO,YAAc,OAAe,UAAU,WAAW;AAAA,EACnE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAC;AAAA,EACZ,OAAO,CAAC;AAAA,EACR,aAAa,EAAsB;AAAA,EAEnC,WAAA,CAAY,MAAa,EAAA,OAAY,EAAE,UAAA,EAAS,EAAE;AAAA,EAElD,aAAA,CAAc,GAAU,MAAY,EAAA,OAAY;AAAA,IAAE,UAAA;AAAA,IAAU,SAAA;AAAA,EAAQ,EAAE;AAAA,EAEtE,GAAG,EAAsB,CAAI;AAAA,EAC7B,GAAG,EAAmB,CAAI;AAAA,EAC1B,GAAG,EAAyB,CAAI;AAClC;AAEA,SAAS,IAAY;AACnB,SAAO;AACT;AAEA,SAAS,EAAW,GAAoB;AACtC,SAAA,EAAW,IAAI,CAAQ,GACvB,MAAa;AACX,IAAA,EAAW,OAAO,CAAQ;AAAA,EAC5B;AACF;AAEA,IAAa,IAAgB;AAAA,EAC3B,UAAU;AAAA,EACV,WAAW;AAAA,EAEX,UAAA,CAAW,MAA4E;AACrF,UAAM,IAAS,OAAO,KAAY,aAAa,EAAQ,CAAM,IAAI;AACjE,IAAA,IAAS;AAAA,MAAE,GAAG;AAAA,MAAQ,GAAG;AAAA,IAAO,GAChC,EAAQ;AAAA,EACV;AACF"}
|
package/dist/stores.js
CHANGED
|
@@ -1,46 +1,55 @@
|
|
|
1
|
-
import { useEidosStore as n } from "./store.js";
|
|
2
1
|
import { countQueueByStatus as a } from "./types.js";
|
|
3
|
-
|
|
2
|
+
import { useEidosStore as u } from "./store.js";
|
|
3
|
+
function l(e, t) {
|
|
4
4
|
const r = Object.keys(e);
|
|
5
5
|
if (r.length !== Object.keys(t).length) return !1;
|
|
6
|
-
for (const
|
|
6
|
+
for (const s of r) if (e[s] !== t[s]) return !1;
|
|
7
7
|
return !0;
|
|
8
8
|
}
|
|
9
|
-
function
|
|
10
|
-
return
|
|
9
|
+
function o(e, t) {
|
|
10
|
+
return l(e, t);
|
|
11
11
|
}
|
|
12
|
-
function
|
|
12
|
+
function n(e, t = Object.is) {
|
|
13
13
|
return {
|
|
14
14
|
subscribe(r) {
|
|
15
|
-
let
|
|
16
|
-
return r(
|
|
17
|
-
const
|
|
18
|
-
t(
|
|
15
|
+
let s = e(u.getState());
|
|
16
|
+
return r(s), u.subscribe(() => {
|
|
17
|
+
const i = e(u.getState());
|
|
18
|
+
t(s, i) || (s = i, r(i));
|
|
19
19
|
});
|
|
20
20
|
},
|
|
21
21
|
getState() {
|
|
22
|
-
return e(
|
|
22
|
+
return e(u.getState());
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
-
var S =
|
|
26
|
+
var S = n((e) => e), b = n((e) => e.queue), d = n((e) => ({
|
|
27
27
|
isOnline: e.isOnline,
|
|
28
28
|
swStatus: e.swStatus,
|
|
29
29
|
swError: e.swError
|
|
30
|
-
}),
|
|
31
|
-
function
|
|
32
|
-
return
|
|
30
|
+
}), o), g = n((e) => a(e.queue), o), q = n((e) => e.reliability, o);
|
|
31
|
+
function h(e) {
|
|
32
|
+
return n((t) => t.resources[e]);
|
|
33
|
+
}
|
|
34
|
+
function v(e) {
|
|
35
|
+
return n((t) => t.queue.find((r) => r.id === e));
|
|
33
36
|
}
|
|
34
|
-
function
|
|
35
|
-
|
|
37
|
+
function w(e) {
|
|
38
|
+
let t = u.getState().queue.length;
|
|
39
|
+
return u.subscribe(() => {
|
|
40
|
+
const r = u.getState().queue.length;
|
|
41
|
+
t > 0 && r === 0 && e(), t = r;
|
|
42
|
+
});
|
|
36
43
|
}
|
|
37
44
|
export {
|
|
38
|
-
|
|
39
|
-
|
|
45
|
+
v as eidosAction,
|
|
46
|
+
b as eidosQueue,
|
|
40
47
|
g as eidosQueueStats,
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
48
|
+
q as eidosReliabilityStats,
|
|
49
|
+
h as eidosResource,
|
|
50
|
+
d as eidosStatus,
|
|
51
|
+
S as eidosStore,
|
|
52
|
+
w as onQueueDrain
|
|
44
53
|
};
|
|
45
54
|
|
|
46
55
|
//# sourceMappingURL=stores.js.map
|
package/dist/stores.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stores.js","names":[],"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 { countQueueByStatus } from './types';\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 shallowEqual<T extends Record<string, unknown>>(a: T, b: T): boolean {\n const keys = Object.keys(a) as (keyof T)[];\n if (keys.length !== Object.keys(b).length) return false;\n for (const k of keys) if (a[k] !== b[k]) return false;\n return true;\n}\n\n// Typed comparator alias so call sites don't need inline casts.\nfunction shallowEq<T extends Record<string, unknown>>(a: T, b: T): boolean {\n return shallowEqual(a, b);\n}\n\nfunction readable<T>(\n selector: (s: EidosStore) => T,\n equal: (a: T, b: T) => boolean = Object.is,\n): EidosReadable<T> {\n return {\n subscribe(run) {\n // Emit current value immediately (Svelte store contract)\n let last = selector(useEidosStore.getState());\n run(last);\n return useEidosStore.subscribe(() => {\n const next = selector(useEidosStore.getState());\n if (!equal(last, next)) {\n last = next;\n run(next);\n }\n });\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 * Only re-emits when isOnline, swStatus, or swError actually changes.\n */\nexport const eidosStatus: EidosReadable<{\n isOnline: boolean;\n swStatus: EidosStore['swStatus'];\n swError: string | undefined;\n}> = readable(\n (s) => ({ isOnline: s.isOnline, swStatus: s.swStatus, swError: s.swError }),\n shallowEq,\n);\n\n/**\n * Queue counts. Re-emits only when a count actually changes, not on every\n * queue mutation (e.g. a status transition that doesn't change counts is skipped).\n */\nexport const eidosQueueStats: EidosReadable<{\n pending: number;\n failed: number;\n replaying: number;\n total: number;\n}> = readable((s) => countQueueByStatus(s.queue), shallowEq);\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"],"mappings":";;AA2BA,SAAS,EAAgD,GAAM,GAAe;AAC5E,QAAM,IAAO,OAAO,KAAK,CAAC;AAC1B,MAAI,EAAK,WAAW,OAAO,KAAK,CAAC,EAAE,OAAQ,QAAO;AAClD,aAAW,KAAK,EAAM,KAAI,EAAE,CAAA,MAAO,EAAE,CAAA,EAAI,QAAO;AAChD,SAAO;AACT;AAGA,SAAS,EAA6C,GAAM,GAAe;AACzE,SAAO,EAAa,GAAG,CAAC;AAC1B;AAEA,SAAS,EACP,GACA,IAAiC,OAAO,IACtB;AAClB,SAAO;AAAA,IACL,UAAU,GAAK;AAEb,UAAI,IAAO,EAAS,EAAc,SAAS,CAAC;AAC5C,aAAA,EAAI,CAAI,GACD,EAAc,UAAA,MAAgB;AACnC,cAAM,IAAO,EAAS,EAAc,SAAS,CAAC;AAC9C,QAAK,EAAM,GAAM,CAAI,MACnB,IAAO,GACP,EAAI,CAAI;AAAA,MAEZ,CAAC;AAAA,IACH;AAAA,IACA,WAAW;AACT,aAAO,EAAS,EAAc,SAAS,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;AAKA,IAAa,IAAwC,EAAA,CAAU,MAAM,CAAC,GAGzD,IAA+C,EAAA,CAAU,MAAM,EAAE,KAAK,GAMtE,IAIR,EAAA,CACF,OAAO;AAAA,EAAE,UAAU,EAAE;AAAA,EAAU,UAAU,EAAE;AAAA,EAAU,SAAS,EAAE;AAAQ,IACzE,CACF,GAMa,IAKR,EAAA,CAAU,MAAM,EAAmB,EAAE,KAAK,GAAG,CAAS;
|
|
1
|
+
{"version":3,"file":"stores.js","names":[],"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 { countQueueByStatus } from './types';\nimport type { ActionQueueItem, ResourceEntry, ReliabilityStats } 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 shallowEqual<T extends Record<string, unknown>>(a: T, b: T): boolean {\n const keys = Object.keys(a) as (keyof T)[];\n if (keys.length !== Object.keys(b).length) return false;\n for (const k of keys) if (a[k] !== b[k]) return false;\n return true;\n}\n\n// Typed comparator alias so call sites don't need inline casts.\nfunction shallowEq<T extends Record<string, unknown>>(a: T, b: T): boolean {\n return shallowEqual(a, b);\n}\n\nfunction readable<T>(\n selector: (s: EidosStore) => T,\n equal: (a: T, b: T) => boolean = Object.is,\n): EidosReadable<T> {\n return {\n subscribe(run) {\n // Emit current value immediately (Svelte store contract)\n let last = selector(useEidosStore.getState());\n run(last);\n return useEidosStore.subscribe(() => {\n const next = selector(useEidosStore.getState());\n if (!equal(last, next)) {\n last = next;\n run(next);\n }\n });\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 * Only re-emits when isOnline, swStatus, or swError actually changes.\n */\nexport const eidosStatus: EidosReadable<{\n isOnline: boolean;\n swStatus: EidosStore['swStatus'];\n swError: string | undefined;\n}> = readable(\n (s) => ({ isOnline: s.isOnline, swStatus: s.swStatus, swError: s.swError }),\n shallowEq,\n);\n\n/**\n * Queue counts. Re-emits only when a count actually changes, not on every\n * queue mutation (e.g. a status transition that doesn't change counts is skipped).\n */\nexport const eidosQueueStats: EidosReadable<{\n pending: number;\n failed: number;\n replaying: number;\n total: number;\n}> = readable((s) => countQueueByStatus(s.queue), shallowEq);\n\n/**\n * Cumulative, session-scoped `neverLose` queue outcome counters — opt-in\n * reliability telemetry. Re-emits only when a counter changes. See\n * `EidosConfig.onReliabilityReport` to forward these to an analytics backend.\n */\nexport const eidosReliabilityStats: EidosReadable<ReliabilityStats> = readable(\n (s) => s.reliability,\n shallowEq,\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\n/**\n * Calls `callback` once each time the action queue drains from non-empty → 0.\n * Framework-agnostic equivalent of `useEidosOnDrain` for Svelte/Vue/vanilla.\n * Returns an unsubscribe function.\n *\n * @example\n * // Svelte\n * onMount(() => onQueueDrain(() => toast.success('All offline actions synced!')))\n */\nexport function onQueueDrain(callback: () => void): () => void {\n let prev = useEidosStore.getState().queue.length;\n return useEidosStore.subscribe(() => {\n const total = useEidosStore.getState().queue.length;\n if (prev > 0 && total === 0) callback();\n prev = total;\n });\n}\n"],"mappings":";;AA2BA,SAAS,EAAgD,GAAM,GAAe;AAC5E,QAAM,IAAO,OAAO,KAAK,CAAC;AAC1B,MAAI,EAAK,WAAW,OAAO,KAAK,CAAC,EAAE,OAAQ,QAAO;AAClD,aAAW,KAAK,EAAM,KAAI,EAAE,CAAA,MAAO,EAAE,CAAA,EAAI,QAAO;AAChD,SAAO;AACT;AAGA,SAAS,EAA6C,GAAM,GAAe;AACzE,SAAO,EAAa,GAAG,CAAC;AAC1B;AAEA,SAAS,EACP,GACA,IAAiC,OAAO,IACtB;AAClB,SAAO;AAAA,IACL,UAAU,GAAK;AAEb,UAAI,IAAO,EAAS,EAAc,SAAS,CAAC;AAC5C,aAAA,EAAI,CAAI,GACD,EAAc,UAAA,MAAgB;AACnC,cAAM,IAAO,EAAS,EAAc,SAAS,CAAC;AAC9C,QAAK,EAAM,GAAM,CAAI,MACnB,IAAO,GACP,EAAI,CAAI;AAAA,MAEZ,CAAC;AAAA,IACH;AAAA,IACA,WAAW;AACT,aAAO,EAAS,EAAc,SAAS,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;AAKA,IAAa,IAAwC,EAAA,CAAU,MAAM,CAAC,GAGzD,IAA+C,EAAA,CAAU,MAAM,EAAE,KAAK,GAMtE,IAIR,EAAA,CACF,OAAO;AAAA,EAAE,UAAU,EAAE;AAAA,EAAU,UAAU,EAAE;AAAA,EAAU,SAAS,EAAE;AAAQ,IACzE,CACF,GAMa,IAKR,EAAA,CAAU,MAAM,EAAmB,EAAE,KAAK,GAAG,CAAS,GAO9C,IAAyD,EAAA,CACnE,MAAM,EAAE,aACT,CACF;AAWA,SAAgB,EAAc,GAAuD;AACnF,SAAO,EAAA,CAAU,MAAM,EAAE,UAAU,CAAA,CAAI;AACzC;AAUA,SAAgB,EAAY,GAAwD;AAClF,SAAO,EAAA,CAAU,MAAM,EAAE,MAAM,KAAA,CAAM,MAAS,EAAK,OAAO,CAAE,CAAC;AAC/D;AAWA,SAAgB,EAAa,GAAkC;AAC7D,MAAI,IAAO,EAAc,SAAS,EAAE,MAAM;AAC1C,SAAO,EAAc,UAAA,MAAgB;AACnC,UAAM,IAAQ,EAAc,SAAS,EAAE,MAAM;AAC7C,IAAI,IAAO,KAAK,MAAU,KAAG,EAAS,GACtC,IAAO;AAAA,EACT,CAAC;AACH"}
|
package/dist/testing.cjs
CHANGED
|
@@ -144,13 +144,14 @@ async function resetEidos() {
|
|
|
144
144
|
* expect(getEidosState().queue).toHaveLength(1)
|
|
145
145
|
*/
|
|
146
146
|
function getEidosState() {
|
|
147
|
-
const { isOnline, swStatus, swError, resources, queue } = _sweidos_eidos.useEidosStore.getState();
|
|
147
|
+
const { isOnline, swStatus, swError, resources, queue, reliability } = _sweidos_eidos.useEidosStore.getState();
|
|
148
148
|
return {
|
|
149
149
|
isOnline,
|
|
150
150
|
swStatus,
|
|
151
151
|
swError,
|
|
152
152
|
resources,
|
|
153
|
-
queue
|
|
153
|
+
queue,
|
|
154
|
+
reliability
|
|
154
155
|
};
|
|
155
156
|
}
|
|
156
157
|
//#endregion
|
package/dist/testing.js
CHANGED
|
@@ -143,13 +143,14 @@ async function resetEidos() {
|
|
|
143
143
|
* expect(getEidosState().queue).toHaveLength(1)
|
|
144
144
|
*/
|
|
145
145
|
function getEidosState() {
|
|
146
|
-
const { isOnline, swStatus, swError, resources, queue } = useEidosStore.getState();
|
|
146
|
+
const { isOnline, swStatus, swError, resources, queue, reliability } = useEidosStore.getState();
|
|
147
147
|
return {
|
|
148
148
|
isOnline,
|
|
149
149
|
swStatus,
|
|
150
150
|
swError,
|
|
151
151
|
resources,
|
|
152
|
-
queue
|
|
152
|
+
queue,
|
|
153
|
+
reliability
|
|
153
154
|
};
|
|
154
155
|
}
|
|
155
156
|
//#endregion
|
package/dist/types.js
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
|
-
function a(
|
|
2
|
-
let n = 0, i = 0, s = 0;
|
|
3
|
-
for (const t of e) t.status === "pending" ? n++ : t.status === "failed" ? i++ : t.status === "replaying" && s++;
|
|
1
|
+
function a() {
|
|
4
2
|
return {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
queued: 0,
|
|
4
|
+
succeeded: 0,
|
|
5
|
+
failed: 0,
|
|
6
|
+
retried: 0,
|
|
7
|
+
conflicted: 0,
|
|
8
|
+
cancelled: 0
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function s(t) {
|
|
12
|
+
let i = 0, n = 0, l = 0;
|
|
13
|
+
for (const e of t) e.status === "pending" ? i++ : e.status === "failed" ? n++ : e.status === "replaying" && l++;
|
|
14
|
+
return {
|
|
15
|
+
pending: i,
|
|
16
|
+
failed: n,
|
|
17
|
+
replaying: l,
|
|
18
|
+
total: t.length
|
|
9
19
|
};
|
|
10
20
|
}
|
|
11
21
|
export {
|
|
12
|
-
|
|
22
|
+
s as countQueueByStatus,
|
|
23
|
+
a as emptyReliabilityStats
|
|
13
24
|
};
|
|
14
25
|
|
|
15
26
|
//# sourceMappingURL=types.js.map
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["// ─────────────────────────────────────────────────────────────────────────────\n// Eidos Core Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type CacheStrategy = 'cache-first' | 'stale-while-revalidate' | 'network-first';\n\n// ── Resource ─────────────────────────────────────────────────────────────────\n\nexport interface ResourceConfig {\n /** Make this resource available when the device is offline. */\n offline: boolean;\n /** Override the auto-selected caching strategy. */\n strategy?: CacheStrategy;\n /** Custom cache bucket name. Defaults to 'eidos-resources-v1'. */\n cacheName?: string;\n /**\n * Cache schema version. Bump when the response shape changes so old\n * cached entries (a different shape) aren't served from a stale bucket.\n * Appended to `cacheName` as a suffix (e.g. `eidos-resources-v1-v2`).\n * Old-versioned buckets are left in Cache Storage — clear them via\n * `caches.delete()` if needed.\n */\n version?: string | number;\n /** Max age of cached response in milliseconds. Expired entries trigger a network fetch. */\n maxAge?: number;\n}\n\nexport interface GeneratedStrategy {\n name: string;\n swStrategy: CacheStrategy;\n cacheName: string;\n /** One-line rationale for why this strategy was chosen. */\n reasoning: string;\n /** Human-readable description of each behavioral step. */\n behavior: string[];\n /** Pseudocode showing the equivalent Workbox config. */\n equivalentCode: string;\n}\n\nexport interface ResourceEntry {\n url: string;\n config: ResourceConfig;\n strategy: GeneratedStrategy;\n status: 'idle' | 'fetching' | 'fresh' | 'stale' | 'error' | 'offline';\n cachedAt?: number;\n fetchedAt?: number;\n cacheHits: number;\n cacheMisses: number;\n lastEvent?: 'cache-hit' | 'cache-updated' | 'network-error' | 'cache-cleared';\n}\n\nexport interface ResourceHandle<T = unknown> {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n fetch: () => Promise<Response>;\n json: () => Promise<T>;\n /** Returns a TanStack Query-compatible options object. */\n query: () => { queryKey: [string, string]; queryFn: () => Promise<T> };\n prefetch: () => Promise<void>;\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same URL with different config. */\n unregister: () => void;\n}\n\n/**\n * Handle for a URL pattern (`/api/products/*`, `/api/users/:id`, `**`).\n * The SW intercepts all matching requests automatically — there is no single\n * URL to fetch/cache directly, so only cache-management methods are exposed.\n * Returned by `resourcePattern()`.\n */\nexport interface PatternResourceHandle {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n /** Clears all cache entries matching this pattern. */\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same pattern with different config. */\n unregister: () => void;\n}\n\n/** A handle returned by either `resource()` or `resourcePattern()`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyResourceHandle = ResourceHandle<any> | PatternResourceHandle;\n\n/** Summary returned by warmCache(). */\nexport interface WarmCacheResult {\n /** Resources that were prefetched successfully. */\n warmed: number;\n /** Resources whose prefetch threw (network error, offline, etc.). */\n failed: number;\n /** The raw errors, in input order, for failed handles. */\n errors: unknown[];\n}\n\n// ── Action ───────────────────────────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface ActionConfigBase<TArgs extends any[] = any[]> {\n /** Max retry attempts before marking as failed. Default: 3. */\n maxRetries?: number;\n /** Human-readable name for the action (used in devtools). */\n name?: string;\n /**\n * Prefixes the registered action id (`namespace::name`). Use to avoid\n * collisions when two actions share a name (e.g. across micro-frontends,\n * or two `createOrder` actions in different modules) — without a\n * namespace, the second registration silently overwrites the first.\n */\n namespace?: string;\n /**\n * Replay order when multiple queued actions are pending.\n * `'high'` items replay before `'normal'`, which replay before `'low'`.\n * Each tier completes fully before the next tier begins.\n * Default: `'normal'`.\n */\n priority?: 'high' | 'normal' | 'low';\n /**\n * Called immediately before the async function executes, with the same args\n * plus a trailing `ActionContext`. Use to apply an optimistic UI update (add\n * item, mark as pending, etc.) and to capture `idempotencyKey` for later\n * `handle.cancel(idempotencyKey)` calls. Called on every invocation —\n * online, offline, and during queue replay.\n */\n onOptimistic?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Called when the action permanently fails and will not be retried.\n * - `best-effort`: called on first throw.\n * - `neverLose`: called when `maxRetries` is exhausted (status → `'failed'`).\n * Use to revert the optimistic update.\n */\n onRollback?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Declarative conflict-resolution strategy used during queue replay when\n * the server responds with a 4xx status (conflict, gone, unprocessable,\n * etc.). If not provided, 4xx errors are treated identically to other\n * errors (retried until `maxRetries` is exhausted, then `onRollback` is\n * called). See `ConflictConfig`.\n */\n conflict?: ConflictConfig;\n /**\n * When `true`, each invocation gets an `AbortController` whose `signal` is\n * passed via `ActionContext.signal`. Forward it to `fetch`/etc. so\n * `handle.cancel(idempotencyKey)` can abort an in-flight call, or remove a\n * not-yet-replayed queued item.\n */\n cancellable?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ActionConfig<TArgs extends any[] = any[]> =\n | (ActionConfigBase<TArgs> & {\n /** Call directly, no persistence on failure. */\n reliability: 'best-effort';\n })\n | (ActionConfigBase<TArgs> & {\n /** Persist to IndexedDB before executing; replay on reconnect. */\n reliability: 'neverLose';\n /**\n * Required for `neverLose` — queued items must survive a page reload\n * and be matched back to this action on replay. `fn.name` is not\n * reliable (minifiers rename it, arrow functions may be anonymous).\n */\n name: string;\n });\n\n/**\n * Passed to `ConflictConfig.resolve` (for `'merge'`/`'custom'` strategies)\n * when a queued action's replay receives a 4xx response.\n */\nexport interface ConflictContext {\n /** Whatever `fn` threw — typically a `Response` or an error with `.status`. */\n error: unknown;\n /** The original arguments the action was queued with. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[];\n /** Number of replay attempts so far (0 on first replay). */\n attempt: number;\n idempotencyKey: string;\n}\n\n/**\n * Outcome of `ConflictConfig.resolve`:\n * - `'retry'`: keep the item queued, retry per normal backoff.\n * - `'skip'`: silently remove the item (no `onRollback`).\n * - `{ resolved: args }`: replace the queued args and retry immediately\n * on the next replay pass.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ConflictResolution = 'retry' | 'skip' | { resolved: any[] };\n\nexport interface ConflictConfig {\n /**\n * - `'serverWins'`: drop the queued item, keeping the server's state.\n * - `'clientWins'`: keep retrying — the client's write should eventually\n * be accepted (e.g. once the server-side conflict is cleared).\n * - `'merge'` / `'custom'`: call `resolve` to decide.\n */\n strategy: 'serverWins' | 'clientWins' | 'merge' | 'custom';\n /** Required for `'merge'` and `'custom'`. */\n resolve?: (ctx: ConflictContext) => ConflictResolution;\n}\n\n/** Bump when ActionQueueItem's shape changes. Used to migrate items persisted by older versions. */\nexport const CURRENT_QUEUE_SCHEMA_VERSION = 2;\n\nexport interface ActionQueueItem {\n /** Shape version this item was persisted with. Items from before v2 are migrated on load. */\n schemaVersion: number;\n id: string;\n /** ID of the registered action (maps to the function in the registry). */\n actionId: string;\n actionName: string;\n /**\n * Stable per-invocation key, generated once and reused across every retry/replay\n * of this item. Pass to your server as an idempotency key so retries that reach\n * the server after a dropped response don't double-execute.\n */\n idempotencyKey: string;\n args: unknown[];\n queuedAt: number;\n retryCount: number;\n maxRetries: number;\n status: 'pending' | 'replaying' | 'succeeded' | 'failed';\n /** Replay priority. High items replay before normal, normal before low. Default: 'normal'. */\n priority?: 'high' | 'normal' | 'low';\n error?: string;\n completedAt?: number;\n /** Earliest timestamp at which this item should be retried (exponential backoff). */\n nextRetryAt?: number;\n}\n\nexport interface QueuedResult {\n readonly queued: true;\n readonly id: string;\n readonly message: string;\n}\n\n/** Summary returned by replayQueue(). */\nexport interface ReplayResult {\n /** Items where the registered function was found and called. */\n attempted: number;\n /** Items that resolved successfully. */\n succeeded: number;\n /** Items that failed and have no retries remaining (status: 'failed'). */\n failed: number;\n /** Items that failed but will be retried later (nextRetryAt set). */\n retrying: number;\n /** Items whose actionId had no registered function — likely not yet imported. */\n skipped: number;\n /** Items that received a 4xx response and were dropped via `conflict: { strategy: 'serverWins' }` (or `resolve()` returning `'skip'`). */\n conflicted: number;\n /** Items removed via `handle.cancel(idempotencyKey)` before/during replay. */\n cancelled: number;\n}\n\n/**\n * Passed as an extra argument after the declared params to `neverLose` actions,\n * on every invocation (initial call, offline queue, and replay). The same\n * `idempotencyKey` is reused across all retries of one logical invocation —\n * forward it to your server (e.g. as an `Idempotency-Key` header) so a retry\n * that reaches the server after a dropped response doesn't double-execute.\n */\nexport interface ActionContext {\n idempotencyKey: string;\n /** 0 on the first attempt, incremented on each replay retry. */\n attempt: number;\n /** Set when `config.cancellable` is true. Forward to `fetch`/etc. for cancellation support. */\n signal?: AbortSignal;\n}\n\n/**\n * Every action function receives its declared args plus a trailing\n * `ActionContext` — on every invocation (online, offline, and replay).\n */\nexport type ActionFn<TArgs extends unknown[], TReturn> = (\n ...args: [...TArgs, ActionContext]\n) => Promise<TReturn>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface ActionHandle<TArgs extends any[], TReturn> {\n (...args: TArgs): Promise<TReturn | QueuedResult>;\n readonly id: string;\n readonly config: ActionConfig;\n /**\n * Cancel an invocation by its `idempotencyKey` (from `ActionContext` /\n * `onOptimistic`). Aborts the in-flight call if `cancellable: true` and\n * still running, otherwise removes a not-yet-replayed queued item.\n * Returns `true` if something was cancelled/removed.\n */\n cancel: (idempotencyKey: string) => Promise<boolean>;\n}\n\n// ── Global State ─────────────────────────────────────────────────────────────\n\nexport interface EidosState {\n isOnline: boolean;\n swStatus: 'idle' | 'registering' | 'active' | 'error' | 'unsupported';\n swError?: string;\n resources: Record<string, ResourceEntry>;\n queue: ActionQueueItem[];\n}\n\nexport interface QueueStatusCounts {\n [key: string]: number;\n pending: number;\n failed: number;\n replaying: number;\n total: number;\n}\n\n/** Single pass over the queue — avoids separate .filter() calls per status. */\nexport function countQueueByStatus(queue: ActionQueueItem[]): QueueStatusCounts {\n let pending = 0,\n failed = 0,\n replaying = 0;\n for (const q of 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: queue.length };\n}\n"],"mappings":"AAwTA,SAAgB,EAAmB,GAA6C;AAC9E,MAAI,IAAU,GACZ,IAAS,GACT,IAAY;AACd,aAAW,KAAK,EACd,CAAI,EAAE,WAAW,YAAW,MACnB,EAAE,WAAW,WAAU,MACvB,EAAE,WAAW,eAAa;AAErC,SAAO;AAAA,IAAE,SAAA;AAAA,IAAS,QAAA;AAAA,IAAQ,WAAA;AAAA,IAAW,OAAO,EAAM;AAAA,EAAO;AAC3D"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["// ─────────────────────────────────────────────────────────────────────────────\n// Eidos Core Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type CacheStrategy = 'cache-first' | 'stale-while-revalidate' | 'network-first';\n\n// ── Resource ─────────────────────────────────────────────────────────────────\n\nexport interface ResourceConfig {\n /** Make this resource available when the device is offline. */\n offline: boolean;\n /** Override the auto-selected caching strategy. */\n strategy?: CacheStrategy;\n /** Custom cache bucket name. Defaults to 'eidos-resources-v1'. */\n cacheName?: string;\n /**\n * Cache schema version. Bump when the response shape changes so old\n * cached entries (a different shape) aren't served from a stale bucket.\n * Appended to `cacheName` as a suffix (e.g. `eidos-resources-v1-v2`).\n * Old-versioned buckets are left in Cache Storage — clear them via\n * `caches.delete()` if needed.\n */\n version?: string | number;\n /** Max age of cached response in milliseconds. Expired entries trigger a network fetch. */\n maxAge?: number;\n}\n\nexport interface GeneratedStrategy {\n name: string;\n swStrategy: CacheStrategy;\n cacheName: string;\n /** One-line rationale for why this strategy was chosen. */\n reasoning: string;\n /** Human-readable description of each behavioral step. */\n behavior: string[];\n /** Pseudocode showing the equivalent Workbox config. */\n equivalentCode: string;\n}\n\nexport interface ResourceEntry {\n url: string;\n config: ResourceConfig;\n strategy: GeneratedStrategy;\n status: 'idle' | 'fetching' | 'fresh' | 'stale' | 'error' | 'offline';\n cachedAt?: number;\n fetchedAt?: number;\n cacheHits: number;\n cacheMisses: number;\n lastEvent?: 'cache-hit' | 'cache-updated' | 'network-error' | 'cache-cleared';\n}\n\nexport interface ResourceHandle<T = unknown> {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n fetch: () => Promise<Response>;\n json: () => Promise<T>;\n /** Returns a TanStack Query-compatible options object. */\n query: () => { queryKey: [string, string]; queryFn: () => Promise<T> };\n prefetch: () => Promise<void>;\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same URL with different config. */\n unregister: () => void;\n}\n\n/**\n * Handle for a URL pattern (`/api/products/*`, `/api/users/:id`, `**`).\n * The SW intercepts all matching requests automatically — there is no single\n * URL to fetch/cache directly, so only cache-management methods are exposed.\n * Returned by `resourcePattern()`.\n */\nexport interface PatternResourceHandle {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n /** Clears all cache entries matching this pattern. */\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same pattern with different config. */\n unregister: () => void;\n}\n\n/** A handle returned by either `resource()` or `resourcePattern()`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyResourceHandle = ResourceHandle<any> | PatternResourceHandle;\n\n/** Summary returned by warmCache(). */\nexport interface WarmCacheResult {\n /** Resources that were prefetched successfully. */\n warmed: number;\n /** Resources whose prefetch threw (network error, offline, etc.). */\n failed: number;\n /** The raw errors, in input order, for failed handles. */\n errors: unknown[];\n}\n\n// ── Action ───────────────────────────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface ActionConfigBase<TArgs extends any[] = any[]> {\n /** Max retry attempts before marking as failed. Default: 3. */\n maxRetries?: number;\n /** Human-readable name for the action (used in devtools). */\n name?: string;\n /**\n * Prefixes the registered action id (`namespace::name`). Use to avoid\n * collisions when two actions share a name (e.g. across micro-frontends,\n * or two `createOrder` actions in different modules) — without a\n * namespace, the second registration silently overwrites the first.\n */\n namespace?: string;\n /**\n * Replay order when multiple queued actions are pending.\n * `'high'` items replay before `'normal'`, which replay before `'low'`.\n * Each tier completes fully before the next tier begins.\n * Default: `'normal'`.\n */\n priority?: 'high' | 'normal' | 'low';\n /**\n * Called immediately before the async function executes, with the same args\n * plus a trailing `ActionContext`. Use to apply an optimistic UI update (add\n * item, mark as pending, etc.) and to capture `idempotencyKey` for later\n * `handle.cancel(idempotencyKey)` calls. Called on every invocation —\n * online, offline, and during queue replay.\n */\n onOptimistic?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Called when the action permanently fails and will not be retried.\n * - `best-effort`: called on first throw.\n * - `neverLose`: called when `maxRetries` is exhausted (status → `'failed'`).\n * Use to revert the optimistic update.\n */\n onRollback?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Declarative conflict-resolution strategy used during queue replay when\n * the server responds with a 4xx status (conflict, gone, unprocessable,\n * etc.). If not provided, 4xx errors are treated identically to other\n * errors (retried until `maxRetries` is exhausted, then `onRollback` is\n * called). See `ConflictConfig`.\n */\n conflict?: ConflictConfig;\n /**\n * When `true`, each invocation gets an `AbortController` whose `signal` is\n * passed via `ActionContext.signal`. Forward it to `fetch`/etc. so\n * `handle.cancel(idempotencyKey)` can abort an in-flight call, or remove a\n * not-yet-replayed queued item.\n */\n cancellable?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ActionConfig<TArgs extends any[] = any[]> =\n | (ActionConfigBase<TArgs> & {\n /** Call directly, no persistence on failure. */\n reliability: 'best-effort';\n })\n | (ActionConfigBase<TArgs> & {\n /** Persist to IndexedDB before executing; replay on reconnect. */\n reliability: 'neverLose';\n /**\n * Required for `neverLose` — queued items must survive a page reload\n * and be matched back to this action on replay. `fn.name` is not\n * reliable (minifiers rename it, arrow functions may be anonymous).\n */\n name: string;\n });\n\n/**\n * Passed to `ConflictConfig.resolve` (for `'merge'`/`'custom'` strategies)\n * when a queued action's replay receives a 4xx response.\n */\nexport interface ConflictContext {\n /** Whatever `fn` threw — typically a `Response` or an error with `.status`. */\n error: unknown;\n /** The original arguments the action was queued with. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[];\n /** Number of replay attempts so far (0 on first replay). */\n attempt: number;\n idempotencyKey: string;\n}\n\n/**\n * Outcome of `ConflictConfig.resolve`:\n * - `'retry'`: keep the item queued, retry per normal backoff.\n * - `'skip'`: silently remove the item (no `onRollback`).\n * - `{ resolved: args }`: replace the queued args and retry immediately\n * on the next replay pass.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ConflictResolution = 'retry' | 'skip' | { resolved: any[] };\n\nexport interface ConflictConfig {\n /**\n * - `'serverWins'`: drop the queued item, keeping the server's state.\n * - `'clientWins'`: keep retrying — the client's write should eventually\n * be accepted (e.g. once the server-side conflict is cleared).\n * - `'merge'` / `'custom'`: call `resolve` to decide.\n */\n strategy: 'serverWins' | 'clientWins' | 'merge' | 'custom';\n /** Required for `'merge'` and `'custom'`. */\n resolve?: (ctx: ConflictContext) => ConflictResolution;\n}\n\n/** Bump when ActionQueueItem's shape changes. Used to migrate items persisted by older versions. */\nexport const CURRENT_QUEUE_SCHEMA_VERSION = 2;\n\nexport interface ActionQueueItem {\n /** Shape version this item was persisted with. Items from before v2 are migrated on load. */\n schemaVersion: number;\n id: string;\n /** ID of the registered action (maps to the function in the registry). */\n actionId: string;\n actionName: string;\n /**\n * Stable per-invocation key, generated once and reused across every retry/replay\n * of this item. Pass to your server as an idempotency key so retries that reach\n * the server after a dropped response don't double-execute.\n */\n idempotencyKey: string;\n args: unknown[];\n queuedAt: number;\n retryCount: number;\n maxRetries: number;\n status: 'pending' | 'replaying' | 'succeeded' | 'failed';\n /** Replay priority. High items replay before normal, normal before low. Default: 'normal'. */\n priority?: 'high' | 'normal' | 'low';\n error?: string;\n completedAt?: number;\n /** Earliest timestamp at which this item should be retried (exponential backoff). */\n nextRetryAt?: number;\n}\n\nexport interface QueuedResult {\n readonly queued: true;\n readonly id: string;\n readonly message: string;\n}\n\n/** Summary returned by replayQueue(). */\nexport interface ReplayResult {\n /** Items where the registered function was found and called. */\n attempted: number;\n /** Items that resolved successfully. */\n succeeded: number;\n /** Items that failed and have no retries remaining (status: 'failed'). */\n failed: number;\n /** Items that failed but will be retried later (nextRetryAt set). */\n retrying: number;\n /** Items whose actionId had no registered function — likely not yet imported. */\n skipped: number;\n /** Items that received a 4xx response and were dropped via `conflict: { strategy: 'serverWins' }` (or `resolve()` returning `'skip'`). */\n conflicted: number;\n /** Items removed via `handle.cancel(idempotencyKey)` before/during replay. */\n cancelled: number;\n}\n\n/**\n * Passed as an extra argument after the declared params to `neverLose` actions,\n * on every invocation (initial call, offline queue, and replay). The same\n * `idempotencyKey` is reused across all retries of one logical invocation —\n * forward it to your server (e.g. as an `Idempotency-Key` header) so a retry\n * that reaches the server after a dropped response doesn't double-execute.\n */\nexport interface ActionContext {\n idempotencyKey: string;\n /** 0 on the first attempt, incremented on each replay retry. */\n attempt: number;\n /** Set when `config.cancellable` is true. Forward to `fetch`/etc. for cancellation support. */\n signal?: AbortSignal;\n}\n\n/**\n * Every action function receives its declared args plus a trailing\n * `ActionContext` — on every invocation (online, offline, and replay).\n */\nexport type ActionFn<TArgs extends unknown[], TReturn> = (\n ...args: [...TArgs, ActionContext]\n) => Promise<TReturn>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface ActionHandle<TArgs extends any[], TReturn> {\n (...args: TArgs): Promise<TReturn | QueuedResult>;\n readonly id: string;\n readonly config: ActionConfig;\n /**\n * Cancel an invocation by its `idempotencyKey` (from `ActionContext` /\n * `onOptimistic`). Aborts the in-flight call if `cancellable: true` and\n * still running, otherwise removes a not-yet-replayed queued item.\n * Returns `true` if something was cancelled/removed.\n */\n cancel: (idempotencyKey: string) => Promise<boolean>;\n}\n\n// ── Global State ─────────────────────────────────────────────────────────────\n\nexport interface EidosState {\n isOnline: boolean;\n swStatus: 'idle' | 'registering' | 'active' | 'error' | 'unsupported';\n swError?: string;\n resources: Record<string, ResourceEntry>;\n queue: ActionQueueItem[];\n reliability: ReliabilityStats;\n}\n\n/**\n * Cumulative, session-scoped counters for `neverLose` queue outcomes — opt-in\n * telemetry surfaced via `eidosReliabilityStats` / `useEidosReliabilityStats()`\n * and `EidosConfig.onReliabilityReport`. Reset on page reload (not persisted).\n */\nexport interface ReliabilityStats {\n [key: string]: number;\n /** Actions persisted to the queue (offline, or online call that threw). */\n queued: number;\n /** Queue items that executed successfully (first attempt or a retry). */\n succeeded: number;\n /** Queue items that exhausted `maxRetries` and moved to `'failed'`. */\n failed: number;\n /** Replay attempts that failed but will retry (haven't exhausted `maxRetries`). */\n retried: number;\n /** Queue items dropped by a `serverWins`/`merge`/`custom` conflict resolution. */\n conflicted: number;\n /** Queue items removed via `handle.cancel(idempotencyKey)` before replay completed. */\n cancelled: number;\n}\n\nexport function emptyReliabilityStats(): ReliabilityStats {\n return { queued: 0, succeeded: 0, failed: 0, retried: 0, conflicted: 0, cancelled: 0 };\n}\n\nexport interface QueueStatusCounts {\n [key: string]: number;\n pending: number;\n failed: number;\n replaying: number;\n total: number;\n}\n\n/** Single pass over the queue — avoids separate .filter() calls per status. */\nexport function countQueueByStatus(queue: ActionQueueItem[]): QueueStatusCounts {\n let pending = 0,\n failed = 0,\n replaying = 0;\n for (const q of 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: queue.length };\n}\n"],"mappings":"AAqUA,SAAgB,IAA0C;AACxD,SAAO;AAAA,IAAE,QAAQ;AAAA,IAAG,WAAW;AAAA,IAAG,QAAQ;AAAA,IAAG,SAAS;AAAA,IAAG,YAAY;AAAA,IAAG,WAAW;AAAA,EAAE;AACvF;AAWA,SAAgB,EAAmB,GAA6C;AAC9E,MAAI,IAAU,GACZ,IAAS,GACT,IAAY;AACd,aAAW,KAAK,EACd,CAAI,EAAE,WAAW,YAAW,MACnB,EAAE,WAAW,WAAU,MACvB,EAAE,WAAW,eAAa;AAErC,SAAO;AAAA,IAAE,SAAA;AAAA,IAAS,QAAA;AAAA,IAAQ,WAAA;AAAA,IAAW,OAAO,EAAM;AAAA,EAAO;AAC3D"}
|
package/dist/version.js
CHANGED
package/dist/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["export const VERSION = '2.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["export const VERSION = '2.2.0';\n"],"mappings":"AAAA,IAAa,IAAU"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sweidos/eidos",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Describe intent. The runtime figures out how. An abstraction layer for offline-first web apps.",
|
|
5
5
|
"author": "Aditya Raj",
|
|
6
6
|
"license": "MIT",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
],
|
|
26
26
|
"homepage": "https://sweidos.vercel.app/overview",
|
|
27
27
|
"bugs": {
|
|
28
|
-
"url": "https://github.com/
|
|
28
|
+
"url": "https://github.com/sweidos/eidos/issues"
|
|
29
29
|
},
|
|
30
30
|
"funding": {
|
|
31
31
|
"type": "github",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
},
|
|
37
37
|
"repository": {
|
|
38
38
|
"type": "git",
|
|
39
|
-
"url": "https://github.com/
|
|
39
|
+
"url": "https://github.com/sweidos/eidos.git",
|
|
40
40
|
"directory": "packages/core"
|
|
41
41
|
},
|
|
42
42
|
"main": "./dist/eidos.cjs",
|