@sweidos/eidos 1.0.17 → 1.0.19

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 CHANGED
@@ -72,7 +72,7 @@ pnpm add @sweidos/eidos
72
72
  cp node_modules/@sweidos/eidos/dist/eidos-sw.js public/eidos-sw.js
73
73
  ```
74
74
 
75
- > **Vite users** — automate this with the [Vite plugin snippet](#vite-plugin).
75
+ > **Vite users** — use the [first-class Vite plugin](#vite-plugin) to automate this.
76
76
 
77
77
  ### 3. Wrap your app
78
78
 
@@ -115,7 +115,16 @@ export const createOrder = action(
115
115
  ### 5. Use in components
116
116
 
117
117
  ```tsx
118
- // TanStack Query
118
+ // TanStack Query — first-class hooks
119
+ import { useEidosQuery, useEidosMutation } from '@sweidos/eidos/query'
120
+
121
+ const { data, isPending } = useEidosQuery<Product[]>(products)
122
+
123
+ const mutation = useEidosMutation(createOrder, {
124
+ invalidates: [products], // clears cache + refetches on success
125
+ })
126
+
127
+ // Or with plain useQuery
119
128
  const { data } = useQuery(products.query<Product[]>())
120
129
 
121
130
  // Or plain async
@@ -499,26 +508,96 @@ eidos/
499
508
 
500
509
  ## Vite Plugin
501
510
 
502
- Automatically copy `eidos-sw.js` into `public/` on build:
511
+ `@sweidos/eidos` ships a first-class Vite plugin via the `@sweidos/eidos/vite` subpath. It automatically copies `eidos-sw.js` from the installed package into your `public/` directory on every build and dev-server start — keeping the SW in sync with the installed version.
503
512
 
504
513
  ```ts
505
514
  // vite.config.ts
506
- import { copyFileSync } from 'fs'
507
- import { resolve } from 'path'
508
-
509
- function eidosPlugin() {
510
- return {
511
- name: 'eidos-sw',
512
- buildStart() {
513
- copyFileSync(
514
- resolve('./node_modules/@sweidos/eidos/dist/eidos-sw.js'),
515
- resolve('./public/eidos-sw.js'),
516
- )
515
+ import { eidos } from '@sweidos/eidos/vite'
516
+ import { defineConfig } from 'vite'
517
+
518
+ export default defineConfig({
519
+ plugins: [eidos()],
520
+ })
521
+ ```
522
+
523
+ **Options:**
524
+
525
+ ```ts
526
+ eidos({
527
+ swDest: 'public/eidos-sw.js', // default — relative to project root
528
+ })
529
+ ```
530
+
531
+ No more manual `cp` step. The plugin runs on `buildStart` (prod builds) and `configureServer` (dev).
532
+
533
+ ---
534
+
535
+ ## TanStack Query Integration
536
+
537
+ `@sweidos/eidos/query` provides first-class hooks for [TanStack Query v5](https://tanstack.com/query/latest). Requires `@tanstack/react-query` — already optional in Eidos, just install it.
538
+
539
+ ### Setup (once)
540
+
541
+ ```ts
542
+ // main.tsx
543
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
544
+ import { withEidosQueryClient } from '@sweidos/eidos/query'
545
+
546
+ const queryClient = new QueryClient()
547
+ withEidosQueryClient(queryClient) // bridges handle.invalidate() → TQ cache
548
+
549
+ root.render(
550
+ <QueryClientProvider client={queryClient}>
551
+ <EidosProvider swPath="/eidos-sw.js">
552
+ <App />
553
+ </EidosProvider>
554
+ </QueryClientProvider>
555
+ )
556
+ ```
557
+
558
+ ### `useEidosQuery(handle, options?)`
559
+
560
+ Wraps `useQuery` with Eidos-smart defaults:
561
+ - `networkMode: 'always'` — Eidos owns offline; queries run even when `navigator.onLine` is false
562
+ - `retry: false` — Eidos handles retries at the SW/replay layer
563
+
564
+ ```tsx
565
+ import { useEidosQuery } from '@sweidos/eidos/query'
566
+
567
+ function ProductList() {
568
+ const { data, isPending, isError } = useEidosQuery<Product[]>(products)
569
+ // ...
570
+ }
571
+ ```
572
+
573
+ ### `useEidosMutation(handle, options?)`
574
+
575
+ Wraps `useMutation` for a single-argument action handle:
576
+ - `networkMode: 'always'` — action queues offline automatically
577
+ - `invalidates` — clears Eidos cache + invalidates TQ entries on success
578
+
579
+ ```tsx
580
+ import { useEidosMutation } from '@sweidos/eidos/query'
581
+
582
+ function OrderForm() {
583
+ const mutation = useEidosMutation(createOrder, {
584
+ invalidates: [products], // refetch product list after order
585
+ onSuccess(data) {
586
+ if ('queued' in data) toast('Saved offline — will sync when back online')
587
+ else toast(`Order #${data.id} created!`)
517
588
  },
518
- }
589
+ })
590
+
591
+ return <button onClick={() => mutation.mutate({ productId: 1, qty: 2 })}>Buy</button>
519
592
  }
