@capybara-devtools/core 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/client.d.ts +3 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +9 -4
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/plugins/state/context.d.ts +102 -0
- package/dist/plugins/state/context.d.ts.map +1 -0
- package/dist/plugins/state/context.js +765 -0
- package/dist/plugins/state/context.js.map +1 -0
- package/dist/plugins/state/engine.d.ts +71 -0
- package/dist/plugins/state/engine.d.ts.map +1 -0
- package/dist/plugins/state/engine.js +710 -0
- package/dist/plugins/state/engine.js.map +1 -0
- package/dist/plugins/state/index.d.ts +59 -0
- package/dist/plugins/state/index.d.ts.map +1 -0
- package/dist/plugins/state/index.js +52 -0
- package/dist/plugins/state/index.js.map +1 -0
- package/dist/plugins/state/redux.d.ts +43 -0
- package/dist/plugins/state/redux.d.ts.map +1 -0
- package/dist/plugins/state/redux.js +580 -0
- package/dist/plugins/state/redux.js.map +1 -0
- package/dist/plugins/state/registry.d.ts +22 -0
- package/dist/plugins/state/registry.d.ts.map +1 -0
- package/dist/plugins/state/registry.js +109 -0
- package/dist/plugins/state/registry.js.map +1 -0
- package/dist/plugins/state/swr.d.ts +49 -0
- package/dist/plugins/state/swr.d.ts.map +1 -0
- package/dist/plugins/state/swr.js +359 -0
- package/dist/plugins/state/swr.js.map +1 -0
- package/dist/plugins/state/tanstack.d.ts +31 -0
- package/dist/plugins/state/tanstack.d.ts.map +1 -0
- package/dist/plugins/state/tanstack.js +461 -0
- package/dist/plugins/state/tanstack.js.map +1 -0
- package/dist/plugins/state/zustand.d.ts +21 -0
- package/dist/plugins/state/zustand.d.ts.map +1 -0
- package/dist/plugins/state/zustand.js +70 -0
- package/dist/plugins/state/zustand.js.map +1 -0
- package/package.json +11 -2
- package/src/client.ts +12 -6
- package/src/index.ts +19 -0
- package/src/plugins/state/context.ts +831 -0
- package/src/plugins/state/engine.ts +739 -0
- package/src/plugins/state/index.ts +112 -0
- package/src/plugins/state/redux.ts +609 -0
- package/src/plugins/state/registry.ts +126 -0
- package/src/plugins/state/swr.ts +375 -0
- package/src/plugins/state/tanstack.ts +488 -0
- package/src/plugins/state/zustand.ts +82 -0
|
@@ -0,0 +1,739 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
EventPayloads,
|
|
3
|
+
SerializedValue,
|
|
4
|
+
StateChangePayload,
|
|
5
|
+
StateCommands,
|
|
6
|
+
StateDiffOp,
|
|
7
|
+
StateEntryOp,
|
|
8
|
+
StateEntrySummary,
|
|
9
|
+
StatePath,
|
|
10
|
+
StateStoreInfo,
|
|
11
|
+
} from '@capybara-devtools/protocol';
|
|
12
|
+
import type { SerializeOptions } from '../../serialize.js';
|
|
13
|
+
import type { StateSink, StoreDriver } from './index.js';
|
|
14
|
+
|
|
15
|
+
// Every function in this file is self-contained: the Metro bridge runs them from their source inside
|
|
16
|
+
// apps without the SDK, so they use nothing from module scope and get their helpers as parameters.
|
|
17
|
+
|
|
18
|
+
export type StateEventKind = 'state.store' | 'state.change' | 'state.entries';
|
|
19
|
+
/** `ts` is when the change happened; records go out in batches, later. */
|
|
20
|
+
export type StateEmit = <K extends StateEventKind>(kind: K, payload: EventPayloads[K], ts?: number) => void;
|
|
21
|
+
export type SerializeFn = (value: unknown, options?: SerializeOptions) => SerializedValue;
|
|
22
|
+
|
|
23
|
+
export interface StateEngineOptions {
|
|
24
|
+
/** Whether events reach a server now. While false, changes are only counted, then sent as one catch-up record. */
|
|
25
|
+
connected(): boolean;
|
|
26
|
+
/** Records past this many per second for one store are folded into the next one. Default 30. */
|
|
27
|
+
maxActionsPerSecond?: number;
|
|
28
|
+
/** Action types kept off the timeline; a string matches the whole type. Their changes show in the next record. */
|
|
29
|
+
actionsDenylist?: Array<string | { source: string; flags: string }>;
|
|
30
|
+
/** Runs before a state is diffed or read; only what it returns leaves the app. */
|
|
31
|
+
sanitizeState?(state: unknown, store: StateStoreInfo): unknown;
|
|
32
|
+
sanitizeAction?(action: unknown, store: StateStoreInfo): unknown;
|
|
33
|
+
/** Leave out keys that hold functions, such as Zustand actions. Default true. */
|
|
34
|
+
hideFunctions?: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface DiffLimits {
|
|
38
|
+
/** Ops kept; the rest are only counted. */
|
|
39
|
+
maxOps: number;
|
|
40
|
+
maxDepth: number;
|
|
41
|
+
/** Objects and arrays compared per call. */
|
|
42
|
+
maxNodes: number;
|
|
43
|
+
/** Profile for each op's `value` and `prev`. */
|
|
44
|
+
preview: SerializeOptions;
|
|
45
|
+
/** Count keys that hold functions as absent. */
|
|
46
|
+
hideFunctions?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface StateEngine extends StateSink {
|
|
50
|
+
/** Announces the store, takes its state as the base for the first diff, and starts its driver. */
|
|
51
|
+
track(id: string, driver: StoreDriver): void;
|
|
52
|
+
/** Stops the store's driver and announces it disposed. */
|
|
53
|
+
untrack(id: string, note?: string): void;
|
|
54
|
+
stores(): StateStoreInfo[];
|
|
55
|
+
read(id: string, path?: StatePath): StateCommands['get']['result'];
|
|
56
|
+
entries(id: string): StateCommands['entries']['result'];
|
|
57
|
+
entry(id: string, key: string, path?: StatePath): StateCommands['entry']['result'];
|
|
58
|
+
act(id: string, key: string, op: StateEntryOp): Promise<StateCommands['act']['result']>;
|
|
59
|
+
/** Stops every driver and the timer. */
|
|
60
|
+
dispose(): void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type DiffStateFn = typeof diffState;
|
|
64
|
+
export type ReadPathFn = typeof readPath;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Diffs two states by reference: an unchanged reference skips its whole branch, so the cost follows what
|
|
68
|
+
* changed. Only plain objects and arrays are walked, arrays by index; anything else is a leaf.
|
|
69
|
+
*/
|
|
70
|
+
export function diffState(
|
|
71
|
+
prev: unknown,
|
|
72
|
+
next: unknown,
|
|
73
|
+
limits: DiffLimits,
|
|
74
|
+
serialize: SerializeFn,
|
|
75
|
+
): { ops: StateDiffOp[]; opCount: number } {
|
|
76
|
+
const ABSENT = {};
|
|
77
|
+
let ops: StateDiffOp[] = [];
|
|
78
|
+
let opCount = 0;
|
|
79
|
+
let nodes = 0;
|
|
80
|
+
|
|
81
|
+
const same = (a: unknown, b: unknown) => a === b || (a !== a && b !== b);
|
|
82
|
+
// Prototype checks rather than instanceof, so objects from another realm still count as plain.
|
|
83
|
+
const plain = (v: unknown): boolean => {
|
|
84
|
+
if (v === null || typeof v !== 'object' || Array.isArray(v)) return false;
|
|
85
|
+
const proto = Object.getPrototypeOf(v);
|
|
86
|
+
return proto === null || Object.getPrototypeOf(proto) === null;
|
|
87
|
+
};
|
|
88
|
+
const has = (obj: object, key: string) => Object.prototype.propertyIsEnumerable.call(obj, key);
|
|
89
|
+
const read = (obj: object, key: string): unknown => {
|
|
90
|
+
try {
|
|
91
|
+
const value = (obj as Record<string, unknown>)[key];
|
|
92
|
+
return limits.hideFunctions && typeof value === 'function' ? ABSENT : value;
|
|
93
|
+
} catch {
|
|
94
|
+
return ABSENT;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const push = (op: StateDiffOp['op'], path: StatePath, key: string | number | null, before: unknown, after: unknown) => {
|
|
99
|
+
opCount++;
|
|
100
|
+
if (ops.length >= limits.maxOps) return;
|
|
101
|
+
const out: StateDiffOp = { op, path: key === null ? path : [...path, key] };
|
|
102
|
+
if (op !== 'del') out.value = serialize(after, limits.preview);
|
|
103
|
+
if (op !== 'add') out.prev = serialize(before, limits.preview);
|
|
104
|
+
ops.push(out);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const walk = (a: unknown, b: unknown, path: StatePath, depth: number): void => {
|
|
108
|
+
const arrays = Array.isArray(a) && Array.isArray(b);
|
|
109
|
+
if ((!arrays && !(plain(a) && plain(b))) || depth >= limits.maxDepth || nodes >= limits.maxNodes) {
|
|
110
|
+
push('set', path, null, a, b);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
nodes++;
|
|
114
|
+
if (arrays) {
|
|
115
|
+
const before = a as unknown[];
|
|
116
|
+
const after = b as unknown[];
|
|
117
|
+
const shared = Math.min(before.length, after.length);
|
|
118
|
+
for (let i = 0; i < shared; i++) {
|
|
119
|
+
if (!same(before[i], after[i])) walk(before[i], after[i], [...path, i], depth + 1);
|
|
120
|
+
}
|
|
121
|
+
for (let i = shared; i < after.length; i++) push('add', path, i, undefined, after[i]);
|
|
122
|
+
for (let i = shared; i < before.length; i++) push('del', path, i, before[i], undefined);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const before = a as object;
|
|
126
|
+
const after = b as object;
|
|
127
|
+
for (const key of Object.keys(after)) {
|
|
128
|
+
const y = read(after, key);
|
|
129
|
+
if (y === ABSENT) continue;
|
|
130
|
+
const x = has(before, key) ? read(before, key) : ABSENT;
|
|
131
|
+
if (x === ABSENT) push('add', path, key, undefined, y);
|
|
132
|
+
else if (!same(x, y)) walk(x, y, [...path, key], depth + 1);
|
|
133
|
+
}
|
|
134
|
+
for (const key of Object.keys(before)) {
|
|
135
|
+
if (has(after, key) && read(after, key) !== ABSENT) continue;
|
|
136
|
+
const x = read(before, key);
|
|
137
|
+
if (x !== ABSENT) push('del', path, key, x, undefined);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
if (!same(prev, next)) {
|
|
142
|
+
try {
|
|
143
|
+
walk(prev, next, [], 0);
|
|
144
|
+
} catch {
|
|
145
|
+
// A proxy or exotic object threw midway; report the whole state as replaced instead.
|
|
146
|
+
ops = [];
|
|
147
|
+
opCount = 0;
|
|
148
|
+
push('set', [], null, prev, next);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return { ops, opCount };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Follows `path` from `root`: keys into objects and arrays, keys into Maps, positions into Sets.
|
|
156
|
+
* `found` is false when some step does not exist, as opposed to a value that is `undefined`.
|
|
157
|
+
*/
|
|
158
|
+
export function readPath(root: unknown, path: StatePath): { found: boolean; value: unknown } {
|
|
159
|
+
let current = root;
|
|
160
|
+
for (const key of path) {
|
|
161
|
+
if (current === null || (typeof current !== 'object' && typeof current !== 'function')) {
|
|
162
|
+
return { found: false, value: undefined };
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
if (current instanceof Map) {
|
|
166
|
+
let mapKey: unknown = key;
|
|
167
|
+
let hit = current.has(key);
|
|
168
|
+
// Paths come through JSON, so a numeric Map key may arrive as a string and the other way round.
|
|
169
|
+
for (const k of hit ? [] : current.keys()) {
|
|
170
|
+
if (String(k) === String(key)) {
|
|
171
|
+
mapKey = k;
|
|
172
|
+
hit = true;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (!hit) return { found: false, value: undefined };
|
|
177
|
+
current = current.get(mapKey);
|
|
178
|
+
} else if (current instanceof Set || Array.isArray(current)) {
|
|
179
|
+
const index = Number(key);
|
|
180
|
+
const size = Array.isArray(current) ? current.length : current.size;
|
|
181
|
+
if (!Number.isInteger(index) || index < 0 || index >= size) return { found: false, value: undefined };
|
|
182
|
+
current = Array.isArray(current) ? current[index] : [...current][index];
|
|
183
|
+
} else {
|
|
184
|
+
if (!Object.prototype.hasOwnProperty.call(current, key)) return { found: false, value: undefined };
|
|
185
|
+
current = (current as Record<string | number, unknown>)[key];
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
return { found: false, value: undefined };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return { found: true, value: current };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Turns what drivers report into `state.*` events and answers reads. Listeners only queue a reference or
|
|
196
|
+
* mark a key; diffing, serializing and emitting wait for a timer, and happen only while connected.
|
|
197
|
+
*/
|
|
198
|
+
export function createStateEngine(
|
|
199
|
+
emit: StateEmit,
|
|
200
|
+
options: StateEngineOptions,
|
|
201
|
+
serialize: SerializeFn,
|
|
202
|
+
diffState: DiffStateFn,
|
|
203
|
+
readPath: ReadPathFn,
|
|
204
|
+
): StateEngine {
|
|
205
|
+
const RECORD_DELAY = 100;
|
|
206
|
+
const ENTRY_DELAY = 200;
|
|
207
|
+
const LOW_ENTRY_DELAY = 1_000;
|
|
208
|
+
/** Plugins hear nothing when the connection comes back, so waiting changes look for it this often. */
|
|
209
|
+
const OFFLINE_POLL = 1_000;
|
|
210
|
+
/** References kept per store between flushes; past it the newest replaces the last one. */
|
|
211
|
+
const QUEUE_LIMIT = 200;
|
|
212
|
+
/** Summaries one store remembers or lists: room for TanStack Query's 1000 queries and 200 mutations. */
|
|
213
|
+
const ENTRY_LIMIT = 1_200;
|
|
214
|
+
/** Summaries per `state.entries` event; after a reset the `entries` command lists the rest. */
|
|
215
|
+
const ENTRIES_PER_EVENT = 200;
|
|
216
|
+
/** Same cap as network bodies. */
|
|
217
|
+
const MAX_READ = 128 * 1024;
|
|
218
|
+
const PREVIEW: SerializeOptions = { maxDepth: 3, maxKeys: 20, maxItems: 20, maxString: 200, maxNodes: 200 };
|
|
219
|
+
// Tried in order until a read fits in MAX_READ.
|
|
220
|
+
const READS: SerializeOptions[] = [
|
|
221
|
+
{ maxDepth: 8, maxKeys: 500, maxItems: 500, maxString: 10_000, maxNodes: 20_000 },
|
|
222
|
+
{ maxDepth: 5, maxKeys: 200, maxItems: 200, maxString: 2_000, maxNodes: 5_000 },
|
|
223
|
+
{ maxDepth: 3, maxKeys: 100, maxItems: 100, maxString: 500, maxNodes: 1_000 },
|
|
224
|
+
{ maxDepth: 1, maxKeys: 50, maxItems: 50, maxString: 200, maxNodes: 100 },
|
|
225
|
+
];
|
|
226
|
+
const hideFunctions = options.hideFunctions !== false;
|
|
227
|
+
const LIMITS: DiffLimits = { maxOps: 100, maxDepth: 12, maxNodes: 5_000, preview: PREVIEW, hideFunctions };
|
|
228
|
+
const perSecond = Math.max(1, Math.floor(options.maxActionsPerSecond ?? 30));
|
|
229
|
+
const denylist = (options.actionsDenylist ?? []).map((pattern) =>
|
|
230
|
+
typeof pattern === 'string' ? pattern : new RegExp(pattern.source, pattern.flags),
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
interface Change {
|
|
234
|
+
state: unknown;
|
|
235
|
+
action: unknown;
|
|
236
|
+
cause: StateChangePayload['cause'];
|
|
237
|
+
/** Changes folded into this one. */
|
|
238
|
+
skipped: number;
|
|
239
|
+
ts: number;
|
|
240
|
+
}
|
|
241
|
+
interface Tracked {
|
|
242
|
+
info: StateStoreInfo;
|
|
243
|
+
driver: { deref(): StoreDriver | undefined };
|
|
244
|
+
rev: number;
|
|
245
|
+
/** State of the last record, or from when tracking began. Diffs start from `base`, its sanitized form. */
|
|
246
|
+
raw: unknown;
|
|
247
|
+
base: unknown;
|
|
248
|
+
based: boolean;
|
|
249
|
+
queue: Change[];
|
|
250
|
+
/** Skipped counts of denylisted changes, passed on to the next record. */
|
|
251
|
+
carry: number;
|
|
252
|
+
windowStart: number;
|
|
253
|
+
windowCount: number;
|
|
254
|
+
dirty: Set<string>;
|
|
255
|
+
removed: Set<string>;
|
|
256
|
+
/** JSON of the last summary sent per key, so an unchanged entry is not sent again. */
|
|
257
|
+
sent: Map<string, string>;
|
|
258
|
+
reset: boolean;
|
|
259
|
+
entriesDue: number;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const stores = new Map<string, Tracked>();
|
|
263
|
+
// Keyed by driver, so a stop function, which may hold on to the store, never outlives it.
|
|
264
|
+
const stops = new WeakMap<StoreDriver, () => void>();
|
|
265
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
266
|
+
let timerAt = Infinity;
|
|
267
|
+
let offline = false;
|
|
268
|
+
let disposed = false;
|
|
269
|
+
|
|
270
|
+
const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
271
|
+
// Weak, so the engine never keeps a store alive; whoever registered the driver decides that.
|
|
272
|
+
const hold = (driver: StoreDriver): Tracked['driver'] =>
|
|
273
|
+
typeof WeakRef === 'function' ? new WeakRef(driver) : { deref: () => driver };
|
|
274
|
+
|
|
275
|
+
const dropFunctions = (value: SerializedValue): SerializedValue => {
|
|
276
|
+
const visit = (v: SerializedValue): void => {
|
|
277
|
+
if (v === null || typeof v !== 'object') return;
|
|
278
|
+
if (Array.isArray(v)) {
|
|
279
|
+
for (const item of v) visit(item);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const node = v as Record<string, any>;
|
|
283
|
+
switch (node.$t) {
|
|
284
|
+
case undefined:
|
|
285
|
+
strip(node);
|
|
286
|
+
break;
|
|
287
|
+
case 'object':
|
|
288
|
+
case 'error':
|
|
289
|
+
if (node.props) strip(node.props);
|
|
290
|
+
break;
|
|
291
|
+
case 'array':
|
|
292
|
+
for (const item of node.items) visit(item);
|
|
293
|
+
break;
|
|
294
|
+
case 'map':
|
|
295
|
+
for (const pair of node.entries) visit(pair[1]);
|
|
296
|
+
break;
|
|
297
|
+
case 'set':
|
|
298
|
+
for (const item of node.values) visit(item);
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const strip = (props: Record<string, SerializedValue>) => {
|
|
303
|
+
for (const key of Object.keys(props)) {
|
|
304
|
+
const child = props[key] as { $t?: unknown } | null;
|
|
305
|
+
if (child !== null && typeof child === 'object' && child.$t === 'function') delete props[key];
|
|
306
|
+
else visit(props[key]!);
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
visit(value);
|
|
310
|
+
return value;
|
|
311
|
+
};
|
|
312
|
+
const shown: SerializeFn = (value, profile) => {
|
|
313
|
+
const out = serialize(value, profile);
|
|
314
|
+
return hideFunctions ? dropFunctions(out) : out;
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
const clean = (t: Tracked, state: unknown): unknown => {
|
|
318
|
+
if (!options.sanitizeState) return state;
|
|
319
|
+
try {
|
|
320
|
+
return options.sanitizeState(state, t.info);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
// Never fall back to the state the sanitizer was meant to filter.
|
|
323
|
+
return `[sanitizeState threw: ${message(error)}]`;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
const actionType = (action: unknown): string => {
|
|
327
|
+
if (typeof action === 'string') return action;
|
|
328
|
+
try {
|
|
329
|
+
const type = (action as { type?: unknown } | null)?.type;
|
|
330
|
+
return typeof type === 'string' ? type : type === undefined ? 'anonymous' : String(type);
|
|
331
|
+
} catch {
|
|
332
|
+
return 'anonymous';
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
const hidden = (action: unknown): boolean => {
|
|
336
|
+
if (denylist.length === 0 || action === undefined) return false;
|
|
337
|
+
const type = actionType(action);
|
|
338
|
+
return denylist.some((pattern) => {
|
|
339
|
+
if (typeof pattern === 'string') return pattern === type;
|
|
340
|
+
pattern.lastIndex = 0;
|
|
341
|
+
return pattern.test(type);
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
/** The type, and a preview of the rest of the action (payload, meta, error). */
|
|
345
|
+
const describeAction = (t: Tracked, action: unknown): NonNullable<StateChangePayload['action']> => {
|
|
346
|
+
let sanitized = action;
|
|
347
|
+
if (options.sanitizeAction) {
|
|
348
|
+
try {
|
|
349
|
+
sanitized = options.sanitizeAction(action, t.info);
|
|
350
|
+
} catch {
|
|
351
|
+
return { type: actionType(action) };
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const type = actionType(sanitized);
|
|
355
|
+
if (sanitized === null || typeof sanitized !== 'object') return { type };
|
|
356
|
+
const rest: Record<string, unknown> = {};
|
|
357
|
+
let any = false;
|
|
358
|
+
try {
|
|
359
|
+
for (const key of Object.keys(sanitized)) {
|
|
360
|
+
if (key === 'type') continue;
|
|
361
|
+
rest[key] = (sanitized as Record<string, unknown>)[key];
|
|
362
|
+
any = true;
|
|
363
|
+
}
|
|
364
|
+
} catch {
|
|
365
|
+
return { type };
|
|
366
|
+
}
|
|
367
|
+
return any ? { type, payload: shown(rest, PREVIEW) } : { type };
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
const wake = (delay: number) => {
|
|
371
|
+
if (disposed) return;
|
|
372
|
+
const wait = Math.max(0, delay);
|
|
373
|
+
const at = Date.now() + wait;
|
|
374
|
+
if (timer !== null) {
|
|
375
|
+
if (timerAt <= at) return;
|
|
376
|
+
clearTimeout(timer);
|
|
377
|
+
}
|
|
378
|
+
timerAt = at;
|
|
379
|
+
timer = setTimeout(flush, wait);
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
const record: StateSink['record'] = (id, state, action, cause) => {
|
|
383
|
+
try {
|
|
384
|
+
const t = stores.get(id);
|
|
385
|
+
if (!t) return;
|
|
386
|
+
const change: Change = { state, action, cause: cause ?? (action === undefined ? 'set' : 'action'), skipped: 0, ts: Date.now() };
|
|
387
|
+
const queue = t.queue;
|
|
388
|
+
if (queue.length < QUEUE_LIMIT) {
|
|
389
|
+
queue.push(change);
|
|
390
|
+
} else {
|
|
391
|
+
change.skipped = queue[queue.length - 1]!.skipped + 1;
|
|
392
|
+
queue[queue.length - 1] = change;
|
|
393
|
+
}
|
|
394
|
+
wake(offline ? OFFLINE_POLL : RECORD_DELAY);
|
|
395
|
+
} catch {
|
|
396
|
+
// never throw into the app's store
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
// Bounded: past the cap, start over with a reset rather than remember more keys.
|
|
400
|
+
const resync = (t: Tracked) => {
|
|
401
|
+
t.dirty.clear();
|
|
402
|
+
t.removed.clear();
|
|
403
|
+
t.sent.clear();
|
|
404
|
+
t.reset = true;
|
|
405
|
+
};
|
|
406
|
+
const entriesSoon = (t: Tracked, delay: number) => {
|
|
407
|
+
const at = Date.now() + delay;
|
|
408
|
+
if (at < t.entriesDue) t.entriesDue = at;
|
|
409
|
+
wake(offline ? OFFLINE_POLL : t.entriesDue - Date.now());
|
|
410
|
+
};
|
|
411
|
+
const dirty: StateSink['dirty'] = (id, key, low) => {
|
|
412
|
+
try {
|
|
413
|
+
const t = stores.get(id);
|
|
414
|
+
if (!t) return;
|
|
415
|
+
t.removed.delete(key);
|
|
416
|
+
t.dirty.add(key);
|
|
417
|
+
if (t.dirty.size > ENTRY_LIMIT) resync(t);
|
|
418
|
+
entriesSoon(t, low ? LOW_ENTRY_DELAY : ENTRY_DELAY);
|
|
419
|
+
} catch {
|
|
420
|
+
// never throw into the app's cache
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
const removed: StateSink['removed'] = (id, key) => {
|
|
424
|
+
try {
|
|
425
|
+
const t = stores.get(id);
|
|
426
|
+
if (!t) return;
|
|
427
|
+
t.dirty.delete(key);
|
|
428
|
+
t.removed.add(key);
|
|
429
|
+
if (t.removed.size > ENTRY_LIMIT) resync(t);
|
|
430
|
+
entriesSoon(t, ENTRY_DELAY);
|
|
431
|
+
} catch {
|
|
432
|
+
// never throw into the app's cache
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
/** Drops denylisted changes; what they changed goes out with the next record, diffed from the last one sent. */
|
|
437
|
+
const visible = (t: Tracked): Change[] => {
|
|
438
|
+
if (denylist.length === 0) return t.queue;
|
|
439
|
+
const out: Change[] = [];
|
|
440
|
+
for (const change of t.queue) {
|
|
441
|
+
if (hidden(change.action)) {
|
|
442
|
+
t.carry += change.skipped;
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
change.skipped += t.carry;
|
|
446
|
+
t.carry = 0;
|
|
447
|
+
out.push(change);
|
|
448
|
+
}
|
|
449
|
+
return out;
|
|
450
|
+
};
|
|
451
|
+
const fold = (changes: Change[]): Change[] => {
|
|
452
|
+
if (changes.length <= 1) return changes;
|
|
453
|
+
const last = changes[changes.length - 1]!;
|
|
454
|
+
for (let i = 0; i < changes.length - 1; i++) last.skipped += changes[i]!.skipped + 1;
|
|
455
|
+
return [last];
|
|
456
|
+
};
|
|
457
|
+
const send = (t: Tracked, change: Change) => {
|
|
458
|
+
const next = clean(t, change.state);
|
|
459
|
+
const { ops, opCount }: { ops: StateDiffOp[]; opCount: number } = t.based
|
|
460
|
+
? diffState(t.base, next, LIMITS, shown)
|
|
461
|
+
: { ops: [{ op: 'set', path: [], value: shown(next, PREVIEW) }], opCount: 1 };
|
|
462
|
+
t.raw = change.state;
|
|
463
|
+
t.base = next;
|
|
464
|
+
t.based = true;
|
|
465
|
+
if (ops.length === 0 && change.action === undefined && change.skipped === 0 && change.cause !== 'init') return;
|
|
466
|
+
const payload: StateChangePayload = { store: t.info.id, rev: ++t.rev, cause: change.cause, ops };
|
|
467
|
+
if (change.action !== undefined) payload.action = describeAction(t, change.action);
|
|
468
|
+
if (opCount > ops.length) payload.opCount = opCount;
|
|
469
|
+
if (change.skipped > 0) payload.skipped = change.skipped;
|
|
470
|
+
t.windowCount++;
|
|
471
|
+
emit('state.change', payload, change.ts);
|
|
472
|
+
};
|
|
473
|
+
const flushChanges = (t: Tracked, live: boolean, now: number) => {
|
|
474
|
+
if (t.queue.length === 0) return;
|
|
475
|
+
const queue = visible(t);
|
|
476
|
+
// Offline, nothing is diffed: changes only pile up as a count on the newest one.
|
|
477
|
+
if (!live) {
|
|
478
|
+
t.queue = fold(queue);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
if (now - t.windowStart >= 1_000) {
|
|
482
|
+
t.windowStart = now;
|
|
483
|
+
t.windowCount = 0;
|
|
484
|
+
}
|
|
485
|
+
const room = perSecond - t.windowCount;
|
|
486
|
+
if (room <= 0) {
|
|
487
|
+
t.queue = fold(queue);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
t.queue = [];
|
|
491
|
+
// The last record of the window carries everything past the limit, so the newest state still goes out.
|
|
492
|
+
const batch = queue.length > room ? [...queue.slice(0, room - 1), ...fold(queue.slice(room - 1))] : queue;
|
|
493
|
+
for (const change of batch) send(t, change);
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
const summarize = (driver: StoreDriver, key: string): StateEntrySummary | undefined => {
|
|
497
|
+
try {
|
|
498
|
+
const summary = driver.summarize?.(key);
|
|
499
|
+
return summary && typeof summary === 'object' ? summary : undefined;
|
|
500
|
+
} catch {
|
|
501
|
+
return undefined;
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
const flushEntries = (t: Tracked, live: boolean, now: number) => {
|
|
505
|
+
if (!live || now < t.entriesDue) return;
|
|
506
|
+
t.entriesDue = Infinity;
|
|
507
|
+
const driver = t.driver.deref();
|
|
508
|
+
const store = t.info.id;
|
|
509
|
+
if (!driver || typeof driver.keys !== 'function') {
|
|
510
|
+
t.dirty.clear();
|
|
511
|
+
t.removed.clear();
|
|
512
|
+
t.reset = false;
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (t.reset) {
|
|
516
|
+
const upserts: StateEntrySummary[] = [];
|
|
517
|
+
const sent = new Map<string, string>();
|
|
518
|
+
for (const key of driver.keys()) {
|
|
519
|
+
if (upserts.length >= ENTRIES_PER_EVENT) break;
|
|
520
|
+
const summary = summarize(driver, key);
|
|
521
|
+
if (!summary) continue;
|
|
522
|
+
upserts.push(summary);
|
|
523
|
+
sent.set(key, JSON.stringify(summary));
|
|
524
|
+
}
|
|
525
|
+
t.reset = false;
|
|
526
|
+
t.dirty.clear();
|
|
527
|
+
t.removed.clear();
|
|
528
|
+
t.sent = sent;
|
|
529
|
+
emit('state.entries', { store, upserts, removed: [], reset: true });
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const upserts: StateEntrySummary[] = [];
|
|
533
|
+
const gone = [...t.removed];
|
|
534
|
+
for (const key of gone) t.sent.delete(key);
|
|
535
|
+
for (const key of t.dirty) {
|
|
536
|
+
const summary = summarize(driver, key);
|
|
537
|
+
if (!summary) {
|
|
538
|
+
if (t.sent.delete(key)) gone.push(key);
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
const json = JSON.stringify(summary);
|
|
542
|
+
if (t.sent.get(key) === json) continue;
|
|
543
|
+
// Re-inserted, so the key sent longest ago is the one forgotten when the map is full.
|
|
544
|
+
t.sent.delete(key);
|
|
545
|
+
t.sent.set(key, json);
|
|
546
|
+
if (t.sent.size > ENTRY_LIMIT) t.sent.delete(t.sent.keys().next().value!);
|
|
547
|
+
upserts.push(summary);
|
|
548
|
+
}
|
|
549
|
+
t.dirty.clear();
|
|
550
|
+
t.removed.clear();
|
|
551
|
+
for (let i = 0; i < upserts.length || (i === 0 && gone.length > 0); i += ENTRIES_PER_EVENT) {
|
|
552
|
+
emit('state.entries', { store, upserts: upserts.slice(i, i + ENTRIES_PER_EVENT), removed: i === 0 ? gone : [] });
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
|
|
556
|
+
const flush = () => {
|
|
557
|
+
timer = null;
|
|
558
|
+
timerAt = Infinity;
|
|
559
|
+
if (disposed) return;
|
|
560
|
+
let live = false;
|
|
561
|
+
try {
|
|
562
|
+
live = options.connected() === true;
|
|
563
|
+
} catch {
|
|
564
|
+
// counts as offline
|
|
565
|
+
}
|
|
566
|
+
offline = !live;
|
|
567
|
+
const now = Date.now();
|
|
568
|
+
let next = Infinity;
|
|
569
|
+
for (const t of [...stores.values()]) {
|
|
570
|
+
try {
|
|
571
|
+
flushChanges(t, live, now);
|
|
572
|
+
} catch {
|
|
573
|
+
t.queue = [];
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
flushEntries(t, live, now);
|
|
577
|
+
} catch {
|
|
578
|
+
t.dirty.clear();
|
|
579
|
+
t.removed.clear();
|
|
580
|
+
}
|
|
581
|
+
if (t.queue.length > 0) next = Math.min(next, live ? t.windowStart + 1_000 : now + OFFLINE_POLL);
|
|
582
|
+
if (t.dirty.size > 0 || t.removed.size > 0 || t.reset) next = Math.min(next, live ? t.entriesDue : now + OFFLINE_POLL);
|
|
583
|
+
}
|
|
584
|
+
if (next < Infinity) wake(next - now);
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
const need = (id: unknown): { t: Tracked; driver: StoreDriver } => {
|
|
588
|
+
const t = typeof id === 'string' ? stores.get(id) : undefined;
|
|
589
|
+
if (!t) throw new Error(`Unknown store "${String(id)}"`);
|
|
590
|
+
const driver = t.driver.deref();
|
|
591
|
+
if (!driver) {
|
|
592
|
+
untrack(t.info.id);
|
|
593
|
+
throw new Error(`${t.info.label} is no longer in the app`);
|
|
594
|
+
}
|
|
595
|
+
return { t, driver };
|
|
596
|
+
};
|
|
597
|
+
const at = (root: unknown, path: unknown): unknown => {
|
|
598
|
+
const keys = Array.isArray(path) ? (path as StatePath) : [];
|
|
599
|
+
const found = readPath(root, keys);
|
|
600
|
+
if (!found.found) throw new Error(`Nothing at ${JSON.stringify(keys)}`);
|
|
601
|
+
return found.value;
|
|
602
|
+
};
|
|
603
|
+
const fit = (value: unknown): { value: SerializedValue; truncated: boolean } => {
|
|
604
|
+
for (let i = 0; i < READS.length; i++) {
|
|
605
|
+
const out = shown(value, READS[i]);
|
|
606
|
+
if (JSON.stringify(out).length <= MAX_READ) return { value: out, truncated: i > 0 };
|
|
607
|
+
}
|
|
608
|
+
return { value: { $t: 'limit', name: Array.isArray(value) ? `Array(${value.length})` : 'Object' }, truncated: true };
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
const read: StateEngine['read'] = (id, path) => {
|
|
612
|
+
const { t, driver } = need(id);
|
|
613
|
+
if (typeof driver.getState !== 'function') {
|
|
614
|
+
throw new Error(`${t.info.label} has entries instead of a state; list them with "entries"`);
|
|
615
|
+
}
|
|
616
|
+
const raw = driver.getState();
|
|
617
|
+
const state = options.sanitizeState ? options.sanitizeState(raw, t.info) : raw;
|
|
618
|
+
return { rev: t.rev, pending: raw !== t.raw, ...fit(at(state, path)) };
|
|
619
|
+
};
|
|
620
|
+
const entries: StateEngine['entries'] = (id) => {
|
|
621
|
+
const { t, driver } = need(id);
|
|
622
|
+
if (typeof driver.keys !== 'function') throw new Error(`${t.info.label} has no entries`);
|
|
623
|
+
const list: StateEntrySummary[] = [];
|
|
624
|
+
let total = 0;
|
|
625
|
+
for (const key of driver.keys()) {
|
|
626
|
+
total++;
|
|
627
|
+
if (list.length >= ENTRY_LIMIT) continue;
|
|
628
|
+
const summary = summarize(driver, key);
|
|
629
|
+
if (summary) list.push(summary);
|
|
630
|
+
}
|
|
631
|
+
return { entries: list, total };
|
|
632
|
+
};
|
|
633
|
+
const entry: StateEngine['entry'] = (id, key, path) => {
|
|
634
|
+
const { t, driver } = need(id);
|
|
635
|
+
if (typeof driver.keys !== 'function') throw new Error(`${t.info.label} has no entries`);
|
|
636
|
+
const summary = summarize(driver, String(key));
|
|
637
|
+
if (!summary) return null;
|
|
638
|
+
const data = typeof driver.data === 'function' ? driver.data(String(key)) : undefined;
|
|
639
|
+
const { value, truncated } = fit(at(data, path));
|
|
640
|
+
return { summary, data: value, truncated };
|
|
641
|
+
};
|
|
642
|
+
const act: StateEngine['act'] = (id, key, op) => {
|
|
643
|
+
try {
|
|
644
|
+
const { t, driver } = need(id);
|
|
645
|
+
if (typeof driver.act !== 'function' || !(t.info.ops ?? []).includes(op)) {
|
|
646
|
+
throw new Error(`${t.info.label} does not support "${String(op)}"`);
|
|
647
|
+
}
|
|
648
|
+
return Promise.resolve(driver.act(String(key), op));
|
|
649
|
+
} catch (error) {
|
|
650
|
+
return Promise.reject(error);
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
const stopDriver = (t: Tracked) => {
|
|
655
|
+
const driver = t.driver.deref();
|
|
656
|
+
const stop = driver && stops.get(driver);
|
|
657
|
+
if (!driver || !stop) return;
|
|
658
|
+
stops.delete(driver);
|
|
659
|
+
try {
|
|
660
|
+
stop();
|
|
661
|
+
} catch {
|
|
662
|
+
// the store may be half torn down already
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
const untrack: StateEngine['untrack'] = (id, note) => {
|
|
666
|
+
const t = stores.get(id);
|
|
667
|
+
if (!t) return;
|
|
668
|
+
stores.delete(id);
|
|
669
|
+
stopDriver(t);
|
|
670
|
+
const info: StateStoreInfo = { ...t.info, disposed: true };
|
|
671
|
+
if (note) info.note = note;
|
|
672
|
+
emit('state.store', { store: info });
|
|
673
|
+
};
|
|
674
|
+
const sink: StateSink = { record, dirty, removed };
|
|
675
|
+
const track: StateEngine['track'] = (id, driver) => {
|
|
676
|
+
if (disposed || stores.has(id)) return;
|
|
677
|
+
let t: Tracked;
|
|
678
|
+
try {
|
|
679
|
+
t = {
|
|
680
|
+
info: { ...driver.info, id },
|
|
681
|
+
driver: hold(driver),
|
|
682
|
+
rev: 0,
|
|
683
|
+
raw: undefined,
|
|
684
|
+
base: undefined,
|
|
685
|
+
based: false,
|
|
686
|
+
queue: [],
|
|
687
|
+
carry: 0,
|
|
688
|
+
windowStart: 0,
|
|
689
|
+
windowCount: 0,
|
|
690
|
+
dirty: new Set(),
|
|
691
|
+
removed: new Set(),
|
|
692
|
+
sent: new Map(),
|
|
693
|
+
reset: false,
|
|
694
|
+
entriesDue: Infinity,
|
|
695
|
+
};
|
|
696
|
+
} catch {
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
stores.set(id, t);
|
|
700
|
+
emit('state.store', { store: t.info });
|
|
701
|
+
try {
|
|
702
|
+
if (typeof driver.getState === 'function') {
|
|
703
|
+
try {
|
|
704
|
+
t.raw = driver.getState();
|
|
705
|
+
t.base = clean(t, t.raw);
|
|
706
|
+
t.based = true;
|
|
707
|
+
} catch {
|
|
708
|
+
// the first record becomes the base instead
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
if (typeof driver.keys === 'function') {
|
|
712
|
+
t.reset = true;
|
|
713
|
+
entriesSoon(t, ENTRY_DELAY);
|
|
714
|
+
}
|
|
715
|
+
const stop = driver.start(sink, id);
|
|
716
|
+
if (typeof stop === 'function') stops.set(driver, stop);
|
|
717
|
+
} catch (error) {
|
|
718
|
+
untrack(id, `Could not watch this store: ${message(error)}`);
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
const list: StateEngine['stores'] = () => {
|
|
722
|
+
const out: StateStoreInfo[] = [];
|
|
723
|
+
for (const t of [...stores.values()]) {
|
|
724
|
+
if (t.driver.deref()) out.push(t.info);
|
|
725
|
+
else untrack(t.info.id);
|
|
726
|
+
}
|
|
727
|
+
return out;
|
|
728
|
+
};
|
|
729
|
+
const dispose: StateEngine['dispose'] = () => {
|
|
730
|
+
if (disposed) return;
|
|
731
|
+
disposed = true;
|
|
732
|
+
if (timer !== null) clearTimeout(timer);
|
|
733
|
+
timer = null;
|
|
734
|
+
for (const t of stores.values()) stopDriver(t);
|
|
735
|
+
stores.clear();
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
return { ...sink, track, untrack, stores: list, read, entries, entry, act, dispose };
|
|
739
|
+
}
|