@three-flatland/devtools 0.1.0-alpha.3 → 1.0.0-alpha.6

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 (172) hide show
  1. package/README.md +1 -1
  2. package/dist/buffers-modal.d.ts +16 -52
  3. package/dist/buffers-modal.d.ts.map +1 -0
  4. package/dist/buffers-modal.js +459 -464
  5. package/dist/buffers-modal.js.map +1 -1
  6. package/dist/buffers-view.d.ts +22 -34
  7. package/dist/buffers-view.d.ts.map +1 -0
  8. package/dist/buffers-view.js +252 -240
  9. package/dist/buffers-view.js.map +1 -1
  10. package/dist/create-pane.d.ts +38 -37
  11. package/dist/create-pane.d.ts.map +1 -0
  12. package/dist/create-pane.js +197 -166
  13. package/dist/create-pane.js.map +1 -1
  14. package/dist/dashboard/app.tsx +2 -0
  15. package/dist/dashboard/export.ts +1 -3
  16. package/dist/dashboard/frame-cursor.ts +81 -0
  17. package/dist/dashboard/hooks.ts +10 -2
  18. package/dist/dashboard/index.html +61 -0
  19. package/dist/dashboard/panels/batches.tsx +5 -18
  20. package/dist/dashboard/panels/buffers.tsx +52 -26
  21. package/dist/dashboard/panels/env.tsx +5 -6
  22. package/dist/dashboard/panels/protocol-log.tsx +146 -58
  23. package/dist/dashboard/panels/registry.tsx +55 -69
  24. package/dist/dashboard/panels/scrubber.tsx +100 -0
  25. package/dist/dashboard/panels/stats.tsx +60 -32
  26. package/dist/dashboard/protocol-store.ts +25 -8
  27. package/dist/dashboard/vendor/hooks.module.d.ts +146 -0
  28. package/dist/dashboard/vendor/jsx-runtime.d.ts +55 -0
  29. package/dist/dashboard/vendor/jsx.d.ts +3123 -0
  30. package/dist/dashboard/vendor/preact.module.d.ts +397 -0
  31. package/dist/devtools-client.d.ts +312 -300
  32. package/dist/devtools-client.d.ts.map +1 -0
  33. package/dist/devtools-client.js +866 -838
  34. package/dist/devtools-client.js.map +1 -1
  35. package/dist/index.d.ts +6 -8
  36. package/dist/index.js +5 -12
  37. package/dist/perf-trace.d.ts +6 -4
  38. package/dist/perf-trace.d.ts.map +1 -0
  39. package/dist/perf-trace.js +80 -66
  40. package/dist/perf-trace.js.map +1 -1
  41. package/dist/plugins.d.ts +6 -6
  42. package/dist/plugins.d.ts.map +1 -0
  43. package/dist/plugins.js +5 -5
  44. package/dist/plugins.js.map +1 -1
  45. package/dist/provider-switcher.d.ts +8 -15
  46. package/dist/provider-switcher.d.ts.map +1 -0
  47. package/dist/provider-switcher.js +68 -68
  48. package/dist/provider-switcher.js.map +1 -1
  49. package/dist/react/devtools-provider.d.ts +11 -10
  50. package/dist/react/devtools-provider.d.ts.map +1 -0
  51. package/dist/react/devtools-provider.js +60 -32
  52. package/dist/react/devtools-provider.js.map +1 -1
  53. package/dist/react/use-fps-graph.d.ts +7 -7
  54. package/dist/react/use-fps-graph.d.ts.map +1 -0
  55. package/dist/react/use-fps-graph.js +27 -21
  56. package/dist/react/use-fps-graph.js.map +1 -1
  57. package/dist/react/use-pane-button.d.ts +4 -4
  58. package/dist/react/use-pane-button.d.ts.map +1 -0
  59. package/dist/react/use-pane-button.js +35 -30
  60. package/dist/react/use-pane-button.js.map +1 -1
  61. package/dist/react/use-pane-folder.d.ts +5 -4
  62. package/dist/react/use-pane-folder.d.ts.map +1 -0
  63. package/dist/react/use-pane-folder.js +33 -20
  64. package/dist/react/use-pane-folder.js.map +1 -1
  65. package/dist/react/use-pane-input.d.ts +31 -30
  66. package/dist/react/use-pane-input.d.ts.map +1 -0
  67. package/dist/react/use-pane-input.js +46 -42
  68. package/dist/react/use-pane-input.js.map +1 -1
  69. package/dist/react/use-pane-radio-grid.d.ts +20 -20
  70. package/dist/react/use-pane-radio-grid.d.ts.map +1 -0
  71. package/dist/react/use-pane-radio-grid.js +72 -50
  72. package/dist/react/use-pane-radio-grid.js.map +1 -1
  73. package/dist/react/use-pane.d.ts +4 -4
  74. package/dist/react/use-pane.d.ts.map +1 -0
  75. package/dist/react/use-pane.js +52 -17
  76. package/dist/react/use-pane.js.map +1 -1
  77. package/dist/react.d.ts +10 -12
  78. package/dist/react.js +2 -12
  79. package/dist/registry-view.d.ts +8 -21
  80. package/dist/registry-view.d.ts.map +1 -0
  81. package/dist/registry-view.js +357 -338
  82. package/dist/registry-view.js.map +1 -1
  83. package/dist/relay.d.ts +16 -0
  84. package/dist/relay.d.ts.map +1 -0
  85. package/dist/relay.js +189 -0
  86. package/dist/relay.js.map +1 -0
  87. package/dist/remote.d.ts +10 -0
  88. package/dist/remote.d.ts.map +1 -0
  89. package/dist/remote.js +28 -0
  90. package/dist/remote.js.map +1 -0
  91. package/dist/stats-graph.d.ts +23 -31
  92. package/dist/stats-graph.d.ts.map +1 -0
  93. package/dist/stats-graph.js +323 -264
  94. package/dist/stats-graph.js.map +1 -1
  95. package/dist/stats-row.d.ts +8 -21
  96. package/dist/stats-row.d.ts.map +1 -0
  97. package/dist/stats-row.js +99 -101
  98. package/dist/stats-row.js.map +1 -1
  99. package/dist/theme.d.ts +3 -1
  100. package/dist/theme.d.ts.map +1 -0
  101. package/dist/theme.js +43 -54
  102. package/dist/theme.js.map +1 -1
  103. package/dist/vite-plugin.d.ts +7 -6
  104. package/dist/vite-plugin.d.ts.map +1 -0
  105. package/dist/vite-plugin.js +87 -78
  106. package/dist/vite-plugin.js.map +1 -1
  107. package/package.json +33 -29
  108. package/dist/buffers-modal.cjs +0 -491
  109. package/dist/buffers-modal.cjs.map +0 -1
  110. package/dist/buffers-modal.d.cts +0 -62
  111. package/dist/buffers-view.cjs +0 -269
  112. package/dist/buffers-view.cjs.map +0 -1
  113. package/dist/buffers-view.d.cts +0 -39
  114. package/dist/create-pane.cjs +0 -203
  115. package/dist/create-pane.cjs.map +0 -1
  116. package/dist/create-pane.d.cts +0 -66
  117. package/dist/devtools-client.cjs +0 -870
  118. package/dist/devtools-client.cjs.map +0 -1
  119. package/dist/devtools-client.d.cts +0 -362
  120. package/dist/index.cjs +0 -42
  121. package/dist/index.cjs.map +0 -1
  122. package/dist/index.d.cts +0 -8
  123. package/dist/index.js.map +0 -1
  124. package/dist/perf-trace.cjs +0 -103
  125. package/dist/perf-trace.cjs.map +0 -1
  126. package/dist/perf-trace.d.cts +0 -27
  127. package/dist/plugins.cjs +0 -44
  128. package/dist/plugins.cjs.map +0 -1
  129. package/dist/plugins.d.cts +0 -7
  130. package/dist/provider-switcher.cjs +0 -95
  131. package/dist/provider-switcher.cjs.map +0 -1
  132. package/dist/provider-switcher.d.cts +0 -18
  133. package/dist/react/devtools-provider.cjs +0 -59
  134. package/dist/react/devtools-provider.cjs.map +0 -1
  135. package/dist/react/devtools-provider.d.cts +0 -39
  136. package/dist/react/use-fps-graph.cjs +0 -49
  137. package/dist/react/use-fps-graph.cjs.map +0 -1
  138. package/dist/react/use-fps-graph.d.cts +0 -15
  139. package/dist/react/use-pane-button.cjs +0 -58
  140. package/dist/react/use-pane-button.cjs.map +0 -1
  141. package/dist/react/use-pane-button.d.cts +0 -10
  142. package/dist/react/use-pane-folder.cjs +0 -48
  143. package/dist/react/use-pane-folder.cjs.map +0 -1
  144. package/dist/react/use-pane-folder.d.cts +0 -15
  145. package/dist/react/use-pane-input.cjs +0 -70
  146. package/dist/react/use-pane-input.cjs.map +0 -1
  147. package/dist/react/use-pane-input.d.cts +0 -44
  148. package/dist/react/use-pane-radio-grid.cjs +0 -78
  149. package/dist/react/use-pane-radio-grid.cjs.map +0 -1
  150. package/dist/react/use-pane-radio-grid.d.cts +0 -35
  151. package/dist/react/use-pane.cjs +0 -45
  152. package/dist/react/use-pane.cjs.map +0 -1
  153. package/dist/react/use-pane.d.cts +0 -40
  154. package/dist/react.cjs +0 -50
  155. package/dist/react.cjs.map +0 -1
  156. package/dist/react.d.cts +0 -12
  157. package/dist/react.js.map +0 -1
  158. package/dist/registry-view.cjs +0 -371
  159. package/dist/registry-view.cjs.map +0 -1
  160. package/dist/registry-view.d.cts +0 -24
  161. package/dist/stats-graph.cjs +0 -297
  162. package/dist/stats-graph.cjs.map +0 -1
  163. package/dist/stats-graph.d.cts +0 -40
  164. package/dist/stats-row.cjs +0 -153
  165. package/dist/stats-row.cjs.map +0 -1
  166. package/dist/stats-row.d.cts +0 -24
  167. package/dist/theme.cjs +0 -260
  168. package/dist/theme.cjs.map +0 -1
  169. package/dist/theme.d.cts +0 -10
  170. package/dist/vite-plugin.cjs +0 -113
  171. package/dist/vite-plugin.cjs.map +0 -1
  172. package/dist/vite-plugin.d.cts +0 -9
