tab-bridge 0.1.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/LICENSE +21 -0
- package/README.md +834 -0
- package/dist/chunk-42VOZR6E.js +1309 -0
- package/dist/chunk-BQCNBNBT.cjs +1332 -0
- package/dist/index.cjs +149 -0
- package/dist/index.d.cts +304 -0
- package/dist/index.d.ts +304 -0
- package/dist/index.js +59 -0
- package/dist/react/index.cjs +174 -0
- package/dist/react/index.d.cts +61 -0
- package/dist/react/index.d.ts +61 -0
- package/dist/react/index.js +167 -0
- package/dist/types-BtK4ixKz.d.cts +306 -0
- package/dist/types-BtK4ixKz.d.ts +306 -0
- package/package.json +90 -0
|
@@ -0,0 +1,1309 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var PROTOCOL_VERSION = 1;
|
|
3
|
+
|
|
4
|
+
// src/utils/id.ts
|
|
5
|
+
function generateTabId() {
|
|
6
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
7
|
+
return crypto.randomUUID();
|
|
8
|
+
}
|
|
9
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
10
|
+
const r = Math.random() * 16 | 0;
|
|
11
|
+
const v = c === "x" ? r : r & 3 | 8;
|
|
12
|
+
return v.toString(16);
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/utils/env.ts
|
|
17
|
+
var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
|
|
18
|
+
var hasDocument = typeof document !== "undefined";
|
|
19
|
+
var hasLocalStorage = (() => {
|
|
20
|
+
try {
|
|
21
|
+
return typeof localStorage !== "undefined" && localStorage !== null;
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
})();
|
|
26
|
+
var hasBroadcastChannel = typeof BroadcastChannel !== "undefined";
|
|
27
|
+
var hasCrypto = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function";
|
|
28
|
+
|
|
29
|
+
// src/channels/broadcast.ts
|
|
30
|
+
var BroadcastChannelTransport = class {
|
|
31
|
+
constructor(channelName) {
|
|
32
|
+
this.closed = false;
|
|
33
|
+
this.bc = new BroadcastChannel(channelName);
|
|
34
|
+
}
|
|
35
|
+
postMessage(message) {
|
|
36
|
+
if (this.closed) return;
|
|
37
|
+
this.bc.postMessage(message);
|
|
38
|
+
}
|
|
39
|
+
onMessage(callback) {
|
|
40
|
+
const handler = (event) => {
|
|
41
|
+
callback(event.data);
|
|
42
|
+
};
|
|
43
|
+
this.bc.addEventListener("message", handler);
|
|
44
|
+
return () => this.bc.removeEventListener("message", handler);
|
|
45
|
+
}
|
|
46
|
+
close() {
|
|
47
|
+
if (this.closed) return;
|
|
48
|
+
this.closed = true;
|
|
49
|
+
this.bc.close();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// src/channels/storage.ts
|
|
54
|
+
var KEY_PREFIX = "__tab_sync__";
|
|
55
|
+
var StorageChannel = class {
|
|
56
|
+
constructor(channelName) {
|
|
57
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
58
|
+
this.closed = false;
|
|
59
|
+
this.seq = 0;
|
|
60
|
+
this.key = `${KEY_PREFIX}${channelName}`;
|
|
61
|
+
}
|
|
62
|
+
postMessage(message) {
|
|
63
|
+
if (this.closed || !hasLocalStorage) return;
|
|
64
|
+
try {
|
|
65
|
+
const wrapped = JSON.stringify({ m: message, s: this.seq++ });
|
|
66
|
+
localStorage.setItem(this.key, wrapped);
|
|
67
|
+
} catch {
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
onMessage(callback) {
|
|
71
|
+
if (!isBrowser) return () => {
|
|
72
|
+
};
|
|
73
|
+
const handler = (event) => {
|
|
74
|
+
if (event.key !== this.key || !event.newValue) return;
|
|
75
|
+
try {
|
|
76
|
+
const { m } = JSON.parse(event.newValue);
|
|
77
|
+
callback(m);
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
this.listeners.add(handler);
|
|
82
|
+
window.addEventListener("storage", handler);
|
|
83
|
+
return () => {
|
|
84
|
+
this.listeners.delete(handler);
|
|
85
|
+
window.removeEventListener("storage", handler);
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
close() {
|
|
89
|
+
if (this.closed) return;
|
|
90
|
+
this.closed = true;
|
|
91
|
+
if (isBrowser) {
|
|
92
|
+
for (const handler of this.listeners) {
|
|
93
|
+
window.removeEventListener("storage", handler);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
this.listeners.clear();
|
|
97
|
+
if (hasLocalStorage) {
|
|
98
|
+
try {
|
|
99
|
+
localStorage.removeItem(this.key);
|
|
100
|
+
} catch {
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// src/channels/channel.ts
|
|
107
|
+
function createChannel(channelName, transport) {
|
|
108
|
+
if (transport === "local-storage") {
|
|
109
|
+
return new StorageChannel(channelName);
|
|
110
|
+
}
|
|
111
|
+
if (transport === "broadcast-channel") {
|
|
112
|
+
return new BroadcastChannelTransport(channelName);
|
|
113
|
+
}
|
|
114
|
+
if (typeof BroadcastChannel !== "undefined") {
|
|
115
|
+
return new BroadcastChannelTransport(channelName);
|
|
116
|
+
}
|
|
117
|
+
return new StorageChannel(channelName);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/utils/timestamp.ts
|
|
121
|
+
var lastTimestamp = 0;
|
|
122
|
+
function monotonic() {
|
|
123
|
+
const now = Date.now();
|
|
124
|
+
lastTimestamp = now > lastTimestamp ? now : lastTimestamp + 1;
|
|
125
|
+
return lastTimestamp;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/utils/batch.ts
|
|
129
|
+
function createBatcher(onFlush, delay = 16) {
|
|
130
|
+
const pending = /* @__PURE__ */ new Map();
|
|
131
|
+
let timer = null;
|
|
132
|
+
function flush() {
|
|
133
|
+
if (timer) {
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
timer = null;
|
|
136
|
+
}
|
|
137
|
+
if (pending.size > 0) {
|
|
138
|
+
const snapshot = new Map(pending);
|
|
139
|
+
pending.clear();
|
|
140
|
+
onFlush(snapshot);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
add(key, value) {
|
|
145
|
+
pending.set(key, value);
|
|
146
|
+
if (!timer) {
|
|
147
|
+
timer = setTimeout(flush, delay);
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
flush,
|
|
151
|
+
destroy() {
|
|
152
|
+
if (timer) {
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
timer = null;
|
|
155
|
+
}
|
|
156
|
+
pending.clear();
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// src/core/state-manager.ts
|
|
162
|
+
var StateManager = class {
|
|
163
|
+
constructor(options) {
|
|
164
|
+
this.state = /* @__PURE__ */ new Map();
|
|
165
|
+
this.keyListeners = /* @__PURE__ */ new Map();
|
|
166
|
+
this.changeListeners = /* @__PURE__ */ new Set();
|
|
167
|
+
this.snapshotCache = null;
|
|
168
|
+
this.send = options.send;
|
|
169
|
+
this.tabId = options.tabId;
|
|
170
|
+
this.mergeFn = options.merge;
|
|
171
|
+
this.interceptRemote = options.interceptRemote;
|
|
172
|
+
this.afterRemoteChange = options.afterRemoteChange;
|
|
173
|
+
if (options.initial) {
|
|
174
|
+
for (const [key, value] of Object.entries(options.initial)) {
|
|
175
|
+
this.state.set(key, { value, timestamp: 0 });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
this.batcher = createBatcher((entries) => {
|
|
179
|
+
const payload = { entries: {} };
|
|
180
|
+
for (const [key, entry] of entries) {
|
|
181
|
+
payload.entries[key] = { value: entry.value, timestamp: entry.timestamp };
|
|
182
|
+
}
|
|
183
|
+
this.send({
|
|
184
|
+
type: "STATE_UPDATE",
|
|
185
|
+
senderId: this.tabId,
|
|
186
|
+
timestamp: monotonic(),
|
|
187
|
+
payload
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
// ── Read ──
|
|
192
|
+
get(key) {
|
|
193
|
+
return this.state.get(key)?.value;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Returns a cached snapshot. The same reference is returned until state
|
|
197
|
+
* changes, making this safe for React's `useSyncExternalStore`.
|
|
198
|
+
*/
|
|
199
|
+
getAll() {
|
|
200
|
+
if (!this.snapshotCache) {
|
|
201
|
+
const result = {};
|
|
202
|
+
for (const [key, entry] of this.state) {
|
|
203
|
+
result[key] = entry.value;
|
|
204
|
+
}
|
|
205
|
+
this.snapshotCache = result;
|
|
206
|
+
}
|
|
207
|
+
return this.snapshotCache;
|
|
208
|
+
}
|
|
209
|
+
// ── Write ──
|
|
210
|
+
set(key, value) {
|
|
211
|
+
const timestamp = monotonic();
|
|
212
|
+
const k = key;
|
|
213
|
+
this.state.set(k, { value, timestamp });
|
|
214
|
+
this.snapshotCache = null;
|
|
215
|
+
const meta = { sourceTabId: this.tabId, isLocal: true, timestamp };
|
|
216
|
+
this.notifyKey(k, value, meta);
|
|
217
|
+
this.notifyChange([key], meta);
|
|
218
|
+
this.batcher.add(k, { value, timestamp });
|
|
219
|
+
}
|
|
220
|
+
patch(partial) {
|
|
221
|
+
const entries = Object.entries(partial);
|
|
222
|
+
if (entries.length === 0) return;
|
|
223
|
+
const timestamp = monotonic();
|
|
224
|
+
const changedKeys = [];
|
|
225
|
+
for (const [key, value] of entries) {
|
|
226
|
+
this.state.set(key, { value, timestamp });
|
|
227
|
+
changedKeys.push(key);
|
|
228
|
+
this.batcher.add(key, { value, timestamp });
|
|
229
|
+
}
|
|
230
|
+
this.snapshotCache = null;
|
|
231
|
+
const meta = { sourceTabId: this.tabId, isLocal: true, timestamp };
|
|
232
|
+
for (const key of changedKeys) {
|
|
233
|
+
this.notifyKey(key, this.state.get(key).value, meta);
|
|
234
|
+
}
|
|
235
|
+
this.notifyChange(changedKeys, meta);
|
|
236
|
+
}
|
|
237
|
+
// ── Subscriptions ──
|
|
238
|
+
on(key, callback) {
|
|
239
|
+
const k = key;
|
|
240
|
+
let set = this.keyListeners.get(k);
|
|
241
|
+
if (!set) {
|
|
242
|
+
set = /* @__PURE__ */ new Set();
|
|
243
|
+
this.keyListeners.set(k, set);
|
|
244
|
+
}
|
|
245
|
+
set.add(callback);
|
|
246
|
+
return () => {
|
|
247
|
+
set.delete(callback);
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
onChange(callback) {
|
|
251
|
+
this.changeListeners.add(callback);
|
|
252
|
+
return () => {
|
|
253
|
+
this.changeListeners.delete(callback);
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
// ── Incoming messages ──
|
|
257
|
+
handleMessage(message) {
|
|
258
|
+
switch (message.type) {
|
|
259
|
+
case "STATE_UPDATE":
|
|
260
|
+
this.applyRemoteUpdate(message);
|
|
261
|
+
break;
|
|
262
|
+
case "STATE_SYNC_RESPONSE":
|
|
263
|
+
if (!message.targetId || message.targetId === this.tabId) {
|
|
264
|
+
this.applySyncResponse(message);
|
|
265
|
+
}
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
// ── Sync protocol ──
|
|
270
|
+
requestSync() {
|
|
271
|
+
this.send({
|
|
272
|
+
type: "STATE_SYNC_REQUEST",
|
|
273
|
+
senderId: this.tabId,
|
|
274
|
+
timestamp: monotonic(),
|
|
275
|
+
payload: null
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
respondToSync(targetId) {
|
|
279
|
+
const state = {};
|
|
280
|
+
for (const [key, entry] of this.state) {
|
|
281
|
+
state[key] = { value: entry.value, timestamp: entry.timestamp };
|
|
282
|
+
}
|
|
283
|
+
this.send({
|
|
284
|
+
type: "STATE_SYNC_RESPONSE",
|
|
285
|
+
senderId: this.tabId,
|
|
286
|
+
targetId,
|
|
287
|
+
timestamp: monotonic(),
|
|
288
|
+
payload: { state }
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
flush() {
|
|
292
|
+
this.batcher.flush();
|
|
293
|
+
}
|
|
294
|
+
destroy() {
|
|
295
|
+
this.batcher.destroy();
|
|
296
|
+
this.keyListeners.clear();
|
|
297
|
+
this.changeListeners.clear();
|
|
298
|
+
}
|
|
299
|
+
// ── Private ──
|
|
300
|
+
applyRemoteUpdate(message) {
|
|
301
|
+
const { entries } = message.payload;
|
|
302
|
+
const changedKeys = [];
|
|
303
|
+
const meta = {
|
|
304
|
+
sourceTabId: message.senderId,
|
|
305
|
+
isLocal: false,
|
|
306
|
+
timestamp: message.timestamp
|
|
307
|
+
};
|
|
308
|
+
for (const [key, remote] of Object.entries(entries)) {
|
|
309
|
+
const local = this.state.get(key);
|
|
310
|
+
let finalValue;
|
|
311
|
+
if (this.mergeFn) {
|
|
312
|
+
finalValue = this.mergeFn(local?.value, remote.value, key);
|
|
313
|
+
} else if (this.shouldAcceptRemote(local, remote, message.senderId)) {
|
|
314
|
+
finalValue = remote.value;
|
|
315
|
+
} else {
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (this.interceptRemote) {
|
|
319
|
+
const result = this.interceptRemote(
|
|
320
|
+
key,
|
|
321
|
+
finalValue,
|
|
322
|
+
local?.value,
|
|
323
|
+
meta
|
|
324
|
+
);
|
|
325
|
+
if (result === false) continue;
|
|
326
|
+
if (result && "value" in result) finalValue = result.value;
|
|
327
|
+
}
|
|
328
|
+
this.state.set(key, { value: finalValue, timestamp: remote.timestamp });
|
|
329
|
+
changedKeys.push(key);
|
|
330
|
+
}
|
|
331
|
+
if (changedKeys.length > 0) {
|
|
332
|
+
this.snapshotCache = null;
|
|
333
|
+
for (const key of changedKeys) {
|
|
334
|
+
const val = this.state.get(key).value;
|
|
335
|
+
this.notifyKey(key, val, meta);
|
|
336
|
+
this.afterRemoteChange?.(key, val, meta);
|
|
337
|
+
}
|
|
338
|
+
this.notifyChange(changedKeys, meta);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/** LWW: accept remote if newer timestamp, or same timestamp with higher senderId. */
|
|
342
|
+
shouldAcceptRemote(local, remote, remoteSenderId) {
|
|
343
|
+
if (!local) return true;
|
|
344
|
+
if (remote.timestamp > local.timestamp) return true;
|
|
345
|
+
if (remote.timestamp === local.timestamp) return remoteSenderId > this.tabId;
|
|
346
|
+
return false;
|
|
347
|
+
}
|
|
348
|
+
applySyncResponse(message) {
|
|
349
|
+
const { state } = message.payload;
|
|
350
|
+
const changedKeys = [];
|
|
351
|
+
const meta = {
|
|
352
|
+
sourceTabId: message.senderId,
|
|
353
|
+
isLocal: false,
|
|
354
|
+
timestamp: message.timestamp
|
|
355
|
+
};
|
|
356
|
+
for (const [key, remote] of Object.entries(state)) {
|
|
357
|
+
const local = this.state.get(key);
|
|
358
|
+
if (!local || remote.timestamp > local.timestamp) {
|
|
359
|
+
this.state.set(key, { value: remote.value, timestamp: remote.timestamp });
|
|
360
|
+
changedKeys.push(key);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (changedKeys.length > 0) {
|
|
364
|
+
this.snapshotCache = null;
|
|
365
|
+
for (const key of changedKeys) {
|
|
366
|
+
const val = this.state.get(key).value;
|
|
367
|
+
this.notifyKey(key, val, meta);
|
|
368
|
+
this.afterRemoteChange?.(key, val, meta);
|
|
369
|
+
}
|
|
370
|
+
this.notifyChange(changedKeys, meta);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
notifyKey(key, value, meta) {
|
|
374
|
+
const listeners = this.keyListeners.get(key);
|
|
375
|
+
if (!listeners) return;
|
|
376
|
+
for (const cb of listeners) {
|
|
377
|
+
cb(value, meta);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
notifyChange(changedKeys, meta) {
|
|
381
|
+
if (this.changeListeners.size === 0) return;
|
|
382
|
+
const snapshot = this.getAll();
|
|
383
|
+
for (const cb of this.changeListeners) {
|
|
384
|
+
cb(snapshot, changedKeys, meta);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
// src/core/tab-registry.ts
|
|
390
|
+
var TabRegistry = class {
|
|
391
|
+
constructor(options) {
|
|
392
|
+
this.tabs = /* @__PURE__ */ new Map();
|
|
393
|
+
this.tabChangeListeners = /* @__PURE__ */ new Set();
|
|
394
|
+
this.heartbeatTimer = null;
|
|
395
|
+
this.pruneTimer = null;
|
|
396
|
+
this.visibilityHandler = null;
|
|
397
|
+
this.unloadHandler = null;
|
|
398
|
+
this.send = options.send;
|
|
399
|
+
this.tabId = options.tabId;
|
|
400
|
+
this.tabCreatedAt = options.tabCreatedAt;
|
|
401
|
+
this.heartbeatInterval = options.heartbeatInterval ?? 2e3;
|
|
402
|
+
this.tabTimeout = options.tabTimeout ?? 6e3;
|
|
403
|
+
this.registerSelf();
|
|
404
|
+
this.startHeartbeat();
|
|
405
|
+
this.startPruning();
|
|
406
|
+
this.listenVisibility();
|
|
407
|
+
this.listenUnload();
|
|
408
|
+
}
|
|
409
|
+
// ── Public API ──
|
|
410
|
+
getTabs() {
|
|
411
|
+
return Array.from(this.tabs.values());
|
|
412
|
+
}
|
|
413
|
+
getTabCount() {
|
|
414
|
+
return this.tabs.size;
|
|
415
|
+
}
|
|
416
|
+
getTab(id) {
|
|
417
|
+
return this.tabs.get(id);
|
|
418
|
+
}
|
|
419
|
+
onTabChange(callback) {
|
|
420
|
+
this.tabChangeListeners.add(callback);
|
|
421
|
+
return () => {
|
|
422
|
+
this.tabChangeListeners.delete(callback);
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
announce() {
|
|
426
|
+
this.send({
|
|
427
|
+
type: "TAB_ANNOUNCE",
|
|
428
|
+
senderId: this.tabId,
|
|
429
|
+
timestamp: monotonic(),
|
|
430
|
+
payload: this.buildAnnouncePayload()
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
handleMessage(message) {
|
|
434
|
+
switch (message.type) {
|
|
435
|
+
case "TAB_ANNOUNCE":
|
|
436
|
+
this.handleAnnounce(message.senderId, message.payload);
|
|
437
|
+
break;
|
|
438
|
+
case "TAB_GOODBYE":
|
|
439
|
+
this.handleGoodbye(message.senderId);
|
|
440
|
+
break;
|
|
441
|
+
case "LEADER_HEARTBEAT":
|
|
442
|
+
case "STATE_UPDATE":
|
|
443
|
+
case "LEADER_CLAIM":
|
|
444
|
+
case "LEADER_ACK":
|
|
445
|
+
this.touchTab(message.senderId);
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
setLeader(tabId) {
|
|
450
|
+
let changed = false;
|
|
451
|
+
for (const [id, info] of this.tabs) {
|
|
452
|
+
const wasLeader = info.isLeader;
|
|
453
|
+
const isNowLeader = id === tabId;
|
|
454
|
+
if (wasLeader !== isNowLeader) {
|
|
455
|
+
this.tabs.set(id, { ...info, isLeader: isNowLeader });
|
|
456
|
+
changed = true;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (changed) this.notifyChange();
|
|
460
|
+
}
|
|
461
|
+
destroy() {
|
|
462
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
463
|
+
if (this.pruneTimer) clearInterval(this.pruneTimer);
|
|
464
|
+
if (this.visibilityHandler && hasDocument) {
|
|
465
|
+
document.removeEventListener("visibilitychange", this.visibilityHandler);
|
|
466
|
+
}
|
|
467
|
+
if (this.unloadHandler && isBrowser) {
|
|
468
|
+
window.removeEventListener("beforeunload", this.unloadHandler);
|
|
469
|
+
}
|
|
470
|
+
this.sendGoodbye();
|
|
471
|
+
this.tabs.clear();
|
|
472
|
+
this.tabChangeListeners.clear();
|
|
473
|
+
}
|
|
474
|
+
// ── Private ──
|
|
475
|
+
registerSelf() {
|
|
476
|
+
this.tabs.set(this.tabId, {
|
|
477
|
+
id: this.tabId,
|
|
478
|
+
createdAt: this.tabCreatedAt,
|
|
479
|
+
lastSeen: Date.now(),
|
|
480
|
+
isLeader: false,
|
|
481
|
+
isActive: hasDocument ? document.visibilityState === "visible" : true,
|
|
482
|
+
url: isBrowser ? location.href : "",
|
|
483
|
+
title: hasDocument ? document.title : void 0
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
buildAnnouncePayload() {
|
|
487
|
+
return {
|
|
488
|
+
createdAt: this.tabCreatedAt,
|
|
489
|
+
isActive: hasDocument ? document.visibilityState === "visible" : true,
|
|
490
|
+
url: isBrowser ? location.href : "",
|
|
491
|
+
title: hasDocument ? document.title : void 0
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
startHeartbeat() {
|
|
495
|
+
this.heartbeatTimer = setInterval(() => {
|
|
496
|
+
this.touchSelf();
|
|
497
|
+
this.announce();
|
|
498
|
+
}, this.heartbeatInterval);
|
|
499
|
+
}
|
|
500
|
+
startPruning() {
|
|
501
|
+
this.pruneTimer = setInterval(() => {
|
|
502
|
+
this.pruneDeadTabs();
|
|
503
|
+
}, this.heartbeatInterval);
|
|
504
|
+
}
|
|
505
|
+
listenVisibility() {
|
|
506
|
+
if (!hasDocument) return;
|
|
507
|
+
this.visibilityHandler = () => {
|
|
508
|
+
const self = this.tabs.get(this.tabId);
|
|
509
|
+
if (self) {
|
|
510
|
+
const isActive = document.visibilityState === "visible";
|
|
511
|
+
this.tabs.set(this.tabId, { ...self, isActive, lastSeen: Date.now() });
|
|
512
|
+
this.announce();
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
document.addEventListener("visibilitychange", this.visibilityHandler);
|
|
516
|
+
}
|
|
517
|
+
listenUnload() {
|
|
518
|
+
if (!isBrowser) return;
|
|
519
|
+
this.unloadHandler = () => this.sendGoodbye();
|
|
520
|
+
window.addEventListener("beforeunload", this.unloadHandler);
|
|
521
|
+
}
|
|
522
|
+
sendGoodbye() {
|
|
523
|
+
this.send({
|
|
524
|
+
type: "TAB_GOODBYE",
|
|
525
|
+
senderId: this.tabId,
|
|
526
|
+
timestamp: monotonic(),
|
|
527
|
+
payload: null
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
handleAnnounce(senderId, payload) {
|
|
531
|
+
const existing = this.tabs.get(senderId);
|
|
532
|
+
this.tabs.set(senderId, {
|
|
533
|
+
id: senderId,
|
|
534
|
+
createdAt: payload.createdAt,
|
|
535
|
+
lastSeen: Date.now(),
|
|
536
|
+
isLeader: existing?.isLeader ?? false,
|
|
537
|
+
isActive: payload.isActive,
|
|
538
|
+
url: payload.url,
|
|
539
|
+
title: payload.title
|
|
540
|
+
});
|
|
541
|
+
this.notifyChange();
|
|
542
|
+
}
|
|
543
|
+
handleGoodbye(senderId) {
|
|
544
|
+
if (this.tabs.delete(senderId)) {
|
|
545
|
+
this.notifyChange();
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
touchTab(tabId) {
|
|
549
|
+
const tab = this.tabs.get(tabId);
|
|
550
|
+
if (tab) {
|
|
551
|
+
this.tabs.set(tabId, { ...tab, lastSeen: Date.now() });
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
touchSelf() {
|
|
555
|
+
const self = this.tabs.get(this.tabId);
|
|
556
|
+
if (self) {
|
|
557
|
+
this.tabs.set(this.tabId, { ...self, lastSeen: Date.now() });
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
pruneDeadTabs() {
|
|
561
|
+
const now = Date.now();
|
|
562
|
+
let changed = false;
|
|
563
|
+
for (const [id, info] of this.tabs) {
|
|
564
|
+
if (id === this.tabId) continue;
|
|
565
|
+
if (now - info.lastSeen > this.tabTimeout) {
|
|
566
|
+
this.tabs.delete(id);
|
|
567
|
+
changed = true;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (changed) this.notifyChange();
|
|
571
|
+
}
|
|
572
|
+
notifyChange() {
|
|
573
|
+
if (this.tabChangeListeners.size === 0) return;
|
|
574
|
+
const tabs = this.getTabs();
|
|
575
|
+
for (const cb of this.tabChangeListeners) {
|
|
576
|
+
cb(tabs);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
|
|
581
|
+
// src/core/leader-election.ts
|
|
582
|
+
var LeaderElection = class {
|
|
583
|
+
constructor(options) {
|
|
584
|
+
this.leaderId = null;
|
|
585
|
+
this.electionTimer = null;
|
|
586
|
+
this.heartbeatTimer = null;
|
|
587
|
+
this.leaderWatchTimer = null;
|
|
588
|
+
this.lastLeaderHeartbeat = 0;
|
|
589
|
+
this.electing = false;
|
|
590
|
+
this.leaderCallbacks = /* @__PURE__ */ new Set();
|
|
591
|
+
this.leaderCleanups = /* @__PURE__ */ new Map();
|
|
592
|
+
this.send = options.send;
|
|
593
|
+
this.tabId = options.tabId;
|
|
594
|
+
this.tabCreatedAt = options.tabCreatedAt;
|
|
595
|
+
this.electionTimeout = options.electionTimeout ?? 300;
|
|
596
|
+
this.heartbeatInterval = options.heartbeatInterval ?? 2e3;
|
|
597
|
+
const missedLimit = options.missedHeartbeatsLimit ?? 3;
|
|
598
|
+
this.leaderTimeout = this.heartbeatInterval * missedLimit;
|
|
599
|
+
}
|
|
600
|
+
// ── Public API ──
|
|
601
|
+
isLeader() {
|
|
602
|
+
return this.leaderId === this.tabId;
|
|
603
|
+
}
|
|
604
|
+
getLeaderId() {
|
|
605
|
+
return this.leaderId;
|
|
606
|
+
}
|
|
607
|
+
onLeader(callback) {
|
|
608
|
+
this.leaderCallbacks.add(callback);
|
|
609
|
+
if (this.isLeader()) {
|
|
610
|
+
const cleanup = callback();
|
|
611
|
+
if (typeof cleanup === "function") {
|
|
612
|
+
this.leaderCleanups.set(callback, cleanup);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return () => {
|
|
616
|
+
this.leaderCallbacks.delete(callback);
|
|
617
|
+
const cleanup = this.leaderCleanups.get(callback);
|
|
618
|
+
if (cleanup) {
|
|
619
|
+
cleanup();
|
|
620
|
+
this.leaderCleanups.delete(callback);
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
start() {
|
|
625
|
+
this.startElection();
|
|
626
|
+
this.startLeaderWatch();
|
|
627
|
+
}
|
|
628
|
+
handleMessage(message) {
|
|
629
|
+
switch (message.type) {
|
|
630
|
+
case "LEADER_CLAIM":
|
|
631
|
+
this.handleClaim(message.payload, message.senderId);
|
|
632
|
+
break;
|
|
633
|
+
case "LEADER_ACK":
|
|
634
|
+
this.handleAck(message.senderId);
|
|
635
|
+
break;
|
|
636
|
+
case "LEADER_HEARTBEAT":
|
|
637
|
+
this.handleHeartbeat(message.senderId);
|
|
638
|
+
break;
|
|
639
|
+
case "LEADER_RESIGN":
|
|
640
|
+
this.handleResign(message.senderId);
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
destroy() {
|
|
645
|
+
if (this.isLeader()) {
|
|
646
|
+
this.send({
|
|
647
|
+
type: "LEADER_RESIGN",
|
|
648
|
+
senderId: this.tabId,
|
|
649
|
+
timestamp: monotonic(),
|
|
650
|
+
payload: null
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
this.clearElectionTimer();
|
|
654
|
+
this.clearHeartbeat();
|
|
655
|
+
this.clearLeaderWatch();
|
|
656
|
+
this.runCleanups();
|
|
657
|
+
this.leaderCallbacks.clear();
|
|
658
|
+
this.leaderId = null;
|
|
659
|
+
}
|
|
660
|
+
// ── Election ──
|
|
661
|
+
startElection() {
|
|
662
|
+
if (this.electing) return;
|
|
663
|
+
this.electing = true;
|
|
664
|
+
this.send({
|
|
665
|
+
type: "LEADER_CLAIM",
|
|
666
|
+
senderId: this.tabId,
|
|
667
|
+
timestamp: monotonic(),
|
|
668
|
+
payload: { createdAt: this.tabCreatedAt }
|
|
669
|
+
});
|
|
670
|
+
this.electionTimer = setTimeout(() => {
|
|
671
|
+
this.electionTimer = null;
|
|
672
|
+
this.electing = false;
|
|
673
|
+
this.becomeLeader();
|
|
674
|
+
}, this.electionTimeout);
|
|
675
|
+
}
|
|
676
|
+
handleClaim(payload, senderId) {
|
|
677
|
+
if (this.hasPriority(payload.createdAt, senderId)) {
|
|
678
|
+
if (!this.electing) this.startElection();
|
|
679
|
+
} else {
|
|
680
|
+
this.clearElectionTimer();
|
|
681
|
+
this.electing = false;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
handleAck(senderId) {
|
|
685
|
+
this.clearElectionTimer();
|
|
686
|
+
this.electing = false;
|
|
687
|
+
this.setLeader(senderId);
|
|
688
|
+
}
|
|
689
|
+
handleHeartbeat(senderId) {
|
|
690
|
+
if (senderId === this.leaderId || !this.leaderId) {
|
|
691
|
+
this.setLeader(senderId);
|
|
692
|
+
}
|
|
693
|
+
this.lastLeaderHeartbeat = Date.now();
|
|
694
|
+
}
|
|
695
|
+
handleResign(senderId) {
|
|
696
|
+
if (senderId === this.leaderId) {
|
|
697
|
+
this.leaderId = null;
|
|
698
|
+
this.runCleanups();
|
|
699
|
+
this.startElection();
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
becomeLeader() {
|
|
703
|
+
this.setLeader(this.tabId);
|
|
704
|
+
this.send({
|
|
705
|
+
type: "LEADER_ACK",
|
|
706
|
+
senderId: this.tabId,
|
|
707
|
+
timestamp: monotonic(),
|
|
708
|
+
payload: null
|
|
709
|
+
});
|
|
710
|
+
this.startHeartbeat();
|
|
711
|
+
}
|
|
712
|
+
setLeader(id) {
|
|
713
|
+
const wasLeader = this.isLeader();
|
|
714
|
+
this.leaderId = id;
|
|
715
|
+
this.lastLeaderHeartbeat = Date.now();
|
|
716
|
+
if (this.isLeader() && !wasLeader) {
|
|
717
|
+
this.startHeartbeat();
|
|
718
|
+
for (const cb of this.leaderCallbacks) {
|
|
719
|
+
const cleanup = cb();
|
|
720
|
+
if (typeof cleanup === "function") {
|
|
721
|
+
this.leaderCleanups.set(cb, cleanup);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
} else if (!this.isLeader() && wasLeader) {
|
|
725
|
+
this.clearHeartbeat();
|
|
726
|
+
this.runCleanups();
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Priority: oldest tab (smaller `createdAt`) wins.
|
|
731
|
+
* Tiebreak: lower `tabId` wins (deterministic).
|
|
732
|
+
*/
|
|
733
|
+
hasPriority(remoteCreatedAt, remoteTabId) {
|
|
734
|
+
if (this.tabCreatedAt < remoteCreatedAt) return true;
|
|
735
|
+
if (this.tabCreatedAt > remoteCreatedAt) return false;
|
|
736
|
+
return this.tabId < remoteTabId;
|
|
737
|
+
}
|
|
738
|
+
// ── Heartbeat ──
|
|
739
|
+
startHeartbeat() {
|
|
740
|
+
this.clearHeartbeat();
|
|
741
|
+
this.heartbeatTimer = setInterval(() => {
|
|
742
|
+
if (!this.isLeader()) return;
|
|
743
|
+
this.send({
|
|
744
|
+
type: "LEADER_HEARTBEAT",
|
|
745
|
+
senderId: this.tabId,
|
|
746
|
+
timestamp: monotonic(),
|
|
747
|
+
payload: null
|
|
748
|
+
});
|
|
749
|
+
}, this.heartbeatInterval);
|
|
750
|
+
}
|
|
751
|
+
clearHeartbeat() {
|
|
752
|
+
if (this.heartbeatTimer) {
|
|
753
|
+
clearInterval(this.heartbeatTimer);
|
|
754
|
+
this.heartbeatTimer = null;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
// ── Leader Watch ──
|
|
758
|
+
startLeaderWatch() {
|
|
759
|
+
this.lastLeaderHeartbeat = Date.now();
|
|
760
|
+
this.leaderWatchTimer = setInterval(() => {
|
|
761
|
+
if (this.isLeader()) return;
|
|
762
|
+
if (this.leaderId && Date.now() - this.lastLeaderHeartbeat > this.leaderTimeout) {
|
|
763
|
+
this.leaderId = null;
|
|
764
|
+
this.runCleanups();
|
|
765
|
+
this.startElection();
|
|
766
|
+
}
|
|
767
|
+
}, this.heartbeatInterval);
|
|
768
|
+
}
|
|
769
|
+
clearLeaderWatch() {
|
|
770
|
+
if (this.leaderWatchTimer) {
|
|
771
|
+
clearInterval(this.leaderWatchTimer);
|
|
772
|
+
this.leaderWatchTimer = null;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
clearElectionTimer() {
|
|
776
|
+
if (this.electionTimer) {
|
|
777
|
+
clearTimeout(this.electionTimer);
|
|
778
|
+
this.electionTimer = null;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
runCleanups() {
|
|
782
|
+
for (const cleanup of this.leaderCleanups.values()) {
|
|
783
|
+
cleanup();
|
|
784
|
+
}
|
|
785
|
+
this.leaderCleanups.clear();
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
|
|
789
|
+
// src/utils/errors.ts
|
|
790
|
+
var ErrorCode = {
|
|
791
|
+
CHANNEL_CLOSED: "CHANNEL_CLOSED",
|
|
792
|
+
CHANNEL_SEND_FAILED: "CHANNEL_SEND_FAILED",
|
|
793
|
+
RPC_TIMEOUT: "RPC_TIMEOUT",
|
|
794
|
+
RPC_NO_HANDLER: "RPC_NO_HANDLER",
|
|
795
|
+
RPC_NO_LEADER: "RPC_NO_LEADER",
|
|
796
|
+
RPC_HANDLER_ERROR: "RPC_HANDLER_ERROR",
|
|
797
|
+
RPC_DESTROYED: "RPC_DESTROYED",
|
|
798
|
+
STORAGE_QUOTA_EXCEEDED: "STORAGE_QUOTA_EXCEEDED",
|
|
799
|
+
MIDDLEWARE_REJECTED: "MIDDLEWARE_REJECTED",
|
|
800
|
+
ALREADY_DESTROYED: "ALREADY_DESTROYED"
|
|
801
|
+
};
|
|
802
|
+
var TabSyncError = class _TabSyncError extends Error {
|
|
803
|
+
constructor(message, code, cause) {
|
|
804
|
+
super(message);
|
|
805
|
+
this.code = code;
|
|
806
|
+
this.name = "TabSyncError";
|
|
807
|
+
this.cause = cause;
|
|
808
|
+
}
|
|
809
|
+
static timeout(method, ms) {
|
|
810
|
+
return new _TabSyncError(
|
|
811
|
+
`RPC "${method}" timed out after ${ms}ms`,
|
|
812
|
+
ErrorCode.RPC_TIMEOUT
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
static noLeader() {
|
|
816
|
+
return new _TabSyncError("No leader available", ErrorCode.RPC_NO_LEADER);
|
|
817
|
+
}
|
|
818
|
+
static noHandler(method) {
|
|
819
|
+
return new _TabSyncError(
|
|
820
|
+
`No handler registered for "${method}"`,
|
|
821
|
+
ErrorCode.RPC_NO_HANDLER
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
static destroyed() {
|
|
825
|
+
return new _TabSyncError("Instance has been destroyed", ErrorCode.ALREADY_DESTROYED);
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
|
|
829
|
+
// src/core/rpc.ts
|
|
830
|
+
var DEFAULT_TIMEOUT = 5e3;
|
|
831
|
+
var RPCHandler = class {
|
|
832
|
+
constructor(options) {
|
|
833
|
+
this.handlers = /* @__PURE__ */ new Map();
|
|
834
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
835
|
+
this.send = options.send;
|
|
836
|
+
this.tabId = options.tabId;
|
|
837
|
+
this.resolveLeaderId = options.resolveLeaderId ?? (() => null);
|
|
838
|
+
this.onError = options.onError ?? (() => {
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
call(targetTabId, method, args, timeout = DEFAULT_TIMEOUT) {
|
|
842
|
+
const resolvedTarget = targetTabId === "leader" ? this.resolveLeaderId() : targetTabId;
|
|
843
|
+
if (!resolvedTarget) {
|
|
844
|
+
return Promise.reject(TabSyncError.noLeader());
|
|
845
|
+
}
|
|
846
|
+
const callId = generateTabId();
|
|
847
|
+
return new Promise((resolve, reject) => {
|
|
848
|
+
const timer = setTimeout(() => {
|
|
849
|
+
this.pending.delete(callId);
|
|
850
|
+
reject(TabSyncError.timeout(method, timeout));
|
|
851
|
+
}, timeout);
|
|
852
|
+
this.pending.set(callId, {
|
|
853
|
+
resolve,
|
|
854
|
+
reject,
|
|
855
|
+
timer
|
|
856
|
+
});
|
|
857
|
+
this.send({
|
|
858
|
+
type: "RPC_REQUEST",
|
|
859
|
+
senderId: this.tabId,
|
|
860
|
+
targetId: resolvedTarget,
|
|
861
|
+
timestamp: monotonic(),
|
|
862
|
+
payload: { callId, method, args }
|
|
863
|
+
});
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
handle(method, handler) {
|
|
867
|
+
this.handlers.set(
|
|
868
|
+
method,
|
|
869
|
+
handler
|
|
870
|
+
);
|
|
871
|
+
return () => {
|
|
872
|
+
this.handlers.delete(method);
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
handleMessage(message) {
|
|
876
|
+
switch (message.type) {
|
|
877
|
+
case "RPC_REQUEST":
|
|
878
|
+
if (!message.targetId || message.targetId === this.tabId) {
|
|
879
|
+
this.handleRequest(message);
|
|
880
|
+
}
|
|
881
|
+
break;
|
|
882
|
+
case "RPC_RESPONSE":
|
|
883
|
+
if (!message.targetId || message.targetId === this.tabId) {
|
|
884
|
+
this.handleResponse(message);
|
|
885
|
+
}
|
|
886
|
+
break;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
destroy() {
|
|
890
|
+
const error = TabSyncError.destroyed();
|
|
891
|
+
for (const [, call] of this.pending) {
|
|
892
|
+
clearTimeout(call.timer);
|
|
893
|
+
call.reject(error);
|
|
894
|
+
}
|
|
895
|
+
this.pending.clear();
|
|
896
|
+
this.handlers.clear();
|
|
897
|
+
}
|
|
898
|
+
// ── Private ──
|
|
899
|
+
async handleRequest(message) {
|
|
900
|
+
const { callId, method, args } = message.payload;
|
|
901
|
+
const handler = this.handlers.get(method);
|
|
902
|
+
if (!handler) {
|
|
903
|
+
const err = TabSyncError.noHandler(method);
|
|
904
|
+
this.onError(err);
|
|
905
|
+
this.sendResponse(message.senderId, callId, void 0, err.message);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
try {
|
|
909
|
+
const result = await handler(args, message.senderId);
|
|
910
|
+
this.sendResponse(message.senderId, callId, result);
|
|
911
|
+
} catch (err) {
|
|
912
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
913
|
+
this.onError(
|
|
914
|
+
new TabSyncError(errorMsg, ErrorCode.RPC_HANDLER_ERROR, err)
|
|
915
|
+
);
|
|
916
|
+
this.sendResponse(message.senderId, callId, void 0, errorMsg);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
handleResponse(message) {
|
|
920
|
+
const { callId, result, error } = message.payload;
|
|
921
|
+
const call = this.pending.get(callId);
|
|
922
|
+
if (!call) return;
|
|
923
|
+
clearTimeout(call.timer);
|
|
924
|
+
this.pending.delete(callId);
|
|
925
|
+
if (error) {
|
|
926
|
+
call.reject(
|
|
927
|
+
new TabSyncError(error, ErrorCode.RPC_HANDLER_ERROR)
|
|
928
|
+
);
|
|
929
|
+
} else {
|
|
930
|
+
call.resolve(result);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
sendResponse(targetId, callId, result, error) {
|
|
934
|
+
this.send({
|
|
935
|
+
type: "RPC_RESPONSE",
|
|
936
|
+
senderId: this.tabId,
|
|
937
|
+
targetId,
|
|
938
|
+
timestamp: monotonic(),
|
|
939
|
+
payload: { callId, result, error }
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
};
|
|
943
|
+
|
|
944
|
+
// src/core/middleware.ts
|
|
945
|
+
function runMiddleware(middlewares, ctx) {
|
|
946
|
+
let currentValue = ctx.value;
|
|
947
|
+
for (const mw of middlewares) {
|
|
948
|
+
const fn = mw.onSet;
|
|
949
|
+
if (!fn) continue;
|
|
950
|
+
const result = fn({ ...ctx, value: currentValue });
|
|
951
|
+
if (result === false) {
|
|
952
|
+
return { value: currentValue, rejected: true };
|
|
953
|
+
}
|
|
954
|
+
if (result && "value" in result) {
|
|
955
|
+
currentValue = result.value;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return { value: currentValue, rejected: false };
|
|
959
|
+
}
|
|
960
|
+
function notifyMiddleware(middlewares, key, value, meta) {
|
|
961
|
+
for (const mw of middlewares) {
|
|
962
|
+
mw.afterChange?.(key, value, meta);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
function destroyMiddleware(middlewares) {
|
|
966
|
+
for (const mw of middlewares) {
|
|
967
|
+
mw.onDestroy?.();
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// src/core/tab-sync.ts
|
|
972
|
+
function resolvePersistOptions(opt) {
|
|
973
|
+
if (!opt) return null;
|
|
974
|
+
if (opt === true) return {};
|
|
975
|
+
return opt;
|
|
976
|
+
}
|
|
977
|
+
function loadPersistedState(opts) {
|
|
978
|
+
const storage = opts.storage ?? (hasLocalStorage ? localStorage : null);
|
|
979
|
+
if (!storage) return {};
|
|
980
|
+
const key = opts.key ?? "tab-sync:state";
|
|
981
|
+
const deserialize = opts.deserialize ?? JSON.parse;
|
|
982
|
+
try {
|
|
983
|
+
const raw = storage.getItem(key);
|
|
984
|
+
if (!raw) return {};
|
|
985
|
+
const parsed = deserialize(raw);
|
|
986
|
+
return filterPersistKeys(parsed, opts);
|
|
987
|
+
} catch {
|
|
988
|
+
return {};
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
function filterPersistKeys(state, opts) {
|
|
992
|
+
const include = opts.include ? new Set(opts.include) : null;
|
|
993
|
+
const exclude = opts.exclude ? new Set(opts.exclude) : null;
|
|
994
|
+
const result = {};
|
|
995
|
+
for (const [key, value] of Object.entries(state)) {
|
|
996
|
+
const k = key;
|
|
997
|
+
if (exclude?.has(k)) continue;
|
|
998
|
+
if (include && !include.has(k)) continue;
|
|
999
|
+
result[key] = value;
|
|
1000
|
+
}
|
|
1001
|
+
return result;
|
|
1002
|
+
}
|
|
1003
|
+
function createPersistSaver(opts, onError) {
|
|
1004
|
+
const storage = opts.storage ?? (hasLocalStorage ? localStorage : null);
|
|
1005
|
+
if (!storage) return { save() {
|
|
1006
|
+
}, flush() {
|
|
1007
|
+
}, destroy() {
|
|
1008
|
+
} };
|
|
1009
|
+
const key = opts.key ?? "tab-sync:state";
|
|
1010
|
+
const serialize = opts.serialize ?? JSON.stringify;
|
|
1011
|
+
const debounce = opts.debounce ?? 100;
|
|
1012
|
+
let timer = null;
|
|
1013
|
+
let latestState = null;
|
|
1014
|
+
function doSave() {
|
|
1015
|
+
if (!latestState) return;
|
|
1016
|
+
try {
|
|
1017
|
+
const filtered = filterPersistKeys({ ...latestState }, opts);
|
|
1018
|
+
storage.setItem(key, serialize(filtered));
|
|
1019
|
+
} catch (e) {
|
|
1020
|
+
onError(e instanceof Error ? e : new Error(String(e)));
|
|
1021
|
+
}
|
|
1022
|
+
latestState = null;
|
|
1023
|
+
}
|
|
1024
|
+
return {
|
|
1025
|
+
save(state) {
|
|
1026
|
+
latestState = state;
|
|
1027
|
+
if (!timer) {
|
|
1028
|
+
timer = setTimeout(() => {
|
|
1029
|
+
timer = null;
|
|
1030
|
+
doSave();
|
|
1031
|
+
}, debounce);
|
|
1032
|
+
}
|
|
1033
|
+
},
|
|
1034
|
+
flush() {
|
|
1035
|
+
if (timer) {
|
|
1036
|
+
clearTimeout(timer);
|
|
1037
|
+
timer = null;
|
|
1038
|
+
}
|
|
1039
|
+
doSave();
|
|
1040
|
+
},
|
|
1041
|
+
destroy() {
|
|
1042
|
+
if (timer) {
|
|
1043
|
+
clearTimeout(timer);
|
|
1044
|
+
timer = null;
|
|
1045
|
+
}
|
|
1046
|
+
doSave();
|
|
1047
|
+
}
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
function createLogger(enabled, tabId) {
|
|
1051
|
+
if (!enabled) return { log: (() => {
|
|
1052
|
+
}) };
|
|
1053
|
+
const prefix = `%c[tab-sync:${tabId.slice(0, 8)}]`;
|
|
1054
|
+
const style = "color:#818cf8;font-weight:600";
|
|
1055
|
+
return {
|
|
1056
|
+
log: (label, ...args) => console.log(prefix, style, label, ...args)
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
function createTabSync(options) {
|
|
1060
|
+
const opts = options ?? {};
|
|
1061
|
+
const tabId = generateTabId();
|
|
1062
|
+
const tabCreatedAt = Date.now();
|
|
1063
|
+
const channelName = opts.channel ?? "tab-sync";
|
|
1064
|
+
const debug = opts.debug ?? false;
|
|
1065
|
+
const onError = opts.onError ?? (() => {
|
|
1066
|
+
});
|
|
1067
|
+
const leaderEnabled = opts.leader !== false;
|
|
1068
|
+
const leaderOpts = typeof opts.leader === "object" ? opts.leader : {};
|
|
1069
|
+
const heartbeatInterval = opts.heartbeatInterval ?? leaderOpts.heartbeatInterval ?? 2e3;
|
|
1070
|
+
const leaderTimeout = opts.leaderTimeout ?? leaderOpts.leaderTimeout ?? 6e3;
|
|
1071
|
+
const missedHeartbeatsLimit = Math.max(
|
|
1072
|
+
1,
|
|
1073
|
+
Math.round(leaderTimeout / heartbeatInterval)
|
|
1074
|
+
);
|
|
1075
|
+
const middlewares = [...opts.middlewares ?? []];
|
|
1076
|
+
const persistOpts = resolvePersistOptions(opts.persist);
|
|
1077
|
+
const persister = persistOpts ? createPersistSaver(persistOpts, onError) : null;
|
|
1078
|
+
let initialState = opts.initial ?? {};
|
|
1079
|
+
if (persistOpts) {
|
|
1080
|
+
const restored = loadPersistedState(persistOpts);
|
|
1081
|
+
if (Object.keys(restored).length > 0) {
|
|
1082
|
+
initialState = { ...initialState, ...restored };
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
const channel = createChannel(channelName, opts.transport);
|
|
1086
|
+
const { log } = createLogger(debug, tabId);
|
|
1087
|
+
const send = (message) => {
|
|
1088
|
+
log("\u2192", message.type, message.payload);
|
|
1089
|
+
channel.postMessage(message);
|
|
1090
|
+
};
|
|
1091
|
+
const stateManager = new StateManager({
|
|
1092
|
+
send,
|
|
1093
|
+
tabId,
|
|
1094
|
+
initial: initialState,
|
|
1095
|
+
merge: opts.merge,
|
|
1096
|
+
afterRemoteChange(key, value, meta) {
|
|
1097
|
+
notifyMiddleware(middlewares, key, value, meta);
|
|
1098
|
+
if (persister) persister.save(stateManager.getAll());
|
|
1099
|
+
}
|
|
1100
|
+
});
|
|
1101
|
+
const registry = new TabRegistry({
|
|
1102
|
+
send,
|
|
1103
|
+
tabId,
|
|
1104
|
+
tabCreatedAt,
|
|
1105
|
+
heartbeatInterval,
|
|
1106
|
+
tabTimeout: leaderTimeout
|
|
1107
|
+
});
|
|
1108
|
+
let election = null;
|
|
1109
|
+
if (leaderEnabled) {
|
|
1110
|
+
election = new LeaderElection({
|
|
1111
|
+
send,
|
|
1112
|
+
tabId,
|
|
1113
|
+
tabCreatedAt,
|
|
1114
|
+
heartbeatInterval,
|
|
1115
|
+
missedHeartbeatsLimit
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
const rpc = new RPCHandler({
|
|
1119
|
+
send,
|
|
1120
|
+
tabId,
|
|
1121
|
+
resolveLeaderId: () => election?.getLeaderId() ?? null,
|
|
1122
|
+
onError
|
|
1123
|
+
});
|
|
1124
|
+
const unsubChannel = channel.onMessage((message) => {
|
|
1125
|
+
log("\u2190", message.type, `from=${message.senderId}`);
|
|
1126
|
+
if (message.senderId === tabId) return;
|
|
1127
|
+
if (message.version && message.version > PROTOCOL_VERSION) {
|
|
1128
|
+
log("\u26A0\uFE0F", `Unknown protocol v${message.version}, ignoring`);
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
registry.handleMessage(message);
|
|
1132
|
+
switch (message.type) {
|
|
1133
|
+
case "STATE_UPDATE":
|
|
1134
|
+
case "STATE_SYNC_RESPONSE":
|
|
1135
|
+
stateManager.handleMessage(message);
|
|
1136
|
+
break;
|
|
1137
|
+
case "STATE_SYNC_REQUEST":
|
|
1138
|
+
if (election?.isLeader() ?? true) {
|
|
1139
|
+
stateManager.respondToSync(message.senderId);
|
|
1140
|
+
}
|
|
1141
|
+
break;
|
|
1142
|
+
case "LEADER_CLAIM":
|
|
1143
|
+
case "LEADER_ACK":
|
|
1144
|
+
case "LEADER_HEARTBEAT":
|
|
1145
|
+
case "LEADER_RESIGN":
|
|
1146
|
+
election?.handleMessage(message);
|
|
1147
|
+
if (election) {
|
|
1148
|
+
registry.setLeader(election.getLeaderId());
|
|
1149
|
+
}
|
|
1150
|
+
break;
|
|
1151
|
+
case "RPC_REQUEST":
|
|
1152
|
+
case "RPC_RESPONSE":
|
|
1153
|
+
rpc.handleMessage(message);
|
|
1154
|
+
break;
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
registry.announce();
|
|
1158
|
+
stateManager.requestSync();
|
|
1159
|
+
election?.start();
|
|
1160
|
+
let ready = true;
|
|
1161
|
+
let destroyed = false;
|
|
1162
|
+
function middlewareSet(key, value) {
|
|
1163
|
+
if (middlewares.length === 0) {
|
|
1164
|
+
stateManager.set(key, value);
|
|
1165
|
+
if (persister) persister.save(stateManager.getAll());
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
const meta = { sourceTabId: tabId, isLocal: true, timestamp: Date.now() };
|
|
1169
|
+
const { value: finalValue, rejected } = runMiddleware(middlewares, {
|
|
1170
|
+
key,
|
|
1171
|
+
value,
|
|
1172
|
+
previousValue: stateManager.get(key),
|
|
1173
|
+
meta
|
|
1174
|
+
});
|
|
1175
|
+
if (rejected) {
|
|
1176
|
+
log("\u{1F6AB}", `Middleware rejected set("${String(key)}")`);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
stateManager.set(key, finalValue);
|
|
1180
|
+
notifyMiddleware(middlewares, key, finalValue, meta);
|
|
1181
|
+
if (persister) persister.save(stateManager.getAll());
|
|
1182
|
+
}
|
|
1183
|
+
function middlewarePatch(partial) {
|
|
1184
|
+
if (middlewares.length === 0) {
|
|
1185
|
+
stateManager.patch(partial);
|
|
1186
|
+
if (persister) persister.save(stateManager.getAll());
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
const meta = { sourceTabId: tabId, isLocal: true, timestamp: Date.now() };
|
|
1190
|
+
const filtered = {};
|
|
1191
|
+
const appliedKeys = [];
|
|
1192
|
+
for (const [key, value] of Object.entries(partial)) {
|
|
1193
|
+
const k = key;
|
|
1194
|
+
const { value: finalValue, rejected } = runMiddleware(middlewares, {
|
|
1195
|
+
key: k,
|
|
1196
|
+
value,
|
|
1197
|
+
previousValue: stateManager.get(k),
|
|
1198
|
+
meta
|
|
1199
|
+
});
|
|
1200
|
+
if (!rejected) {
|
|
1201
|
+
filtered[key] = finalValue;
|
|
1202
|
+
appliedKeys.push(k);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
if (Object.keys(filtered).length > 0) {
|
|
1206
|
+
stateManager.patch(filtered);
|
|
1207
|
+
for (const k of appliedKeys) {
|
|
1208
|
+
notifyMiddleware(middlewares, k, stateManager.get(k), meta);
|
|
1209
|
+
}
|
|
1210
|
+
if (persister) persister.save(stateManager.getAll());
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
const instance = {
|
|
1214
|
+
// State
|
|
1215
|
+
get: (key) => stateManager.get(key),
|
|
1216
|
+
getAll: () => stateManager.getAll(),
|
|
1217
|
+
set: middlewareSet,
|
|
1218
|
+
patch: middlewarePatch,
|
|
1219
|
+
// Subscriptions
|
|
1220
|
+
on: (key, callback) => stateManager.on(key, callback),
|
|
1221
|
+
once: (key, callback) => {
|
|
1222
|
+
const unsub = stateManager.on(key, ((value, meta) => {
|
|
1223
|
+
unsub();
|
|
1224
|
+
callback(value, meta);
|
|
1225
|
+
}));
|
|
1226
|
+
return unsub;
|
|
1227
|
+
},
|
|
1228
|
+
onChange: (callback) => stateManager.onChange(callback),
|
|
1229
|
+
select: (selector, callback, isEqual = Object.is) => {
|
|
1230
|
+
let prev = selector(stateManager.getAll());
|
|
1231
|
+
return stateManager.onChange((state, _keys, meta) => {
|
|
1232
|
+
const next = selector(state);
|
|
1233
|
+
if (!isEqual(prev, next)) {
|
|
1234
|
+
prev = next;
|
|
1235
|
+
callback(next, meta);
|
|
1236
|
+
}
|
|
1237
|
+
});
|
|
1238
|
+
},
|
|
1239
|
+
// Leader
|
|
1240
|
+
isLeader: () => election?.isLeader() ?? true,
|
|
1241
|
+
onLeader: (callback) => {
|
|
1242
|
+
if (!election) {
|
|
1243
|
+
const cleanup = callback();
|
|
1244
|
+
return () => {
|
|
1245
|
+
if (typeof cleanup === "function") cleanup();
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
return election.onLeader(callback);
|
|
1249
|
+
},
|
|
1250
|
+
getLeader: () => {
|
|
1251
|
+
const leaderId = election?.getLeaderId();
|
|
1252
|
+
if (!leaderId) return null;
|
|
1253
|
+
return registry.getTab(leaderId) ?? null;
|
|
1254
|
+
},
|
|
1255
|
+
waitForLeader: () => {
|
|
1256
|
+
const leader = instance.getLeader();
|
|
1257
|
+
if (leader) return Promise.resolve(leader);
|
|
1258
|
+
return new Promise((resolve) => {
|
|
1259
|
+
const unsubs = [];
|
|
1260
|
+
const check = () => {
|
|
1261
|
+
const l = instance.getLeader();
|
|
1262
|
+
if (l) {
|
|
1263
|
+
for (const u of unsubs) u();
|
|
1264
|
+
resolve(l);
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
unsubs.push(registry.onTabChange(check));
|
|
1268
|
+
if (election) {
|
|
1269
|
+
unsubs.push(election.onLeader(() => {
|
|
1270
|
+
check();
|
|
1271
|
+
return () => {
|
|
1272
|
+
};
|
|
1273
|
+
}));
|
|
1274
|
+
}
|
|
1275
|
+
});
|
|
1276
|
+
},
|
|
1277
|
+
// Tabs
|
|
1278
|
+
id: tabId,
|
|
1279
|
+
getTabs: () => registry.getTabs(),
|
|
1280
|
+
getTabCount: () => registry.getTabCount(),
|
|
1281
|
+
onTabChange: (callback) => registry.onTabChange(callback),
|
|
1282
|
+
// RPC
|
|
1283
|
+
call: ((target, method, args, timeout) => rpc.call(target, method, args, timeout)),
|
|
1284
|
+
handle: ((method, handler) => rpc.handle(method, handler)),
|
|
1285
|
+
// Lifecycle
|
|
1286
|
+
destroy: () => {
|
|
1287
|
+
if (destroyed) return;
|
|
1288
|
+
destroyed = true;
|
|
1289
|
+
ready = false;
|
|
1290
|
+
stateManager.flush();
|
|
1291
|
+
persister?.destroy();
|
|
1292
|
+
destroyMiddleware(middlewares);
|
|
1293
|
+
election?.destroy();
|
|
1294
|
+
registry.destroy();
|
|
1295
|
+
rpc.destroy();
|
|
1296
|
+
stateManager.destroy();
|
|
1297
|
+
unsubChannel();
|
|
1298
|
+
channel.close();
|
|
1299
|
+
log("\u{1F480}", "Instance destroyed");
|
|
1300
|
+
},
|
|
1301
|
+
get ready() {
|
|
1302
|
+
return ready;
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
log("\u{1F680}", "Instance created", { channel: channelName, leader: leaderEnabled });
|
|
1306
|
+
return instance;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
export { BroadcastChannelTransport, ErrorCode, LeaderElection, PROTOCOL_VERSION, RPCHandler, StateManager, StorageChannel, TabRegistry, TabSyncError, createBatcher, createChannel, createTabSync, destroyMiddleware, generateTabId, hasBroadcastChannel, hasCrypto, hasDocument, hasLocalStorage, isBrowser, monotonic, notifyMiddleware, runMiddleware };
|