@capybara-devtools/core 0.2.1 → 0.3.1

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.
Files changed (52) hide show
  1. package/README.md +2 -2
  2. package/dist/client.d.ts +3 -2
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +9 -4
  5. package/dist/client.js.map +1 -1
  6. package/dist/index.d.ts +12 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +6 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/plugins/state/context.d.ts +102 -0
  11. package/dist/plugins/state/context.d.ts.map +1 -0
  12. package/dist/plugins/state/context.js +765 -0
  13. package/dist/plugins/state/context.js.map +1 -0
  14. package/dist/plugins/state/engine.d.ts +71 -0
  15. package/dist/plugins/state/engine.d.ts.map +1 -0
  16. package/dist/plugins/state/engine.js +710 -0
  17. package/dist/plugins/state/engine.js.map +1 -0
  18. package/dist/plugins/state/index.d.ts +59 -0
  19. package/dist/plugins/state/index.d.ts.map +1 -0
  20. package/dist/plugins/state/index.js +52 -0
  21. package/dist/plugins/state/index.js.map +1 -0
  22. package/dist/plugins/state/redux.d.ts +43 -0
  23. package/dist/plugins/state/redux.d.ts.map +1 -0
  24. package/dist/plugins/state/redux.js +580 -0
  25. package/dist/plugins/state/redux.js.map +1 -0
  26. package/dist/plugins/state/registry.d.ts +22 -0
  27. package/dist/plugins/state/registry.d.ts.map +1 -0
  28. package/dist/plugins/state/registry.js +109 -0
  29. package/dist/plugins/state/registry.js.map +1 -0
  30. package/dist/plugins/state/swr.d.ts +49 -0
  31. package/dist/plugins/state/swr.d.ts.map +1 -0
  32. package/dist/plugins/state/swr.js +359 -0
  33. package/dist/plugins/state/swr.js.map +1 -0
  34. package/dist/plugins/state/tanstack.d.ts +31 -0
  35. package/dist/plugins/state/tanstack.d.ts.map +1 -0
  36. package/dist/plugins/state/tanstack.js +461 -0
  37. package/dist/plugins/state/tanstack.js.map +1 -0
  38. package/dist/plugins/state/zustand.d.ts +21 -0
  39. package/dist/plugins/state/zustand.d.ts.map +1 -0
  40. package/dist/plugins/state/zustand.js +70 -0
  41. package/dist/plugins/state/zustand.js.map +1 -0
  42. package/package.json +11 -2
  43. package/src/client.ts +12 -6
  44. package/src/index.ts +19 -0
  45. package/src/plugins/state/context.ts +831 -0
  46. package/src/plugins/state/engine.ts +739 -0
  47. package/src/plugins/state/index.ts +112 -0
  48. package/src/plugins/state/redux.ts +609 -0
  49. package/src/plugins/state/registry.ts +126 -0
  50. package/src/plugins/state/swr.ts +375 -0
  51. package/src/plugins/state/tanstack.ts +488 -0
  52. package/src/plugins/state/zustand.ts +82 -0