@@ -1,852 +1,880 @@
1
- import {
2
- ACK_INTERVAL_MS,
3
- DEBUG_PROTOCOL_VERSION,
4
- DISCOVERY_CHANNEL,
5
- SERVER_LIVENESS_MS,
6
- providerChannelName
7
- } from "three-flatland/debug-protocol";
8
1
  import { tracePerf } from "./perf-trace.js";
2
+ import { ACK_INTERVAL_MS, DEBUG_PROTOCOL_VERSION, DISCOVERY_CHANNEL, SERVER_LIVENESS_MS, providerChannelName } from "three-flatland/debug-protocol";
3
+ //#region src/devtools-client.ts
4
+ /**
5
+ * Discovery retry backoff. Starts at `QUERY_RETRY_MIN_MS`, doubles each
6
+ * attempt, caps at `QUERY_RETRY_MAX_MS`, and gives up after `QUERY_MAX_RETRIES`
7
+ * total tries. After giving up, a provider that comes online later will
8
+ * still wire us up via its own startup `provider:announce`.
9
+ */
9
10
  const QUERY_RETRY_MIN_MS = 500;
10
11
  const QUERY_RETRY_MAX_MS = 5e3;
11
12
  const QUERY_MAX_RETRIES = 10;
13
+ /**
14
+ * Size of the client-side decoded series rings. Sized generously so
15
+ * downstream consumers (graphs, percentile detail panels) have plenty
16
+ * of history across both 4 Hz batch and 60 Hz sample cadences. 1024 ×
17
+ * Float32 × ~9 fields ≈ 36 KB total — negligible.
18
+ */
12
19
  const CLIENT_SERIES_SIZE = 1024;
