@buoy-gg/events 7.0.17 → 7.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.
@@ -1,3 +1,8 @@
1
+ import {
2
+ approxJsonSize,
3
+ isJsonSerializable,
4
+ isOverWireBudget,
5
+ } from "@buoy-gg/shared-ui";
1
6
  import { unifiedEventStore } from "../stores/unifiedEventStore";
2
7
  import type { EventSource } from "../types";
3
8
  import { generateExport } from "../utils/eventExportFormatter";
@@ -37,57 +42,6 @@ interface TruncatedOriginalEvent {
37
42
  note: string;
38
43
  }
39
44
 
40
- /**
41
- * Early-aborting size estimate. The previous guard measured with
42
- * JSON.stringify(payload).length — an O(payload) cost to enforce a 16KB cap,
43
- * which meant the protection itself blocked the JS thread for seconds (and
44
- * could OOM) on enterprise-scale redux state trees. This walk accumulates
45
- * approximate byte counts and bails as soon as the limit is exceeded, so the
46
- * cost is O(limit) no matter how large the payload is. `cyclic` is reported
47
- * because cyclic payloads must never reach the socket serializer.
48
- */
49
- function approxSizeOver(
50
- value: unknown,
51
- limit: number
52
- ): { over: boolean; approxBytes: number; cyclic: boolean } {
53
- let bytes = 0;
54
- let cyclic = false;
55
- const stack: unknown[] = [value];
56
- const seen = new Set<object>();
57
- while (stack.length > 0) {
58
- if (bytes > limit) return { over: true, approxBytes: bytes, cyclic };
59
- const v = stack.pop();
60
- if (v === null || v === undefined) {
61
- bytes += 4;
62
- } else if (typeof v === "string") {
63
- bytes += v.length + 2; // O(1): length read, no scan
64
- } else if (typeof v === "number") {
65
- bytes += 8;
66
- } else if (typeof v === "boolean") {
67
- bytes += 5;
68
- } else if (typeof v === "object") {
69
- if (seen.has(v as object)) {
70
- cyclic = true;
71
- continue;
72
- }
73
- seen.add(v as object);
74
- if (Array.isArray(v)) {
75
- bytes += 2 + v.length;
76
- for (let i = 0; i < v.length; i++) stack.push(v[i]);
77
- } else {
78
- bytes += 2;
79
- for (const k in v as Record<string, unknown>) {
80
- bytes += k.length + 4;
81
- stack.push((v as Record<string, unknown>)[k]);
82
- }
83
- }
84
- } else {
85
- bytes += 4; // function/symbol/bigint — JSON drops or errors; count nominally
86
- }
87
- }
88
- return { over: bytes > limit, approxBytes: bytes, cyclic };
89
- }
90
-
91
45
  function truncatedMarker(approxBytes: number, note?: string): TruncatedOriginalEvent {
92
46
  return {
93
47
  __buoyTruncated: true,
@@ -104,6 +58,73 @@ const STATE_TREE_OMITTED = {
104
58
  note: "prevState/nextState stay on the device (use get_redux_state / the on-device tool).",
105
59
  } as const;
106
60
 
61
+ /** Marker replacing oversized / unserializable react-query payloads. */
62
+ const QUERY_PAYLOAD_OMITTED = {
63
+ __buoyOmitted: "query-payload",
64
+ note: "Query/mutation data stays on the device (open the Query tool or the on-device Events detail).",
65
+ } as const;
66
+
67
+ const NETWORK_BODY_OMITTED = {
68
+ __buoyOmitted: "network-body",
69
+ note: "Request/response body stays on the device (open the Network tool or the on-device Events detail).",
70
+ } as const;
71
+
72
+ const NETWORK_HEADERS_OMITTED = {
73
+ __buoyOmitted: "network-headers",
74
+ note: "Request/response headers stay on the device (open the Network tool or the on-device Events detail).",
75
+ } as const;
76
+
77
+ const GRAPHQL_VARS_OMITTED = {
78
+ __buoyOmitted: "graphql-variables",
79
+ note: "GraphQL variables stay on the device (open the Network tool or the on-device Events detail).",
80
+ } as const;
81
+
82
+ const STORAGE_VALUE_OMITTED = {
83
+ __buoyOmitted: "storage-value",
84
+ note: "Storage value stays on the device (open the Storage tool or the on-device Events detail).",
85
+ } as const;
86
+
87
+ const ROUTE_PARAMS_OMITTED = {
88
+ __buoyOmitted: "route-params",
89
+ note: "Navigation params stay on the device (open the Routes tool or the on-device Events detail).",
90
+ } as const;
91
+
92
+ function isReactQuerySource(source?: string): boolean {
93
+ return (
94
+ source === "react-query" ||
95
+ source === "react-query-query" ||
96
+ source === "react-query-mutation"
97
+ );
98
+ }
99
+
100
+ /**
101
+ * Markers are CLONED per field rather than shared. Not for correctness any
102
+ * more — sharing a reference is now handled properly below — but because a
103
+ * repeated reference makes the size walk report `sawRepeat`, which costs a
104
+ * full serializability check on an event we already know is fine.
105
+ */
106
+ function omitIfHeavy(
107
+ value: unknown,
108
+ marker: { __buoyOmitted: string; note: string },
109
+ ): unknown {
110
+ if (value === undefined) return undefined;
111
+ return isOverWireBudget(value, MAX_SYNC_ORIGINAL_EVENT_BYTES)
112
+ ? { ...marker }
113
+ : value;
114
+ }
115
+
116
+ function wireQueryPayload(value: unknown): unknown {
117
+ return omitIfHeavy(value, QUERY_PAYLOAD_OMITTED);
118
+ }
119
+
120
+ function wireError(value: unknown): unknown {
121
+ if (value == null) return value;
122
+ if (value instanceof Error) {
123
+ return { name: value.name, message: value.message };
124
+ }
125
+ return wireQueryPayload(value);
126
+ }
127
+
107
128
  // Events are immutable once created, so compaction is computed once per event
108
129
  // object and drops out of the cache when the store evicts the event.
109
130
  const compactionCache = new WeakMap<object, unknown>();
@@ -125,28 +146,162 @@ function compactEventForSync<T extends { source?: string; originalEvent: unknown
125
146
  // (type/payload/meta/diff) still makes it onto the wire when it fits.
126
147
  let candidate = original as Record<string, unknown>;
127
148
  if (
128
- event.source === "redux" &&
149
+ (event.source === "redux" || event.source === "zustand") &&
129
150
  ("prevState" in candidate || "nextState" in candidate)
130
151
  ) {
152
+ // Clone the sentinel per field. `approxSizeOver` flags a repeated object
153
+ // reference as cyclic, and a shared marker would truncate the whole
154
+ // originalEvent — dropping type/payload, which is the part we kept.
155
+ candidate = {
156
+ ...candidate,
157
+ prevState: { ...STATE_TREE_OMITTED },
158
+ nextState: { ...STATE_TREE_OMITTED },
159
+ ...(event.source === "zustand" && "partial" in candidate
160
+ ? { partial: { ...STATE_TREE_OMITTED } }
161
+ : {}),
162
+ };
163
+ result = { ...event, originalEvent: candidate };
164
+ } else if (
165
+ event.source === "jotai" &&
166
+ ("prevValue" in candidate || "nextValue" in candidate)
167
+ ) {
168
+ candidate = {
169
+ ...candidate,
170
+ prevValue: { ...STATE_TREE_OMITTED },
171
+ nextValue: { ...STATE_TREE_OMITTED },
172
+ };
173
+ result = { ...event, originalEvent: candidate };
174
+ } else if (event.source === "render") {
175
+ // Highlight-updates events embed the full TrackedRender (including
176
+ // renderHistory) plus the RenderEvent (captured props/state, hookChanges).
177
+ // Drop those trees so the timeline keeps title/cause type.
178
+ const render = candidate.render as Record<string, unknown> | undefined;
179
+ const nested = candidate.event as Record<string, unknown> | undefined;
180
+ const omitCause = (cause: unknown) => {
181
+ if (!cause || typeof cause !== "object") return cause;
182
+ const { hookChanges: _hookChanges, ...rest } = cause as Record<
183
+ string,
184
+ unknown
185
+ >;
186
+ return rest;
187
+ };
188
+ candidate = {
189
+ ...candidate,
190
+ render: render
191
+ ? {
192
+ ...render,
193
+ renderHistory: undefined,
194
+ lastRenderCause: omitCause(render.lastRenderCause),
195
+ }
196
+ : render,
197
+ event: nested
198
+ ? {
199
+ ...nested,
200
+ capturedProps: undefined,
201
+ capturedState: undefined,
202
+ cause: omitCause(nested.cause),
203
+ }
204
+ : nested,
205
+ };
206
+ result = { ...event, originalEvent: candidate };
207
+ } else if (isReactQuerySource(event.source)) {
208
+ // React Query events embed the live Query/Mutation objects (cyclic —
209
+ // observers point back at the query) plus full cache `queryData`.
210
+ // Walking those either flags cyclic and truncates the WHOLE originalEvent
211
+ // (losing type/queryKey/duration) or blows the 16KB cap. Drop the live
212
+ // objects unconditionally; keep light fields; replace heavy data.
213
+ const { query: _query, mutation: _mutation, ...rest } = candidate;
214
+ candidate = {
215
+ ...rest,
216
+ queryData: wireQueryPayload(rest.queryData),
217
+ mutationData: wireQueryPayload(rest.mutationData),
218
+ mutationVariables: wireQueryPayload(rest.mutationVariables),
219
+ queryError: wireError(rest.queryError),
220
+ mutationError: wireError(rest.mutationError),
221
+ };
222
+ result = { ...event, originalEvent: candidate };
223
+ } else if (event.source === "network") {
224
+ // Network events carry request/response bodies. A 20KB body blows the
225
+ // 16KB cap and truncates the WHOLE originalEvent — method/url/status
226
+ // never reach the dashboard. Strip heavy bodies first (same 16KB
227
+ // threshold as the network adapter).
228
+ const requestSize =
229
+ typeof candidate.requestSize === "number"
230
+ ? candidate.requestSize
231
+ : undefined;
232
+ const responseSize =
233
+ typeof candidate.responseSize === "number"
234
+ ? candidate.responseSize
235
+ : undefined;
236
+ candidate = {
237
+ ...candidate,
238
+ requestData:
239
+ requestSize !== undefined && requestSize > MAX_SYNC_ORIGINAL_EVENT_BYTES
240
+ ? { ...NETWORK_BODY_OMITTED }
241
+ : omitIfHeavy(candidate.requestData, NETWORK_BODY_OMITTED),
242
+ responseData:
243
+ responseSize !== undefined &&
244
+ responseSize > MAX_SYNC_ORIGINAL_EVENT_BYTES
245
+ ? { ...NETWORK_BODY_OMITTED }
246
+ : omitIfHeavy(candidate.responseData, NETWORK_BODY_OMITTED),
247
+ graphqlVariables: omitIfHeavy(
248
+ candidate.graphqlVariables,
249
+ GRAPHQL_VARS_OMITTED,
250
+ ),
251
+ requestHeaders: omitIfHeavy(
252
+ candidate.requestHeaders,
253
+ NETWORK_HEADERS_OMITTED,
254
+ ),
255
+ responseHeaders: omitIfHeavy(
256
+ candidate.responseHeaders,
257
+ NETWORK_HEADERS_OMITTED,
258
+ ),
259
+ };
260
+ result = { ...event, originalEvent: candidate };
261
+ } else if (
262
+ event.source === "storage-async" ||
263
+ event.source === "storage-mmkv"
264
+ ) {
265
+ const data = candidate.data as Record<string, unknown> | undefined;
266
+ if (data) {
267
+ candidate = {
268
+ ...candidate,
269
+ data: {
270
+ ...data,
271
+ value: omitIfHeavy(data.value, STORAGE_VALUE_OMITTED),
272
+ prevValue: omitIfHeavy(data.prevValue, STORAGE_VALUE_OMITTED),
273
+ pairs: omitIfHeavy(data.pairs, STORAGE_VALUE_OMITTED),
274
+ },
275
+ };
276
+ result = { ...event, originalEvent: candidate };
277
+ }
278
+ } else if (event.source === "route") {
279
+ // Route events embed navigate() params. A fat object (or a 20KB
280
+ // stringified payload) blows the 16KB cap and truncates the WHOLE
281
+ // originalEvent — pathname never reaches the dashboard.
131
282
  candidate = {
132
283
  ...candidate,
133
- prevState: STATE_TREE_OMITTED,
134
- nextState: STATE_TREE_OMITTED,
284
+ params: omitIfHeavy(candidate.params, ROUTE_PARAMS_OMITTED),
135
285
  };
136
286
  result = { ...event, originalEvent: candidate };
137
287
  }
138
288
 
139
- const { over, approxBytes, cyclic } = approxSizeOver(
289
+ const { bytes, sawRepeat, sawBigInt } = approxJsonSize(
140
290
  candidate,
141
291
  MAX_SYNC_ORIGINAL_EVENT_BYTES
142
292
  );
143
- if (over) {
144
- result = { ...event, originalEvent: truncatedMarker(approxBytes) };
145
- } else if (cyclic) {
146
- // Cyclic payloads would crash the socket serializer — never ship them.
293
+ if (bytes > MAX_SYNC_ORIGINAL_EVENT_BYTES) {
294
+ result = { ...event, originalEvent: truncatedMarker(bytes) };
295
+ } else if ((sawRepeat || sawBigInt) && !isJsonSerializable(candidate)) {
296
+ // Only a CONFIRMED failure truncates. The walk dedupes by identity to stay
297
+ // O(limit), so it cannot distinguish a cycle from ordinary structural
298
+ // sharing — and `{ user, currentUser }` pointing at one object is both
299
+ // commonplace and perfectly serializable. Treating that as cyclic threw
300
+ // away the whole event, type and title included, for a payload that was
301
+ // always safe to send.
147
302
  result = {
148
303
  ...event,
149
- originalEvent: truncatedMarker(-1, "Payload is not JSON-serializable (cyclic) and stayed on the device."),
304
+ originalEvent: truncatedMarker(-1, "Payload is not JSON-serializable (cyclic or bigint) and stayed on the device."),
150
305
  };
151
306
  }
152
307
 
@@ -199,7 +354,7 @@ export const eventsSyncAdapter = {
199
354
  * the dashboard's source badges. Ref-counted in the store, so disabling a
200
355
  * source here only stops its capture if no other consumer wants it.
201
356
  */
202
- setEnabledSources: (params: unknown) => {
357
+ setEnabledSources: (params?: unknown) => {
203
358
  const sources =
204
359
  (params as { sources?: EventSource[] } | undefined)?.sources ?? [];
205
360
  unifiedEventStore.setRemoteEnabledSources(sources);
@@ -213,7 +368,7 @@ export const eventsSyncAdapter = {
213
368
  * by default and only pulls more detail when it asks. Returns the formatted
214
369
  * string + metadata so the caller knows how much was returned.
215
370
  */
216
- exportEvents: (params: unknown) => {
371
+ exportEvents: (params?: unknown) => {
217
372
  const p = (params as ExportEventsParams | undefined) ?? {};
218
373
  const base =
219
374
  p.preset && COPY_PRESETS[p.preset]