@@ -0,0 +1,126 @@
1
+ import type { StateEngine } from './engine.js';
2
+ import type { StoreDriver } from './index.js';
3
+
4
+ /**
5
+ * Where registered stores live. On `globalThis` so adapters can run before or after `init()`, and stores
6
+ * outlive hot reloads, a client stopped and started again, and a second copy of the SDK in the bundle.
7
+ * The name carries the version of the shape: changing the shape means a new name.
8
+ */
9
+ export const REGISTRY_GLOBAL = '__CAPYBARA_STATE_V1__';
10
+ /** Hot reload re-creates a store under the same label; the older instances make way. */
11
+ const MAX_INSTANCES = 3;
12
+ const MAX_STORES = 100;
13
+
14
+ /** What the registry calls on the running client's engine. Shared through the global, so its shape is fixed. */
15
+ export type RegistrySink = Pick<StateEngine, 'track' | 'untrack'>;
16
+
17
+ interface Slot {
18
+ info: StoreDriver['info'];
19
+ driver: { deref(): StoreDriver | undefined };
20
+ }
21
+
22
+ interface Registry {
23
+ version: 1;
24
+ /** Registered stores by id, oldest first. */
25
+ stores: Map<string, Slot>;
26
+ /** Id of each registered target (or driver, when there is no target), so registering again returns it. */
27
+ ids: WeakMap<object, string>;
28
+ /** Keeps each driver alive exactly as long as its target. */
29
+ keep: WeakMap<object, StoreDriver>;
30
+ /** Last number given out per library, for ids such as "redux:2". */
31
+ counts: Record<string, number>;
32
+ sink: RegistrySink | null;
33
+ }
34
+
35
+ function registry(): Registry {
36
+ const scope = globalThis as Record<string, unknown>;
37
+ let reg = scope[REGISTRY_GLOBAL] as Registry | undefined;
38
+ if (!reg) {
39
+ reg = { version: 1, stores: new Map(), ids: new WeakMap(), keep: new WeakMap(), counts: {}, sink: null };
40
+ scope[REGISTRY_GLOBAL] = reg;
41
+ }
42
+ return reg;
43
+ }
44
+
45
+ /**
46
+ * Adds a store and returns its id, e.g. "zustand:2"; undefined where there is no `window` (server
47
+ * rendering, Node). Pass the store, client or cache the driver reads as `target`: registering the same
48
+ * target again then returns the same id, and the driver is held only as long as the target lives.
49
+ * Without a target the driver is held until it is unregistered or pushed out by the caps.
50
+ */
51
+ export function register(driver: StoreDriver, target?: object): string | undefined {
52
+ if (typeof window === 'undefined') return undefined;
53
+ let id: string;
54
+ try {
55
+ const reg = registry();
56
+ const key = target ?? driver;
57
+ const known = reg.ids.get(key);
58
+ if (known !== undefined && reg.stores.has(known)) return known;
59
+ sweep(reg);
60
+ const { library, label } = driver.info;
61
+ const twins = [...reg.stores].filter(([, slot]) => slot.info.library === library && slot.info.label === label);
62
+ for (const [old] of twins.slice(0, Math.max(0, twins.length - (MAX_INSTANCES - 1)))) dispose(reg, old);
63
+ while (reg.stores.size >= MAX_STORES) {
64
+ dispose(reg, reg.stores.keys().next().value!, `Dropped to stay under ${MAX_STORES} stores`);
65
+ }
66
+ const n = (reg.counts[library] ?? 0) + 1;
67
+ reg.counts[library] = n;
68
+ id = `${library}:${n}`;
69
+ let held: Slot['driver'] = { deref: () => driver };
70
+ if (target && typeof WeakRef === 'function') {
71
+ reg.keep.set(target, driver);
72
+ held = new WeakRef(driver);
73
+ }
74
+ reg.stores.set(id, { info: driver.info, driver: held });
75
+ reg.ids.set(key, id);
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ try {
80
+ registry().sink?.track(id, driver);
81
+ } catch {
82
+ // the engine reports its own failures as a disposed store
83
+ }
84
+ return id;
85
+ }
86
+
87
+ /** Removes a store, e.g. when an adapter's untrack function runs. */
88
+ export function unregister(id: string): void {
89
+ if (typeof window === 'undefined') return;
90
+ dispose(registry(), id);
91
+ }
92
+
93
+ /** Has `sink` watch every registered store, and the ones registered later. Returns the undo. */
94
+ export function attach(sink: RegistrySink): () => void {
95
+ const reg = registry();
96
+ sweep(reg);
97
+ reg.sink = sink;
98
+ for (const [id, slot] of [...reg.stores]) {
99
+ const driver = slot.driver.deref();
100
+ if (!driver) continue;
101
+ try {
102
+ sink.track(id, driver);
103
+ } catch {
104
+ // keep attaching the rest
105
+ }
106
+ }
107
+ return () => {
108
+ if (reg.sink === sink) reg.sink = null;
109
+ };
110
+ }
111
+
112
+ // Hermes may lack FinalizationRegistry, so collected stores are found by looking, whenever stores change.
113
+ function sweep(reg: Registry): void {
114
+ for (const [id, slot] of [...reg.stores]) {
115
+ if (!slot.driver.deref()) dispose(reg, id);
116
+ }
117
+ }
118
+
119
+ function dispose(reg: Registry, id: string, note?: string): void {
120
+ if (!reg.stores.delete(id)) return;
121
+ try {
122
+ reg.sink?.untrack(id, note);
123
+ } catch {
124
+ // nothing to report then
125
+ }
126
+ }
@@ -0,0 +1,375 @@
1
+ import type { StateEntrySummary } from '@capybara-devtools/protocol';
2
+ import { errorMessage } from '../../utils.js';
3
+ import type { StoreDriver } from './index.js';
4
+ import { register, unregister } from './registry.js';
5
+
6
+ /** What Capybara uses of an SWR cache. SWR's `Cache` and a `Map` both fit. */
7
+ export interface SWRCacheLike {
8
+ keys(): IterableIterator<string>;
9
+ get(key: string): any;
10
+ set(key: string, value: any): void;
11
+ delete(key: string): void;
12
+ }
13
+
14
+ /** A cache and the `mutate` bound to it, as `useSWRConfig()` and `SWRConfig.defaultValue` hold them. */
15
+ export interface SWRHandle {
16
+ cache: SWRCacheLike;
17
+ /** Runs the revalidate, clear and reset commands. */
18
+ mutate?: (...args: any[]) => unknown;
19
+ unload?: unknown;
20
+ }
21
+
22
+ export interface WatchSWROptions {
23
+ /** Names the cache in the State tab. Defaults to "default" for SWR's own cache, else "cache #1", "cache #2"… */
24
+ name?: string;
25
+ }
26
+
27
+ /** SWR's hook, as a middleware receives it. */
28
+ type SWRHookLike = (key: any, fetcher: any, config: any) => any;
29
+
30
+ interface Watch {
31
+ mutate?: (...args: any[]) => unknown;
32
+ untrack: () => void;
33
+ }
34
+
35
+ /** Keys listed per cache. SWR never evicts, so a long session can hold many more. */
36
+ const MAX_KEYS = 1_000;
37
+ /** How long a revalidate waits for its fetch before answering anyway; the UI gives up on a command after 15 s. */
38
+ const REVALIDATE_WAIT = 10_000;
39
+ const NO_HOOK = 'No mounted hook fetches this key, so nothing was revalidated';
40
+ const NO_MUTATE = 'Capybara has no mutate() for this cache yet: add swrMiddleware to the SWRConfig that creates it';
41
+
42
+ /** Caches already registered, so the middleware, which runs on every render, only looks one up. */
43
+ const watched = new WeakMap<object, Watch>();
44
+ let unnamed = 0;
45
+ const noop = () => {};
46
+
47
+ /**
48
+ * Shows an SWR cache in the State tab. Pass `SWRConfig` for SWR's default cache, the result of
49
+ * `useSWRConfig()`, or `{ cache, mutate }`. Watching a cache again only fills in a `mutate` it lacked.
50
+ * Returns a function that stops showing it. Does nothing where there is no `window` (server rendering).
51
+ */
52
+ export function watchSWR(target: SWRHandle | { defaultValue: SWRHandle }, options: WatchSWROptions = {}): () => void {
53
+ if (typeof window === 'undefined') return noop;
54
+ try {
55
+ const defaults = (target as { defaultValue?: SWRHandle }).defaultValue;
56
+ const handle = (defaults ?? target) as SWRHandle;
57
+ const cache = handle.cache;
58
+ if (!isCache(cache)) return noop;
59
+ const mutate = typeof handle.mutate === 'function' ? handle.mutate : undefined;
60
+ const known = watched.get(cache);
61
+ if (known) {
62
+ known.mutate ??= mutate;
63
+ return known.untrack;
64
+ }
65
+ const watch: Watch = { mutate, untrack: noop };
66
+ const label = options.name ?? (defaults ? 'default' : `cache #${++unnamed}`);
67
+ const id = register(swrDriver(cache, label, watch), cache);
68
+ if (id === undefined) return noop;
69
+ watch.untrack = () => {
70
+ if (watched.get(cache) === watch) watched.delete(cache);
71
+ unregister(id);
72
+ };
73
+ watched.set(cache, watch);
74
+ return watch.untrack;
75
+ } catch {
76
+ return noop;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Watches the cache of each hook rendered under it: `<SWRConfig value={{ use: [swrMiddleware] }}>`.
82
+ * For an SWRConfig with its own `provider`, as React Native apps have; it also hands over the `mutate`
83
+ * that commands need, which `swrProvider` cannot reach.
84
+ */
85
+ export function swrMiddleware(useSWRNext: SWRHookLike): SWRHookLike {
86
+ return (key, fetcher, config) => {
87
+ if (config) watchSWR(config);
88
+ return useSWRNext(key, fetcher, config);
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Watches the cache an SWRConfig `provider` makes: `provider: swrProvider(() => new Map())`. Without
94
+ * `inner`, watches the parent cache. SWR creates the cache's `mutate` only after the provider returns,
95
+ * so add `swrMiddleware` too for the revalidate, clear and reset commands.
96
+ */
97
+ export function swrProvider(
98
+ inner?: (parent: SWRCacheLike) => SWRCacheLike,
99
+ options?: WatchSWROptions,
100
+ ): (parent: SWRCacheLike) => SWRCacheLike {
101
+ return (parent) => {
102
+ const cache = inner ? inner(parent) : parent;
103
+ // SWR keys its state for a cache by the object itself, so a wrapper would split the hooks from `mutate`.
104
+ watchSWR({ cache }, options);
105
+ return cache;
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Describes an SWR cache entry without its data. Self-contained: the Metro bridge runs it from its source
111
+ * inside apps without the SDK, so it uses nothing from module scope. `updatedAt` is when the entry's
112
+ * data or error was last seen changing. Entries with only SWR's internal fields give undefined.
113
+ */
114
+ export function summarizeSWREntry(key: string, entry: unknown, updatedAt?: number): StateEntrySummary | undefined {
115
+ if (entry === null || typeof entry !== 'object') return undefined;
116
+ const state = entry as { data?: unknown; error?: unknown; isValidating?: unknown; isLoading?: unknown; _k?: unknown };
117
+ // `useSWRMutation` leaves `{ _c: undefined }` behind, and a hook that has not fetched only `{ _k }`.
118
+ if (!('data' in state || 'error' in state || 'isValidating' in state || 'isLoading' in state)) return undefined;
119
+
120
+ const cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
121
+ // The shape alone, never a value: the MCP server hands previews to AI assistants as they are.
122
+ const preview = (value: unknown): string => {
123
+ if (value === null) return 'null';
124
+ if (typeof value === 'string') return `string(${value.length})`;
125
+ if (typeof value !== 'object') return typeof value;
126
+ if (Array.isArray(value)) return `Array(${value.length})`;
127
+ const tag = Object.prototype.toString.call(value).slice(8, -1);
128
+ if (tag === 'Map' || tag === 'Set') return `${tag}(${(value as { size: number }).size})`;
129
+ if (tag === 'Date') return 'Date';
130
+ // Only names that look like fields: an object keyed by ids, emails or tokens would show those.
131
+ const fields: string[] = [];
132
+ let more = false;
133
+ let checked = 0;
134
+ for (const name in value) {
135
+ if (!Object.prototype.hasOwnProperty.call(value, name)) continue;
136
+ if (fields.length === 3 || ++checked > 10) {
137
+ more = true;
138
+ break;
139
+ }
140
+ if (name.length <= 24 && /^[A-Za-z_$]+\d*$/.test(name)) fields.push(name);
141
+ else more = true;
142
+ }
143
+ const shape = `{${fields.join(', ')}${more ? (fields.length > 0 ? ', …' : '…') : ''}}`;
144
+ const proto = Object.getPrototypeOf(value);
145
+ const type = proto && proto !== Object.prototype && typeof proto.constructor === 'function' && proto.constructor.name;
146
+ return type ? `${type} ${shape}` : shape;
147
+ };
148
+ const describeError = (error: unknown): string => {
149
+ if (typeof error === 'string') return error;
150
+ const { name, message, status } = (error !== null && typeof error === 'object' ? error : {}) as {
151
+ name?: unknown;
152
+ message?: unknown;
153
+ status?: unknown;
154
+ };
155
+ const title = typeof name === 'string' && name ? name : 'Error';
156
+ // Anything thrown that is not an error is described like data.
157
+ let text = typeof message !== 'string' ? preview(error) : message ? `${title}: ${message}` : title;
158
+ // SWR's docs put the HTTP status on the error, and the State tab shows a status it finds as "error 404".
159
+ if (typeof status === 'number' && !text.includes(String(status))) text += ` (status ${status})`;
160
+ return text;
161
+ };
162
+
163
+ const prefix = key.startsWith('$inf$') ? '$inf$' : key.startsWith('$sub$') ? '$sub$' : '';
164
+ const kind: StateEntrySummary['kind'] = prefix === '$inf$' ? 'swr-infinite' : prefix ? 'swr-subscription' : 'swr';
165
+ let label = key.slice(prefix.length);
166
+ // A key that is not a string is stored hashed, e.g. `@"/api/user",1,`; `_k` keeps the hook's arguments.
167
+ if (state._k !== null && typeof state._k === 'object') {
168
+ try {
169
+ label = JSON.stringify(state._k, (_, value) => (typeof value === 'bigint' ? `${value}n` : value)) ?? label;
170
+ } catch {
171
+ // cyclic arguments: the hashed key will do
172
+ }
173
+ }
174
+ const { data, error } = state;
175
+ const fetching = state.isValidating === true;
176
+ const loading = fetching || state.isLoading === true;
177
+ const status: StateEntrySummary['status'] =
178
+ error !== undefined ? 'error' : data !== undefined ? 'success' : loading ? 'pending' : 'idle';
179
+ const summary: StateEntrySummary = { key, label: cut(label, 1_000), kind, status, fetching };
180
+ if (updatedAt !== undefined) summary.updatedAt = updatedAt;
181
+ if (error !== undefined) summary.error = cut(describeError(error), 500);
182
+ if (data !== undefined) summary.preview = preview(data);
183
+ return summary;
184
+ }
185
+
186
+ // The registry holds this driver only as long as the cache lives, so the driver can hold the cache.
187
+ function swrDriver(cache: SWRCacheLike, label: string, watch: Watch): StoreDriver {
188
+ interface Mark {
189
+ data: unknown;
190
+ error: unknown;
191
+ /** When `data` or `error` last changed. */
192
+ at: number;
193
+ }
194
+ /** The last write seen per key, least recent first. */
195
+ const marks = new Map<string, Mark>();
196
+ let report: ((key: unknown, value: unknown, removal: boolean) => void) | null = null;
197
+ let probe: { key: string; hit: boolean } | null = null;
198
+ /** Undo of each method patched; kept while another patch sits on top of ours, which then only passes calls on. */
199
+ const restores: Partial<Record<'set' | 'delete', () => boolean>> = {};
200
+
201
+ const read = (key: string): unknown => {
202
+ try {
203
+ return cache.get(key);
204
+ } catch {
205
+ return undefined;
206
+ }
207
+ };
208
+ // Same rule as summarizeSWREntry, without building a summary for every key in the cache.
209
+ const listed = (entry: unknown): boolean =>
210
+ entry !== null &&
211
+ typeof entry === 'object' &&
212
+ ('data' in entry || 'error' in entry || 'isValidating' in entry || 'isLoading' in entry);
213
+
214
+ const keys = (): string[] => {
215
+ const shown: string[] = [];
216
+ try {
217
+ for (const key of cache.keys()) {
218
+ if (typeof key === 'string' && listed(read(key))) shown.push(key);
219
+ }
220
+ } catch {
221
+ // list what was read before the cache failed
222
+ }
223
+ if (shown.length <= MAX_KEYS) return shown;
224
+ // The keys written to most recently, then the newest others; in cache order, so rows keep their place.
225
+ const present = new Set(shown);
226
+ const picked = new Set<string>();
227
+ const recent = [...marks.keys()];
228
+ for (let i = recent.length - 1; i >= 0 && picked.size < MAX_KEYS; i--) {
229
+ if (present.has(recent[i]!)) picked.add(recent[i]!);
230
+ }
231
+ for (let i = shown.length - 1; i >= 0 && picked.size < MAX_KEYS; i--) picked.add(shown[i]!);
232
+ return shown.filter((key) => picked.has(key));
233
+ };
234
+
235
+ const wrap = (name: 'set' | 'delete') => {
236
+ if (restores[name]) return;
237
+ const target = cache as unknown as Record<string, unknown>;
238
+ const own = Object.getOwnPropertyDescriptor(target, name);
239
+ const original = own && 'value' in own ? own.value : target[name];
240
+ if (typeof original !== 'function') throw new Error(`The cache has no ${name}()`);
241
+ const removal = name === 'delete';
242
+ // SWR writes during render too (Suspense, providers): the write goes first, and the rest is O(1) and never throws.
243
+ const wrapper = function (this: unknown, key: unknown, value: unknown) {
244
+ const result = (original as (...args: unknown[]) => unknown).apply(this, arguments as unknown as unknown[]);
245
+ if (report) {
246
+ try {
247
+ report(key, value, removal);
248
+ } catch {
249
+ // never break the app's cache
250
+ }
251
+ }
252
+ return result;
253
+ };
254
+ const ours = () => Object.getOwnPropertyDescriptor(target, name)?.value === wrapper;
255
+ Object.defineProperty(target, name, { value: wrapper, configurable: true, writable: true, enumerable: own?.enumerable ?? false });
256
+ // A proxy can accept the definition and keep the old method.
257
+ if (!ours()) throw new Error(`Could not patch the cache's ${name}()`);
258
+ restores[name] = () => {
259
+ if (!ours()) return false;
260
+ if (own) Object.defineProperty(target, name, own);
261
+ else delete target[name];
262
+ return true;
263
+ };
264
+ };
265
+ const unpatch = () => {
266
+ for (const name of ['set', 'delete'] as const) {
267
+ try {
268
+ if (restores[name]?.()) delete restores[name];
269
+ } catch {
270
+ // left in place, passing calls on
271
+ }
272
+ }
273
+ };
274
+
275
+ const start: StoreDriver['start'] = (sink, id) => {
276
+ report = (key, value, removal) => {
277
+ if (typeof key !== 'string') return;
278
+ if (removal) {
279
+ marks.delete(key);
280
+ sink.removed(id, key);
281
+ return;
282
+ }
283
+ const state = (value !== null && typeof value === 'object' ? value : {}) as { data?: unknown; error?: unknown; isValidating?: unknown };
284
+ const { data, error } = state;
285
+ if (probe && probe.key === key && state.isValidating === true) probe.hit = true;
286
+ let mark = marks.get(key);
287
+ if (mark) marks.delete(key);
288
+ if (!mark || mark.data !== data || mark.error !== error) mark = { data, error, at: Date.now() };
289
+ marks.set(key, mark);
290
+ sink.dirty(id, key);
291
+ };
292
+ try {
293
+ wrap('set');
294
+ wrap('delete');
295
+ } catch (error) {
296
+ report = null;
297
+ unpatch();
298
+ throw error;
299
+ }
300
+ return () => {
301
+ report = null;
302
+ marks.clear();
303
+ unpatch();
304
+ };
305
+ };
306
+
307
+ const act: StoreDriver['act'] = async (key, op) => {
308
+ const mutate = watch.mutate;
309
+ if (!mutate) return { done: false, note: NO_MUTATE };
310
+ try {
311
+ if (op === 'clear') {
312
+ await mutate(key, undefined, { revalidate: false });
313
+ return { done: true };
314
+ }
315
+ if (op !== 'revalidate' && op !== 'reset') return { done: false, note: `SWR has no "${op}"` };
316
+ // A mounted hook revalidates within the call, and its first write sets `isValidating`.
317
+ const call = { key, hit: false };
318
+ probe = call;
319
+ let pending: unknown;
320
+ try {
321
+ pending = op === 'revalidate' ? mutate(key) : mutate(key, undefined);
322
+ } finally {
323
+ probe = null;
324
+ }
325
+ if (op === 'reset') {
326
+ await pending;
327
+ return call.hit ? { done: true } : { done: true, note: 'Cleared; no mounted hook fetched it again' };
328
+ }
329
+ if (!call.hit) {
330
+ Promise.resolve(pending).catch(noop);
331
+ return { done: false, note: NO_HOOK };
332
+ }
333
+ await settle(pending, REVALIDATE_WAIT);
334
+ return { done: true };
335
+ } catch (error) {
336
+ return { done: false, note: errorMessage(error) };
337
+ }
338
+ };
339
+
340
+ return {
341
+ info: { library: 'swr', label, via: 'cache', actions: false, ops: ['revalidate', 'clear', 'reset'] },
342
+ keys,
343
+ summarize: (key) => summarizeSWREntry(key, read(key), marks.get(key)?.at),
344
+ data: (key) => {
345
+ const entry = read(key);
346
+ return entry !== null && typeof entry === 'object' ? (entry as { data?: unknown }).data : undefined;
347
+ },
348
+ act,
349
+ start,
350
+ };
351
+ }
352
+
353
+ function isCache(value: unknown): value is SWRCacheLike {
354
+ if (value === null || typeof value !== 'object') return false;
355
+ const cache = value as Record<string, unknown>;
356
+ return (
357
+ typeof cache.get === 'function' &&
358
+ typeof cache.set === 'function' &&
359
+ typeof cache.delete === 'function' &&
360
+ typeof cache.keys === 'function'
361
+ );
362
+ }
363
+
364
+ /** Resolves once `pending` settles, or after `ms`. */
365
+ function settle(pending: unknown, ms: number): Promise<void> {
366
+ return new Promise((resolve) => {
367
+ const timer = setTimeout(resolve, ms);
368
+ Promise.resolve(pending)
369
+ .catch(noop)
370
+ .then(() => {
371
+ clearTimeout(timer);
372
+ resolve();
373
+ });
374
+ });
375
+ }