520
593
  ```
521
594
 
595
+ ### `withEidosQueryClient(client)`
596
+
597
+ Registers a `QueryClient` with Eidos. After calling this:
598
+ - `handle.invalidate()` also calls `queryClient.invalidateQueries({ queryKey: ['eidos', url] })`
599
+ - Both systems stay in sync automatically, even when cache is cleared outside of mutations
600
+
522
601
  ---
523
602
 
524
603
  ## Known Limitations
@@ -541,9 +620,9 @@ function eidosPlugin() {
541
620
  - [x] URL pattern matching (`*`, `**`, `:param`)
542
621
  - [x] Cross-origin resource support
543
622
  - [x] Background Sync API integration
544
- - [ ] Vite plugin (first-class, published separately)
623
+ - [x] Vite plugin (`@sweidos/eidos/vite` subpath — ships in the main package)
545
624
  - [x] Vue / Svelte bindings (framework-agnostic reactive stores)
546
- - [ ] TanStack Query integration package
625
+ - [x] TanStack Query integration (`@sweidos/eidos/query` subpath — `useEidosQuery`, `useEidosMutation`, `withEidosQueryClient`)
547
626
 
548
627
  ---
549
628
 
package/dist/eidos.cjs.js CHANGED
@@ -168,6 +168,10 @@ function flushPendingMessages() {
168
168
  _pendingMessages = [];
169
169
  }
170
170
  const _registry = /* @__PURE__ */ new Map();
171
+ let _queryInvalidator = null;
172
+ function setQueryInvalidator(fn) {
173
+ _queryInvalidator = fn;
174
+ }
171
175
  function isPattern(url) {
172
176
  return url.includes("*") || /:[^/]+/.test(url);
173
177
  }
@@ -314,6 +318,7 @@ function resource(url, config) {
314
318
  cacheMisses: 0
315
319
  });
316
320
  }
321
+ _queryInvalidator == null ? void 0 : _queryInvalidator(["eidos", url]);
317
322
  },
318
323
  unregister: () => {
319
324
  _registry.delete(url);
@@ -745,6 +750,7 @@ exports.isBgSyncSupported = isBgSyncSupported;
745
750
  exports.replayQueue = replayQueue;
746
751
  exports.resource = resource;
747
752
  exports.setOfflineSimulation = setOfflineSimulation;
753
+ exports.setQueryInvalidator = setQueryInvalidator;
748
754
  exports.useEidos = useEidos;
749
755
  exports.useEidosAction = useEidosAction;
750
756
  exports.useEidosOnDrain = useEidosOnDrain;
@@ -1 +1 @@
1
- {"version":3,"file":"eidos.cjs.js","sources":["../src/store.ts","../src/sw-bridge.ts","../src/resource.ts","../src/idb.ts","../src/action.ts","../src/runtime.ts","../src/react/Provider.tsx","../src/react/hooks.ts","../src/version.ts","../src/stores.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","import { useEidosStore } from './store'\n\nlet _registration: ServiceWorkerRegistration | null = null\n// Messages sent before the SW activates are buffered here and flushed once\n// the SW is ready. Covers resource registrations, cache clears, offline\n// simulation — anything sent at module scope before EidosProvider mounts.\nlet _pendingMessages: Record<string, unknown>[] = []\n\nexport function getSwRegistration() {\n return _registration\n}\n\nexport async function registerServiceWorker(swPath: string): Promise<void> {\n if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {\n useEidosStore.getState().setSwStatus('unsupported')\n return\n }\n\n const store = useEidosStore.getState()\n store.setSwStatus('registering')\n\n try {\n _registration = await navigator.serviceWorker.register(swPath, { scope: '/' })\n\n await waitForActivation(_registration)\n\n store.setSwStatus('active')\n\n // Receive messages from SW\n navigator.serviceWorker.addEventListener('message', onSwMessage)\n\n // Track online/offline\n window.addEventListener('online', () => store.setOnline(true))\n window.addEventListener('offline', () => store.setOnline(false))\n\n flushPendingMessages()\n } catch (err) {\n store.setSwStatus('error', String(err))\n }\n}\n\nfunction waitForActivation(reg: ServiceWorkerRegistration): Promise<void> {\n return new Promise((resolve) => {\n if (reg.active) { resolve(); return }\n const sw = reg.installing ?? reg.waiting\n if (!sw) { resolve(); return }\n\n // Resolve after 10s regardless — another tab may be blocking activation\n const timer = setTimeout(resolve, 10_000)\n\n sw.addEventListener('statechange', function handler() {\n if (sw.state === 'activated') {\n clearTimeout(timer)\n sw.removeEventListener('statechange', handler)\n resolve()\n }\n })\n })\n}\n\nexport function sendToWorker(message: Record<string, unknown>): void {\n const sw = _registration?.active\n if (sw) {\n sw.postMessage(message)\n } else {\n _pendingMessages.push(message)\n }\n}\n\nlet _bgSyncHandler: (() => void) | null = null\n\nexport function registerBgSyncHandler(fn: () => void): void {\n _bgSyncHandler = fn\n}\n\nexport function isBgSyncSupported(): boolean {\n try {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n _registration !== null &&\n 'sync' in _registration\n )\n } catch {\n return false\n }\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as { type: string; url?: string; strategy?: string }\n if (!data?.type) return\n\n const store = useEidosStore.getState()\n const { type, url } = data\n\n if (type === 'EIDOS_BACKGROUND_SYNC') {\n _bgSyncHandler?.()\n return\n }\n\n if (!url) return\n\n switch (type) {\n case 'EIDOS_CACHE_HIT': {\n const current = store.resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n break\n }\n case 'EIDOS_CACHE_UPDATED': {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-updated',\n cachedAt: Date.now(),\n })\n break\n }\n case 'EIDOS_NETWORK_ERROR': {\n store.updateResource(url, {\n status: 'error',\n lastEvent: 'network-error',\n })\n break\n }\n }\n}\n\nexport function setOfflineSimulation(enabled: boolean): void {\n sendToWorker({ type: 'EIDOS_SIMULATE_OFFLINE', enabled })\n useEidosStore.getState().setOnline(!enabled)\n}\n\nfunction flushPendingMessages(): void {\n const sw = _registration?.active\n if (!sw) return\n for (const msg of _pendingMessages) sw.postMessage(msg)\n _pendingMessages = []\n}\n","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// ── 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 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 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 },\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// ─────────────────────────────────────────────────────────────────────────────\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","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","import { useEidosStore } from './store'\nimport { getSwRegistration } from './sw-bridge'\nimport {\n idbAddToQueue,\n idbGetPendingItems,\n idbUpdateQueueItem,\n idbRemoveFromQueue,\n idbClearQueue,\n} from './idb'\nimport type {\n ActionConfig,\n ActionHandle,\n ActionFn,\n ActionQueueItem,\n QueuedResult,\n ReplayResult,\n} from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _actionRegistry = new Map<string, ActionFn<any[], any>>()\n\nfunction uid() {\n return crypto.randomUUID()\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function action<TArgs extends any[], TReturn>(\n fn: ActionFn<TArgs, TReturn>,\n config: ActionConfig,\n): ActionHandle<TArgs, TReturn> {\n // || not ?? — fn.name can be '' (anonymous arrow fn) which ?? treats as a\n // valid value, causing all anonymous actions to share actionId ''.\n const actionId = config.name || fn.name || uid()\n\n if (import.meta.env.DEV && config.reliability === 'neverLose' && !config.name && !fn.name) {\n console.warn(\n `[eidos] action() registered with neverLose but no stable name was found (fn.name=\"${fn.name}\"). Pass config.name so queued items survive a page reload and can be replayed.`,\n )\n }\n\n // Registering here means the function is available for replay after\n // the user refreshes the page (actions are defined at module scope).\n _actionRegistry.set(actionId, fn as ActionFn<unknown[], unknown>)\n\n const wrapped = async (...args: TArgs): Promise<TReturn | QueuedResult> => {\n const { isOnline } = useEidosStore.getState()\n\n if (config.reliability === 'neverLose') {\n if (!isOnline) {\n return persistAndQueue(actionId, actionId, args, config)\n }\n // Online + neverLose: execute, queue on failure\n try {\n return await fn(...args)\n } catch {\n return persistAndQueue(actionId, actionId, args, config)\n }\n }\n\n // best-effort: execute directly, no queuing\n return fn(...args)\n }\n\n Object.defineProperty(wrapped, 'id', { value: actionId, writable: false })\n Object.defineProperty(wrapped, 'config', { value: config, writable: false })\n\n return wrapped as unknown as ActionHandle<TArgs, TReturn>\n}\n\nfunction isJsonSerializable(value: unknown): boolean {\n try {\n JSON.stringify(value)\n return true\n } catch {\n return false\n }\n}\n\nasync function persistAndQueue(\n actionId: string,\n actionName: string,\n args: unknown[],\n config: ActionConfig,\n): Promise<QueuedResult> {\n if (import.meta.env.DEV && !isJsonSerializable(args)) {\n console.warn(\n `[eidos] action \"${actionName}\" queued with non-JSON-serializable args. These args will be lost after a page reload. Use plain JSON values for neverLose actions.`,\n args,\n )\n }\n\n const id = uid()\n const item: ActionQueueItem = {\n id,\n actionId,\n actionName,\n args,\n queuedAt: Date.now(),\n retryCount: 0,\n maxRetries: config.maxRetries ?? 3,\n status: 'pending',\n }\n\n await idbAddToQueue(item)\n useEidosStore.getState().addQueueItem(item)\n\n // Register Background Sync tag so the browser can wake up open clients\n // when connectivity returns, even if the user navigated away briefly.\n // Graceful no-op when Background Sync is unsupported.\n try {\n const reg = getSwRegistration()\n if (reg && 'sync' in reg) {\n await (reg as unknown as { sync: { register(tag: string): Promise<void> } }).sync.register('eidos-queue-replay')\n }\n } catch {\n // Background Sync not available — online-event replay remains the fallback\n }\n\n return {\n queued: true,\n id,\n message: `\"${actionName}\" queued — will execute when online`,\n }\n}\n\n// Base delay 2s, doubles per retry, capped at 5 minutes, ±20% jitter\nfunction backoffMs(retryCount: number): number {\n const base = Math.min(2000 * 2 ** retryCount, 300_000)\n return base * (0.8 + Math.random() * 0.4)\n}\n\nlet _replaying = false\n\nexport async function replayQueue(): Promise<ReplayResult> {\n const store = useEidosStore.getState()\n if (!store.isOnline || _replaying) {\n return { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n }\n _replaying = true\n try {\n return await _doReplayQueue(store)\n } finally {\n _replaying = false\n }\n}\n\nasync function _doReplayQueue(store: ReturnType<typeof useEidosStore.getState>): Promise<ReplayResult> {\n\n const candidates = await idbGetPendingItems()\n const now = Date.now()\n const pending = candidates.filter(\n (item) => !item.nextRetryAt || item.nextRetryAt <= now,\n )\n\n const result: ReplayResult = { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n\n const outcomes = await Promise.allSettled(\n pending.map(async (item): Promise<'succeeded' | 'failed' | 'retrying' | 'skipped'> => {\n const fn = _actionRegistry.get(item.actionId)\n if (!fn) return 'skipped'\n\n store.updateQueueItem(item.id, { status: 'replaying' })\n await idbUpdateQueueItem(item.id, { status: 'replaying' })\n\n try {\n await fn(...(item.args as unknown[]))\n const completedAt = Date.now()\n store.updateQueueItem(item.id, { status: 'succeeded', completedAt })\n await idbUpdateQueueItem(item.id, { status: 'succeeded', completedAt })\n\n // Remove from queue after a delay so the UI can show the success state\n setTimeout(() => {\n store.removeQueueItem(item.id)\n idbRemoveFromQueue(item.id)\n }, 3000)\n return 'succeeded'\n } catch (err) {\n const retryCount = item.retryCount + 1\n if (retryCount >= item.maxRetries) {\n store.updateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n await idbUpdateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n return 'failed'\n } else {\n const nextRetryAt = Date.now() + backoffMs(retryCount)\n store.updateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n await idbUpdateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n return 'retrying'\n }\n }\n }),\n )\n\n for (const o of outcomes) {\n const outcome = o.status === 'fulfilled' ? o.value : 'failed'\n if (outcome === 'skipped') { result.skipped++ }\n else { result.attempted++; result[outcome]++ }\n }\n\n return result\n}\n\n/** Remove all items from the action queue (IDB + in-memory store). */\nexport async function clearQueue(): Promise<void> {\n await idbClearQueue()\n useEidosStore.getState().hydrateQueue([])\n}\n","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","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","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","export const VERSION = '1.0.12'\n","/**\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 pending: s.queue.filter((q) => q.status === 'pending').length,\n failed: s.queue.filter((q) => q.status === 'failed').length,\n replaying: s.queue.filter((q) => q.status === 'replaying').length,\n 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":["useEffect","useSyncExternalStore","useRef"],"mappings":";;;;AAoBA,IAAI;AACJ,MAAM,iCAAiB,IAAA;AAEvB,SAAS,UAAU;AACjB,aAAW,QAAQ,CAAC,OAAO,GAAA,CAAI;AACjC;AAEA,SAAS,KAAK,SAAoD;AAChE,WAAS,EAAE,GAAG,QAAQ,GAAG,QAAQ,MAAM,EAAA;AACvC,UAAA;AACF;AAEA,SAAS;AAAA,EACP,UAAU,OAAO,cAAc,cAAc,UAAU,SAAS;AAAA,EAChE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAA;AAAA,EACX,OAAO,CAAA;AAAA,EAEP,WAAW,CAAC,aAAa,KAAK,OAAO,EAAE,WAAW;AAAA,EAElD,aAAa,CAAC,UAAU,YAAY,KAAK,OAAO,EAAE,UAAU,QAAA,EAAU;AAAA,EAEtE,kBAAkB,CAAC,KAAK,UACtB,KAAK,CAAC,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,GAAG,MAAA,IAAU;AAAA,EAE/D,gBAAgB,CAAC,KAAK,WACpB,KAAK,CAAC,OAAO;AAAA,IACX,WAAW;AAAA,MACT,GAAG,EAAE;AAAA,MACL,CAAC,GAAG,GAAG,EAAE,UAAU,GAAG,IAAI,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C,MAAM,EAAE,WAAW,SAAS,EAAE;AAAA,EACzD,QAAW,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,QAAQ,EAAE;AAAA,EACxD,WAAW,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,EAAE;AAAA,EAC3D,OAAW,EAAE,MAAM;AACrB,EAAE;AAWK,SAAS,cAAc,KAAuD;AACnF,SAAO,SAAS,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC;AACzC;AAUO,SAAS,YAAY,IAAwD;AAClF,SAAO,SAAS,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;AAC/D;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"eidos.cjs.js","sources":["../src/store.ts","../src/sw-bridge.ts","../src/resource.ts","../src/idb.ts","../src/action.ts","../src/runtime.ts","../src/react/Provider.tsx","../src/react/hooks.ts","../src/version.ts","../src/stores.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","import { useEidosStore } from './store'\n\nlet _registration: ServiceWorkerRegistration | null = null\n// Messages sent before the SW activates are buffered here and flushed once\n// the SW is ready. Covers resource registrations, cache clears, offline\n// simulation — anything sent at module scope before EidosProvider mounts.\nlet _pendingMessages: Record<string, unknown>[] = []\n\nexport function getSwRegistration() {\n return _registration\n}\n\nexport async function registerServiceWorker(swPath: string): Promise<void> {\n if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {\n useEidosStore.getState().setSwStatus('unsupported')\n return\n }\n\n const store = useEidosStore.getState()\n store.setSwStatus('registering')\n\n try {\n _registration = await navigator.serviceWorker.register(swPath, { scope: '/' })\n\n await waitForActivation(_registration)\n\n store.setSwStatus('active')\n\n // Receive messages from SW\n navigator.serviceWorker.addEventListener('message', onSwMessage)\n\n // Track online/offline\n window.addEventListener('online', () => store.setOnline(true))\n window.addEventListener('offline', () => store.setOnline(false))\n\n flushPendingMessages()\n } catch (err) {\n store.setSwStatus('error', String(err))\n }\n}\n\nfunction waitForActivation(reg: ServiceWorkerRegistration): Promise<void> {\n return new Promise((resolve) => {\n if (reg.active) { resolve(); return }\n const sw = reg.installing ?? reg.waiting\n if (!sw) { resolve(); return }\n\n // Resolve after 10s regardless — another tab may be blocking activation\n const timer = setTimeout(resolve, 10_000)\n\n sw.addEventListener('statechange', function handler() {\n if (sw.state === 'activated') {\n clearTimeout(timer)\n sw.removeEventListener('statechange', handler)\n resolve()\n }\n })\n })\n}\n\nexport function sendToWorker(message: Record<string, unknown>): void {\n const sw = _registration?.active\n if (sw) {\n sw.postMessage(message)\n } else {\n _pendingMessages.push(message)\n }\n}\n\nlet _bgSyncHandler: (() => void) | null = null\n\nexport function registerBgSyncHandler(fn: () => void): void {\n _bgSyncHandler = fn\n}\n\nexport function isBgSyncSupported(): boolean {\n try {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n _registration !== null &&\n 'sync' in _registration\n )\n } catch {\n return false\n }\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as { type: string; url?: string; strategy?: string }\n if (!data?.type) return\n\n const store = useEidosStore.getState()\n const { type, url } = data\n\n if (type === 'EIDOS_BACKGROUND_SYNC') {\n _bgSyncHandler?.()\n return\n }\n\n if (!url) return\n\n switch (type) {\n case 'EIDOS_CACHE_HIT': {\n const current = store.resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n break\n }\n case 'EIDOS_CACHE_UPDATED': {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-updated',\n cachedAt: Date.now(),\n })\n break\n }\n case 'EIDOS_NETWORK_ERROR': {\n store.updateResource(url, {\n status: 'error',\n lastEvent: 'network-error',\n })\n break\n }\n }\n}\n\nexport function setOfflineSimulation(enabled: boolean): void {\n sendToWorker({ type: 'EIDOS_SIMULATE_OFFLINE', enabled })\n useEidosStore.getState().setOnline(!enabled)\n}\n\nfunction flushPendingMessages(): void {\n const sw = _registration?.active\n if (!sw) return\n for (const msg of _pendingMessages) sw.postMessage(msg)\n _pendingMessages = []\n}\n","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// ── 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 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 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// ─────────────────────────────────────────────────────────────────────────────\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","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","import { useEidosStore } from './store'\nimport { getSwRegistration } from './sw-bridge'\nimport {\n idbAddToQueue,\n idbGetPendingItems,\n idbUpdateQueueItem,\n idbRemoveFromQueue,\n idbClearQueue,\n} from './idb'\nimport type {\n ActionConfig,\n ActionHandle,\n ActionFn,\n ActionQueueItem,\n QueuedResult,\n ReplayResult,\n} from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _actionRegistry = new Map<string, ActionFn<any[], any>>()\n\nfunction uid() {\n return crypto.randomUUID()\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function action<TArgs extends any[], TReturn>(\n fn: ActionFn<TArgs, TReturn>,\n config: ActionConfig,\n): ActionHandle<TArgs, TReturn> {\n // || not ?? — fn.name can be '' (anonymous arrow fn) which ?? treats as a\n // valid value, causing all anonymous actions to share actionId ''.\n const actionId = config.name || fn.name || uid()\n\n if (import.meta.env.DEV && config.reliability === 'neverLose' && !config.name && !fn.name) {\n console.warn(\n `[eidos] action() registered with neverLose but no stable name was found (fn.name=\"${fn.name}\"). Pass config.name so queued items survive a page reload and can be replayed.`,\n )\n }\n\n // Registering here means the function is available for replay after\n // the user refreshes the page (actions are defined at module scope).\n _actionRegistry.set(actionId, fn as ActionFn<unknown[], unknown>)\n\n const wrapped = async (...args: TArgs): Promise<TReturn | QueuedResult> => {\n const { isOnline } = useEidosStore.getState()\n\n if (config.reliability === 'neverLose') {\n if (!isOnline) {\n return persistAndQueue(actionId, actionId, args, config)\n }\n // Online + neverLose: execute, queue on failure\n try {\n return await fn(...args)\n } catch {\n return persistAndQueue(actionId, actionId, args, config)\n }\n }\n\n // best-effort: execute directly, no queuing\n return fn(...args)\n }\n\n Object.defineProperty(wrapped, 'id', { value: actionId, writable: false })\n Object.defineProperty(wrapped, 'config', { value: config, writable: false })\n\n return wrapped as unknown as ActionHandle<TArgs, TReturn>\n}\n\nfunction isJsonSerializable(value: unknown): boolean {\n try {\n JSON.stringify(value)\n return true\n } catch {\n return false\n }\n}\n\nasync function persistAndQueue(\n actionId: string,\n actionName: string,\n args: unknown[],\n config: ActionConfig,\n): Promise<QueuedResult> {\n if (import.meta.env.DEV && !isJsonSerializable(args)) {\n console.warn(\n `[eidos] action \"${actionName}\" queued with non-JSON-serializable args. These args will be lost after a page reload. Use plain JSON values for neverLose actions.`,\n args,\n )\n }\n\n const id = uid()\n const item: ActionQueueItem = {\n id,\n actionId,\n actionName,\n args,\n queuedAt: Date.now(),\n retryCount: 0,\n maxRetries: config.maxRetries ?? 3,\n status: 'pending',\n }\n\n await idbAddToQueue(item)\n useEidosStore.getState().addQueueItem(item)\n\n // Register Background Sync tag so the browser can wake up open clients\n // when connectivity returns, even if the user navigated away briefly.\n // Graceful no-op when Background Sync is unsupported.\n try {\n const reg = getSwRegistration()\n if (reg && 'sync' in reg) {\n await (reg as unknown as { sync: { register(tag: string): Promise<void> } }).sync.register('eidos-queue-replay')\n }\n } catch {\n // Background Sync not available — online-event replay remains the fallback\n }\n\n return {\n queued: true,\n id,\n message: `\"${actionName}\" queued — will execute when online`,\n }\n}\n\n// Base delay 2s, doubles per retry, capped at 5 minutes, ±20% jitter\nfunction backoffMs(retryCount: number): number {\n const base = Math.min(2000 * 2 ** retryCount, 300_000)\n return base * (0.8 + Math.random() * 0.4)\n}\n\nlet _replaying = false\n\nexport async function replayQueue(): Promise<ReplayResult> {\n const store = useEidosStore.getState()\n if (!store.isOnline || _replaying) {\n return { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n }\n _replaying = true\n try {\n return await _doReplayQueue(store)\n } finally {\n _replaying = false\n }\n}\n\nasync function _doReplayQueue(store: ReturnType<typeof useEidosStore.getState>): Promise<ReplayResult> {\n\n const candidates = await idbGetPendingItems()\n const now = Date.now()\n const pending = candidates.filter(\n (item) => !item.nextRetryAt || item.nextRetryAt <= now,\n )\n\n const result: ReplayResult = { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n\n const outcomes = await Promise.allSettled(\n pending.map(async (item): Promise<'succeeded' | 'failed' | 'retrying' | 'skipped'> => {\n const fn = _actionRegistry.get(item.actionId)\n if (!fn) return 'skipped'\n\n store.updateQueueItem(item.id, { status: 'replaying' })\n await idbUpdateQueueItem(item.id, { status: 'replaying' })\n\n try {\n await fn(...(item.args as unknown[]))\n const completedAt = Date.now()\n store.updateQueueItem(item.id, { status: 'succeeded', completedAt })\n await idbUpdateQueueItem(item.id, { status: 'succeeded', completedAt })\n\n // Remove from queue after a delay so the UI can show the success state\n setTimeout(() => {\n store.removeQueueItem(item.id)\n idbRemoveFromQueue(item.id)\n }, 3000)\n return 'succeeded'\n } catch (err) {\n const retryCount = item.retryCount + 1\n if (retryCount >= item.maxRetries) {\n store.updateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n await idbUpdateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n return 'failed'\n } else {\n const nextRetryAt = Date.now() + backoffMs(retryCount)\n store.updateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n await idbUpdateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n return 'retrying'\n }\n }\n }),\n )\n\n for (const o of outcomes) {\n const outcome = o.status === 'fulfilled' ? o.value : 'failed'\n if (outcome === 'skipped') { result.skipped++ }\n else { result.attempted++; result[outcome]++ }\n }\n\n return result\n}\n\n/** Remove all items from the action queue (IDB + in-memory store). */\nexport async function clearQueue(): Promise<void> {\n await idbClearQueue()\n useEidosStore.getState().hydrateQueue([])\n}\n","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","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","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","export const VERSION = '1.0.12'\n","/**\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 pending: s.queue.filter((q) => q.status === 'pending').length,\n failed: s.queue.filter((q) => q.status === 'failed').length,\n replaying: s.queue.filter((q) => q.status === 'replaying').length,\n 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":["useEffect","useSyncExternalStore","useRef"],"mappings":";;;;AAoBA,IAAI;AACJ,MAAM,iCAAiB,IAAA;AAEvB,SAAS,UAAU;AACjB,aAAW,QAAQ,CAAC,OAAO,GAAA,CAAI;AACjC;AAEA,SAAS,K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PendingMessages() {
166
166
  _pendingMessages = [];
167
167
  }