13
- const EMPTY_SAMPLE = new Float32Array(0);
14
- class DevtoolsClient {
15
- id;
16
- state;
17
- /** Shared discovery bus — carries query/announce/gone only. */
18
- _discoveryBus;
19
- /** Per-provider data bus. Opened when we subscribe; closed on switch / gone. */
20
- _dataBus = null;
21
- /** Bound handler for the current `_dataBus`. Tracked so we can detach on close. */
22
- _dataHandler = null;
23
- _features;
24
- /**
25
- * Registry entry filter. `null` = all entries; `string[]` = only
26
- * these. Starts empty-array so providers don't drain (sometimes
27
- * expensive) registry payloads until the pane actually needs them.
28
- */
29
- _registrySelection = [];
30
- /**
31
- * Buffer subscription. Map of entry-name → { mode, thumbSize? }.
32
- * Empty map = metadata-only (consumer is connected to the `buffers`
33
- * feature but isn't actually watching anything — provider skips all
34
- * readbacks). `null` is not a distinct state; represented by `{}`.
35
- */
36
- _buffersSelection = {};
37
- _listeners = /* @__PURE__ */ new Set();
38
- _chunkListeners = /* @__PURE__ */ new Set();
39
- _rawMessageListeners = /* @__PURE__ */ new Set();
40
- _ackTimer = null;
41
- _livenessTimer = null;
42
- _queryRetryTimer = null;
43
- _lastServerAt = 0;
44
- _subscribed = false;
45
- _disposed = false;
46
- /** Known providers by id updated live via `provider:announce` + `provider:gone`. */
47
- _providers = /* @__PURE__ */ new Map();
48
- constructor(options) {
49
- this.id = generateUuid();
50
- this._features = [...options.features];
51
- if (options.onChange) this._listeners.add(options.onChange);
52
- this._discoveryBus = new BroadcastChannel(options.discoveryChannelName ?? DISCOVERY_CHANNEL);
53
- const mkSeries = () => ({
54
- data: new Float32Array(CLIENT_SERIES_SIZE),
55
- write: 0,
56
- length: 0
57
- });
58
- this.state = {
59
- series: {
60
- fps: mkSeries(),
61
- cpuMs: mkSeries(),
62
- gpuMs: mkSeries(),
63
- heapUsedMB: mkSeries(),
64
- drawCalls: mkSeries(),
65
- triangles: mkSeries(),
66
- primitives: mkSeries(),
67
- geometries: mkSeries(),
68
- textures: mkSeries()
69
- },
70
- registry: /* @__PURE__ */ new Map(),
71
- buffers: /* @__PURE__ */ new Map(),
72
- batches: { frame: 0, passes: [], batches: [] },
73
- providers: [],
74
- selectedProviderId: null,
75
- serverAlive: false,
76
- serverLagMs: 0
77
- };
78
- this._discoveryBus.addEventListener("message", (ev) => {
79
- this._onDiscoveryMessage(ev.data);
80
- });
81
- }
82
- /**
83
- * Begin discovery + subscription. Sends a `provider:query`, waits
84
- * `DISCOVERY_WINDOW_MS` for `provider:announce` responses, then picks
85
- * the best provider (user > system) and subscribes to it.
86
- *
87
- * Idempotent — calling again while already started is a no-op.
88
- */
89
- start() {
90
- if (this._disposed || this._subscribed) return;
91
- this._subscribed = true;
92
- this._sendQuery();
93
- let retries = 0;
94
- let nextDelay = QUERY_RETRY_MIN_MS;
95
- const tick = () => {
96
- if (this._disposed || this.state.selectedProviderId !== null) {
97
- this._queryRetryTimer = null;
98
- return;
99
- }
100
- if (retries >= QUERY_MAX_RETRIES) {
101
- this._queryRetryTimer = null;
102
- return;
103
- }
104
- retries++;
105
- this._sendQuery();
106
- nextDelay = Math.min(nextDelay * 2, QUERY_RETRY_MAX_MS);
107
- this._queryRetryTimer = setTimeout(tick, nextDelay);
108
- };
109
- this._queryRetryTimer = setTimeout(tick, nextDelay);
110
- this._livenessTimer = setInterval(() => this._checkLiveness(), 1e3);
111
- }
112
- _sendQuery() {
113
- this._postDiscovery({
114
- type: "provider:query",
115
- payload: { requesterId: this.id }
116
- });
117
- }
118
- /**
119
- * Update the feature set. Re-posts `subscribe` on the current
120
- * provider's data channel.
121
- */
122
- setFeatures(features) {
123
- if (sameSet(this._features, features)) return;
124
- this._features = [...features];
125
- this._resubscribe();
126
- }
127
- /**
128
- * Update the registry entry filter. Pass `null` for "every entry",
129
- * `[]` to stop all registry traffic, or a list of names to narrow.
130
- * Re-posts `subscribe` if the filter actually changed.
131
- */
132
- /**
133
- * Narrow which registry entries the provider should ship samples
134
- * for. `null` = all entries; `[]` = none; `[name, …]` = only these.
135
- * Metadata still flows regardless — only sample bytes are gated.
136
- */
137
- setRegistry(names) {
138
- if (sameFilter(this._registrySelection, names)) return;
139
- this._registrySelection = names === null ? null : [...names];
140
- this._resubscribe();
141
- }
142
- /**
143
- * Update the buffer subscription. Map of entry-name (mode, thumbSize?).
144
- * - Empty map / missing names → metadata-only (provider sends no pixels,
145
- * runs no readbacks). This is the idle state when no preview or
146
- * modal is visible.
147
- * - `{ name: { mode: 'thumbnail', thumbSize: 256 } }` → small
148
- * downsampled preview. Use when a thumbnail card is visible.
149
- * - `{ name: { mode: 'stream' } }` → full-size VP9 video stream.
150
- * Use when the fullscreen modal is open.
151
- *
152
- * Mode changes (incl. unsubscribing) take effect on the next
153
- * provider flush; the producer will drop old readbacks immediately.
154
- */
155
- setBuffers(subscription) {
156
- if (sameBufferSubscription(this._buffersSelection, subscription)) return;
157
- this._buffersSelection = { ...subscription };
158
- this._resubscribe();
159
- }
160
- _resubscribe() {
161
- if (this._subscribed && this._dataBus !== null) {
162
- const hasBuffers = Object.keys(this._buffersSelection).length > 0;
163
- this._postData({
164
- type: "subscribe",
165
- payload: {
166
- id: this.id,
167
- features: this._features,
168
- registry: this._registrySelection ?? void 0,
169
- buffers: hasBuffers ? this._buffersSelection : void 0
170
- }
171
- });
172
- }
173
- }
174
- /**
175
- * Manually switch to a different provider. No-op if unknown or if
176
- * already selected. Closes the old data channel and opens the new one.
177
- */
178
- selectProvider(providerId) {
179
- if (!this._providers.has(providerId)) return;
180
- if (this.state.selectedProviderId === providerId) return;
181
- this._leaveDataChannel();
182
- this.state.selectedProviderId = providerId;
183
- this._resetAccumulatedState();
184
- this._joinDataChannel(providerId);
185
- this._postData({
186
- type: "subscribe",
187
- payload: {
188
- id: this.id,
189
- features: this._features,
190
- registry: this._registrySelection ?? void 0,
191
- buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
192
- }
193
- });
194
- this._fire();
195
- }
196
- dispose() {
197
- if (this._disposed) return;
198
- this._disposed = true;
199
- this._leaveDataChannel();
200
- this._subscribed = false;
201
- if (this._ackTimer !== null) {
202
- clearInterval(this._ackTimer);
203
- this._ackTimer = null;
204
- }
205
- if (this._livenessTimer !== null) {
206
- clearInterval(this._livenessTimer);
207
- this._livenessTimer = null;
208
- }
209
- if (this._queryRetryTimer !== null) {
210
- clearTimeout(this._queryRetryTimer);
211
- this._queryRetryTimer = null;
212
- }
213
- try {
214
- this._discoveryBus.close();
215
- } catch {
216
- }
217
- }
218
- /**
219
- * Open a fresh per-provider data channel and start listening on it.
220
- * Caller is responsible for posting the initial `subscribe`.
221
- */
222
- _joinDataChannel(providerId) {
223
- this._dataBus = new BroadcastChannel(providerChannelName(providerId));
224
- this._dataHandler = (ev) => {
225
- this._onDataMessage(ev.data);
226
- };
227
- this._dataBus.addEventListener("message", this._dataHandler);
228
- }
229
- /**
230
- * Send `unsubscribe` (if we have someone to tell) and close the data
231
- * channel. Idempotent — safe to call when there's no active channel.
232
- */
233
- _leaveDataChannel() {
234
- if (this._dataBus !== null) {
235
- if (this._subscribed) {
236
- try {
237
- this._postData({ type: "unsubscribe", payload: { id: this.id } });
238
- } catch {
239
- }
240
- }
241
- if (this._dataHandler !== null) {
242
- try {
243
- this._dataBus.removeEventListener("message", this._dataHandler);
244
- } catch {
245
- }
246
- }
247
- try {
248
- this._dataBus.close();
249
- } catch {
250
- }
251
- this._dataBus = null;
252
- this._dataHandler = null;
253
- }
254
- }
255
- // ── Internal ──────────────────────────────────────────────────────────
256
- /**
257
- * Handler for the shared discovery bus. Only discovery messages land
258
- * here by protocol; anything else is ignored.
259
- */
260
- _onDiscoveryMessage(msg) {
261
- if (!msg || typeof msg !== "object" || !("type" in msg)) return;
262
- tracePerf(msg);
263
- switch (msg.type) {
264
- case "provider:announce": {
265
- const id = msg.payload.identity.id;
266
- this._providers.set(id, msg.payload.identity);
267
- this.state.providers = Array.from(this._providers.values());
268
- this._fire();
269
- if (this.state.selectedProviderId === null) this._pickProviderAndSubscribe();
270
- break;
271
- }
272
- case "provider:gone": {
273
- const id = msg.payload.id;
274
- if (!this._providers.has(id)) return;
275
- this._providers.delete(id);
276
- this.state.providers = Array.from(this._providers.values());
277
- if (this.state.selectedProviderId === id) {
278
- this._leaveDataChannel();
279
- this.state.selectedProviderId = null;
280
- this._resetAccumulatedState();
281
- this._pickProviderAndSubscribe();
282
- }
283
- this._fire();
284
- break;
285
- }
286
- default:
287
- break;
288
- }
289
- }
290
- /**
291
- * Handler for the per-provider data channel. Everything here is
292
- * already implicitly addressed to us (we opened the channel with the
293
- * provider's id), so no per-message filtering is required beyond
294
- * matching our consumer `id` on `subscribe:ack`.
295
- */
296
- _onDataMessage(msg) {
297
- if (!msg || typeof msg !== "object" || !("type" in msg)) return;
298
- tracePerf(msg);
299
- if (this._rawMessageListeners.size > 0) {
300
- for (const cb of this._rawMessageListeners) {
301
- try {
302
- cb(msg, "in");
303
- } catch {
304
- }
305
- }
306
- }
307
- switch (msg.type) {
308
- case "subscribe:ack": {
309
- if (msg.payload.id !== this.id) return;
310
- this._markServerAlive();
311
- this._applyEnv(msg.payload.env);
312
- if (this._ackTimer === null) {
313
- this._ackTimer = setInterval(() => this._sendAck(), ACK_INTERVAL_MS);
314
- }
315
- this._fire();
316
- break;
317
- }
318
- case "data": {
319
- this._markServerAlive();
320
- this.state.frame = msg.payload.frame;
321
- const features = msg.payload.features;
322
- if (features.stats !== void 0) this._applyStats(features.stats);
323
- if (features.env !== void 0) this._applyEnv(features.env);
324
- if (features.registry !== void 0) this._applyRegistry(features.registry);
325
- if (features.buffers !== void 0) this._applyBuffers(features.buffers);
326
- if (features.batches !== void 0) this._applyBatches(features.batches);
327
- this._fire();
328
- break;
329
- }
330
- case "buffer:chunk": {
331
- this._markServerAlive();
332
- const payload = msg.payload;
333
- for (const cb of this._chunkListeners) {
334
- try {
335
- cb(payload);
336
- } catch {
337
- }
338
- }
339
- break;
340
- }
341
- case "buffer:raw": {
342
- this._markServerAlive();
343
- const payload = msg.payload;
344
- let snap = this.state.buffers.get(payload.name);
345
- if (snap !== void 0) {
346
- snap.pixels = new Uint8Array(payload.data);
347
- snap.width = payload.width;
348
- snap.height = payload.height;
349
- snap.version++;
350
- } else {
351
- snap = {
352
- name: payload.name,
353
- width: payload.width,
354
- height: payload.height,
355
- srcWidth: payload.width,
356
- srcHeight: payload.height,
357
- pixelType: "rgba8",
358
- display: "colors",
359
- version: 0,
360
- pixels: new Uint8Array(payload.data)
361
- };
362
- this.state.buffers.set(payload.name, snap);
363
- }
364
- this._fire();
365
- break;
366
- }
367
- case "ping": {
368
- this._markServerAlive();
369
- break;
370
- }
371
- default:
372
- break;
373
- }
374
- }
375
- _markServerAlive() {
376
- this._lastServerAt = Date.now();
377
- if (!this.state.serverAlive) {
378
- this.state.serverAlive = true;
379
- this._fire();
380
- }
381
- }
382
- /**
383
- * Pick the best provider from the currently-known set and subscribe
384
- * to it. Preference: `user` over `system`; first-announced as
385
- * tiebreak. No-op if zero providers are known (we'll stay waiting;
386
- * any future `provider:announce` that arrives doesn't auto-trigger
387
- * this call it again or restart discovery).
388
- */
389
- _pickProviderAndSubscribe() {
390
- if (this.state.selectedProviderId !== null) return;
391
- const providers = Array.from(this._providers.values());
392
- if (providers.length === 0) return;
393
- const user = providers.find((p) => p.kind === "user");
394
- const chosen = user ?? providers[0];
395
- this.state.selectedProviderId = chosen.id;
396
- this._joinDataChannel(chosen.id);
397
- this._postData({
398
- type: "subscribe",
399
- payload: {
400
- id: this.id,
401
- features: this._features,
402
- registry: this._registrySelection ?? void 0,
403
- buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
404
- }
405
- });
406
- this._fire();
407
- }
408
- /** Clear all feature-derived state so the next data packet can start fresh. */
409
- _resetAccumulatedState() {
410
- this.state.frame = void 0;
411
- this._applyStats(null);
412
- this._applyEnv(null);
413
- this.state.registry.clear();
414
- this.state.buffers.clear();
415
- this._applyBatches(null);
416
- }
417
- /**
418
- * Apply a stats batch. Null = reset (feature cleared / provider gone).
419
- * Otherwise: decode each typed array onto the matching Float32 ring
420
- * and update the scalar with the batch mean (natural smoothing for
421
- * the text label).
422
- */
423
- _applyStats(batch) {
424
- if (batch === null) {
425
- this.state.drawCalls = void 0;
426
- this.state.triangles = void 0;
427
- this.state.primitives = void 0;
428
- this.state.geometries = void 0;
429
- this.state.textures = void 0;
430
- this.state.cpuMs = void 0;
431
- this.state.fps = void 0;
432
- this.state.gpuMs = void 0;
433
- this.state.heapUsedMB = void 0;
434
- this.state.heapLimitMB = void 0;
435
- const s2 = this.state.series;
436
- s2.fps.write = 0;
437
- s2.fps.length = 0;
438
- s2.cpuMs.write = 0;
439
- s2.cpuMs.length = 0;
440
- s2.gpuMs.write = 0;
441
- s2.gpuMs.length = 0;
442
- s2.heapUsedMB.write = 0;
443
- s2.heapUsedMB.length = 0;
444
- s2.drawCalls.write = 0;
445
- s2.drawCalls.length = 0;
446
- s2.triangles.write = 0;
447
- s2.triangles.length = 0;
448
- s2.primitives.write = 0;
449
- s2.primitives.length = 0;
450
- s2.geometries.write = 0;
451
- s2.geometries.length = 0;
452
- s2.textures.write = 0;
453
- s2.textures.length = 0;
454
- return;
455
- }
456
- const count = batch.count;
457
- if (count <= 0) return;
458
- const s = this.state.series;
459
- if (batch.fps) this.state.fps = this._ingestI16(s.fps, batch.fps, count, 0.1);
460
- if (batch.cpuMs) this.state.cpuMs = this._ingestU16(s.cpuMs, batch.cpuMs, count, 0.01);
461
- if (batch.gpuMs) this.state.gpuMs = this._ingestU16(s.gpuMs, batch.gpuMs, count, 0.01);
462
- if (batch.heapUsedMB) this.state.heapUsedMB = this._ingestU16(s.heapUsedMB, batch.heapUsedMB, count, 1);
463
- if (batch.drawCalls) this.state.drawCalls = this._ingestU32(s.drawCalls, batch.drawCalls, count);
464
- if (batch.triangles) this.state.triangles = this._ingestU32(s.triangles, batch.triangles, count);
465
- if (batch.primitives) this.state.primitives = this._ingestU32(s.primitives, batch.primitives, count);
466
- if (batch.geometries) this.state.geometries = this._ingestU32(s.geometries, batch.geometries, count);
467
- if (batch.textures) this.state.textures = this._ingestU32(s.textures, batch.textures, count);
468
- if (batch.heapLimitMB !== void 0) this.state.heapLimitMB = batch.heapLimitMB;
469
- }
470
- /**
471
- * Append `count` samples from a scaled integer view to a Float32 ring;
472
- * return the batch mean (scaled). Zero-alloc past the ring itself.
473
- */
474
- _ingestI16(ring, src, count, scale) {
475
- const size = ring.data.length;
476
- let sum = 0;
477
- let w = ring.write;
478
- for (let i = 0; i < count; i++) {
479
- const v = src[i] * scale;
480
- ring.data[w] = v;
481
- sum += v;
482
- w = (w + 1) % size;
483
- }
484
- ring.write = w;
485
- ring.length = Math.min(size, ring.length + count);
486
- return sum / count;
487
- }
488
- _ingestU16(ring, src, count, scale) {
489
- const size = ring.data.length;
490
- let sum = 0;
491
- let w = ring.write;
492
- for (let i = 0; i < count; i++) {
493
- const v = src[i] * scale;
494
- ring.data[w] = v;
495
- sum += v;
496
- w = (w + 1) % size;
497
- }
498
- ring.write = w;
499
- ring.length = Math.min(size, ring.length + count);
500
- return sum / count;
501
- }
502
- _ingestU32(ring, src, count) {
503
- const size = ring.data.length;
504
- let sum = 0;
505
- let w = ring.write;
506
- for (let i = 0; i < count; i++) {
507
- const v = src[i];
508
- ring.data[w] = v;
509
- sum += v;
510
- w = (w + 1) % size;
511
- }
512
- ring.write = w;
513
- ring.length = Math.min(size, ring.length + count);
514
- return sum / count;
515
- }
516
- /**
517
- * Apply a batches feature payload — replaces the snapshot wholesale.
518
- * The wire arrays are scratch pools on the producer; we truncate by
519
- * the provided counts and copy fields into persistent snapshot
520
- * objects the UI can hold across subsequent frames.
521
- *
522
- * The client-side snapshot arrays grow monotonically to the high
523
- * watermark and entries are overwritten in place — same alloc
524
- * discipline as the producer.
525
- */
526
- _applyBatches(delta) {
527
- if (delta === null) {
528
- this.state.batches.frame = 0;
529
- this.state.batches.passes.length = 0;
530
- this.state.batches.batches.length = 0;
531
- return;
532
- }
533
- this.state.batches.frame = delta.frame;
534
- const passesIn = delta.passes;
535
- const passCount = delta.passCount | 0;
536
- const passesOut = this.state.batches.passes;
537
- if (passesIn !== void 0) {
538
- for (let i = 0; i < passCount; i++) {
539
- const src = passesIn[i];
540
- if (src === void 0) continue;
541
- let dst = passesOut[i];
542
- if (dst === void 0) {
543
- dst = { label: "", calls: 0, triangles: 0, cpuMs: 0, depth: 0, parent: -1 };
544
- passesOut[i] = dst;
545
- }
546
- dst.label = src.label;
547
- dst.calls = src.calls;
548
- dst.triangles = src.triangles;
549
- dst.cpuMs = src.cpuMs;
550
- dst.depth = src.depth;
551
- dst.parent = src.parent;
552
- }
553
- }
554
- if (passesOut.length > passCount) passesOut.length = passCount;
555
- const batchesIn = delta.batches;
556
- const batchCount = delta.batchCount | 0;
557
- const batchesOut = this.state.batches.batches;
558
- if (batchesIn !== void 0) {
559
- for (let i = 0; i < batchCount; i++) {
560
- const src = batchesIn[i];
561
- if (src === void 0) continue;
562
- let dst = batchesOut[i];
563
- if (dst === void 0) {
564
- dst = {
565
- runKey: 0,
566
- materialId: 0,
567
- layer: 0,
568
- materialName: "",
569
- spriteCount: 0,
570
- batchIdx: 0,
571
- kind: "sprite",
572
- label: ""
573
- };
574
- batchesOut[i] = dst;
575
- }
576
- dst.runKey = src.runKey;
577
- dst.materialId = src.materialId;
578
- dst.layer = src.layer;
579
- dst.materialName = src.materialName;
580
- dst.spriteCount = src.spriteCount;
581
- dst.batchIdx = src.batchIdx;
582
- dst.kind = src.kind ?? "sprite";
583
- dst.label = src.label ?? "";
584
- }
585
- }
586
- if (batchesOut.length > batchCount) batchesOut.length = batchCount;
587
- }
588
- /**
589
- * Apply a registry delta. `entries[name] === null` → remove;
590
- * `entries[name]` present → upsert a snapshot keyed by `name`.
591
- * A `null` batch (feature cleared) drops every entry.
592
- */
593
- _applyRegistry(delta) {
594
- if (delta === null) {
595
- this.state.registry.clear();
596
- return;
597
- }
598
- if (!delta.entries) return;
599
- const entries = delta.entries;
600
- for (const name in entries) {
601
- const d = entries[name];
602
- if (d === void 0) continue;
603
- if (d === null) {
604
- this.state.registry.delete(name);
605
- continue;
606
- }
607
- let snap = this.state.registry.get(name);
608
- const sample = d.sample ?? snap?.sample ?? EMPTY_SAMPLE;
609
- if (snap === void 0) {
610
- snap = {
611
- name,
612
- kind: d.kind,
613
- version: d.version,
614
- count: d.count,
615
- sample,
616
- label: d.label
617
- };
618
- this.state.registry.set(name, snap);
619
- } else {
620
- snap.kind = d.kind;
621
- snap.version = d.version;
622
- snap.count = d.count;
623
- snap.sample = sample;
624
- snap.label = d.label;
625
- }
626
- }
627
- }
628
- /**
629
- * Apply a buffers delta. Metadata (width/height/version/pixelType)
630
- * ships regardless of the client's selection; `pixels` only arrives
631
- * when this entry is in the current selection. Retain the previous
632
- * `pixels` when the delta is metadata-only so the UI keeps showing
633
- * the last thumbnail while browsing.
634
- */
635
- _applyBuffers(delta) {
636
- if (delta === null) {
637
- this.state.buffers.clear();
638
- return;
639
- }
640
- if (!delta.entries) return;
641
- const entries = delta.entries;
642
- for (const name in entries) {
643
- const d = entries[name];
644
- if (d === void 0) continue;
645
- if (d === null) {
646
- this.state.buffers.delete(name);
647
- continue;
648
- }
649
- let snap = this.state.buffers.get(name);
650
- const pixels = d.pixels ?? snap?.pixels ?? null;
651
- const isFloat = d.pixelType === "rgba16f" || d.pixelType === "rgba32f";
652
- const display = d.display ?? (isFloat ? "normalize" : "colors");
653
- const srcW = d.srcWidth ?? d.width;
654
- const srcH = d.srcHeight ?? d.height;
655
- if (snap === void 0) {
656
- snap = {
657
- name,
658
- width: d.width,
659
- height: d.height,
660
- srcWidth: srcW,
661
- srcHeight: srcH,
662
- pixelType: d.pixelType,
663
- display,
664
- version: d.version,
665
- pixels,
666
- label: d.label
667
- };
668
- this.state.buffers.set(name, snap);
669
- } else {
670
- snap.width = d.width;
671
- snap.height = d.height;
672
- snap.srcWidth = srcW;
673
- snap.srcHeight = srcH;
674
- snap.pixelType = d.pixelType;
675
- snap.display = display;
676
- snap.version = d.version;
677
- snap.pixels = pixels;
678
- snap.label = d.label;
679
- }
680
- }
681
- }
682
- _applyEnv(delta) {
683
- if (delta === null) {
684
- this.state.threeFlatlandVersion = void 0;
685
- this.state.threeRevision = void 0;
686
- this.state.backendName = void 0;
687
- this.state.backendTrackTimestamp = void 0;
688
- this.state.backendDisjoint = void 0;
689
- this.state.gpuModeEnabled = void 0;
690
- this.state.canvasWidth = void 0;
691
- this.state.canvasHeight = void 0;
692
- this.state.canvasPixelRatio = void 0;
693
- return;
694
- }
695
- if ("threeFlatlandVersion" in delta) this.state.threeFlatlandVersion = delta.threeFlatlandVersion ?? void 0;
696
- if ("threeRevision" in delta) this.state.threeRevision = delta.threeRevision ?? void 0;
697
- if (delta.backend !== void 0) {
698
- const b = delta.backend;
699
- if (b === null) {
700
- this.state.backendName = void 0;
701
- this.state.backendTrackTimestamp = void 0;
702
- this.state.backendDisjoint = void 0;
703
- this.state.gpuModeEnabled = void 0;
704
- } else {
705
- if ("name" in b) this.state.backendName = b.name ?? void 0;
706
- if ("trackTimestamp" in b) this.state.backendTrackTimestamp = b.trackTimestamp ?? void 0;
707
- if ("disjoint" in b) this.state.backendDisjoint = b.disjoint ?? void 0;
708
- if ("gpuModeEnabled" in b) this.state.gpuModeEnabled = b.gpuModeEnabled ?? void 0;
709
- }
710
- }
711
- if (delta.canvas !== void 0) {
712
- const c = delta.canvas;
713
- if (c === null) {
714
- this.state.canvasWidth = void 0;
715
- this.state.canvasHeight = void 0;
716
- this.state.canvasPixelRatio = void 0;
717
- } else {
718
- if ("width" in c) this.state.canvasWidth = c.width ?? void 0;
719
- if ("height" in c) this.state.canvasHeight = c.height ?? void 0;
720
- if ("pixelRatio" in c) this.state.canvasPixelRatio = c.pixelRatio ?? void 0;
721
- }
722
- }
723
- }
724
- _checkLiveness() {
725
- const now = Date.now();
726
- const lag = this._lastServerAt === 0 ? now : now - this._lastServerAt;
727
- this.state.serverLagMs = lag;
728
- if (this._lastServerAt !== 0 && lag > SERVER_LIVENESS_MS) {
729
- if (this.state.serverAlive) {
730
- this.state.serverAlive = false;
731
- }
732
- if (this._dataBus !== null) {
733
- this._postData({
734
- type: "subscribe",
735
- payload: {
736
- id: this.id,
737
- features: this._features,
738
- registry: this._registrySelection ?? void 0,
739
- buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
740
- }
741
- });
742
- }
743
- }
744
- this._fire();
745
- }
746
- _sendAck() {
747
- if (this._disposed || this._dataBus === null) return;
748
- this._postData({ type: "ack", payload: { id: this.id } });
749
- }
750
- _postDiscovery(body) {
751
- const msg = { v: DEBUG_PROTOCOL_VERSION, ts: Date.now(), ...body };
752
- this._fireRawMessage(msg, "out");
753
- try {
754
- this._discoveryBus.postMessage(msg);
755
- } catch {
756
- }
757
- }
758
- _postData(body) {
759
- if (this._dataBus === null) return;
760
- const msg = { v: DEBUG_PROTOCOL_VERSION, ts: Date.now(), ...body };
761
- this._fireRawMessage(msg, "out");
762
- try {
763
- this._dataBus.postMessage(msg);
764
- } catch {
765
- }
766
- }
767
- _fireRawMessage(msg, direction) {
768
- if (this._rawMessageListeners.size === 0) return;
769
- for (const cb of this._rawMessageListeners) {
770
- try {
771
- cb(msg, direction);
772
- } catch {
773
- }
774
- }
775
- }
776
- /** Subscribe to state-change events. Returns an unsubscribe function. */
777
- addListener(cb) {
778
- this._listeners.add(cb);
779
- return () => {
780
- this._listeners.delete(cb);
781
- };
782
- }
783
- /** Explicit remove — equivalent to calling the unsubscribe returned from `addListener`. */
784
- removeListener(cb) {
785
- this._listeners.delete(cb);
786
- }
787
- /** Subscribe to incoming WebCodecs buffer chunks. Returns an unsubscribe function. */
788
- addChunkListener(cb) {
789
- this._chunkListeners.add(cb);
790
- return () => {
791
- this._chunkListeners.delete(cb);
792
- };
793
- }
794
- /**
795
- * Subscribe to every bus message — both inbound (from providers) and
796
- * outbound (our own `subscribe`/`ack`/etc.). Used by the dashboard's
797
- * protocol-log panel. Listeners fire on the hot path so keep them
798
- * cheap — filter and format lazily.
799
- */
800
- addRawMessageListener(cb) {
801
- this._rawMessageListeners.add(cb);
802
- return () => {
803
- this._rawMessageListeners.delete(cb);
804
- };
805
- }
806
- _fire() {
807
- for (const cb of this._listeners) {
808
- try {
809
- cb(this.state);
810
- } catch {
811
- }
812
- }
813
- }
814
- }
20
+ /** Shared zero-length placeholder used for metadata-only registry snapshots. */
21
+ const EMPTY_SAMPLE = /* @__PURE__ */ new Float32Array(0);
22
+ /**
23
+ * Bus consumer. One per viewing surface (tweakpane panel, pop-out
24
+ * window, remote dashboard). Owns:
25
+ *
26
+ * - A stable consumer id (UUID v4).
27
+ * - A `BroadcastChannel` subscription.
28
+ * - Accumulated `DevtoolsState` derived from `data` packet deltas.
29
+ * - Ack timer (1 s, starts on `subscribe:ack`).
30
+ * - Server-liveness monitor; re-subscribes if no server message
31
+ * within `SERVER_LIVENESS_MS`.
32
+ *
33
+ * Call `start()` to send the initial subscribe + begin timers.
34
+ * `dispose()` sends unsubscribe, clears timers, closes the channel.
35
+ */
36
+ var DevtoolsClient = class {
37
+ id;
38
+ state;
39
+ /** Shared discovery bus carries query/announce/gone only. */
40
+ _discoveryBus;
41
+ /** Per-provider data bus. Opened when we subscribe; closed on switch / gone. */
42
+ _dataBus = null;
43
+ /** Bound handler for the current `_dataBus`. Tracked so we can detach on close. */
44
+ _dataHandler = null;
45
+ _features;
46
+ /**
47
+ * Registry entry filter. `null` = all entries; `string[]` = only
48
+ * these. Starts empty-array so providers don't drain (sometimes
49
+ * expensive) registry payloads until the pane actually needs them.
50
+ */
51
+ _registrySelection = [];
52
+ /**
53
+ * Buffer subscription. Map of entry-name { mode, thumbSize? }.
54
+ * Empty map = metadata-only (consumer is connected to the `buffers`
55
+ * feature but isn't actually watching anything — provider skips all
56
+ * readbacks). `null` is not a distinct state; represented by `{}`.
57
+ */
58
+ _buffersSelection = {};
59
+ _listeners = /* @__PURE__ */ new Set();
60
+ _chunkListeners = /* @__PURE__ */ new Set();
61
+ _rawMessageListeners = /* @__PURE__ */ new Set();
62
+ _ackTimer = null;
63
+ _livenessTimer = null;
64
+ _queryRetryTimer = null;
65
+ _lastServerAt = 0;
66
+ _subscribed = false;
67
+ _disposed = false;
68
+ /** Known providers by id — updated live via `provider:announce` + `provider:gone`. */
69
+ _providers = /* @__PURE__ */ new Map();
70
+ constructor(options) {
71
+ this.id = generateUuid();
72
+ this._features = [...options.features];
73
+ if (options.onChange) this._listeners.add(options.onChange);
74
+ this._discoveryBus = new BroadcastChannel(options.discoveryChannelName ?? DISCOVERY_CHANNEL);
75
+ const mkSeries = () => ({
76
+ data: new Float32Array(CLIENT_SERIES_SIZE),
77
+ write: 0,
78
+ length: 0
79
+ });
80
+ this.state = {
81
+ series: {
82
+ fps: mkSeries(),
83
+ cpuMs: mkSeries(),
84
+ gpuMs: mkSeries(),
85
+ heapUsedMB: mkSeries(),
86
+ drawCalls: mkSeries(),
87
+ triangles: mkSeries(),
88
+ primitives: mkSeries(),
89
+ geometries: mkSeries(),
90
+ textures: mkSeries(),
91
+ frames: {
92
+ data: new Uint32Array(CLIENT_SERIES_SIZE),
93
+ write: 0,
94
+ length: 0
95
+ }
96
+ },
97
+ registry: /* @__PURE__ */ new Map(),
98
+ buffers: /* @__PURE__ */ new Map(),
99
+ batches: {
100
+ frame: 0,
101
+ passes: [],
102
+ batches: []
103
+ },
104
+ providers: [],
105
+ selectedProviderId: null,
106
+ serverAlive: false,
107
+ serverLagMs: 0
108
+ };
109
+ this._discoveryBus.addEventListener("message", (ev) => {
110
+ this._onDiscoveryMessage(ev.data);
111
+ });
112
+ }
113
+ /**
114
+ * Begin discovery + subscription. Sends a `provider:query`, waits
115
+ * `DISCOVERY_WINDOW_MS` for `provider:announce` responses, then picks
116
+ * the best provider (user > system) and subscribes to it.
117
+ *
118
+ * Idempotent — calling again while already started is a no-op.
119
+ */
120
+ start() {
121
+ if (this._disposed || this._subscribed) return;
122
+ this._subscribed = true;
123
+ this._sendQuery();
124
+ let retries = 0;
125
+ let nextDelay = QUERY_RETRY_MIN_MS;
126
+ const tick = () => {
127
+ if (this._disposed || this.state.selectedProviderId !== null) {
128
+ this._queryRetryTimer = null;
129
+ return;
130
+ }
131
+ if (retries >= QUERY_MAX_RETRIES) {
132
+ this._queryRetryTimer = null;
133
+ return;
134
+ }
135
+ retries++;
136
+ this._sendQuery();
137
+ nextDelay = Math.min(nextDelay * 2, QUERY_RETRY_MAX_MS);
138
+ this._queryRetryTimer = setTimeout(tick, nextDelay);
139
+ };
140
+ this._queryRetryTimer = setTimeout(tick, nextDelay);
141
+ this._livenessTimer = setInterval(() => this._checkLiveness(), 1e3);
142
+ }
143
+ _sendQuery() {
144
+ this._postDiscovery({
145
+ type: "provider:query",
146
+ payload: { requesterId: this.id }
147
+ });
148
+ }
149
+ /**
150
+ * Update the feature set. Re-posts `subscribe` on the current
151
+ * provider's data channel.
152
+ */
153
+ setFeatures(features) {
154
+ if (sameSet(this._features, features)) return;
155
+ this._features = [...features];
156
+ this._resubscribe();
157
+ }
158
+ /**
159
+ * Update the registry entry filter. Pass `null` for "every entry",
160
+ * `[]` to stop all registry traffic, or a list of names to narrow.
161
+ * Re-posts `subscribe` if the filter actually changed.
162
+ */
163
+ /**
164
+ * Narrow which registry entries the provider should ship samples
165
+ * for. `null` = all entries; `[]` = none; `[name, …]` = only these.
166
+ * Metadata still flows regardless — only sample bytes are gated.
167
+ */
168
+ setRegistry(names) {
169
+ if (sameFilter(this._registrySelection, names)) return;
170
+ this._registrySelection = names === null ? null : [...names];
171
+ this._resubscribe();
172
+ }
173
+ /**
174
+ * Update the buffer subscription. Map of entry-name → (mode, thumbSize?).
175
+ * - Empty map / missing names → metadata-only (provider sends no pixels,
176
+ * runs no readbacks). This is the idle state when no preview or
177
+ * modal is visible.
178
+ * - `{ name: { mode: 'thumbnail', thumbSize: 256 } }` → small
179
+ * downsampled preview. Use when a thumbnail card is visible.
180
+ * - `{ name: { mode: 'stream' } }` → full-size VP9 video stream.
181
+ * Use when the fullscreen modal is open.
182
+ *
183
+ * Mode changes (incl. unsubscribing) take effect on the next
184
+ * provider flush; the producer will drop old readbacks immediately.
185
+ */
186
+ setBuffers(subscription) {
187
+ if (sameBufferSubscription(this._buffersSelection, subscription)) return;
188
+ this._buffersSelection = { ...subscription };
189
+ this._resubscribe();
190
+ }
191
+ _resubscribe() {
192
+ if (this._subscribed && this._dataBus !== null) {
193
+ const hasBuffers = Object.keys(this._buffersSelection).length > 0;
194
+ this._postData({
195
+ type: "subscribe",
196
+ payload: {
197
+ id: this.id,
198
+ features: this._features,
199
+ registry: this._registrySelection ?? void 0,
200
+ buffers: hasBuffers ? this._buffersSelection : void 0
201
+ }
202
+ });
203
+ }
204
+ }
205
+ /**
206
+ * Manually switch to a different provider. No-op if unknown or if
207
+ * already selected. Closes the old data channel and opens the new one.
208
+ */
209
+ selectProvider(providerId) {
210
+ if (!this._providers.has(providerId)) return;
211
+ if (this.state.selectedProviderId === providerId) return;
212
+ this._leaveDataChannel();
213
+ this.state.selectedProviderId = providerId;
214
+ this._resetAccumulatedState();
215
+ this._joinDataChannel(providerId);
216
+ this._postData({
217
+ type: "subscribe",
218
+ payload: {
219
+ id: this.id,
220
+ features: this._features,
221
+ registry: this._registrySelection ?? void 0,
222
+ buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
223
+ }
224
+ });
225
+ this._fire();
226
+ }
227
+ dispose() {
228
+ if (this._disposed) return;
229
+ this._disposed = true;
230
+ this._leaveDataChannel();
231
+ this._subscribed = false;
232
+ if (this._ackTimer !== null) {
233
+ clearInterval(this._ackTimer);
234
+ this._ackTimer = null;
235
+ }
236
+ if (this._livenessTimer !== null) {
237
+ clearInterval(this._livenessTimer);
238
+ this._livenessTimer = null;
239
+ }
240
+ if (this._queryRetryTimer !== null) {
241
+ clearTimeout(this._queryRetryTimer);
242
+ this._queryRetryTimer = null;
243
+ }
244
+ try {
245
+ this._discoveryBus.close();
246
+ } catch {}
247
+ }
248
+ /**
249
+ * Open a fresh per-provider data channel and start listening on it.
250
+ * Caller is responsible for posting the initial `subscribe`.
251
+ */
252
+ _joinDataChannel(providerId) {
253
+ this._dataBus = new BroadcastChannel(providerChannelName(providerId));
254
+ this._dataHandler = (ev) => {
255
+ this._onDataMessage(ev.data);
256
+ };
257
+ this._dataBus.addEventListener("message", this._dataHandler);
258
+ }
259
+ /**
260
+ * Send `unsubscribe` (if we have someone to tell) and close the data
261
+ * channel. Idempotent — safe to call when there's no active channel.
262
+ */
263
+ _leaveDataChannel() {
264
+ if (this._dataBus !== null) {
265
+ if (this._subscribed) try {
266
+ this._postData({
267
+ type: "unsubscribe",
268
+ payload: { id: this.id }
269
+ });
270
+ } catch {}
271
+ if (this._dataHandler !== null) try {
272
+ this._dataBus.removeEventListener("message", this._dataHandler);
273
+ } catch {}
274
+ try {
275
+ this._dataBus.close();
276
+ } catch {}
277
+ this._dataBus = null;
278
+ this._dataHandler = null;
279
+ }
280
+ }
281
+ /**
282
+ * Handler for the shared discovery bus. Only discovery messages land
283
+ * here by protocol; anything else is ignored.
284
+ */
285
+ _onDiscoveryMessage(msg) {
286
+ if (!msg || typeof msg !== "object" || !("type" in msg)) return;
287
+ tracePerf(msg);
288
+ switch (msg.type) {
289
+ case "provider:announce": {
290
+ const id = msg.payload.identity.id;
291
+ this._providers.set(id, msg.payload.identity);
292
+ this.state.providers = Array.from(this._providers.values());
293
+ this._fire();
294
+ if (this.state.selectedProviderId === null) this._pickProviderAndSubscribe();
295
+ break;
296
+ }
297
+ case "provider:gone": {
298
+ const id = msg.payload.id;
299
+ if (!this._providers.has(id)) return;
300
+ this._providers.delete(id);
301
+ this.state.providers = Array.from(this._providers.values());
302
+ if (this.state.selectedProviderId === id) {
303
+ this._leaveDataChannel();
304
+ this.state.selectedProviderId = null;
305
+ this._resetAccumulatedState();
306
+ this._pickProviderAndSubscribe();
307
+ }
308
+ this._fire();
309
+ break;
310
+ }
311
+ default: break;
312
+ }
313
+ }
314
+ /**
315
+ * Handler for the per-provider data channel. Everything here is
316
+ * already implicitly addressed to us (we opened the channel with the
317
+ * provider's id), so no per-message filtering is required beyond
318
+ * matching our consumer `id` on `subscribe:ack`.
319
+ */
320
+ _onDataMessage(msg) {
321
+ if (!msg || typeof msg !== "object" || !("type" in msg)) return;
322
+ tracePerf(msg);
323
+ if (this._rawMessageListeners.size > 0) for (const cb of this._rawMessageListeners) try {
324
+ cb(msg, "in");
325
+ } catch {}
326
+ switch (msg.type) {
327
+ case "subscribe:ack":
328
+ if (msg.payload.id !== this.id) return;
329
+ this._markServerAlive();
330
+ this._applyEnv(msg.payload.env);
331
+ if (this._ackTimer === null) this._ackTimer = setInterval(() => this._sendAck(), ACK_INTERVAL_MS);
332
+ this._fire();
333
+ break;
334
+ case "data": {
335
+ this._markServerAlive();
336
+ this.state.frame = msg.payload.frame;
337
+ const features = msg.payload.features;
338
+ if (features.stats !== void 0) this._applyStats(features.stats, msg.payload.frame);
339
+ if (features.env !== void 0) this._applyEnv(features.env);
340
+ if (features.registry !== void 0) this._applyRegistry(features.registry);
341
+ if (features.buffers !== void 0) this._applyBuffers(features.buffers);
342
+ if (features.batches !== void 0) this._applyBatches(features.batches);
343
+ this._fire();
344
+ break;
345
+ }
346
+ case "buffer:chunk": {
347
+ this._markServerAlive();
348
+ const payload = msg.payload;
349
+ for (const cb of this._chunkListeners) try {
350
+ cb(payload);
351
+ } catch {}
352
+ break;
353
+ }
354
+ case "buffer:raw": {
355
+ this._markServerAlive();
356
+ const payload = msg.payload;
357
+ let snap = this.state.buffers.get(payload.name);
358
+ if (snap !== void 0) {
359
+ snap.pixels = new Uint8Array(payload.data);
360
+ snap.width = payload.width;
361
+ snap.height = payload.height;
362
+ snap.version++;
363
+ } else {
364
+ snap = {
365
+ name: payload.name,
366
+ width: payload.width,
367
+ height: payload.height,
368
+ srcWidth: payload.width,
369
+ srcHeight: payload.height,
370
+ pixelType: "rgba8",
371
+ display: "colors",
372
+ version: 0,
373
+ pixels: new Uint8Array(payload.data)
374
+ };
375
+ this.state.buffers.set(payload.name, snap);
376
+ }
377
+ this._fire();
378
+ break;
379
+ }
380
+ case "ping":
381
+ this._markServerAlive();
382
+ break;
383
+ default: break;
384
+ }
385
+ }
386
+ _markServerAlive() {
387
+ this._lastServerAt = Date.now();
388
+ if (!this.state.serverAlive) {
389
+ this.state.serverAlive = true;
390
+ this._fire();
391
+ }
392
+ }
393
+ /**
394
+ * Pick the best provider from the currently-known set and subscribe
395
+ * to it. Preference: `user` over `system`; first-announced as
396
+ * tiebreak. No-op if zero providers are known (we'll stay waiting;
397
+ * any future `provider:announce` that arrives doesn't auto-trigger
398
+ * this call it again or restart discovery).
399
+ */
400
+ _pickProviderAndSubscribe() {
401
+ if (this.state.selectedProviderId !== null) return;
402
+ const providers = Array.from(this._providers.values());
403
+ if (providers.length === 0) return;
404
+ const chosen = providers.find((p) => p.kind === "user") ?? providers[0];
405
+ this.state.selectedProviderId = chosen.id;
406
+ this._joinDataChannel(chosen.id);
407
+ this._postData({
408
+ type: "subscribe",
409
+ payload: {
410
+ id: this.id,
411
+ features: this._features,
412
+ registry: this._registrySelection ?? void 0,
413
+ buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
414
+ }
415
+ });
416
+ this._fire();
417
+ }
418
+ /** Clear all feature-derived state so the next data packet can start fresh. */
419
+ _resetAccumulatedState() {
420
+ this.state.frame = void 0;
421
+ this._applyStats(null);
422
+ this._applyEnv(null);
423
+ this.state.registry.clear();
424
+ this.state.buffers.clear();
425
+ this._applyBatches(null);
426
+ }
427
+ /**
428
+ * Apply a stats batch. Null = reset (feature cleared / provider gone).
429
+ * Otherwise: decode each typed array onto the matching Float32 ring
430
+ * and update the scalar with the batch mean (natural smoothing for
431
+ * the text label).
432
+ */
433
+ _applyStats(batch, batchFrame = 0) {
434
+ if (batch === null) {
435
+ this.state.drawCalls = void 0;
436
+ this.state.triangles = void 0;
437
+ this.state.primitives = void 0;
438
+ this.state.geometries = void 0;
439
+ this.state.textures = void 0;
440
+ this.state.cpuMs = void 0;
441
+ this.state.fps = void 0;
442
+ this.state.gpuMs = void 0;
443
+ this.state.heapUsedMB = void 0;
444
+ this.state.heapLimitMB = void 0;
445
+ const s = this.state.series;
446
+ s.fps.write = 0;
447
+ s.fps.length = 0;
448
+ s.cpuMs.write = 0;
449
+ s.cpuMs.length = 0;
450
+ s.gpuMs.write = 0;
451
+ s.gpuMs.length = 0;
452
+ s.heapUsedMB.write = 0;
453
+ s.heapUsedMB.length = 0;
454
+ s.drawCalls.write = 0;
455
+ s.drawCalls.length = 0;
456
+ s.triangles.write = 0;
457
+ s.triangles.length = 0;
458
+ s.primitives.write = 0;
459
+ s.primitives.length = 0;
460
+ s.geometries.write = 0;
461
+ s.geometries.length = 0;
462
+ s.textures.write = 0;
463
+ s.textures.length = 0;
464
+ s.frames.write = 0;
465
+ s.frames.length = 0;
466
+ return;
467
+ }
468
+ const count = batch.count;
469
+ if (count <= 0) return;
470
+ const s = this.state.series;
471
+ {
472
+ const ring = s.frames;
473
+ const size = ring.data.length;
474
+ let w = ring.write;
475
+ for (let i = 0; i < count; i++) {
476
+ ring.data[w] = Math.max(0, batchFrame - count + 1 + i);
477
+ w = (w + 1) % size;
478
+ }
479
+ ring.write = w;
480
+ ring.length = Math.min(size, ring.length + count);
481
+ }
482
+ if (batch.fps) this.state.fps = this._ingestI16(s.fps, batch.fps, count, .1);
483
+ if (batch.cpuMs) this.state.cpuMs = this._ingestU16(s.cpuMs, batch.cpuMs, count, .01);
484
+ if (batch.gpuMs) this.state.gpuMs = this._ingestU16(s.gpuMs, batch.gpuMs, count, .01);
485
+ if (batch.heapUsedMB) this.state.heapUsedMB = this._ingestU16(s.heapUsedMB, batch.heapUsedMB, count, 1);
486
+ if (batch.drawCalls) this.state.drawCalls = this._ingestU32(s.drawCalls, batch.drawCalls, count);
487
+ if (batch.triangles) this.state.triangles = this._ingestU32(s.triangles, batch.triangles, count);
488
+ if (batch.primitives) this.state.primitives = this._ingestU32(s.primitives, batch.primitives, count);
489
+ if (batch.geometries) this.state.geometries = this._ingestU32(s.geometries, batch.geometries, count);
490
+ if (batch.textures) this.state.textures = this._ingestU32(s.textures, batch.textures, count);
491
+ if (batch.heapLimitMB !== void 0) this.state.heapLimitMB = batch.heapLimitMB;
492
+ }
493
+ /**
494
+ * Append `count` samples from a scaled integer view to a Float32 ring;
495
+ * return the batch mean (scaled). Zero-alloc past the ring itself.
496
+ */
497
+ _ingestI16(ring, src, count, scale) {
498
+ const size = ring.data.length;
499
+ let sum = 0;
500
+ let w = ring.write;
501
+ for (let i = 0; i < count; i++) {
502
+ const v = src[i] * scale;
503
+ ring.data[w] = v;
504
+ sum += v;
505
+ w = (w + 1) % size;
506
+ }
507
+ ring.write = w;
508
+ ring.length = Math.min(size, ring.length + count);
509
+ return sum / count;
510
+ }
511
+ _ingestU16(ring, src, count, scale) {
512
+ const size = ring.data.length;
513
+ let sum = 0;
514
+ let w = ring.write;
515
+ for (let i = 0; i < count; i++) {
516
+ const v = src[i] * scale;
517
+ ring.data[w] = v;
518
+ sum += v;
519
+ w = (w + 1) % size;
520
+ }
521
+ ring.write = w;
522
+ ring.length = Math.min(size, ring.length + count);
523
+ return sum / count;
524
+ }
525
+ _ingestU32(ring, src, count) {
526
+ const size = ring.data.length;
527
+ let sum = 0;
528
+ let w = ring.write;
529
+ for (let i = 0; i < count; i++) {
530
+ const v = src[i];
531
+ ring.data[w] = v;
532
+ sum += v;
533
+ w = (w + 1) % size;
534
+ }
535
+ ring.write = w;
536
+ ring.length = Math.min(size, ring.length + count);
537
+ return sum / count;
538
+ }
539
+ /**
540
+ * Apply a batches feature payload — replaces the snapshot wholesale.
541
+ * The wire arrays are scratch pools on the producer; we truncate by
542
+ * the provided counts and copy fields into persistent snapshot
543
+ * objects the UI can hold across subsequent frames.
544
+ *
545
+ * The client-side snapshot arrays grow monotonically to the high
546
+ * watermark and entries are overwritten in place — same alloc
547
+ * discipline as the producer.
548
+ */
549
+ _applyBatches(delta) {
550
+ if (delta === null) {
551
+ this.state.batches.frame = 0;
552
+ this.state.batches.passes.length = 0;
553
+ this.state.batches.batches.length = 0;
554
+ return;
555
+ }
556
+ this.state.batches.frame = delta.frame;
557
+ const passesIn = delta.passes;
558
+ const passCount = delta.passCount | 0;
559
+ const passesOut = this.state.batches.passes;
560
+ if (passesIn !== void 0) for (let i = 0; i < passCount; i++) {
561
+ const src = passesIn[i];
562
+ if (src === void 0) continue;
563
+ let dst = passesOut[i];
564
+ if (dst === void 0) {
565
+ dst = {
566
+ label: "",
567
+ calls: 0,
568
+ triangles: 0,
569
+ cpuMs: 0,
570
+ depth: 0,
571
+ parent: -1
572
+ };
573
+ passesOut[i] = dst;
574
+ }
575
+ dst.label = src.label;
576
+ dst.calls = src.calls;
577
+ dst.triangles = src.triangles;
578
+ dst.cpuMs = src.cpuMs;
579
+ dst.depth = src.depth;
580
+ dst.parent = src.parent;
581
+ }
582
+ if (passesOut.length > passCount) passesOut.length = passCount;
583
+ const batchesIn = delta.batches;
584
+ const batchCount = delta.batchCount | 0;
585
+ const batchesOut = this.state.batches.batches;
586
+ if (batchesIn !== void 0) for (let i = 0; i < batchCount; i++) {
587
+ const src = batchesIn[i];
588
+ if (src === void 0) continue;
589
+ let dst = batchesOut[i];
590
+ if (dst === void 0) {
591
+ dst = {
592
+ runKey: 0,
593
+ materialId: 0,
594
+ layer: 0,
595
+ materialName: "",
596
+ spriteCount: 0,
597
+ batchIdx: 0,
598
+ kind: "sprite",
599
+ label: ""
600
+ };
601
+ batchesOut[i] = dst;
602
+ }
603
+ dst.runKey = src.runKey;
604
+ dst.materialId = src.materialId;
605
+ dst.layer = src.layer;
606
+ dst.materialName = src.materialName;
607
+ dst.spriteCount = src.spriteCount;
608
+ dst.batchIdx = src.batchIdx;
609
+ dst.kind = src.kind ?? "sprite";
610
+ dst.label = src.label ?? "";
611
+ }
612
+ if (batchesOut.length > batchCount) batchesOut.length = batchCount;
613
+ }
614
+ /**
615
+ * Apply a registry delta. `entries[name] === null` → remove;
616
+ * `entries[name]` present upsert a snapshot keyed by `name`.
617
+ * A `null` batch (feature cleared) drops every entry.
618
+ */
619
+ _applyRegistry(delta) {
620
+ if (delta === null) {
621
+ this.state.registry.clear();
622
+ return;
623
+ }
624
+ if (!delta.entries) return;
625
+ const entries = delta.entries;
626
+ for (const name in entries) {
627
+ const d = entries[name];
628
+ if (d === void 0) continue;
629
+ if (d === null) {
630
+ this.state.registry.delete(name);
631
+ continue;
632
+ }
633
+ let snap = this.state.registry.get(name);
634
+ const sample = d.sample ?? snap?.sample ?? EMPTY_SAMPLE;
635
+ if (snap === void 0) {
636
+ snap = {
637
+ name,
638
+ kind: d.kind,
639
+ version: d.version,
640
+ count: d.count,
641
+ sample,
642
+ label: d.label
643
+ };
644
+ this.state.registry.set(name, snap);
645
+ } else {
646
+ snap.kind = d.kind;
647
+ snap.version = d.version;
648
+ snap.count = d.count;
649
+ snap.sample = sample;
650
+ snap.label = d.label;
651
+ }
652
+ }
653
+ }
654
+ /**
655
+ * Apply a buffers delta. Metadata (width/height/version/pixelType)
656
+ * ships regardless of the client's selection; `pixels` only arrives
657
+ * when this entry is in the current selection. Retain the previous
658
+ * `pixels` when the delta is metadata-only so the UI keeps showing
659
+ * the last thumbnail while browsing.
660
+ */
661
+ _applyBuffers(delta) {
662
+ if (delta === null) {
663
+ this.state.buffers.clear();
664
+ return;
665
+ }
666
+ if (!delta.entries) return;
667
+ const entries = delta.entries;
668
+ for (const name in entries) {
669
+ const d = entries[name];
670
+ if (d === void 0) continue;
671
+ if (d === null) {
672
+ this.state.buffers.delete(name);
673
+ continue;
674
+ }
675
+ let snap = this.state.buffers.get(name);
676
+ const pixels = d.pixels ?? snap?.pixels ?? null;
677
+ const isFloat = d.pixelType === "rgba16f" || d.pixelType === "rgba32f";
678
+ const display = d.display ?? (isFloat ? "normalize" : "colors");
679
+ const srcW = d.srcWidth ?? d.width;
680
+ const srcH = d.srcHeight ?? d.height;
681
+ if (snap === void 0) {
682
+ snap = {
683
+ name,
684
+ width: d.width,
685
+ height: d.height,
686
+ srcWidth: srcW,
687
+ srcHeight: srcH,
688
+ pixelType: d.pixelType,
689
+ display,
690
+ version: d.version,
691
+ pixels,
692
+ label: d.label
693
+ };
694
+ this.state.buffers.set(name, snap);
695
+ } else {
696
+ snap.width = d.width;
697
+ snap.height = d.height;
698
+ snap.srcWidth = srcW;
699
+ snap.srcHeight = srcH;
700
+ snap.pixelType = d.pixelType;
701
+ snap.display = display;
702
+ snap.version = d.version;
703
+ snap.pixels = pixels;
704
+ snap.label = d.label;
705
+ }
706
+ }
707
+ }
708
+ _applyEnv(delta) {
709
+ if (delta === null) {
710
+ this.state.threeFlatlandVersion = void 0;
711
+ this.state.threeRevision = void 0;
712
+ this.state.backendName = void 0;
713
+ this.state.backendTrackTimestamp = void 0;
714
+ this.state.backendDisjoint = void 0;
715
+ this.state.gpuModeEnabled = void 0;
716
+ this.state.canvasWidth = void 0;
717
+ this.state.canvasHeight = void 0;
718
+ this.state.canvasPixelRatio = void 0;
719
+ return;
720
+ }
721
+ if ("threeFlatlandVersion" in delta) this.state.threeFlatlandVersion = delta.threeFlatlandVersion ?? void 0;
722
+ if ("threeRevision" in delta) this.state.threeRevision = delta.threeRevision ?? void 0;
723
+ if (delta.backend !== void 0) {
724
+ const b = delta.backend;
725
+ if (b === null) {
726
+ this.state.backendName = void 0;
727
+ this.state.backendTrackTimestamp = void 0;
728
+ this.state.backendDisjoint = void 0;
729
+ this.state.gpuModeEnabled = void 0;
730
+ } else {
731
+ if ("name" in b) this.state.backendName = b.name ?? void 0;
732
+ if ("trackTimestamp" in b) this.state.backendTrackTimestamp = b.trackTimestamp ?? void 0;
733
+ if ("disjoint" in b) this.state.backendDisjoint = b.disjoint ?? void 0;
734
+ if ("gpuModeEnabled" in b) this.state.gpuModeEnabled = b.gpuModeEnabled ?? void 0;
735
+ }
736
+ }
737
+ if (delta.canvas !== void 0) {
738
+ const c = delta.canvas;
739
+ if (c === null) {
740
+ this.state.canvasWidth = void 0;
741
+ this.state.canvasHeight = void 0;
742
+ this.state.canvasPixelRatio = void 0;
743
+ } else {
744
+ if ("width" in c) this.state.canvasWidth = c.width ?? void 0;
745
+ if ("height" in c) this.state.canvasHeight = c.height ?? void 0;
746
+ if ("pixelRatio" in c) this.state.canvasPixelRatio = c.pixelRatio ?? void 0;
747
+ }
748
+ }
749
+ }
750
+ _checkLiveness() {
751
+ const now = Date.now();
752
+ const lag = this._lastServerAt === 0 ? now : now - this._lastServerAt;
753
+ this.state.serverLagMs = lag;
754
+ if (this._lastServerAt !== 0 && lag > SERVER_LIVENESS_MS) {
755
+ if (this.state.serverAlive) this.state.serverAlive = false;
756
+ if (this._dataBus !== null) this._postData({
757
+ type: "subscribe",
758
+ payload: {
759
+ id: this.id,
760
+ features: this._features,
761
+ registry: this._registrySelection ?? void 0,
762
+ buffers: Object.keys(this._buffersSelection).length > 0 ? this._buffersSelection : void 0
763
+ }
764
+ });
765
+ }
766
+ this._fire();
767
+ }
768
+ _sendAck() {
769
+ if (this._disposed || this._dataBus === null) return;
770
+ this._postData({
771
+ type: "ack",
772
+ payload: { id: this.id }
773
+ });
774
+ }
775
+ _postDiscovery(body) {
776
+ const msg = {
777
+ v: DEBUG_PROTOCOL_VERSION,
778
+ ts: Date.now(),
779
+ ...body
780
+ };
781
+ this._fireRawMessage(msg, "out");
782
+ try {
783
+ this._discoveryBus.postMessage(msg);
784
+ } catch {}
785
+ }
786
+ _postData(body) {
787
+ if (this._dataBus === null) return;
788
+ const msg = {
789
+ v: DEBUG_PROTOCOL_VERSION,
790
+ ts: Date.now(),
791
+ ...body
792
+ };
793
+ this._fireRawMessage(msg, "out");
794
+ try {
795
+ this._dataBus.postMessage(msg);
796
+ } catch {}
797
+ }
798
+ _fireRawMessage(msg, direction) {
799
+ if (this._rawMessageListeners.size === 0) return;
800
+ for (const cb of this._rawMessageListeners) try {
801
+ cb(msg, direction);
802
+ } catch {}
803
+ }
804
+ /** Subscribe to state-change events. Returns an unsubscribe function. */
805
+ addListener(cb) {
806
+ this._listeners.add(cb);
807
+ return () => {
808
+ this._listeners.delete(cb);
809
+ };
810
+ }
811
+ /** Explicit remove — equivalent to calling the unsubscribe returned from `addListener`. */
812
+ removeListener(cb) {
813
+ this._listeners.delete(cb);
814
+ }
815
+ /** Subscribe to incoming WebCodecs buffer chunks. Returns an unsubscribe function. */
816
+ addChunkListener(cb) {
817
+ this._chunkListeners.add(cb);
818
+ return () => {
819
+ this._chunkListeners.delete(cb);
820
+ };
821
+ }
822
+ /**
823
+ * Subscribe to every bus message — both inbound (from providers) and
824
+ * outbound (our own `subscribe`/`ack`/etc.). Used by the dashboard's
825
+ * protocol-log panel. Listeners fire on the hot path so keep them
826
+ * cheap — filter and format lazily.
827
+ */
828
+ addRawMessageListener(cb) {
829
+ this._rawMessageListeners.add(cb);
830
+ return () => {
831
+ this._rawMessageListeners.delete(cb);
832
+ };
833
+ }
834
+ _fire() {
835
+ for (const cb of this._listeners) try {
836
+ cb(this.state);
837
+ } catch {}
838
+ }
839
+ };
840
+ /** Cheap equality for two small feature lists treated as sets. */
815
841
  function sameSet(a, b) {
816
- if (a.length !== b.length) return false;
817
- for (const v of a) if (!b.includes(v)) return false;
818
- return true;
842
+ if (a.length !== b.length) return false;
843
+ for (const v of a) if (!b.includes(v)) return false;
844
+ return true;
819
845
  }
