react-broadcast-sync 1.11.2 → 2.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/README.md +155 -30
- package/TELEMETRY.md +13 -19
- package/dist/BroadcastProvider.d.ts +21 -2
- package/dist/hooks/useBroadcastChannel.d.ts +19 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/types/types.d.ts +8 -10
- package/llms.txt +367 -0
- package/package.json +16 -3
- package/skills/react-broadcast-sync/SKILL.md +102 -0
package/README.md
CHANGED
|
@@ -34,6 +34,17 @@
|
|
|
34
34
|
|
|
35
35
|
Easily sync UI state or user events across browser tabs in React apps — notifications, presence, forms, and more. This package provides a clean and type-safe abstraction over the native API, enabling efficient, scoped, and reliable cross-tab messaging.
|
|
36
36
|
|
|
37
|
+
**When to use it:** React apps that need to share ephemeral state or events between browser tabs of the same origin (logout, notifications, presence, draft sync). It wraps the browser `BroadcastChannel` API in a hook (`useBroadcastChannel`) and an optional `BroadcastProvider`.
|
|
38
|
+
|
|
39
|
+
**When not to use it:** syncing to a server or other devices, persisting data across reloads (use `localStorage`/IndexedDB), or messaging across different origins.
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
import { useBroadcastChannel } from 'react-broadcast-sync';
|
|
43
|
+
|
|
44
|
+
const { messages, postMessage } = useBroadcastChannel('my-channel');
|
|
45
|
+
postMessage('logout', { at: Date.now() }); // other tabs receive it in `messages`
|
|
46
|
+
```
|
|
47
|
+
|
|
37
48
|
<p align="center">
|
|
38
49
|
<img src="https://raw.githubusercontent.com/IdanShalem/react-broadcast-sync/main/demo/react-broadcast-sync-demo/public/assets/react-broadcast-sync-demo-video.gif" alt="React Broadcast Sync Demo" width="600" />
|
|
39
50
|
</p>
|
|
@@ -41,12 +52,15 @@ Easily sync UI state or user events across browser tabs in React apps — notifi
|
|
|
41
52
|
## Table of Contents
|
|
42
53
|
|
|
43
54
|
- [Features](#features)
|
|
55
|
+
- [Why Not localStorage?](#why-not-localstorage)
|
|
44
56
|
- [Demo App](#demo-app)
|
|
45
57
|
- [Installation](#installation)
|
|
46
58
|
- [Quick Start](#quick-start)
|
|
47
59
|
- [Advanced Usage](#️advanced-usage)
|
|
48
60
|
- [BroadcastProvider](#using-broadcastprovider)
|
|
49
61
|
- [API Reference](#api-reference)
|
|
62
|
+
- [Agent Skill](#agent-skill-optional)
|
|
63
|
+
- [Gotchas](#gotchas)
|
|
50
64
|
- [Best Practices](#best-practices)
|
|
51
65
|
- [Common Use Cases](#common-use-cases)
|
|
52
66
|
- [Performance Considerations](#performance-considerations)
|
|
@@ -74,6 +88,25 @@ Easily sync UI state or user events across browser tabs in React apps — notifi
|
|
|
74
88
|
- **Ping and active source detection** (discover other tabs and their source names)
|
|
75
89
|
- **Per-type `onMessage` callbacks** (react to incoming messages without polling state)
|
|
76
90
|
|
|
91
|
+
## Why Not localStorage?
|
|
92
|
+
|
|
93
|
+
The first instinct for sharing state between tabs is often `localStorage` plus the `storage` event. It works for simple cases, but it was designed for persistence, not messaging - and the ecosystem offers a few different trade-offs. Here's how `react-broadcast-sync` compares:
|
|
94
|
+
|
|
95
|
+
| | **react-broadcast-sync** | **localStorage + `storage` events** | **jotai `atomWithStorage`** | **`broadcast-channel`** | **`zustand-sync-tabs`** |
|
|
96
|
+
| ------------------ | ------------------------------------------------------- | ------------------------------------- | ----------------------------- | ------------------------------------ | ----------------------- |
|
|
97
|
+
| What it syncs | Typed messages on named channels | Raw key-value strings | A single persisted atom value | Messages on a channel | A Zustand store's state |
|
|
98
|
+
| React integration | First-class hook + provider | Manual event listeners | Requires Jotai | None - framework agnostic | Requires Zustand |
|
|
99
|
+
| Payloads | Any serializable value | Strings only (manual JSON) | JSON-serializable value | Any serializable value | Store state |
|
|
100
|
+
| Message lifecycle | Expiration, deduplication, batching, selective clearing | None | None | None | Latest state only |
|
|
101
|
+
| Tab awareness | Source naming, ping & active-source detection | None (no event in the tab that wrote) | None | Leader election | None |
|
|
102
|
+
| Extra environments | Browsers (same origin) | Browsers (same origin) | React Native via AsyncStorage | Old browsers, WebWorkers, Node, Deno | Browsers (same origin) |
|
|
103
|
+
|
|
104
|
+
A few honest notes:
|
|
105
|
+
|
|
106
|
+
- **If you need persistence across reloads**, use a storage-based tool (`atomWithStorage`, plain `localStorage`). Messages in `react-broadcast-sync` are ephemeral - they notify and sync live tabs, they don't survive a refresh.
|
|
107
|
+
- **If you need old-browser, WebWorker, or Node support**, [`broadcast-channel`](https://github.com/pubkey/broadcast-channel) is the right low-level primitive. `react-broadcast-sync` builds on the native `BroadcastChannel` API and gives you the React layer on top: hooks, typed messages, and lifecycle handling out of the box.
|
|
108
|
+
- **If your app already lives in Zustand or Jotai**, their sync utilities may be enough. `react-broadcast-sync` is state-manager agnostic - it works next to any of them, or with plain `useState`.
|
|
109
|
+
|
|
77
110
|
## Demo App
|
|
78
111
|
|
|
79
112
|
Check out our [live demo](https://react-broadcast-sync-3w3m.vercel.app/) to see the library in action! The demo showcases three main features:
|
|
@@ -226,6 +259,64 @@ All fields in `BroadcastOptions` (see the table in the [API Reference](#broadcas
|
|
|
226
259
|
</BroadcastProvider>
|
|
227
260
|
```
|
|
228
261
|
|
|
262
|
+
## Syncing Shared State (filters, settings)
|
|
263
|
+
|
|
264
|
+
`messages` is an event log of what other tabs sent, not the current state. To keep a piece of state
|
|
265
|
+
(for example dashboard filters) in sync, update local state and send one message from the handler,
|
|
266
|
+
and apply incoming messages with `onMessage`:
|
|
267
|
+
|
|
268
|
+
```tsx
|
|
269
|
+
function Dashboard() {
|
|
270
|
+
const [filters, setFilters] = useState({ status: 'all' });
|
|
271
|
+
|
|
272
|
+
const { postMessage } = useBroadcastChannel('dashboard', {
|
|
273
|
+
// sourceName is optional: a unique one is generated for each tab.
|
|
274
|
+
// Do not build it inline with crypto.randomUUID(): it would change on every render.
|
|
275
|
+
onMessage: {
|
|
276
|
+
'filters-update': msg => setFilters(msg.message),
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
const updateFilters = (next: typeof filters) => {
|
|
281
|
+
setFilters(next);
|
|
282
|
+
postMessage('filters-update', next);
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
return <FilterBar value={filters} onChange={updateFilters} />;
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Do not call `postMessage` from a `useEffect` on state that you also set from incoming messages.
|
|
290
|
+
Each tab re-broadcasts what it receives, the tabs ping-pong, and they can end up with different
|
|
291
|
+
values. Deduplication is by message ID, so it does not stop this.
|
|
292
|
+
|
|
293
|
+
### New tabs do not receive past messages
|
|
294
|
+
|
|
295
|
+
Messages are not replayed. A tab opened later only sees messages sent after it opened, and
|
|
296
|
+
`keepLatestMessage` and `getLatestMessage` do not change that. To give a new tab the current state,
|
|
297
|
+
let it ask for it and let an existing tab answer:
|
|
298
|
+
|
|
299
|
+
```tsx
|
|
300
|
+
const { postMessage } = useBroadcastChannel('dashboard', {
|
|
301
|
+
sourceName: sourceName, // unique per tab
|
|
302
|
+
onMessage: {
|
|
303
|
+
'filters-update': msg => setFilters(msg.message),
|
|
304
|
+
'state-request': () => postMessage('filters-update', filtersRef.current),
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
// Ask once when this tab mounts
|
|
309
|
+
useEffect(() => {
|
|
310
|
+
postMessage('state-request', null);
|
|
311
|
+
}, []);
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Keep the current value in a ref (`filtersRef.current = filters`) so the `state-request` handler
|
|
315
|
+
always answers with the latest state. If no other tab is open, nothing answers and the tab keeps its
|
|
316
|
+
default state.
|
|
317
|
+
|
|
318
|
+
---
|
|
319
|
+
|
|
229
320
|
---
|
|
230
321
|
|
|
231
322
|
## API Reference
|
|
@@ -248,7 +339,7 @@ const {
|
|
|
248
339
|
|
|
249
340
|
```typescript
|
|
250
341
|
interface BroadcastOptions {
|
|
251
|
-
sourceName?: string; // Custom name for the message source
|
|
342
|
+
sourceName?: string; // Custom name for the message source. Must be unique per tab: a tab ignores messages from its own sourceName
|
|
252
343
|
cleaningInterval?: number; // Interval in ms for cleaning expired messages (default: 1000)
|
|
253
344
|
keepLatestMessage?: boolean; // Keep only the latest message (default: false)
|
|
254
345
|
registeredTypes?: string[]; // List of allowed message types
|
|
@@ -258,25 +349,25 @@ interface BroadcastOptions {
|
|
|
258
349
|
batchingDelayMs?: number; // Delay in ms to batch outgoing messages (default: 20). If > 0, messages are batched and sent together.
|
|
259
350
|
excludedBatchMessageTypes?: string[]; // Message types to always send immediately, never batched (default: []).
|
|
260
351
|
onMessage?: MessageCallback | OnMessageMap; // Callback(s) fired when a received message passes all filters (default: undefined).
|
|
261
|
-
telemetry?: boolean; //
|
|
352
|
+
telemetry?: boolean; // Privacy-first: off by default. Pass true to opt in.
|
|
262
353
|
}
|
|
263
354
|
```
|
|
264
355
|
|
|
265
356
|
#### Default Values
|
|
266
357
|
|
|
267
|
-
| Option | Default Value | Description
|
|
268
|
-
| --------------------------- | ------------- |
|
|
269
|
-
| `sourceName` | `undefined` | Auto-generated if not provided
|
|
270
|
-
| `cleaningInterval` | `1000` | 1 second between cleanup runs
|
|
271
|
-
| `keepLatestMessage` | `false` | Keep all messages by default
|
|
272
|
-
| `registeredTypes` | `[]` | Accept all message types by default
|
|
273
|
-
| `namespace` | `''` | No namespace by default
|
|
274
|
-
| `deduplicationTTL` | `300000` | 5 minutes (5 × 60 × 1000 ms)
|
|
275
|
-
| `cleanupDebounceMs` | `0` | No debounce by default
|
|
276
|
-
| `batchingDelayMs` | `20` | Batch delay in ms (0 = off)
|
|
277
|
-
| `excludedBatchMessageTypes` | `[]` | Types never batched
|
|
278
|
-
| `onMessage` | `undefined` | Callback(s) for received messages
|
|
279
|
-
| `telemetry` | `
|
|
358
|
+
| Option | Default Value | Description |
|
|
359
|
+
| --------------------------- | ------------- | -------------------------------------------- |
|
|
360
|
+
| `sourceName` | `undefined` | Auto-generated if not provided |
|
|
361
|
+
| `cleaningInterval` | `1000` | 1 second between cleanup runs |
|
|
362
|
+
| `keepLatestMessage` | `false` | Keep all messages by default |
|
|
363
|
+
| `registeredTypes` | `[]` | Accept all message types by default |
|
|
364
|
+
| `namespace` | `''` | No namespace by default |
|
|
365
|
+
| `deduplicationTTL` | `300000` | 5 minutes (5 × 60 × 1000 ms) |
|
|
366
|
+
| `cleanupDebounceMs` | `0` | No debounce by default |
|
|
367
|
+
| `batchingDelayMs` | `20` | Batch delay in ms (0 = off) |
|
|
368
|
+
| `excludedBatchMessageTypes` | `[]` | Types never batched |
|
|
369
|
+
| `onMessage` | `undefined` | Callback(s) for received messages |
|
|
370
|
+
| `telemetry` | `false` | Anonymous usage stats. Pass `true` to opt in |
|
|
280
371
|
|
|
281
372
|
#### Return Value
|
|
282
373
|
|
|
@@ -488,7 +579,7 @@ useBroadcastChannel('my-channel', {
|
|
|
488
579
|
|
|
489
580
|
#### `telemetry` Option
|
|
490
581
|
|
|
491
|
-
`react-broadcast-sync` collects
|
|
582
|
+
**Privacy-first: telemetry is off by default.** Nothing is sent to Mixpanel unless you explicitly set `telemetry: true` on the hook or provider. When enabled, `react-broadcast-sync` collects structural usage signals to help the maintainer understand how the library is used.
|
|
492
583
|
|
|
493
584
|
**What is collected:**
|
|
494
585
|
|
|
@@ -502,9 +593,17 @@ useBroadcastChannel('my-channel', {
|
|
|
502
593
|
**What is never collected:**
|
|
503
594
|
|
|
504
595
|
- Channel names, source names, message content, or message types
|
|
505
|
-
- Any user
|
|
596
|
+
- Any application user identifiers in the event payload (Mixpanel may process IP addresses from request metadata)
|
|
597
|
+
|
|
598
|
+
Telemetry is **off by default**. Pass `telemetry: true` to opt in for a channel:
|
|
506
599
|
|
|
507
|
-
|
|
600
|
+
```tsx
|
|
601
|
+
useBroadcastChannel('my-channel', { telemetry: true });
|
|
602
|
+
// or
|
|
603
|
+
<BroadcastProvider channelName="my-channel" options={{ telemetry: true }} />;
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
**Upgrading to 2.0.0 from 1.x:** telemetry is now off by default. Omit the option or leave `telemetry: false` to keep it off; pass `telemetry: true` only if you want to opt in. This default change is breaking.
|
|
508
607
|
|
|
509
608
|
Events are batched and flushed in a single request when the tab is hidden or after 30 seconds. A failed request is silently discarded and never surfaces to your application.
|
|
510
609
|
|
|
@@ -512,6 +611,26 @@ See [TELEMETRY.md](./TELEMETRY.md) for the full legal notice.
|
|
|
512
611
|
|
|
513
612
|
---
|
|
514
613
|
|
|
614
|
+
## Agent Skill (optional)
|
|
615
|
+
|
|
616
|
+
The package ships an agent skill at `skills/react-broadcast-sync/SKILL.md` (the [agentskills.io](https://agentskills.io) format) with safe recipes for coding agents. Nothing is installed automatically: there is no postinstall script and your agent settings are never modified. To use it, copy it into your project yourself:
|
|
617
|
+
|
|
618
|
+
```bash
|
|
619
|
+
mkdir -p .agents/skills
|
|
620
|
+
cp -r node_modules/react-broadcast-sync/skills/react-broadcast-sync .agents/skills/
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
Tools such as `skills-npm` can also extract it for you. Check your agent's docs for where it reads skills from.
|
|
624
|
+
|
|
625
|
+
## Gotchas
|
|
626
|
+
|
|
627
|
+
- **Duplicate `sourceName`:** a tab ignores any message whose `source` equals its own `sourceName`. If two tabs use the same `sourceName`, they will not receive each other's messages. Leave it unset (a unique name is generated) unless you need a stable name, and keep it unique per tab.
|
|
628
|
+
- **`keepLatestMessage` is one slot:** with `keepLatestMessage: true`, `messages` holds only the single most recent message across all types, so a `"b"` message replaces a prior `"a"`. Use `registeredTypes` or separate channels/namespaces if you need the latest message per type.
|
|
629
|
+
- **`cleanupDebounceMs` vs `cleaningInterval`:** cleanup is debounced. If `cleanupDebounceMs` is longer than `cleaningInterval`, each interval tick restarts the debounce and expired messages may never be removed. Keep `cleanupDebounceMs` smaller than `cleaningInterval`.
|
|
630
|
+
- **Deduplication is by message ID**, not content (see [Message Deduplication](#message-deduplication)).
|
|
631
|
+
- **Same origin only:** `BroadcastChannel` does not cross origins, and a tab does not receive its own messages.
|
|
632
|
+
- **Telemetry is off by default:** pass `telemetry: true` to opt in (see [Telemetry](#telemetry)).
|
|
633
|
+
|
|
515
634
|
## Best Practices
|
|
516
635
|
|
|
517
636
|
- **Use `namespace`** to isolate functionality between different app modules.
|
|
@@ -635,11 +754,10 @@ postMessage('alert', { message: 'Something happened!' });
|
|
|
635
754
|
|
|
636
755
|
### Message Deduplication
|
|
637
756
|
|
|
638
|
-
The `deduplicationTTL` option creates a time window (in milliseconds) during which
|
|
757
|
+
The `deduplicationTTL` option creates a time window (in milliseconds) during which a received message with an already-seen **message ID** is ignored. Deduplication is by ID, not by content: two separate `postMessage` calls with identical type and payload get different IDs and are both delivered. This is particularly useful for:
|
|
639
758
|
|
|
640
759
|
- **Preventing Message Loops**: Avoids infinite message echo between tabs when they broadcast the same message back and forth
|
|
641
|
-
- **Reducing Redundancy**:
|
|
642
|
-
- **Natural Debouncing**: Provides built-in debouncing behavior for broadcast events without additional code
|
|
760
|
+
- **Reducing Redundancy**: Drops the same message if it is delivered to a tab more than once within the window
|
|
643
761
|
|
|
644
762
|
Recommended TTL values based on use case:
|
|
645
763
|
|
|
@@ -715,18 +833,25 @@ This will log:
|
|
|
715
833
|
import { renderHook, act } from '@testing-library/react-hooks';
|
|
716
834
|
import { useBroadcastChannel } from 'react-broadcast-sync';
|
|
717
835
|
|
|
718
|
-
test('
|
|
836
|
+
test('postMessage records the message in sentMessages', () => {
|
|
719
837
|
const { result } = renderHook(() => useBroadcastChannel('test-channel'));
|
|
720
838
|
|
|
721
839
|
act(() => {
|
|
722
840
|
result.current.postMessage('test', { data: 'hello' });
|
|
723
841
|
});
|
|
724
842
|
|
|
725
|
-
|
|
726
|
-
|
|
843
|
+
// The hook does not echo your own messages back into `messages`.
|
|
844
|
+
// `messages` only holds messages sent by other tabs or hook instances.
|
|
845
|
+
expect(result.current.messages).toHaveLength(0);
|
|
846
|
+
expect(result.current.sentMessages).toHaveLength(1);
|
|
847
|
+
expect(result.current.sentMessages[0].message.data).toBe('hello');
|
|
727
848
|
});
|
|
728
849
|
```
|
|
729
850
|
|
|
851
|
+
To test receiving, render two hooks with different `sourceName` values on the same channel name
|
|
852
|
+
(this needs a `BroadcastChannel` implementation in the test environment, such as a mock that
|
|
853
|
+
delivers to other instances). The message sent by one appears in the other's `messages`.
|
|
854
|
+
|
|
730
855
|
### Integration Testing
|
|
731
856
|
|
|
732
857
|
```tsx
|
|
@@ -779,16 +904,16 @@ Relies on [BroadcastChannel API](https://developer.mozilla.org/en-US/docs/Web/AP
|
|
|
779
904
|
|
|
780
905
|
## Telemetry
|
|
781
906
|
|
|
782
|
-
|
|
907
|
+
**Privacy-first: telemetry is off by default.** Only when you explicitly pass `telemetry: true` does `react-broadcast-sync` send structural usage statistics to Mixpanel. No channel names, source names, message content, or application user identifiers are included in the event payload. Mixpanel may process request metadata, including IP addresses; see TELEMETRY.md.
|
|
783
908
|
|
|
784
|
-
|
|
909
|
+
If telemetry is enabled, a random session ID is generated per page load and not persisted by this package. Mixpanel may still process request metadata such as IP addresses.
|
|
785
910
|
|
|
786
|
-
**To opt
|
|
911
|
+
**To opt in**, pass `telemetry: true`:
|
|
787
912
|
|
|
788
913
|
```tsx
|
|
789
|
-
useBroadcastChannel('my-channel', { telemetry:
|
|
914
|
+
useBroadcastChannel('my-channel', { telemetry: true });
|
|
790
915
|
// or
|
|
791
|
-
<BroadcastProvider channelName="my-channel" options={{ telemetry:
|
|
916
|
+
<BroadcastProvider channelName="my-channel" options={{ telemetry: true }} />;
|
|
792
917
|
```
|
|
793
918
|
|
|
794
919
|
See [TELEMETRY.md](./TELEMETRY.md) for full details, legal basis, and the complete list of signals collected.
|
|
@@ -809,7 +934,7 @@ We're actively improving `react-broadcast-sync`! Here are some features and enha
|
|
|
809
934
|
Real browser cross-tab tests using Playwright that go beyond what jsdom mocks can cover.
|
|
810
935
|
|
|
811
936
|
- **Anonymous Usage Telemetry**
|
|
812
|
-
✅ Released — the package
|
|
937
|
+
✅ Released — off by default in 2.0.0. Only with `telemetry: true` does the package send structural signals (options used, methods called, hook vs. provider). No message content or application user identifiers in the event payload; Mixpanel may process request metadata such as IP addresses.
|
|
813
938
|
|
|
814
939
|
We're committed to keeping this package lightweight, flexible, and production-ready.
|
|
815
940
|
Your feedback and contributions are welcome — feel free to [open an issue](https://github.com/IdanShalem/react-broadcast-sync/issues)!
|
package/TELEMETRY.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## What is collected
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
**Privacy-first: telemetry is off by default.** No usage events are sent to Mixpanel unless the application explicitly passes `telemetry: true` to `useBroadcastChannel` or `BroadcastProvider`. When enabled, structural usage signals help the maintainer prioritise features and fix issues.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
When telemetry is enabled, the following structural signals are sent on channel mount or method use:
|
|
8
8
|
|
|
9
9
|
| Signal | Description |
|
|
10
10
|
| ------------------- | --------------------------------------------------------------------------------------------- |
|
|
@@ -20,8 +20,8 @@ The following structural signals are sent on every channel mount:
|
|
|
20
20
|
- Channel names
|
|
21
21
|
- Source names (`sourceName`)
|
|
22
22
|
- Message content or message types
|
|
23
|
-
-
|
|
24
|
-
- IP addresses (Mixpanel may
|
|
23
|
+
- Application user identifiers in the event payload
|
|
24
|
+
- IP addresses in the event payload (Mixpanel may process them from request metadata; see its privacy policy)
|
|
25
25
|
- Any data from the messages your application sends or receives
|
|
26
26
|
|
|
27
27
|
## Session identifier
|
|
@@ -30,35 +30,29 @@ Each page load generates a random, ephemeral session ID using `crypto.randomUUID
|
|
|
30
30
|
|
|
31
31
|
- Is **not persisted** to cookies, `localStorage`, `sessionStorage`, or any other storage mechanism.
|
|
32
32
|
- Is **regenerated on every page load**, making it impossible to track users across sessions.
|
|
33
|
-
-
|
|
33
|
+
- Does not by itself identify a user, though the recipient may process request metadata such as IP addresses.
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
## Legal basis
|
|
38
|
-
|
|
39
|
-
The data collected is fully anonymous and structural. No personal data or data that can identify a natural person is processed. The collection falls under the **legitimate interests** of the package maintainer (GDPR Article 6(1)(f)) to understand aggregate library usage patterns.
|
|
40
|
-
|
|
41
|
-
Because no cookies or persistent identifiers are set on the user's device, the ePrivacy Directive (Directive 2002/58/EC) cookie consent requirements do not apply.
|
|
35
|
+
The session ID is not persisted by this package, but Mixpanel may process request metadata such as IP addresses. Applications enabling telemetry should assess their own privacy obligations and disclose this transfer to their users.
|
|
42
36
|
|
|
43
37
|
## Data processor
|
|
44
38
|
|
|
45
39
|
Usage statistics are processed by [Mixpanel](https://mixpanel.com). Mixpanel's privacy policy is available at [https://mixpanel.com/legal/privacy-policy/](https://mixpanel.com/legal/privacy-policy/).
|
|
46
40
|
|
|
47
|
-
## How to opt
|
|
41
|
+
## How to opt in
|
|
48
42
|
|
|
49
|
-
Telemetry is
|
|
43
|
+
Telemetry is disabled by default. Enable it explicitly per hook or provider with `telemetry: true`:
|
|
50
44
|
|
|
51
45
|
```tsx
|
|
52
|
-
//
|
|
53
|
-
useBroadcastChannel('my-channel', { telemetry:
|
|
46
|
+
// Enable for a specific channel
|
|
47
|
+
useBroadcastChannel('my-channel', { telemetry: true });
|
|
54
48
|
|
|
55
|
-
//
|
|
56
|
-
<BroadcastProvider channelName="my-channel" options={{ telemetry:
|
|
49
|
+
// Enable via BroadcastProvider
|
|
50
|
+
<BroadcastProvider channelName="my-channel" options={{ telemetry: true }}>
|
|
57
51
|
<App />
|
|
58
52
|
</BroadcastProvider>;
|
|
59
53
|
```
|
|
60
54
|
|
|
61
|
-
There is no penalty
|
|
55
|
+
There is no penalty or degraded functionality when leaving telemetry off. Upgrading from a version where telemetry was enabled by default? No option is needed to keep it off; use `telemetry: true` only if you want to opt in.
|
|
62
56
|
|
|
63
57
|
## Contact
|
|
64
58
|
|
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import { BroadcastActions, BroadcastOptions } from './types/types';
|
|
3
|
-
interface BroadcastProviderProps {
|
|
3
|
+
export interface BroadcastProviderProps {
|
|
4
|
+
/** Name of the BroadcastChannel. Combined with `options.namespace` when one is set. */
|
|
4
5
|
channelName: string;
|
|
6
|
+
/** Same options as `useBroadcastChannel`. */
|
|
5
7
|
options?: BroadcastOptions;
|
|
6
8
|
children: React.ReactNode;
|
|
7
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* Opens one BroadcastChannel (by calling `useBroadcastChannel` once) and shares it with all
|
|
12
|
+
* descendants through context. Read it with `useBroadcastProvider()`.
|
|
13
|
+
*
|
|
14
|
+
* Same rules as the hook: the tab ignores its own messages, `messages` is an event log (not
|
|
15
|
+
* current state), and a tab opened later does not receive earlier messages.
|
|
16
|
+
*
|
|
17
|
+
* ```tsx
|
|
18
|
+
* <BroadcastProvider channelName="app" options={{ namespace: 'v1' }}>
|
|
19
|
+
* <App />
|
|
20
|
+
* </BroadcastProvider>
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
8
23
|
export declare const BroadcastProvider: React.FC<BroadcastProviderProps>;
|
|
24
|
+
/**
|
|
25
|
+
* Returns the channel actions shared by the nearest `BroadcastProvider`.
|
|
26
|
+
*
|
|
27
|
+
* @throws Error if called outside a `BroadcastProvider`.
|
|
28
|
+
*/
|
|
9
29
|
export declare const useBroadcastProvider: () => BroadcastActions;
|
|
10
|
-
export {};
|
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
import { BroadcastActions, BroadcastOptions } from '../types/types';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Opens a BroadcastChannel and returns its state and actions. Scoped to one component: each
|
|
4
|
+
* call has its own connection and state.
|
|
5
|
+
*
|
|
6
|
+
* Behavior to know:
|
|
7
|
+
* - Self-filtering: messages sent by this tab (same `sourceName`) are ignored. They never appear
|
|
8
|
+
* in `messages` or trigger `onMessage`; they are listed in `sentMessages`. Two tabs that share a
|
|
9
|
+
* `sourceName` will not receive each other's messages.
|
|
10
|
+
* - `messages` is an event log of what other tabs sent, not current state.
|
|
11
|
+
* - No replay: a tab opened later only receives messages sent after it opened.
|
|
12
|
+
* - `keepLatestMessage` keeps only the most recent received message in `messages`. It does not
|
|
13
|
+
* affect `sentMessages` and does not replay anything to new tabs.
|
|
14
|
+
* - Batching: with `batchingDelayMs > 0` (default 20 ms) outgoing messages are grouped and sent
|
|
15
|
+
* together. Types in `excludedBatchMessageTypes` are sent immediately. Set it to 0 to disable.
|
|
16
|
+
* - Defaults: `cleaningInterval` 1000 ms, `deduplicationTTL` 5 minutes (300000 ms),
|
|
17
|
+
* `cleanupDebounceMs` 0, `batchingDelayMs` 20 ms, `telemetry` false. Duplicates are dropped by
|
|
18
|
+
* message ID.
|
|
19
|
+
* - Errors are reported through the `error` string (it clears itself after 3 seconds); the hook
|
|
20
|
+
* does not throw for channel errors. `useBroadcastProvider` (not this hook) throws when used
|
|
21
|
+
* outside a `BroadcastProvider`.
|
|
4
22
|
*
|
|
5
23
|
* Note: When batching is enabled (batchingDelayMs > 0), messages sent over the channel may be received as either:
|
|
6
24
|
* - a single BroadcastMessage (object), or
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("react"),t=require("tslib"),n=require("react/jsx-runtime");const r="__INTERNAL__",s=()=>Math.random().toString(36).substr(2,9),a=(e,t)=>{const n=`${s()}-${e}-${t}`;return btoa(n).replace(/=+$/,"")},o=e=>!!e.expirationDate&&e.expirationDate<Date.now(),c=(e,t,n,r={})=>{var s;const o=Date.now();return{id:a(n,o),type:e,message:t,timestamp:o,source:n,expirationDate:null!==(s=r.expirationDate)&&void 0!==s?s:r.expirationDuration?o+r.expirationDuration:void 0}},i=(e,t,n="")=>{const s=btoa(`react-broadcast-sync:${e}:${`${t}-${n}`}`);return`${r}:${e}:${s}`},l=e=>e&&"object"==typeof e&&"string"==typeof e.type&&e.type.startsWith(`${r}:`)&&"string"==typeof e.source,u=(e,t,n)=>{if("undefined"==typeof process||!process.env||"true"!==process.env.REACT_APP_DEBUG_BROADCAST)return;const r=`[${(new Date).toISOString()}] [react-broadcast-sync]`;switch(e){case"info":console.log(r,t,n||"");break;case"warn":console.warn(r,t,n||"");break;case"error":console.error(r,t,n||"")}},d={created:e=>u("info","Channel created:",e),closed:e=>u("info","Channel closed:",e)},p={sent:e=>u("info","Message sent:",e),received:e=>u("info","Message received:",e),cleared:e=>u("info","Message cleared:",e),expired:e=>u("info","Message expired:",e),duplicate:e=>u("warn","Duplicate message ignored:",e),allSentCleared:()=>u("info","All sent messages cleared"),allReceivedCleared:()=>u("info","All received messages cleared"),ignored:e=>u("info","Message ignored due to type filter:",e)},g={inProgress:()=>u("warn","Ping already in progress. Skipping call.")},f={started:()=>u("info","Cleanup started"),completed:e=>u("info","Cleanup completed:",e)},h=e=>{const{action:t,channelName:n,type:r,source:s,originalError:a}=e;let o=`${t}`;if(n&&(o+=` | channel: ${n}`),r&&(o+=` | type: ${r}`),s&&(o+=` | source: ${s}`),a instanceof Error)o+=` | cause: ${a.message}`;else if("string"==typeof a)o+=` | cause: ${a}`;else if(null!=a)try{o+=` | cause: ${JSON.stringify(a)}`}catch(e){o+=" | cause: [unserializable]"}u("error","Error:",o)};var y;let m=null!==(y="5464f5ff80645bf551138116c319240b")?y:"";const v=(()=>{var e,t,n;try{return null!==(n=null===(t=(e=crypto).randomUUID)||void 0===t?void 0:t.call(e))&&void 0!==n?n:Math.random().toString(36).slice(2)+Date.now().toString(36)}catch(e){return Math.random().toString(36).slice(2)+Date.now().toString(36)}})(),E=[],b=new Set;let M=null;function S(e,t){return{event:e,properties:Object.assign({token:m,distinct_id:v,time:Math.floor(Date.now()/1e3)},t)}}function C(){return t.__awaiter(this,void 0,void 0,(function*(){if(0===E.length||!m)return;const e=E.splice(0);try{yield fetch("https://api-eu.mixpanel.com/track",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch(e){}}))}function N(){m&&null===M&&(M=setTimeout((()=>{M=null,C()}),3e4))}function w(e){b.has(e)||(b.add(e),E.push(S("method_called",{method:e})),N())}"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&(null!==M&&(clearTimeout(M),M=null),C())}));const T="CLEAR_SENT_MESSAGES",P="PING",_="PONG";let D;if("test"===process.env.NODE_ENV)try{D=require("react-dom").flushSync}catch(y){}const $=(t,n={},r="hook")=>{const{sourceName:a,cleaningInterval:u=1e3,keepLatestMessage:y=!1,registeredTypes:m=[],namespace:v="",deduplicationTTL:b=3e5,cleanupDebounceMs:M=0,batchingDelayMs:C=20,excludedBatchMessageTypes:$=[],onMessage:k,telemetry:B=!0}=n,[R,A]=e.useState([]),[x,G]=e.useState([]),[I,L]=e.useState(null),[O,j]=e.useState(!1),q=e.useRef(null),F=e.useRef(new Map),U=e.useRef(null),J=e.useRef(null),z=e.useRef([]),V=e.useRef(!1),W=e.useRef(k);W.current=k;const H=e.useMemo((()=>a||`tab-${s()}`),[a]),K=e.useMemo((()=>({CLEAR_SENT_MESSAGES:i(T,t,v),PING:i(P,t,v),PONG:i(_,t,v)})),[t,v]),Q=e.useMemo((()=>v?`${t}-${v}`:t),[t,v]),X=e.useRef(m);X.current=m,e.useEffect((()=>{if(!B)return;const e=[];var t;void 0!==a&&e.push("sourceName"),1e3!==u&&e.push("cleaningInterval"),y&&e.push("keepLatestMessage"),m.length>0&&e.push("registeredTypes"),v&&e.push("namespace"),3e5!==b&&e.push("deduplicationTTL"),M>0&&e.push("cleanupDebounceMs"),20!==C&&e.push("batchingDelayMs"),$.length>0&&e.push("excludedBatchMessageTypes"),void 0!==k&&e.push("onMessage"),t={entry:r,options_used:e,onmessage_shape:void 0===k?"none":"function"==typeof k?"function":"map",batching_enabled:C>0,browser_supported:"undefined"!=typeof BroadcastChannel},E.push(S("channel_init",t)),N()}),[]);const Y=e.useCallback((()=>{A((e=>e.filter((e=>!o(e)))))}),[]),Z=e.useRef(M>0?((e,t)=>{let n,r=null,s=null;const a=(...a)=>{s=a,null!==r&&clearTimeout(r),r=setTimeout((()=>{r=null,null!==s&&(n=e(...s),s=null)}),t)};return a.cancel=()=>{null!==r&&(clearTimeout(r),r=null,s=null)},a.flush=()=>(null!==r&&(clearTimeout(r),r=null,null!==s&&(n=e(...s),s=null)),n),a})(Y,M):Object.assign(Y,{cancel:()=>{}})).current,ee=e.useCallback((e=>{L(e),setTimeout((()=>L(null)),3e3)}),[]),te=e.useCallback(((e=300)=>{if(B&&w("ping"),O)return g.inProgress(),Promise.resolve([]);if(!q.current){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return h({action:"ping",channelName:Q,originalError:e}),ee(e),Promise.resolve([])}D?D((()=>j(!0))):j(!0);const t=new Set;return U.current=t,q.current.postMessage(c(K.PING,null,H)),new Promise((n=>{setTimeout((()=>{j(!1),U.current===t&&(U.current=null),n(Array.from(t))}),e)}))}),[K.PING,H,ee,O,D]),ne=e.useCallback(((e,t,n={})=>{B&&w("postMessage");const r=q.current;if(!r){const t="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return h({action:"postMessage",channelName:Q,type:e,originalError:t}),void ee(t)}const s=c(e,t,H,n);if(!C||C<0||$.includes(e))try{r.postMessage(s)}catch(t){const n="Failed to send message";h({action:"postMessage",channelName:Q,type:e,originalError:n}),ee(n),V.current=!0}else z.current.push(s),J.current||(J.current=setTimeout((()=>{if(V.current)return z.current=[],void(J.current=null);try{r.postMessage(z.current)}catch(t){const n="Failed to send message";h({action:"postMessage",channelName:Q,type:e,originalError:n}),ee(n),V.current=!0}z.current=[],J.current=null}),C));p.sent(s),G((e=>[...e,s]))}),[H,ee,C,$]),re=e.useCallback(((e={})=>{B&&w("clearReceivedMessages");const t=Boolean(e.ids&&e.ids.length||e.types&&e.types.length||e.sources&&e.sources.length);A((n=>t?n.filter((t=>!(e.ids&&e.ids.includes(t.id)||e.types&&e.types.includes(t.type)||e.sources&&e.sources.includes(t.source)))):[])),t||p.allReceivedCleared()}),[]),se=e.useCallback(((e={})=>{var t,n,r;B&&w("clearSentMessages");const{ids:s=[],types:a=[],sync:o=!1}=null!=e?e:{};G((e=>s.length>0||a.length>0?e.filter((e=>{if(e.source!==H)return!0;const t=0===s.length||s.includes(e.id),n=0===a.length||a.includes(e.type);return!(t&&n)})):[])),0===s.length&&0===a.length&&p.allSentCleared(),o&&(null===(t=q.current)||void 0===t||t.postMessage(c(K.CLEAR_SENT_MESSAGES,{ids:null!==(n=e.ids)&&void 0!==n?n:[],types:null!==(r=e.types)&&void 0!==r?r:[]},H)))}),[H,K.CLEAR_SENT_MESSAGES]),ae=e.useCallback(((e={})=>{B&&w("getLatestMessage");const{source:t,type:n}=e;for(let e=R.length-1;e>=0;e--){const r=R[e],s=!t||r.source===t,a=!n||r.type===n;if(s&&a)return r}return null}),[R]),oe=e.useCallback((e=>{var t,n;try{const r=e.data;if(p.received(r),!(e=>Boolean(e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.type&&"string"==typeof e.source&&"number"==typeof e.timestamp))(r))return;if(r.source===H)return;if(l(r)){if(r.type===K.CLEAR_SENT_MESSAGES){const{ids:e=[],types:t=[]}=r.message||{};return void A((n=>[...n.filter((n=>{if(n.source!==r.source)return!0;const s=0===e.length||e.includes(n.id),a=0===t.length||t.includes(n.type);return!(s&&a)}))]))}if(r.type===K.PING)return void(null===(t=q.current)||void 0===t||t.postMessage(c(K.PONG,null,H)));if(r.type===K.PONG){const e=r.source,t=U.current;return void(t&&!1===t.has(e)&&t.add(e))}}if(X.current.length>0&&!X.current.includes(r.type))return void p.ignored(r.type);if(o(r))return void p.expired(r.id);const s=Date.now(),a=F.current.get(r.id);if(a&&s-a<b)return void p.duplicate(r.id);F.current.set(r.id,s),A((e=>y?[r]:[...e,r]));try{const e=W.current;"function"==typeof e?e(r):e&&(null===(n=e[r.type])||void 0===n||n.call(e,r))}catch(e){h({action:"onMessage",channelName:Q,originalError:e instanceof Error?e.message:String(e)})}}catch(e){const t="Error processing broadcast message";h({action:"handleMessage",channelName:Q,originalError:t}),ee(t)}}),[H,y,ee,K,b]),ce=e.useCallback((()=>{B&&w("closeChannel");const e=q.current;e&&"function"==typeof e.close&&(e.removeEventListener("message",oe),e.close(),d.closed(Q),q.current=null)}),[oe,Q]);return e.useEffect((()=>{if("undefined"==typeof BroadcastChannel){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return h({action:"useBroadcastChannel",channelName:Q,originalError:e}),B&&(E.push(S("browser_unsupported",{})),N()),void ee(e)}let e=null;try{e=new BroadcastChannel(Q)}catch(e){const t="Failed to create BroadcastChannel";return h({action:"useBroadcastChannel",channelName:Q,originalError:e instanceof Error?e:String(e)}),void ee(t)}return q.current=e,d.created(Q),e.addEventListener("message",(e=>{Array.isArray(e.data)?e.data.forEach((e=>{oe({data:e})})):oe(e)})),()=>{ce()}}),[Q,oe,ee]),e.useEffect((()=>{if(u<=0)return;const e=setInterval((()=>{f.started();const e=R.length;Z(),f.completed(e-R.length)}),u);return()=>{var t;clearInterval(e),M>0&&(null===(t=Z.cancel)||void 0===t||t.call(Z))}}),[u,Z,M]),e.useEffect((()=>{const e=setInterval((()=>{const e=Date.now();for(const[t,n]of F.current.entries())e-n>=b&&F.current.delete(t)}),6e4);return()=>clearInterval(e)}),[b]),e.useEffect((()=>()=>{if(z.current.length>0&&q.current&&!V.current){try{q.current.postMessage(z.current)}catch(e){const t="Failed to send message";h({action:"useBroadcastChannel",channelName:Q,originalError:e instanceof Error?e:String(e)}),ee(t)}z.current=[],setTimeout((()=>{}),0)}J.current&&(clearTimeout(J.current),J.current=null),V.current=!1}),[]),{channelName:Q,messages:R,sentMessages:x,isPingInProgress:O,ping:te,postMessage:ne,clearReceivedMessages:re,clearSentMessages:se,getLatestMessage:ae,error:I,closeChannel:ce}},k=e.createContext(void 0);exports.BroadcastProvider=({children:e,channelName:t,options:r})=>{const s=$(t,r,"provider");return n.jsx(k.Provider,{value:s,children:e})},exports.useBroadcastChannel=$,exports.useBroadcastProvider=()=>{const t=e.useContext(k);if(!t)throw new Error("useBroadcastProvider must be used within a BroadcastProvider");return t};
|
|
1
|
+
"use strict";var e=require("react"),t=require("tslib"),n=require("react/jsx-runtime");const r="__INTERNAL__",s=()=>Math.random().toString(36).substr(2,9),a=(e,t)=>{const n=`${s()}-${e}-${t}`;return btoa(n).replace(/=+$/,"")},o=e=>!!e.expirationDate&&e.expirationDate<Date.now(),c=(e,t,n,r={})=>{var s;const o=Date.now();return{id:a(n,o),type:e,message:t,timestamp:o,source:n,expirationDate:null!==(s=r.expirationDate)&&void 0!==s?s:r.expirationDuration?o+r.expirationDuration:void 0}},i=(e,t,n="")=>{const s=btoa(`react-broadcast-sync:${e}:${`${t}-${n}`}`);return`${r}:${e}:${s}`},l=e=>e&&"object"==typeof e&&"string"==typeof e.type&&e.type.startsWith(`${r}:`)&&"string"==typeof e.source,u=(e,t,n)=>{if("undefined"==typeof process||!process.env||"true"!==process.env.REACT_APP_DEBUG_BROADCAST)return;const r=`[${(new Date).toISOString()}] [react-broadcast-sync]`;switch(e){case"info":console.log(r,t,n||"");break;case"warn":console.warn(r,t,n||"");break;case"error":console.error(r,t,n||"")}},d={created:e=>u("info","Channel created:",e),closed:e=>u("info","Channel closed:",e)},p={sent:e=>u("info","Message sent:",e),received:e=>u("info","Message received:",e),cleared:e=>u("info","Message cleared:",e),expired:e=>u("info","Message expired:",e),duplicate:e=>u("warn","Duplicate message ignored:",e),allSentCleared:()=>u("info","All sent messages cleared"),allReceivedCleared:()=>u("info","All received messages cleared"),ignored:e=>u("info","Message ignored due to type filter:",e)},g={inProgress:()=>u("warn","Ping already in progress. Skipping call.")},f={started:()=>u("info","Cleanup started"),completed:e=>u("info","Cleanup completed:",e)},h=e=>{const{action:t,channelName:n,type:r,source:s,originalError:a}=e;let o=`${t}`;if(n&&(o+=` | channel: ${n}`),r&&(o+=` | type: ${r}`),s&&(o+=` | source: ${s}`),a instanceof Error)o+=` | cause: ${a.message}`;else if("string"==typeof a)o+=` | cause: ${a}`;else if(null!=a)try{o+=` | cause: ${JSON.stringify(a)}`}catch(e){o+=" | cause: [unserializable]"}u("error","Error:",o)};var y;let m=null!==(y="5464f5ff80645bf551138116c319240b")?y:"";const v=(()=>{var e,t,n;try{return null!==(n=null===(t=(e=crypto).randomUUID)||void 0===t?void 0:t.call(e))&&void 0!==n?n:Math.random().toString(36).slice(2)+Date.now().toString(36)}catch(e){return Math.random().toString(36).slice(2)+Date.now().toString(36)}})(),E=[],b=new Set;let M=null;function S(e,t){return{event:e,properties:Object.assign({token:m,distinct_id:v,time:Math.floor(Date.now()/1e3)},t)}}function C(){return t.__awaiter(this,void 0,void 0,(function*(){if(0===E.length||!m)return;const e=E.splice(0);try{yield fetch("https://api-eu.mixpanel.com/track",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0})}catch(e){}}))}function N(){m&&null===M&&(M=setTimeout((()=>{M=null,C()}),3e4))}function w(e){b.has(e)||(b.add(e),E.push(S("method_called",{method:e})),N())}"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&(null!==M&&(clearTimeout(M),M=null),C())}));const T="CLEAR_SENT_MESSAGES",P="PING",_="PONG";let D;if("test"===process.env.NODE_ENV)try{D=require("react-dom").flushSync}catch(y){}const $=(t,n={},r="hook")=>{const{sourceName:a,cleaningInterval:u=1e3,keepLatestMessage:y=!1,registeredTypes:m=[],namespace:v="",deduplicationTTL:b=3e5,cleanupDebounceMs:M=0,batchingDelayMs:C=20,excludedBatchMessageTypes:$=[],onMessage:k,telemetry:B=!1}=n,[R,A]=e.useState([]),[x,G]=e.useState([]),[I,L]=e.useState(null),[O,j]=e.useState(!1),q=e.useRef(null),F=e.useRef(new Map),U=e.useRef(null),J=e.useRef(null),z=e.useRef([]),V=e.useRef(!1),W=e.useRef(k);W.current=k;const H=e.useMemo((()=>a||`tab-${s()}`),[a]),K=e.useMemo((()=>({CLEAR_SENT_MESSAGES:i(T,t,v),PING:i(P,t,v),PONG:i(_,t,v)})),[t,v]),Q=e.useMemo((()=>v?`${t}-${v}`:t),[t,v]),X=e.useRef(m);X.current=m,e.useEffect((()=>{if(!B)return;const e=[];var t;void 0!==a&&e.push("sourceName"),1e3!==u&&e.push("cleaningInterval"),y&&e.push("keepLatestMessage"),m.length>0&&e.push("registeredTypes"),v&&e.push("namespace"),3e5!==b&&e.push("deduplicationTTL"),M>0&&e.push("cleanupDebounceMs"),20!==C&&e.push("batchingDelayMs"),$.length>0&&e.push("excludedBatchMessageTypes"),void 0!==k&&e.push("onMessage"),t={entry:r,options_used:e,onmessage_shape:void 0===k?"none":"function"==typeof k?"function":"map",batching_enabled:C>0,browser_supported:"undefined"!=typeof BroadcastChannel},E.push(S("channel_init",t)),N()}),[]);const Y=e.useCallback((()=>{A((e=>e.filter((e=>!o(e)))))}),[]),Z=e.useRef(M>0?((e,t)=>{let n,r=null,s=null;const a=(...a)=>{s=a,null!==r&&clearTimeout(r),r=setTimeout((()=>{r=null,null!==s&&(n=e(...s),s=null)}),t)};return a.cancel=()=>{null!==r&&(clearTimeout(r),r=null,s=null)},a.flush=()=>(null!==r&&(clearTimeout(r),r=null,null!==s&&(n=e(...s),s=null)),n),a})(Y,M):Object.assign(Y,{cancel:()=>{}})).current,ee=e.useCallback((e=>{L(e),setTimeout((()=>L(null)),3e3)}),[]),te=e.useCallback(((e=300)=>{if(B&&w("ping"),O)return g.inProgress(),Promise.resolve([]);if(!q.current){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return h({action:"ping",channelName:Q,originalError:e}),ee(e),Promise.resolve([])}D?D((()=>j(!0))):j(!0);const t=new Set;return U.current=t,q.current.postMessage(c(K.PING,null,H)),new Promise((n=>{setTimeout((()=>{j(!1),U.current===t&&(U.current=null),n(Array.from(t))}),e)}))}),[K.PING,H,ee,O,D]),ne=e.useCallback(((e,t,n={})=>{B&&w("postMessage");const r=q.current;if(!r){const t="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return h({action:"postMessage",channelName:Q,type:e,originalError:t}),void ee(t)}const s=c(e,t,H,n);if(!C||C<0||$.includes(e))try{r.postMessage(s)}catch(t){const n="Failed to send message";h({action:"postMessage",channelName:Q,type:e,originalError:n}),ee(n),V.current=!0}else z.current.push(s),J.current||(J.current=setTimeout((()=>{if(V.current)return z.current=[],void(J.current=null);try{r.postMessage(z.current)}catch(t){const n="Failed to send message";h({action:"postMessage",channelName:Q,type:e,originalError:n}),ee(n),V.current=!0}z.current=[],J.current=null}),C));p.sent(s),G((e=>[...e,s]))}),[H,ee,C,$]),re=e.useCallback(((e={})=>{B&&w("clearReceivedMessages");const t=Boolean(e.ids&&e.ids.length||e.types&&e.types.length||e.sources&&e.sources.length);A((n=>t?n.filter((t=>!(e.ids&&e.ids.includes(t.id)||e.types&&e.types.includes(t.type)||e.sources&&e.sources.includes(t.source)))):[])),t||p.allReceivedCleared()}),[]),se=e.useCallback(((e={})=>{var t,n,r;B&&w("clearSentMessages");const{ids:s=[],types:a=[],sync:o=!1}=null!=e?e:{};G((e=>s.length>0||a.length>0?e.filter((e=>{if(e.source!==H)return!0;const t=0===s.length||s.includes(e.id),n=0===a.length||a.includes(e.type);return!(t&&n)})):[])),0===s.length&&0===a.length&&p.allSentCleared(),o&&(null===(t=q.current)||void 0===t||t.postMessage(c(K.CLEAR_SENT_MESSAGES,{ids:null!==(n=e.ids)&&void 0!==n?n:[],types:null!==(r=e.types)&&void 0!==r?r:[]},H)))}),[H,K.CLEAR_SENT_MESSAGES]),ae=e.useCallback(((e={})=>{B&&w("getLatestMessage");const{source:t,type:n}=e;for(let e=R.length-1;e>=0;e--){const r=R[e],s=!t||r.source===t,a=!n||r.type===n;if(s&&a)return r}return null}),[R]),oe=e.useCallback((e=>{var t,n;try{const r=e.data;if(p.received(r),!(e=>Boolean(e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.type&&"string"==typeof e.source&&"number"==typeof e.timestamp))(r))return;if(r.source===H)return;if(l(r)){if(r.type===K.CLEAR_SENT_MESSAGES){const{ids:e=[],types:t=[]}=r.message||{};return void A((n=>[...n.filter((n=>{if(n.source!==r.source)return!0;const s=0===e.length||e.includes(n.id),a=0===t.length||t.includes(n.type);return!(s&&a)}))]))}if(r.type===K.PING)return void(null===(t=q.current)||void 0===t||t.postMessage(c(K.PONG,null,H)));if(r.type===K.PONG){const e=r.source,t=U.current;return void(t&&!1===t.has(e)&&t.add(e))}}if(X.current.length>0&&!X.current.includes(r.type))return void p.ignored(r.type);if(o(r))return void p.expired(r.id);const s=Date.now(),a=F.current.get(r.id);if(a&&s-a<b)return void p.duplicate(r.id);F.current.set(r.id,s),A((e=>y?[r]:[...e,r]));try{const e=W.current;"function"==typeof e?e(r):e&&(null===(n=e[r.type])||void 0===n||n.call(e,r))}catch(e){h({action:"onMessage",channelName:Q,originalError:e instanceof Error?e.message:String(e)})}}catch(e){const t="Error processing broadcast message";h({action:"handleMessage",channelName:Q,originalError:t}),ee(t)}}),[H,y,ee,K,b]),ce=e.useCallback((()=>{B&&w("closeChannel");const e=q.current;e&&"function"==typeof e.close&&(e.removeEventListener("message",oe),e.close(),d.closed(Q),q.current=null)}),[oe,Q]);return e.useEffect((()=>{if("undefined"==typeof BroadcastChannel){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return h({action:"useBroadcastChannel",channelName:Q,originalError:e}),B&&(E.push(S("browser_unsupported",{})),N()),void ee(e)}let e=null;try{e=new BroadcastChannel(Q)}catch(e){const t="Failed to create BroadcastChannel";return h({action:"useBroadcastChannel",channelName:Q,originalError:e instanceof Error?e:String(e)}),void ee(t)}return q.current=e,d.created(Q),e.addEventListener("message",(e=>{Array.isArray(e.data)?e.data.forEach((e=>{oe({data:e})})):oe(e)})),()=>{ce()}}),[Q,oe,ee]),e.useEffect((()=>{if(u<=0)return;const e=setInterval((()=>{f.started();const e=R.length;Z(),f.completed(e-R.length)}),u);return()=>{var t;clearInterval(e),M>0&&(null===(t=Z.cancel)||void 0===t||t.call(Z))}}),[u,Z,M]),e.useEffect((()=>{const e=setInterval((()=>{const e=Date.now();for(const[t,n]of F.current.entries())e-n>=b&&F.current.delete(t)}),6e4);return()=>clearInterval(e)}),[b]),e.useEffect((()=>()=>{if(z.current.length>0&&q.current&&!V.current){try{q.current.postMessage(z.current)}catch(e){const t="Failed to send message";h({action:"useBroadcastChannel",channelName:Q,originalError:e instanceof Error?e:String(e)}),ee(t)}z.current=[],setTimeout((()=>{}),0)}J.current&&(clearTimeout(J.current),J.current=null),V.current=!1}),[]),{channelName:Q,messages:R,sentMessages:x,isPingInProgress:O,ping:te,postMessage:ne,clearReceivedMessages:re,clearSentMessages:se,getLatestMessage:ae,error:I,closeChannel:ce}},k=e.createContext(void 0);exports.BroadcastProvider=({children:e,channelName:t,options:r})=>{const s=$(t,r,"provider");return n.jsx(k.Provider,{value:s,children:e})},exports.useBroadcastChannel=$,exports.useBroadcastProvider=()=>{const t=e.useContext(k);if(!t)throw new Error("useBroadcastProvider must be used within a BroadcastProvider");return t};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/utils/messageUtils.ts","../src/utils/debug.ts","../src/utils/telemetry.ts","../src/hooks/useBroadcastChannel.ts","../src/BroadcastProvider.tsx"],"sourcesContent":[null,null,null,null,null],"names":["INTERNAL_PREFIX","generateRandomPart","Math","random","toString","substr","generateMessageId","source","timestamp","raw","btoa","replace","isMessageExpired","message","expirationDate","Date","now","createMessage","type","content","options","id","_a","expirationDuration","undefined","getInternalMessageType","baseType","channelName","namespace","hash","isValidInternalClearMessage","startsWith","log","level","data","process","env","REACT_APP_DEBUG_BROADCAST","prefix","toISOString","console","warn","error","debug","created","name","closed","sent","received","cleared","messageId","expired","duplicate","allSentCleared","allReceivedCleared","ignored","messageType","inProgress","started","completed","removedCount","context","action","originalError","Error","JSON","stringify","MIXPANEL_TOKEN","sessionId","_c","_b","crypto","randomUUID","call","slice","_d","queue","calledMethods","Set","flushTimer","buildEvent","props","event","properties","Object","assign","token","distinct_id","time","floor","flush","length","batch","splice","fetch","method","headers","body","keepalive","scheduleFlush","setTimeout","trackMethodCalled","has","add","push","document","addEventListener","visibilityState","clearTimeout","INTERNAL_MESSAGE_TYPES","flushSyncFn","NODE_ENV","require","flushSync","useBroadcastChannel","_entry","sourceName","cleaningInterval","keepLatestMessage","registeredTypes","deduplicationTTL","cleanupDebounceMs","batchingDelayMs","excludedBatchMessageTypes","onMessage","telemetry","messages","setMessages","useState","sentMessages","setSentMessages","setError","isPingInProgress","setIsPingInProgress","channel","useRef","receivedMessageIds","Map","activeSourcesCollector","batchingTimeoutRef","batchingMessagesRef","batchingErrorRef","onMessageRef","current","useMemo","internalTypes","CLEAR_SENT_MESSAGES","PING","PONG","resolvedChannelName","registeredTypesRef","useEffect","optionsUsed","entry","options_used","onmessage_shape","batching_enabled","browser_supported","BroadcastChannel","performCleanup","useCallback","prev","filter","msg","debouncedCleanup","debounce","fn","wait","result","timeoutId","lastArgs","debounced","args","cancel","setErrorMessage","ping","timeoutMs","Promise","resolve","collector","postMessage","Array","from","messageContent","channelCurrent","includes","e","clearReceivedMessages","hasFilters","Boolean","ids","types","sources","clearSentMessages","sync","idMatches","typeMatches","getLatestMessage","i","sourceMatches","handleMessage","isValidMessage","pongSource","receivedAt","get","set","cb","String","closeChannel","bc","close","removeEventListener","isArray","forEach","interval","setInterval","before","clearInterval","key","entries","delete","BroadcastChannelContext","createContext","BroadcastProvider","children","BroadcastChannelActions","_jsx","jsx","Provider","value","useBroadcastProvider","useContext"],"mappings":"sFAEA,MAAMA,EAAkB,eAIXC,EAAqBA,IAAMC,KAAKC,SAASC,SAAS,IAAIC,OAAO,EAAG,GAMhEC,EAAoBA,CAACC,EAAgBC,KAChD,MAAMC,EAAM,GAAGR,OAAwBM,KAAUC,IACjD,OAAOE,KAAKD,G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K,EAAUA,WAACV,GAC3B,IAAKhK,EACH,MAAM,IAAIG,MAAM,gEAElB,OAAOH"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/utils/messageUtils.ts","../src/utils/debug.ts","../src/utils/telemetry.ts","../src/hooks/useBroadcastChannel.ts","../src/BroadcastProvider.tsx"],"sourcesContent":[null,null,null,null,null],"names":["INTERNAL_PREFIX","generateRandomPart","Math","random","toString","substr","generateMessageId","source","timestamp","raw","btoa","replace","isMessageExpired","message","expirationDate","Date","now","createMessage","type","content","options","id","_a","expirationDuration","undefined","getInternalMessageType","baseType","channelName","namespace","hash","isValidInternalClearMessage","startsWith","log","level","data","process","env","REACT_APP_DEBUG_BROADCAST","prefix","toISOString","console","warn","error","debug","created","name","closed","sent","received","cleared","messageId","expired","duplicate","allSentCleared","allReceivedCleared","ignored","messageType","inProgress","started","completed","removedCount","context","action","originalError","Error","JSON","stringify","MIXPANEL_TOKEN","sessionId","_c","_b","crypto","randomUUID","call","slice","_d","queue","calledMethods","Set","flushTimer","buildEvent","props","event","properties","Object","assign","token","distinct_id","time","floor","flush","length","batch","splice","fetch","method","headers","body","keepalive","scheduleFlush","setTimeout","trackMethodCalled","has","add","push","document","addEventListener","visibilityState","clearTimeout","INTERNAL_MESSAGE_TYPES","flushSyncFn","NODE_ENV","require","flushSync","useBroadcastChannel","_entry","sourceName","cleaningInterval","keepLatestMessage","registeredTypes","deduplicationTTL","cleanupDebounceMs","batchingDelayMs","excludedBatchMessageTypes","onMessage","telemetry","messages","setMessages","useState","sentMessages","setSentMessages","setError","isPingInProgress","setIsPingInProgress","channel","useRef","receivedMessageIds","Map","activeSourcesCollector","batchingTimeoutRef","batchingMessagesRef","batchingErrorRef","onMessageRef","current","useMemo","internalTypes","CLEAR_SENT_MESSAGES","PING","PONG","resolvedChannelName","registeredTypesRef","useEffect","optionsUsed","entry","options_used","onmessage_shape","batching_enabled","browser_supported","BroadcastChannel","performCleanup","useCallback","prev","filter","msg","debouncedCleanup","debounce","fn","wait","result","timeoutId","lastArgs","debounced","args","cancel","setErrorMessage","ping","timeoutMs","Promise","resolve","collector","postMessage","Array","from","messageContent","channelCurrent","includes","e","clearReceivedMessages","hasFilters","Boolean","ids","types","sources","clearSentMessages","sync","idMatches","typeMatches","getLatestMessage","i","sourceMatches","handleMessage","isValidMessage","pongSource","receivedAt","get","set","cb","String","closeChannel","bc","close","removeEventListener","isArray","forEach","interval","setInterval","before","clearInterval","key","entries","delete","BroadcastChannelContext","createContext","BroadcastProvider","children","BroadcastChannelActions","_jsx","jsx","Provider","value","useBroadcastProvider","useContext"],"mappings":"sFAEA,MAAMA,EAAkB,eAIXC,EAAqBA,IAAMC,KAAKC,SAASC,SAAS,IAAIC,OAAO,EAAG,GAMhEC,EAAoBA,CAACC,EAAgBC,KAChD,MAAMC,EAAM,GAAGR,OAAwBM,KAAUC,IACjD,OAAOE,KAAKD,GAAKE,QAAQ,MAAO,KAgBrBC,EAAoBC,KACxBA,EAAQC,gBAAiBD,EAAQC,eAAiBC,KAAKC,MAInDC,EAAgBA,CAC3BC,EACAC,EACAZ,EACAa,EAAoE,CAAA,WAEpE,MAAMZ,EAAYO,KAAKC,MACvB,MAAO,CACLK,GAAIf,EAAkBC,EAAQC,GAC9BU,OACAL,QAASM,EACTX,YACAD,SACAO,eAEE,UADAM,EAAQN,sBACR,IAAAQ,EAAAA,EAACF,EAAQG,mBAAqBf,EAAYY,EAAQG,wBAAqBC,IAIhEC,EAAyBA,CACpCC,EACAC,EACAC,EAAY,MAEZ,MAEMC,EAAOnB,KADC,wBAAagB,KADP,GAAGC,KAAeC,OAGtC,MAAO,GAAG5B,KAAmB0B,KAAYG,KAO9BC,EAA+BjB,GAExCA,GACmB,iBAAZA,GACiB,iBAAjBA,EAAQK,MACAL,EAAQK,KARba,WAAW,GAAG/B,OASE,iBAAnBa,EAAQN,OChEbyB,EAAMA,CAACC,EAAiBpB,EAAiBqB,KAC7C,GATuB,oBAAZC,UAA2BA,QAAQC,KACK,SA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CACVmB,OAAQ,sBACRnC,YAAa0H,EACbtF,cAAe2H,aAAa1H,MAAQ0H,EAAIqB,OAAOrB,KAEjDZ,GAAgBpI,EAClB,CACAkG,EAAoBG,QAAU,GAE9B3C,YAAW,QAAU,EACvB,CACIuC,EAAmBI,UACrBnC,aAAa+B,EAAmBI,SAChCJ,EAAmBI,QAAU,MAE/BF,EAAiBE,SAAU,IAE5B,IAEI,CACLpH,YAAa0H,EACbvB,WACAG,eACAG,mBACA2C,QACAK,eACAO,yBACAM,qBACAI,oBACA3J,QACAsK,kBClkBEa,EAA0BC,EAAaA,mBAA+BtM,6BAuBTuM,EACjEC,WACArM,cACAP,cAEA,MAAM6M,EAA0B/G,EAAoBvF,EAAaP,EAAS,YAE1E,OACE8M,EAAAC,IAACN,EAAwBO,SAAQ,CAACC,MAAOJ,EAAuBD,SAC7DA,gEAU6BM,KAClC,MAAMzK,EAAU0K,EAAUA,WAACV,GAC3B,IAAKhK,EACH,MAAM,IAAIG,MAAM,gEAElB,OAAOH"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { useBroadcastChannel } from './hooks/useBroadcastChannel';
|
|
2
2
|
export { BroadcastProvider, useBroadcastProvider } from './BroadcastProvider';
|
|
3
|
-
export type { BroadcastOptions, SendMessageOptions, BroadcastMessage, BroadcastActions, } from './types/types';
|
|
3
|
+
export type { BroadcastOptions, SendMessageOptions, BroadcastMessage, BroadcastActions, ClearOptions, ClearReceivedMessagesOptions, ClearSentMessagesOptions, GetLatestMessageOptions, MessageCallback, OnMessageMap, } from './types/types';
|
|
4
|
+
export type { BroadcastProviderProps } from './BroadcastProvider';
|