168
168
  const _registry = /* @__PURE__ */ new Map();
169
+ let _queryInvalidator = null;
170
+ function setQueryInvalidator(fn) {
171
+ _queryInvalidator = fn;
172
+ }
169
173
  function isPattern(url) {
170
174
  return url.includes("*") || /:[^/]+/.test(url);
171
175
  }
@@ -312,6 +316,7 @@ function resource(url, config) {
312
316
  cacheMisses: 0
313
317
  });
314
318
  }
319
+ _queryInvalidator == null ? void 0 : _queryInvalidator(["eidos", url]);
315
320
  },
316
321
  unregister: () => {
317
322
  _registry.delete(url);
@@ -744,6 +749,7 @@ export {
744
749
  replayQueue,
745
750
  resource,
746
751
  setOfflineSimulation,
752
+ setQueryInvalidator,
747
753
  useEidos,
748
754
  useEidosAction,
749
755
  useEidosOnDrain,
@@ -1 +1 @@
1
- {"version":3,"file":"eidos.es.js","sources":["../src/store.ts","../src/sw-bridge.ts","../src/resource.ts","../src/idb.ts","../src/action.ts","../src/runtime.ts","../src/react/Provider.tsx","../src/react/hooks.ts","../src/version.ts","../src/stores.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","import { useEidosStore } from './store'\n\nlet _registration: ServiceWorkerRegistration | null = null\n// Messages sent before the SW activates are buffered here and flushed once\n// the SW is ready. Covers resource registrations, cache clears, offline\n// simulation — anything sent at module scope before EidosProvider mounts.\nlet _pendingMessages: Record<string, unknown>[] = []\n\nexport function getSwRegistration() {\n return _registration\n}\n\nexport async function registerServiceWorker(swPath: string): Promise<void> {\n if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {\n useEidosStore.getState().setSwStatus('unsupported')\n return\n }\n\n const store = useEidosStore.getState()\n store.setSwStatus('registering')\n\n try {\n _registration = await navigator.serviceWorker.register(swPath, { scope: '/' })\n\n await waitForActivation(_registration)\n\n store.setSwStatus('active')\n\n // Receive messages from SW\n navigator.serviceWorker.addEventListener('message', onSwMessage)\n\n // Track online/offline\n window.addEventListener('online', () => store.setOnline(true))\n window.addEventListener('offline', () => store.setOnline(false))\n\n flushPendingMessages()\n } catch (err) {\n store.setSwStatus('error', String(err))\n }\n}\n\nfunction waitForActivation(reg: ServiceWorkerRegistration): Promise<void> {\n return new Promise((resolve) => {\n if (reg.active) { resolve(); return }\n const sw = reg.installing ?? reg.waiting\n if (!sw) { resolve(); return }\n\n // Resolve after 10s regardless — another tab may be blocking activation\n const timer = setTimeout(resolve, 10_000)\n\n sw.addEventListener('statechange', function handler() {\n if (sw.state === 'activated') {\n clearTimeout(timer)\n sw.removeEventListener('statechange', handler)\n resolve()\n }\n })\n })\n}\n\nexport function sendToWorker(message: Record<string, unknown>): void {\n const sw = _registration?.active\n if (sw) {\n sw.postMessage(message)\n } else {\n _pendingMessages.push(message)\n }\n}\n\nlet _bgSyncHandler: (() => void) | null = null\n\nexport function registerBgSyncHandler(fn: () => void): void {\n _bgSyncHandler = fn\n}\n\nexport function isBgSyncSupported(): boolean {\n try {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n _registration !== null &&\n 'sync' in _registration\n )\n } catch {\n return false\n }\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as { type: string; url?: string; strategy?: string }\n if (!data?.type) return\n\n const store = useEidosStore.getState()\n const { type, url } = data\n\n if (type === 'EIDOS_BACKGROUND_SYNC') {\n _bgSyncHandler?.()\n return\n }\n\n if (!url) return\n\n switch (type) {\n case 'EIDOS_CACHE_HIT': {\n const current = store.resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n break\n }\n case 'EIDOS_CACHE_UPDATED': {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-updated',\n cachedAt: Date.now(),\n })\n break\n }\n case 'EIDOS_NETWORK_ERROR': {\n store.updateResource(url, {\n status: 'error',\n lastEvent: 'network-error',\n })\n break\n }\n }\n}\n\nexport function setOfflineSimulation(enabled: boolean): void {\n sendToWorker({ type: 'EIDOS_SIMULATE_OFFLINE', enabled })\n useEidosStore.getState().setOnline(!enabled)\n}\n\nfunction flushPendingMessages(): void {\n const sw = _registration?.active\n if (!sw) return\n for (const msg of _pendingMessages) sw.postMessage(msg)\n _pendingMessages = []\n}\n","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// ── 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 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 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 },\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// ─────────────────────────────────────────────────────────────────────────────\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","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","import { useEidosStore } from './store'\nimport { getSwRegistration } from './sw-bridge'\nimport {\n idbAddToQueue,\n idbGetPendingItems,\n idbUpdateQueueItem,\n idbRemoveFromQueue,\n idbClearQueue,\n} from './idb'\nimport type {\n ActionConfig,\n ActionHandle,\n ActionFn,\n ActionQueueItem,\n QueuedResult,\n ReplayResult,\n} from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _actionRegistry = new Map<string, ActionFn<any[], any>>()\n\nfunction uid() {\n return crypto.randomUUID()\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function action<TArgs extends any[], TReturn>(\n fn: ActionFn<TArgs, TReturn>,\n config: ActionConfig,\n): ActionHandle<TArgs, TReturn> {\n // || not ?? — fn.name can be '' (anonymous arrow fn) which ?? treats as a\n // valid value, causing all anonymous actions to share actionId ''.\n const actionId = config.name || fn.name || uid()\n\n if (import.meta.env.DEV && config.reliability === 'neverLose' && !config.name && !fn.name) {\n console.warn(\n `[eidos] action() registered with neverLose but no stable name was found (fn.name=\"${fn.name}\"). Pass config.name so queued items survive a page reload and can be replayed.`,\n )\n }\n\n // Registering here means the function is available for replay after\n // the user refreshes the page (actions are defined at module scope).\n _actionRegistry.set(actionId, fn as ActionFn<unknown[], unknown>)\n\n const wrapped = async (...args: TArgs): Promise<TReturn | QueuedResult> => {\n const { isOnline } = useEidosStore.getState()\n\n if (config.reliability === 'neverLose') {\n if (!isOnline) {\n return persistAndQueue(actionId, actionId, args, config)\n }\n // Online + neverLose: execute, queue on failure\n try {\n return await fn(...args)\n } catch {\n return persistAndQueue(actionId, actionId, args, config)\n }\n }\n\n // best-effort: execute directly, no queuing\n return fn(...args)\n }\n\n Object.defineProperty(wrapped, 'id', { value: actionId, writable: false })\n Object.defineProperty(wrapped, 'config', { value: config, writable: false })\n\n return wrapped as unknown as ActionHandle<TArgs, TReturn>\n}\n\nfunction isJsonSerializable(value: unknown): boolean {\n try {\n JSON.stringify(value)\n return true\n } catch {\n return false\n }\n}\n\nasync function persistAndQueue(\n actionId: string,\n actionName: string,\n args: unknown[],\n config: ActionConfig,\n): Promise<QueuedResult> {\n if (import.meta.env.DEV && !isJsonSerializable(args)) {\n console.warn(\n `[eidos] action \"${actionName}\" queued with non-JSON-serializable args. These args will be lost after a page reload. Use plain JSON values for neverLose actions.`,\n args,\n )\n }\n\n const id = uid()\n const item: ActionQueueItem = {\n id,\n actionId,\n actionName,\n args,\n queuedAt: Date.now(),\n retryCount: 0,\n maxRetries: config.maxRetries ?? 3,\n status: 'pending',\n }\n\n await idbAddToQueue(item)\n useEidosStore.getState().addQueueItem(item)\n\n // Register Background Sync tag so the browser can wake up open clients\n // when connectivity returns, even if the user navigated away briefly.\n // Graceful no-op when Background Sync is unsupported.\n try {\n const reg = getSwRegistration()\n if (reg && 'sync' in reg) {\n await (reg as unknown as { sync: { register(tag: string): Promise<void> } }).sync.register('eidos-queue-replay')\n }\n } catch {\n // Background Sync not available — online-event replay remains the fallback\n }\n\n return {\n queued: true,\n id,\n message: `\"${actionName}\" queued — will execute when online`,\n }\n}\n\n// Base delay 2s, doubles per retry, capped at 5 minutes, ±20% jitter\nfunction backoffMs(retryCount: number): number {\n const base = Math.min(2000 * 2 ** retryCount, 300_000)\n return base * (0.8 + Math.random() * 0.4)\n}\n\nlet _replaying = false\n\nexport async function replayQueue(): Promise<ReplayResult> {\n const store = useEidosStore.getState()\n if (!store.isOnline || _replaying) {\n return { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n }\n _replaying = true\n try {\n return await _doReplayQueue(store)\n } finally {\n _replaying = false\n }\n}\n\nasync function _doReplayQueue(store: ReturnType<typeof useEidosStore.getState>): Promise<ReplayResult> {\n\n const candidates = await idbGetPendingItems()\n const now = Date.now()\n const pending = candidates.filter(\n (item) => !item.nextRetryAt || item.nextRetryAt <= now,\n )\n\n const result: ReplayResult = { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n\n const outcomes = await Promise.allSettled(\n pending.map(async (item): Promise<'succeeded' | 'failed' | 'retrying' | 'skipped'> => {\n const fn = _actionRegistry.get(item.actionId)\n if (!fn) return 'skipped'\n\n store.updateQueueItem(item.id, { status: 'replaying' })\n await idbUpdateQueueItem(item.id, { status: 'replaying' })\n\n try {\n await fn(...(item.args as unknown[]))\n const completedAt = Date.now()\n store.updateQueueItem(item.id, { status: 'succeeded', completedAt })\n await idbUpdateQueueItem(item.id, { status: 'succeeded', completedAt })\n\n // Remove from queue after a delay so the UI can show the success state\n setTimeout(() => {\n store.removeQueueItem(item.id)\n idbRemoveFromQueue(item.id)\n }, 3000)\n return 'succeeded'\n } catch (err) {\n const retryCount = item.retryCount + 1\n if (retryCount >= item.maxRetries) {\n store.updateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n await idbUpdateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n return 'failed'\n } else {\n const nextRetryAt = Date.now() + backoffMs(retryCount)\n store.updateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n await idbUpdateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n return 'retrying'\n }\n }\n }),\n )\n\n for (const o of outcomes) {\n const outcome = o.status === 'fulfilled' ? o.value : 'failed'\n if (outcome === 'skipped') { result.skipped++ }\n else { result.attempted++; result[outcome]++ }\n }\n\n return result\n}\n\n/** Remove all items from the action queue (IDB + in-memory store). */\nexport async function clearQueue(): Promise<void> {\n await idbClearQueue()\n useEidosStore.getState().hydrateQueue([])\n}\n","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","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","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","export const VERSION = '1.0.12'\n","/**\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 pending: s.queue.filter((q) => q.status === 'pending').length,\n failed: s.queue.filter((q) => q.status === 'failed').length,\n replaying: s.queue.filter((q) => q.status === 'replaying').length,\n 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":[],"mappings":";;AAoBA,IAAI;AACJ,MAAM,iCAAiB,IAAA;AAEvB,SAAS,UAAU;AACjB,aAAW,QAAQ,CAAC,OAAO,GAAA,CAAI;AACjC;AAEA,SAAS,KAAK,SAAoD;AAChE,WAAS,EAAE,GAAG,QAAQ,GAAG,QAAQ,MAAM,EAAA;AACvC,UAAA;AACF;AAEA,SAAS;AAAA,EACP,UAAU,OAAO,cAAc,cAAc,UAAU,SAAS;AAAA,EAChE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAA;AAAA,EACX,OAAO,CAAA;AAAA,EAEP,WAAW,CAAC,aAAa,KAAK,OAAO,EAAE,WAAW;AAAA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;AAEJ;AAKO,MAAM,aAAwC,SAAS,CAAC,MAAM,CAAC;AAG/D,MAAM,aAA+C,SAAS,CAAC,MAAM,EAAE,KAAK;AAO5E,MAAM,cAIR,SAAS,CAAC,OAAO;AAAA,EACpB,UAAU,EAAE;AAAA,EACZ,UAAU,EAAE;AAAA,EACZ,SAAS,EAAE;AACb,EAAE;AAMK,MAAM,kBAKR,SAAS,CAAC,OAAO;AAAA,EACpB,SAAW,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,SAAS,EAAE;AAAA,EACzD,QAAW,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,QAAQ,EAAE;AAAA,EACxD,WAAW,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,WAAW,EAAE;AAAA,EAC3D,OAAW,EAAE,MAAM;AACrB,EAAE;AAWK,SAAS,cAAc,KAAuD;AACnF,SAAO,SAAS,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC;AACzC;AAUO,SAAS,YAAY,IAAwD;AAClF,SAAO,SAAS,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;AAC/D;"}
1
+ {"version":3,"file":"eidos.es.js","sources":["../src/store.ts","../src/sw-bridge.ts","../src/resource.ts","../src/idb.ts","../src/action.ts","../src/runtime.ts","../src/react/Provider.tsx","../src/react/hooks.ts","../src/version.ts","../src/stores.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","import { useEidosStore } from './store'\n\nlet _registration: ServiceWorkerRegistration | null = null\n// Messages sent before the SW activates are buffered here and flushed once\n// the SW is ready. Covers resource registrations, cache clears, offline\n// simulation — anything sent at module scope before EidosProvider mounts.\nlet _pendingMessages: Record<string, unknown>[] = []\n\nexport function getSwRegistration() {\n return _registration\n}\n\nexport async function registerServiceWorker(swPath: string): Promise<void> {\n if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {\n useEidosStore.getState().setSwStatus('unsupported')\n return\n }\n\n const store = useEidosStore.getState()\n store.setSwStatus('registering')\n\n try {\n _registration = await navigator.serviceWorker.register(swPath, { scope: '/' })\n\n await waitForActivation(_registration)\n\n store.setSwStatus('active')\n\n // Receive messages from SW\n navigator.serviceWorker.addEventListener('message', onSwMessage)\n\n // Track online/offline\n window.addEventListener('online', () => store.setOnline(true))\n window.addEventListener('offline', () => store.setOnline(false))\n\n flushPendingMessages()\n } catch (err) {\n store.setSwStatus('error', String(err))\n }\n}\n\nfunction waitForActivation(reg: ServiceWorkerRegistration): Promise<void> {\n return new Promise((resolve) => {\n if (reg.active) { resolve(); return }\n const sw = reg.installing ?? reg.waiting\n if (!sw) { resolve(); return }\n\n // Resolve after 10s regardless — another tab may be blocking activation\n const timer = setTimeout(resolve, 10_000)\n\n sw.addEventListener('statechange', function handler() {\n if (sw.state === 'activated') {\n clearTimeout(timer)\n sw.removeEventListener('statechange', handler)\n resolve()\n }\n })\n })\n}\n\nexport function sendToWorker(message: Record<string, unknown>): void {\n const sw = _registration?.active\n if (sw) {\n sw.postMessage(message)\n } else {\n _pendingMessages.push(message)\n }\n}\n\nlet _bgSyncHandler: (() => void) | null = null\n\nexport function registerBgSyncHandler(fn: () => void): void {\n _bgSyncHandler = fn\n}\n\nexport function isBgSyncSupported(): boolean {\n try {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n _registration !== null &&\n 'sync' in _registration\n )\n } catch {\n return false\n }\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as { type: string; url?: string; strategy?: string }\n if (!data?.type) return\n\n const store = useEidosStore.getState()\n const { type, url } = data\n\n if (type === 'EIDOS_BACKGROUND_SYNC') {\n _bgSyncHandler?.()\n return\n }\n\n if (!url) return\n\n switch (type) {\n case 'EIDOS_CACHE_HIT': {\n const current = store.resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n break\n }\n case 'EIDOS_CACHE_UPDATED': {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-updated',\n cachedAt: Date.now(),\n })\n break\n }\n case 'EIDOS_NETWORK_ERROR': {\n store.updateResource(url, {\n status: 'error',\n lastEvent: 'network-error',\n })\n break\n }\n }\n}\n\nexport function setOfflineSimulation(enabled: boolean): void {\n sendToWorker({ type: 'EIDOS_SIMULATE_OFFLINE', enabled })\n useEidosStore.getState().setOnline(!enabled)\n}\n\nfunction flushPendingMessages(): void {\n const sw = _registration?.active\n if (!sw) return\n for (const msg of _pendingMessages) sw.postMessage(msg)\n _pendingMessages = []\n}\n","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// ── 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 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 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// ─────────────────────────────────────────────────────────────────────────────\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","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","import { useEidosStore } from './store'\nimport { getSwRegistration } from './sw-bridge'\nimport {\n idbAddToQueue,\n idbGetPendingItems,\n idbUpdateQueueItem,\n idbRemoveFromQueue,\n idbClearQueue,\n} from './idb'\nimport type {\n ActionConfig,\n ActionHandle,\n ActionFn,\n ActionQueueItem,\n QueuedResult,\n ReplayResult,\n} from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _actionRegistry = new Map<string, ActionFn<any[], any>>()\n\nfunction uid() {\n return crypto.randomUUID()\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function action<TArgs extends any[], TReturn>(\n fn: ActionFn<TArgs, TReturn>,\n config: ActionConfig,\n): ActionHandle<TArgs, TReturn> {\n // || not ?? — fn.name can be '' (anonymous arrow fn) which ?? treats as a\n // valid value, causing all anonymous actions to share actionId ''.\n const actionId = config.name || fn.name || uid()\n\n if (import.meta.env.DEV && config.reliability === 'neverLose' && !config.name && !fn.name) {\n console.warn(\n `[eidos] action() registered with neverLose but no stable name was found (fn.name=\"${fn.name}\"). Pass config.name so queued items survive a page reload and can be replayed.`,\n )\n }\n\n // Registering here means the function is available for replay after\n // the user refreshes the page (actions are defined at module scope).\n _actionRegistry.set(actionId, fn as ActionFn<unknown[], unknown>)\n\n const wrapped = async (...args: TArgs): Promise<TReturn | QueuedResult> => {\n const { isOnline } = useEidosStore.getState()\n\n if (config.reliability === 'neverLose') {\n if (!isOnline) {\n return persistAndQueue(actionId, actionId, args, config)\n }\n // Online + neverLose: execute, queue on failure\n try {\n return await fn(...args)\n } catch {\n return persistAndQueue(actionId, actionId, args, config)\n }\n }\n\n // best-effort: execute directly, no queuing\n return fn(...args)\n }\n\n Object.defineProperty(wrapped, 'id', { value: actionId, writable: false })\n Object.defineProperty(wrapped, 'config', { value: config, writable: false })\n\n return wrapped as unknown as ActionHandle<TArgs, TReturn>\n}\n\nfunction isJsonSerializable(value: unknown): boolean {\n try {\n JSON.stringify(value)\n return true\n } catch {\n return false\n }\n}\n\nasync function persistAndQueue(\n actionId: string,\n actionName: string,\n args: unknown[],\n config: ActionConfig,\n): Promise<QueuedResult> {\n if (import.meta.env.DEV && !isJsonSerializable(args)) {\n console.warn(\n `[eidos] action \"${actionName}\" queued with non-JSON-serializable args. These args will be lost after a page reload. Use plain JSON values for neverLose actions.`,\n args,\n )\n }\n\n const id = uid()\n const item: ActionQueueItem = {\n id,\n actionId,\n actionName,\n args,\n queuedAt: Date.now(),\n retryCount: 0,\n maxRetries: config.maxRetries ?? 3,\n status: 'pending',\n }\n\n await idbAddToQueue(item)\n useEidosStore.getState().addQueueItem(item)\n\n // Register Background Sync tag so the browser can wake up open clients\n // when connectivity returns, even if the user navigated away briefly.\n // Graceful no-op when Background Sync is unsupported.\n try {\n const reg = getSwRegistration()\n if (reg && 'sync' in reg) {\n await (reg as unknown as { sync: { register(tag: string): Promise<void> } }).sync.register('eidos-queue-replay')\n }\n } catch {\n // Background Sync not available — online-event replay remains the fallback\n }\n\n return {\n queued: true,\n id,\n message: `\"${actionName}\" queued — will execute when online`,\n }\n}\n\n// Base delay 2s, doubles per retry, capped at 5 minutes, ±20% jitter\nfunction backoffMs(retryCount: number): number {\n const base = Math.min(2000 * 2 ** retryCount, 300_000)\n return base * (0.8 + Math.random() * 0.4)\n}\n\nlet _replaying = false\n\nexport async function replayQueue(): Promise<ReplayResult> {\n const store = useEidosStore.getState()\n if (!store.isOnline || _replaying) {\n return { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n }\n _replaying = true\n try {\n return await _doReplayQueue(store)\n } finally {\n _replaying = false\n }\n}\n\nasync function _doReplayQueue(store: ReturnType<typeof useEidosStore.getState>): Promise<ReplayResult> {\n\n const candidates = await idbGetPendingItems()\n const now = Date.now()\n const pending = candidates.filter(\n (item) => !item.nextRetryAt || item.nextRetryAt <= now,\n )\n\n const result: ReplayResult = { attempted: 0, succeeded: 0, failed: 0, retrying: 0, skipped: 0 }\n\n const outcomes = await Promise.allSettled(\n pending.map(async (item): Promise<'succeeded' | 'failed' | 'retrying' | 'skipped'> => {\n const fn = _actionRegistry.get(item.actionId)\n if (!fn) return 'skipped'\n\n store.updateQueueItem(item.id, { status: 'replaying' })\n await idbUpdateQueueItem(item.id, { status: 'replaying' })\n\n try {\n await fn(...(item.args as unknown[]))\n const completedAt = Date.now()\n store.updateQueueItem(item.id, { status: 'succeeded', completedAt })\n await idbUpdateQueueItem(item.id, { status: 'succeeded', completedAt })\n\n // Remove from queue after a delay so the UI can show the success state\n setTimeout(() => {\n store.removeQueueItem(item.id)\n idbRemoveFromQueue(item.id)\n }, 3000)\n return 'succeeded'\n } catch (err) {\n const retryCount = item.retryCount + 1\n if (retryCount >= item.maxRetries) {\n store.updateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n await idbUpdateQueueItem(item.id, { status: 'failed', error: String(err), retryCount })\n return 'failed'\n } else {\n const nextRetryAt = Date.now() + backoffMs(retryCount)\n store.updateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n await idbUpdateQueueItem(item.id, { status: 'pending', retryCount, nextRetryAt })\n return 'retrying'\n }\n }\n }),\n )\n\n for (const o of outcomes) {\n const outcome = o.status === 'fulfilled' ? o.value : 'failed'\n if (outcome === 'skipped') { result.skipped++ }\n else { result.attempted++; result[outcome]++ }\n }\n\n return result\n}\n\n/** Remove all items from the action queue (IDB + in-memory store). */\nexport async function clearQueue(): Promise<void> {\n await idbClearQueue()\n useEidosStore.getState().hydrateQueue([])\n}\n","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","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","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","export const VERSION = '1.0.12'\n","/**\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 pending: s.queue.filter((q) => q.status === 'pending').length,\n failed: s.queue.filter((q) => q.status === 'failed').length,\n replaying: s.queue.filter((q) => q.status === 'replaying').length,\n 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":[],"mappings":";;AAoBA,IAAI;AACJ,MAAM,iCAAiB,IAAA;AAEvB,SAAS,UAAU;AACjB,aAAW,QAAQ,CAAC,OAAO,GAAA,CAAI;AACjC;AAEA,SAAS,KAAK,SAAoD;AAChE,WAAS,EAAE,GAAG,QAAQ,GAAG,QAAQ,MAAM,EAAA;AACvC,UAAA;AACF;AAEA,SAAS;AAAA,EACP,UAAU,OAAO,cAAc,cAAc,UAAU,SAAS;AAAA,EAChE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAA;AAAA,EACX,OAAO,CAAA;AAAA,EAEP,WAAW,CAAC,aAAa,KAAK,OAAO,EAAE,WAAW;AAAA,EAElD,aAAa,CAAC,UAAU,YAAY,KAAK,OAAO,EAAE,UAAU,QAAA,EAAU;AAAA,EAEtE,kBAAkB,CAAC,KAAK,UACtB,KAAK,CAAC,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,CAAC,GAAG,GAAG,MAAA,IAAU;AAAA,EAE/D,gBAAgB,CAAC,KAAK,WACpB,KAAK,CAAC,OAAO;AAAA,IACX,WAAW;AAAA,MACT,GAAG,EAAE;AAAA,MACL,CAAC,GAAG,GAAG,EAAE,UAAU,GAAG,IAAI,EAAE,GAAG,EAAE,UAAU,GAAG,GAAG,GAAG,WAAW,EAAE,UAAU,GAAG;AAAA,IAAA;AAAA,EAChF,EACA;AAAA,EAEJ,oBAAoB,CAAC,QACnB,KAAK,CAAC,MAAM;AAEV,UAAM,EAAE,CAAC,GAAG,GAAG,UAAU,GAAG,KAAA,IAAS,EAAE;AACvC,WAAO,EAAE,WAAW,KAAA;AAAA,EACtB,CAAC;AAAA,EAEH,cAAc,CAAC,SAAS,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,IAAI,IAAI;AAAA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C;AACzC;AAUO,SAAS,YAAY,IAAwD;AAClF,SAAO,SAAS,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;AAC/D;"}
package/dist/index.d.ts CHANGED
@@ -160,6 +160,8 @@ export declare function isBgSyncSupported(): boolean;
160
160
 
161
161
  declare type Listener = () => void;
162
162
 
163
+ declare type QueryInvalidator = (queryKey: [string, string]) => void;
164
+
163
165
  export declare interface QueuedResult {
164
166
  readonly queued: true;
165
167
  readonly id: string;
@@ -226,6 +228,8 @@ export declare interface ResourceHandle<T = unknown> {
226
228
 
227
229
  export declare function setOfflineSimulation(enabled: boolean): void;
228
230
 
231
+ /* Excluded from this release type: setQueryInvalidator */
232
+
229
233
  declare function _subscribe(listener: Listener): () => void;
230
234
 
231
235
  /** Full Eidos store — prefer the narrower hooks below for performance. */
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const reactQuery = require("@tanstack/react-query");
4
+ const eidos = require("@sweidos/eidos");
5
+ let _globalClient = null;
6
+ function withEidosQueryClient(client) {
7
+ _globalClient = client;
8
+ eidos.setQueryInvalidator((queryKey) => {
9
+ client.invalidateQueries({ queryKey });
10
+ });
11
+ }
12
+ function useEidosQuery(handle, options) {
13
+ return reactQuery.useQuery({
14
+ networkMode: "always",
15
+ retry: false,
16
+ ...options,
17
+ ...handle.query()
18
+ });
19
+ }
20
+ function useEidosMutation(handle, options) {
21
+ let contextClient = null;
22
+ try {
23
+ contextClient = reactQuery.useQueryClient();
24
+ } catch {
25
+ }
26
+ const { invalidates, onSuccess, ...rest } = options ?? {};
27
+ return reactQuery.useMutation({
28
+ networkMode: "always",
29
+ ...rest,
30
+ mutationFn: (arg) => handle(arg),
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ onSuccess: async (...args) => {
33
+ const [data] = args;
34
+ if (invalidates == null ? void 0 : invalidates.length) {
35
+ await Promise.all(invalidates.map((h) => h.invalidate()));
36
+ if (!_globalClient && contextClient) {
37
+ invalidates.forEach((h) => {
38
+ contextClient.invalidateQueries({ queryKey: h.query().queryKey });
39
+ });
40
+ }
41
+ }
42
+ if (onSuccess) await onSuccess(...args);
43
+ }
44
+ });
45
+ }
46
+ exports.useEidosMutation = useEidosMutation;
47
+ exports.useEidosQuery = useEidosQuery;
48
+ exports.withEidosQueryClient = withEidosQueryClient;
@@ -0,0 +1,81 @@
1
+ import { UseQueryOptions, UseQueryResult, UseMutationOptions, UseMutationResult, QueryClient } from '@tanstack/react-query';
2
+ import { ResourceHandle, ActionHandle, QueuedResult } from '@sweidos/eidos';
3
+
4
+ /**
5
+ * Register a QueryClient with Eidos.
6
+ *
7
+ * Once called, `handle.invalidate()` will also call
8
+ * `queryClient.invalidateQueries({ queryKey: ['eidos', url] })`, keeping
9
+ * TanStack Query's cache in sync with Eidos's Cache Storage.
10
+ *
11
+ * Call this once, before rendering — e.g. alongside `new QueryClient()`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const queryClient = new QueryClient()
16
+ * withEidosQueryClient(queryClient)
17
+ *
18
+ * // Wrap your app as usual
19
+ * <QueryClientProvider client={queryClient}>
20
+ * <App />
21
+ * </QueryClientProvider>
22
+ * ```
23
+ */
24
+ export declare function withEidosQueryClient(client: QueryClient): void;
25
+ type EidosQueryOptions<T> = Omit<UseQueryOptions<T, Error, T, [string, string]>, 'queryKey' | 'queryFn'>;
26
+ /**
27
+ * Wraps `useQuery` with Eidos-smart defaults.
28
+ *
29
+ * Key differences from plain `useQuery`:
30
+ * - `networkMode: 'always'` — Eidos owns offline logic; queries run even when
31
+ * `navigator.onLine` is false (the SW cache or IndexedDB serves the data).
32
+ * - `retry: false` — Eidos handles retries at the SW / replay layer; TQ
33
+ * retrying on top would double-fire and fight Eidos's backoff.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * const products = resource('/api/products', { offline: true })
38
+ *
39
+ * // Automatically typed as UseQueryResult<Product[]>
40
+ * const { data, isPending, isError } = useEidosQuery<Product[]>(products)
41
+ *
42
+ * // Override any TQ option
43
+ * const { data } = useEidosQuery(products, { staleTime: 30_000 })
44
+ * ```
45
+ */
46
+ export declare function useEidosQuery<T>(handle: ResourceHandle<T>, options?: EidosQueryOptions<T>): UseQueryResult<T, Error>;
47
+ type AnyResourceHandle = ResourceHandle<any>;
48
+ export interface EidosMutationOptions<TArg, TData> extends Omit<UseMutationOptions<TData | QueuedResult, Error, TArg>, 'mutationFn' | 'networkMode'> {
49
+ /**
50
+ * Resource handles to invalidate (Cache Storage + TanStack Query) after
51
+ * every successful mutation — including offline-queued ones.
52
+ */
53
+ invalidates?: AnyResourceHandle[];
54
+ }
55
+ /**
56
+ * Wraps `useMutation` for a single-argument Eidos action handle.
57
+ *
58
+ * Key differences from plain `useMutation`:
59
+ * - `networkMode: 'always'` — action executes (or queues) even when offline.
60
+ * - `invalidates` — shorthand to clear resource caches on success. Triggers
61
+ * both Eidos Cache Storage and TanStack Query invalidation (requires
62
+ * `withEidosQueryClient` for the TQ half).
63
+ * - Return type is `TData | QueuedResult`. Narrow with `'queued' in data` to
64
+ * detect the offline-queued case.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const mutation = useEidosMutation(createOrder, {
69
+ * invalidates: [products],
70
+ * onSuccess(data) {
71
+ * if ('queued' in data) toast('Saved offline — will sync when back online')
72
+ * else toast(`Order #${data.id} created!`)
73
+ * },
74
+ * })
75
+ *
76
+ * // Trigger
77
+ * mutation.mutate({ productId: 1, qty: 2 })
78
+ * ```
79
+ */
80
+ export declare function useEidosMutation<TArg, TData>(handle: ActionHandle<[TArg], TData>, options?: EidosMutationOptions<TArg, TData>): UseMutationResult<TData | QueuedResult, Error, TArg>;
81
+ export {};
package/dist/query.js ADDED
@@ -0,0 +1,48 @@
1
+ import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
2
+ import { setQueryInvalidator } from "@sweidos/eidos";
3
+ let _globalClient = null;
4
+ function withEidosQueryClient(client) {
5
+ _globalClient = client;
6
+ setQueryInvalidator((queryKey) => {
7
+ client.invalidateQueries({ queryKey });
8
+ });
9
+ }
10
+ function useEidosQuery(handle, options) {
11
+ return useQuery({
12
+ networkMode: "always",
13
+ retry: false,
14
+ ...options,
15
+ ...handle.query()
16
+ });
17
+ }
18
+ function useEidosMutation(handle, options) {
19
+ let contextClient = null;
20
+ try {
21
+ contextClient = useQueryClient();
22
+ } catch {
23
+ }
24
+ const { invalidates, onSuccess, ...rest } = options ?? {};
25
+ return useMutation({
26
+ networkMode: "always",
27
+ ...rest,
28
+ mutationFn: (arg) => handle(arg),
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ onSuccess: async (...args) => {
31
+ const [data] = args;
32
+ if (invalidates == null ? void 0 : invalidates.length) {
33
+ await Promise.all(invalidates.map((h) => h.invalidate()));
34
+ if (!_globalClient && contextClient) {
35
+ invalidates.forEach((h) => {
36
+ contextClient.invalidateQueries({ queryKey: h.query().queryKey });
37
+ });
38
+ }
39
+ }
40
+ if (onSuccess) await onSuccess(...args);
41
+ }
42
+ });
43
+ }
44
+ export {
45
+ useEidosMutation,
46
+ useEidosQuery,
47
+ withEidosQueryClient
48
+ };
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ function eidos(options) {
6
+ const swDest = (options == null ? void 0 : options.swDest) ?? "public/eidos-sw.js";
7
+ function copySW(root) {
8
+ const src = path.resolve(root, "node_modules/@sweidos/eidos/dist/eidos-sw.js");
9
+ if (!fs.existsSync(src)) {
10
+ console.warn(
11
+ "[eidos-vite] Could not locate eidos-sw.js in node_modules. Make sure @sweidos/eidos is installed."
12
+ );
13
+ return;
14
+ }
15
+ const dest = path.resolve(root, swDest);
16
+ const destDir = path.dirname(dest);
17
+ if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
18
+ fs.copyFileSync(src, dest);
19
+ console.log(`[eidos-vite] eidos-sw.js → ${swDest} ✓`);
20
+ }
21
+ return {
22
+ name: "eidos",
23
+ buildStart() {
24
+ copySW(process.cwd());
25
+ },
26
+ configureServer(server) {
27
+ copySW(server.config.root);
28
+ }
29
+ };
30
+ }
31
+ exports.eidos = eidos;
package/dist/vite.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ export interface EidosPluginOptions {
4
+ /**
5
+ * Destination path for the service worker, relative to the project root.
6
+ * @default 'public/eidos-sw.js'
7
+ */
8
+ swDest?: string;
9
+ }
10
+ /**
11
+ * Vite plugin for Eidos.
12
+ *
13
+ * Automatically copies `eidos-sw.js` from the installed package into your
14
+ * `public/` directory on every build and dev-server start, so the service
15
+ * worker is always in sync with the installed package version.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * // vite.config.ts
20
+ * import { eidos } from '@sweidos/eidos/vite'
21
+ * import { defineConfig } from 'vite'
22
+ *
23
+ * export default defineConfig({
24
+ * plugins: [eidos()],
25
+ * })
26
+ * ```
27
+ */
28
+ export declare function eidos(options?: EidosPluginOptions): Plugin;
package/dist/vite.js ADDED
@@ -0,0 +1,31 @@
1
+ import { existsSync, mkdirSync, copyFileSync } from "fs";
2
+ import { resolve, dirname } from "path";
3
+ function eidos(options) {
4
+ const swDest = (options == null ? void 0 : options.swDest) ?? "public/eidos-sw.js";
5
+ function copySW(root) {
6
+ const src = resolve(root, "node_modules/@sweidos/eidos/dist/eidos-sw.js");
7
+ if (!existsSync(src)) {
8
+ console.warn(
9
+ "[eidos-vite] Could not locate eidos-sw.js in node_modules. Make sure @sweidos/eidos is installed."
10
+ );
11
+ return;
12
+ }
13
+ const dest = resolve(root, swDest);
14
+ const destDir = dirname(dest);
15
+ if (!existsSync(destDir)) mkdirSync(destDir, { recursive: true });
16
+ copyFileSync(src, dest);
17
+ console.log(`[eidos-vite] eidos-sw.js → ${swDest} ✓`);
18
+ }
19
+ return {
20
+ name: "eidos",
21
+ buildStart() {
22
+ copySW(process.cwd());
23
+ },
24
+ configureServer(server) {
25
+ copySW(server.config.root);
26
+ }
27
+ };
28
+ }
29
+ export {
30
+ eidos
31
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sweidos/eidos",
3
- "version": "1.0.17",
3
+ "version": "1.0.19",
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",
@@ -33,6 +33,16 @@
33
33
  },
34
34
  "./sw": {
35
35
  "default": "./dist/eidos-sw.js"
36
+ },
37
+ "./vite": {
38
+ "import": "./dist/vite.js",
39
+ "require": "./dist/vite.cjs.js",
40
+ "types": "./dist/vite.d.ts"
41
+ },
42
+ "./query": {
43
+ "import": "./dist/query.js",
44
+ "require": "./dist/query.cjs.js",
45
+ "types": "./dist/query.d.ts"
36
46
  }
37
47
  },
38
48
  "files": [
@@ -40,11 +50,21 @@
40
50
  "README.md"
41
51
  ],
42
52
  "peerDependencies": {
53
+ "@tanstack/react-query": ">=5.0.0",
43
54
  "react": ">=18.0.0",
44
- "react-dom": ">=18.0.0"
55
+ "react-dom": ">=18.0.0",
56
+ "vite": ">=4.0.0"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "vite": {
60
+ "optional": true
61
+ },
62
+ "@tanstack/react-query": {
63
+ "optional": true
64
+ }
45
65
  },
46
- "dependencies": {},
47
66
  "devDependencies": {
67
+ "@tanstack/react-query": "^5.45.0",
48
68
  "@types/react": "^18.3.3",
49
69
  "@types/react-dom": "^18.3.0",
50
70
  "@vitejs/plugin-react": "^4.3.1",
@@ -57,7 +77,7 @@
57
77
  "vitest": "^2.1.9"
58
78
  },
59
79
  "scripts": {
60
- "build": "vite build && node scripts/copy-sw.mjs",
80
+ "build": "vite build && vite build --config vite.plugin.config.ts && vite build --config vite.query.config.ts && node scripts/copy-sw.mjs",
61
81
  "dev": "vite build --watch",
62
82
  "type-check": "tsc --noEmit",
63
83
  "test": "vitest run",