846
+ /** Equality for registry filters (where `null` has a distinct meaning). */
820
847
  function sameFilter(a, b) {
821
- if (a === b) return true;
822
- if (a === null || b === null) return false;
823
- return sameSet(a, b);
848
+ if (a === b) return true;
849
+ if (a === null || b === null) return false;
850
+ return sameSet(a, b);
824
851
  }
852
+ /** Equality for buffer subscription records. Compares keys and nested fields. */
825
853
  function sameBufferSubscription(a, b) {
826
- const ak = Object.keys(a);
827
- const bk = Object.keys(b);
828
- if (ak.length !== bk.length) return false;
829
- for (const k of ak) {
830
- const av = a[k];
831
- const bv = b[k];
832
- if (av === void 0 || bv === void 0) return false;
833
- if (av.mode !== bv.mode) return false;
834
- if ((av.thumbSize ?? 256) !== (bv.thumbSize ?? 256)) return false;
835
- }
836
- return true;
854
+ const ak = Object.keys(a);
855
+ const bk = Object.keys(b);
856
+ if (ak.length !== bk.length) return false;
857
+ for (const k of ak) {
858
+ const av = a[k];
859
+ const bv = b[k];
860
+ if (av === void 0 || bv === void 0) return false;
861
+ if (av.mode !== bv.mode) return false;
862
+ if ((av.thumbSize ?? 256) !== (bv.thumbSize ?? 256)) return false;
863
+ }
864
+ return true;
837
865
  }
