@sweidos/eidos 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sw-bridge.js CHANGED
@@ -1,22 +1,22 @@
1
- import { useEidosStore as i } from "./store.js";
1
+ import { useEidosStore as a } from "./store.js";
2
2
  var s = null, o = [];
3
- function l() {
3
+ function E() {
4
4
  return s;
5
5
  }
6
- async function w(e) {
6
+ async function p(e) {
7
7
  if (typeof navigator > "u" || !("serviceWorker" in navigator)) {
8
- i.getState().setSwStatus("unsupported");
8
+ a.getState().setSwStatus("unsupported");
9
9
  return;
10
10
  }
11
- const t = i.getState();
11
+ const t = a.getState();
12
12
  t.setSwStatus("registering");
13
13
  try {
14
- s = await navigator.serviceWorker.register(e, { scope: "/" }), await f(s), t.setSwStatus("active"), navigator.serviceWorker.addEventListener("message", d), window.addEventListener("online", () => t.setOnline(!0)), window.addEventListener("offline", () => t.setOnline(!1)), S();
14
+ s = await navigator.serviceWorker.register(e, { scope: "/" }), await d(s), t.setSwStatus("active"), navigator.serviceWorker.addEventListener("message", g), window.addEventListener("online", () => t.setOnline(!0)), window.addEventListener("offline", () => t.setOnline(!1)), l();
15
15
  } catch (n) {
16
16
  t.setSwStatus("error", String(n));
17
17
  }
18
18
  }
19
- function f(e) {
19
+ function d(e) {
20
20
  return new Promise((t) => {
21
21
  if (e.active) {
22
22
  t();
@@ -27,43 +27,55 @@ function f(e) {
27
27
  t();
28
28
  return;
29
29
  }
30
- const a = setTimeout(t, 1e4);
30
+ const i = setTimeout(t, 1e4);
31
31
  n.addEventListener("statechange", function r() {
32
- n.state === "activated" && (clearTimeout(a), n.removeEventListener("statechange", r), t());
32
+ n.state === "activated" && (clearTimeout(i), n.removeEventListener("statechange", r), t());
33
33
  });
34
34
  });
35
35
  }
36
- function g(e) {
36
+ function S(e) {
37
37
  const t = s?.active;
38
38
  t ? t.postMessage(e) : o.push(e);
39
39
  }
40
- var c = null;
41
- function E(e) {
42
- c = e;
40
+ var u = null;
41
+ function w(e) {
42
+ u = e;
43
43
  }
44
- function p() {
44
+ function h() {
45
45
  try {
46
46
  return typeof navigator < "u" && "serviceWorker" in navigator && s !== null && "sync" in s;
47
47
  } catch {
48
48
  return !1;
49
49
  }
50
50
  }
51
- function d(e) {
51
+ var c = {};
52
+ function O(e) {
53
+ c = e;
54
+ }
55
+ function g(e) {
52
56
  const t = e.data;
53
57
  if (!t?.type) return;
54
- const n = i.getState(), { type: a, url: r } = t;
55
- if (a === "EIDOS_BACKGROUND_SYNC") {
56
- c?.();
58
+ const n = a.getState(), { type: i, url: r } = t;
59
+ if (i === "EIDOS_BACKGROUND_SYNC") {
60
+ u?.();
61
+ return;
62
+ }
63
+ if (i === "EIDOS_NOTIFICATION_CLICK") {
64
+ c.onNotificationClick?.(t.data);
65
+ return;
66
+ }
67
+ if (i === "EIDOS_SUBSCRIPTION_EXPIRED") {
68
+ c.onSubscriptionExpired?.(t.subscription);
57
69
  return;
58
70
  }
59
71
  if (r)
60
- switch (a) {
72
+ switch (i) {
61
73
  case "EIDOS_CACHE_HIT": {
62
- const u = n.resources[r];
74
+ const f = n.resources[r];
63
75
  n.updateResource(r, {
64
76
  status: "fresh",
65
77
  lastEvent: "cache-hit",
66
- cacheHits: (u?.cacheHits ?? 0) + 1
78
+ cacheHits: (f?.cacheHits ?? 0) + 1
67
79
  });
68
80
  break;
69
81
  }
@@ -82,13 +94,13 @@ function d(e) {
82
94
  break;
83
95
  }
84
96
  }
85
- function h(e) {
86
- g({
97
+ function _(e) {
98
+ S({
87
99
  type: "EIDOS_SIMULATE_OFFLINE",
88
100
  enabled: e
89
- }), i.getState().setOnline(!e);
101
+ }), a.getState().setOnline(!e);
90
102
  }
91
- function S() {
103
+ function l() {
92
104
  const e = s?.active;
93
105
  if (e) {
94
106
  for (const t of o) e.postMessage(t);
@@ -96,12 +108,13 @@ function S() {
96
108
  }
97
109
  }
98
110
  export {
99
- l as getSwRegistration,
100
- p as isBgSyncSupported,
101
- E as registerBgSyncHandler,
102
- w as registerServiceWorker,
103
- g as sendToWorker,
104
- h as setOfflineSimulation
111
+ E as getSwRegistration,
112
+ h as isBgSyncSupported,
113
+ w as registerBgSyncHandler,
114
+ O as registerPushCallbacks,
115
+ p as registerServiceWorker,
116
+ S as sendToWorker,
117
+ _ as setOfflineSimulation
105
118
  };
106
119
 
107
120
  //# sourceMappingURL=sw-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sw-bridge.js","names":[],"sources":["../src/sw-bridge.ts"],"sourcesContent":["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) {\n resolve();\n return;\n }\n const sw = reg.installing ?? reg.waiting;\n if (!sw) {\n resolve();\n return;\n }\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\ninterface PushHandlers {\n onNotificationClick?: (data: unknown) => void;\n onSubscriptionExpired?: (sub: PushSubscriptionJSON) => void;\n}\n\nlet _pushHandlers: PushHandlers = {};\n\nexport function registerPushCallbacks(handlers: PushHandlers): void {\n _pushHandlers = handlers;\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as {\n type: string;\n url?: string;\n strategy?: string;\n data?: unknown;\n subscription?: unknown;\n };\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 (type === 'EIDOS_NOTIFICATION_CLICK') {\n _pushHandlers.onNotificationClick?.(data.data);\n return;\n }\n\n if (type === 'EIDOS_SUBSCRIPTION_EXPIRED') {\n _pushHandlers.onSubscriptionExpired?.(data.subscription as PushSubscriptionJSON);\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\n/** Test-only: resets module-level state between test cases. */\nexport function _resetSwBridgeForTests(): void {\n _registration = null;\n _pendingMessages = [];\n _bgSyncHandler = null;\n _pushHandlers = {};\n}\n"],"mappings":"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"}
package/dist/types.js ADDED
@@ -0,0 +1,15 @@
1
+ function a(e) {
2
+ let n = 0, i = 0, s = 0;
3
+ for (const t of e) t.status === "pending" ? n++ : t.status === "failed" ? i++ : t.status === "replaying" && s++;
4
+ return {
5
+ pending: n,
6
+ failed: i,
7
+ replaying: s,
8
+ total: e.length
9
+ };
10
+ }
11
+ export {
12
+ a as countQueueByStatus
13
+ };
14
+
15
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["// ─────────────────────────────────────────────────────────────────────────────\n// Eidos Core Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type CacheStrategy = 'cache-first' | 'stale-while-revalidate' | 'network-first';\n\n// ── Resource ─────────────────────────────────────────────────────────────────\n\nexport interface ResourceConfig {\n /** Make this resource available when the device is offline. */\n offline: boolean;\n /** Override the auto-selected caching strategy. */\n strategy?: CacheStrategy;\n /** Custom cache bucket name. Defaults to 'eidos-resources-v1'. */\n cacheName?: string;\n /** Max age of cached response in milliseconds. Expired entries trigger a network fetch. */\n maxAge?: number;\n}\n\nexport interface GeneratedStrategy {\n name: string;\n swStrategy: CacheStrategy;\n cacheName: string;\n /** One-line rationale for why this strategy was chosen. */\n reasoning: string;\n /** Human-readable description of each behavioral step. */\n behavior: string[];\n /** Pseudocode showing the equivalent Workbox config. */\n equivalentCode: string;\n}\n\nexport interface ResourceEntry {\n url: string;\n config: ResourceConfig;\n strategy: GeneratedStrategy;\n status: 'idle' | 'fetching' | 'fresh' | 'stale' | 'error' | 'offline';\n cachedAt?: number;\n fetchedAt?: number;\n cacheHits: number;\n cacheMisses: number;\n lastEvent?: 'cache-hit' | 'cache-updated' | 'network-error' | 'cache-cleared';\n}\n\nexport interface ResourceHandle<T = unknown> {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n fetch: () => Promise<Response>;\n json: () => Promise<T>;\n /** Returns a TanStack Query-compatible options object. */\n query: () => { queryKey: [string, string]; queryFn: () => Promise<T> };\n prefetch: () => Promise<void>;\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same URL with different config. */\n unregister: () => void;\n}\n\n/**\n * Handle for a URL pattern (`/api/products/*`, `/api/users/:id`, `**`).\n * The SW intercepts all matching requests automatically — there is no single\n * URL to fetch/cache directly, so only cache-management methods are exposed.\n * Returned by `resourcePattern()`.\n */\nexport interface PatternResourceHandle {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n /** Clears all cache entries matching this pattern. */\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same pattern with different config. */\n unregister: () => void;\n}\n\n/** A handle returned by either `resource()` or `resourcePattern()`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyResourceHandle = ResourceHandle<any> | PatternResourceHandle;\n\n/** Summary returned by warmCache(). */\nexport interface WarmCacheResult {\n /** Resources that were prefetched successfully. */\n warmed: number;\n /** Resources whose prefetch threw (network error, offline, etc.). */\n failed: number;\n /** The raw errors, in input order, for failed handles. */\n errors: unknown[];\n}\n\n// ── Action ───────────────────────────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface ActionConfigBase<TArgs extends any[] = any[]> {\n /** Max retry attempts before marking as failed. Default: 3. */\n maxRetries?: number;\n /** Human-readable name for the action (used in devtools). */\n name?: string;\n /**\n * Prefixes the registered action id (`namespace::name`). Use to avoid\n * collisions when two actions share a name (e.g. across micro-frontends,\n * or two `createOrder` actions in different modules) — without a\n * namespace, the second registration silently overwrites the first.\n */\n namespace?: string;\n /**\n * Replay order when multiple queued actions are pending.\n * `'high'` items replay before `'normal'`, which replay before `'low'`.\n * Each tier completes fully before the next tier begins.\n * Default: `'normal'`.\n */\n priority?: 'high' | 'normal' | 'low';\n /**\n * Called immediately before the async function executes, with the same args\n * plus a trailing `ActionContext`. Use to apply an optimistic UI update (add\n * item, mark as pending, etc.) and to capture `idempotencyKey` for later\n * `handle.cancel(idempotencyKey)` calls. Called on every invocation —\n * online, offline, and during queue replay.\n */\n onOptimistic?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Called when the action permanently fails and will not be retried.\n * - `best-effort`: called on first throw.\n * - `neverLose`: called when `maxRetries` is exhausted (status → `'failed'`).\n * Use to revert the optimistic update.\n */\n onRollback?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Declarative conflict-resolution strategy used during queue replay when\n * the server responds with a 4xx status (conflict, gone, unprocessable,\n * etc.). If not provided, 4xx errors are treated identically to other\n * errors (retried until `maxRetries` is exhausted, then `onRollback` is\n * called). See `ConflictConfig`.\n */\n conflict?: ConflictConfig;\n /**\n * When `true`, each invocation gets an `AbortController` whose `signal` is\n * passed via `ActionContext.signal`. Forward it to `fetch`/etc. so\n * `handle.cancel(idempotencyKey)` can abort an in-flight call, or remove a\n * not-yet-replayed queued item.\n */\n cancellable?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ActionConfig<TArgs extends any[] = any[]> =\n | (ActionConfigBase<TArgs> & {\n /** Call directly, no persistence on failure. */\n reliability: 'best-effort';\n })\n | (ActionConfigBase<TArgs> & {\n /** Persist to IndexedDB before executing; replay on reconnect. */\n reliability: 'neverLose';\n /**\n * Required for `neverLose` — queued items must survive a page reload\n * and be matched back to this action on replay. `fn.name` is not\n * reliable (minifiers rename it, arrow functions may be anonymous).\n */\n name: string;\n });\n\n/**\n * Passed to `ConflictConfig.resolve` (for `'merge'`/`'custom'` strategies)\n * when a queued action's replay receives a 4xx response.\n */\nexport interface ConflictContext {\n /** Whatever `fn` threw — typically a `Response` or an error with `.status`. */\n error: unknown;\n /** The original arguments the action was queued with. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[];\n /** Number of replay attempts so far (0 on first replay). */\n attempt: number;\n idempotencyKey: string;\n}\n\n/**\n * Outcome of `ConflictConfig.resolve`:\n * - `'retry'`: keep the item queued, retry per normal backoff.\n * - `'skip'`: silently remove the item (no `onRollback`).\n * - `{ resolved: args }`: replace the queued args and retry immediately\n * on the next replay pass.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ConflictResolution = 'retry' | 'skip' | { resolved: any[] };\n\nexport interface ConflictConfig {\n /**\n * - `'serverWins'`: drop the queued item, keeping the server's state.\n * - `'clientWins'`: keep retrying — the client's write should eventually\n * be accepted (e.g. once the server-side conflict is cleared).\n * - `'merge'` / `'custom'`: call `resolve` to decide.\n */\n strategy: 'serverWins' | 'clientWins' | 'merge' | 'custom';\n /** Required for `'merge'` and `'custom'`. */\n resolve?: (ctx: ConflictContext) => ConflictResolution;\n}\n\n/** Bump when ActionQueueItem's shape changes. Used to migrate items persisted by older versions. */\nexport const CURRENT_QUEUE_SCHEMA_VERSION = 2;\n\nexport interface ActionQueueItem {\n /** Shape version this item was persisted with. Items from before v2 are migrated on load. */\n schemaVersion: number;\n id: string;\n /** ID of the registered action (maps to the function in the registry). */\n actionId: string;\n actionName: string;\n /**\n * Stable per-invocation key, generated once and reused across every retry/replay\n * of this item. Pass to your server as an idempotency key so retries that reach\n * the server after a dropped response don't double-execute.\n */\n idempotencyKey: string;\n args: unknown[];\n queuedAt: number;\n retryCount: number;\n maxRetries: number;\n status: 'pending' | 'replaying' | 'succeeded' | 'failed';\n /** Replay priority. High items replay before normal, normal before low. Default: 'normal'. */\n priority?: 'high' | 'normal' | 'low';\n error?: string;\n completedAt?: number;\n /** Earliest timestamp at which this item should be retried (exponential backoff). */\n nextRetryAt?: number;\n}\n\nexport interface QueuedResult {\n readonly queued: true;\n readonly id: string;\n readonly message: string;\n}\n\n/** Summary returned by replayQueue(). */\nexport interface ReplayResult {\n /** Items where the registered function was found and called. */\n attempted: number;\n /** Items that resolved successfully. */\n succeeded: number;\n /** Items that failed and have no retries remaining (status: 'failed'). */\n failed: number;\n /** Items that failed but will be retried later (nextRetryAt set). */\n retrying: number;\n /** Items whose actionId had no registered function — likely not yet imported. */\n skipped: number;\n /** Items that received a 4xx response and were dropped via `conflict: { strategy: 'serverWins' }` (or `resolve()` returning `'skip'`). */\n conflicted: number;\n /** Items removed via `handle.cancel(idempotencyKey)` before/during replay. */\n cancelled: number;\n}\n\n/**\n * Passed as an extra argument after the declared params to `neverLose` actions,\n * on every invocation (initial call, offline queue, and replay). The same\n * `idempotencyKey` is reused across all retries of one logical invocation —\n * forward it to your server (e.g. as an `Idempotency-Key` header) so a retry\n * that reaches the server after a dropped response doesn't double-execute.\n */\nexport interface ActionContext {\n idempotencyKey: string;\n /** 0 on the first attempt, incremented on each replay retry. */\n attempt: number;\n /** Set when `config.cancellable` is true. Forward to `fetch`/etc. for cancellation support. */\n signal?: AbortSignal;\n}\n\n/**\n * Every action function receives its declared args plus a trailing\n * `ActionContext` — on every invocation (online, offline, and replay).\n */\nexport type ActionFn<TArgs extends unknown[], TReturn> = (\n ...args: [...TArgs, ActionContext]\n) => Promise<TReturn>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface ActionHandle<TArgs extends any[], TReturn> {\n (...args: TArgs): Promise<TReturn | QueuedResult>;\n readonly id: string;\n readonly config: ActionConfig;\n /**\n * Cancel an invocation by its `idempotencyKey` (from `ActionContext` /\n * `onOptimistic`). Aborts the in-flight call if `cancellable: true` and\n * still running, otherwise removes a not-yet-replayed queued item.\n * Returns `true` if something was cancelled/removed.\n */\n cancel: (idempotencyKey: string) => Promise<boolean>;\n}\n\n// ── Global State ─────────────────────────────────────────────────────────────\n\nexport interface EidosState {\n isOnline: boolean;\n swStatus: 'idle' | 'registering' | 'active' | 'error' | 'unsupported';\n swError?: string;\n resources: Record<string, ResourceEntry>;\n queue: ActionQueueItem[];\n}\n\nexport interface QueueStatusCounts {\n [key: string]: number;\n pending: number;\n failed: number;\n replaying: number;\n total: number;\n}\n\n/** Single pass over the queue — avoids separate .filter() calls per status. */\nexport function countQueueByStatus(queue: ActionQueueItem[]): QueueStatusCounts {\n let pending = 0,\n failed = 0,\n replaying = 0;\n for (const q of queue) {\n if (q.status === 'pending') pending++;\n else if (q.status === 'failed') failed++;\n else if (q.status === 'replaying') replaying++;\n }\n return { pending, failed, replaying, total: queue.length };\n}\n"],"mappings":"AAgTA,SAAgB,EAAmB,GAA6C;AAC9E,MAAI,IAAU,GACZ,IAAS,GACT,IAAY;AACd,aAAW,KAAK,EACd,CAAI,EAAE,WAAW,YAAW,MACnB,EAAE,WAAW,WAAU,MACvB,EAAE,WAAW,eAAa;AAErC,SAAO;AAAA,IAAE,SAAA;AAAA,IAAS,QAAA;AAAA,IAAQ,WAAA;AAAA,IAAW,OAAO,EAAM;AAAA,EAAO;AAC3D"}
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
- var r = "1.1.0";
1
+ var r = "2.0.0";
2
2
  export {
3
3
  r as VERSION
4
4
  };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["export const VERSION = '2.0.0';\n"],"mappings":"AAAA,IAAa,IAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sweidos/eidos",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Describe intent. The runtime figures out how. An abstraction layer for offline-first web apps.",
5
5
  "author": "Aditya Raj",
6
6
  "license": "MIT",
@@ -42,6 +42,9 @@
42
42
  "main": "./dist/eidos.cjs",
43
43
  "module": "./dist/index.js",
44
44
  "types": "./dist/index.d.ts",
45
+ "bin": {
46
+ "eidos": "./dist/cli.js"
47
+ },
45
48
  "exports": {
46
49
  ".": {
47
50
  "types": "./dist/index.d.ts",
@@ -61,6 +64,11 @@
61
64
  "import": "./dist/query.js",
62
65
  "require": "./dist/query.cjs"
63
66
  },
67
+ "./push": {
68
+ "types": "./dist/push.d.ts",
69
+ "import": "./dist/push.js",
70
+ "require": "./dist/push.cjs"
71
+ },
64
72
  "./testing": {
65
73
  "types": "./dist/testing.d.ts",
66
74
  "import": "./dist/testing.js",
@@ -85,14 +93,13 @@
85
93
  },
86
94
  "files": [
87
95
  "dist",
88
- "!dist/**/*.map",
89
96
  "README.md"
90
97
  ],
91
98
  "size-limit": [
92
99
  {
93
100
  "name": "core (resource + action + store)",
94
101
  "path": "dist/index.js",
95
- "limit": "6 KB"
102
+ "limit": "7 KB"
96
103
  },
97
104
  {
98
105
  "name": "react hooks",
@@ -141,7 +148,7 @@
141
148
  "vitest": "^4.1.8"
142
149
  },
143
150
  "scripts": {
144
- "build": "vite build && vite build --config vite.cjs.config.ts && vite build --config vite.plugin.config.ts && vite build --config vite.query.config.ts && vite build --config vite.testing.config.ts && vite build --config vite.nextjs.config.ts && vite build --config vite.sveltekit.config.ts && vite build --config vite.devtools.config.ts && vite build --config vite.react-native.config.ts && node scripts/copy-sw.mjs",
151
+ "build": "vite build && vite build --config vite.cjs.config.ts && vite build --config vite.plugin.config.ts && vite build --config vite.query.config.ts && vite build --config vite.push.config.ts && vite build --config vite.testing.config.ts && vite build --config vite.nextjs.config.ts && vite build --config vite.sveltekit.config.ts && vite build --config vite.devtools.config.ts && vite build --config vite.react-native.config.ts && vite build --config vite.cli.config.ts && node scripts/copy-sw.mjs",
145
152
  "dev": "vite build --watch",
146
153
  "type-check": "tsc --noEmit",
147
154
  "test": "vitest run",