838
866
  function generateUuid() {
839
- const c = typeof crypto !== "undefined" ? crypto : void 0;
840
- if (c && typeof c.randomUUID === "function") return c.randomUUID();
841
- const bytes = new Uint8Array(16);
842
- if (c && typeof c.getRandomValues === "function") c.getRandomValues(bytes);
843
- else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
844
- bytes[6] = bytes[6] & 15 | 64;
845
- bytes[8] = bytes[8] & 63 | 128;
846
- const h = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
847
- return `${h.slice(0, 4).join("")}-${h.slice(4, 6).join("")}-${h.slice(6, 8).join("")}-${h.slice(8, 10).join("")}-${h.slice(10).join("")}`;
867
+ const c = typeof crypto !== "undefined" ? crypto : void 0;
868
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
869
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
870
+ if (c && typeof c.getRandomValues === "function") c.getRandomValues(bytes);
871
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
872
+ bytes[6] = bytes[6] & 15 | 64;
873
+ bytes[8] = bytes[8] & 63 | 128;
874
+ const h = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
875
+ return `${h.slice(0, 4).join("")}-${h.slice(4, 6).join("")}-${h.slice(6, 8).join("")}-${h.slice(8, 10).join("")}-${h.slice(10).join("")}`;
848
876
  }
849
- export {
850
- DevtoolsClient
851
- };
877
+ //#endregion
878
+ export { DevtoolsClient };
879
+
852
880
  //# sourceMappingURL=devtools-client.js.map