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/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useState as e,useRef as t,useMemo as n,useEffect as r,useCallback as s,createContext as o,useContext as a}from"react";import{__awaiter as c}from"tslib";import{jsx as i}from"react/jsx-runtime";const l="__INTERNAL__",u=()=>Math.random().toString(36).substr(2,9),d=(e,t)=>{const n=`${u()}-${e}-${t}`;return btoa(n).replace(/=+$/,"")},p=e=>!!e.expirationDate&&e.expirationDate<Date.now(),g=(e,t,n,r={})=>{var s;const o=Date.now();return{id:d(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}},h=(e,t,n="")=>{const r=btoa(`react-broadcast-sync:${e}:${`${t}-${n}`}`);return`${l}:${e}:${r}`},f=e=>e&&"object"==typeof e&&"string"==typeof e.type&&e.type.startsWith(`${l}:`)&&"string"==typeof e.source,m=(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||"")}},y={created:e=>m("info","Channel created:",e),closed:e=>m("info","Channel closed:",e)},v={sent:e=>m("info","Message sent:",e),received:e=>m("info","Message received:",e),cleared:e=>m("info","Message cleared:",e),expired:e=>m("info","Message expired:",e),duplicate:e=>m("warn","Duplicate message ignored:",e),allSentCleared:()=>m("info","All sent messages cleared"),allReceivedCleared:()=>m("info","All received messages cleared"),ignored:e=>m("info","Message ignored due to type filter:",e)},E={inProgress:()=>m("warn","Ping already in progress. Skipping call.")},M={started:()=>m("info","Cleanup started"),completed:e=>m("info","Cleanup completed:",e)},S=e=>{const{action:t,channelName:n,type:r,source:s,originalError:o}=e;let a=`${t}`;if(n&&(a+=` | channel: ${n}`),r&&(a+=` | type: ${r}`),s&&(a+=` | source: ${s}`),o instanceof Error)a+=` | cause: ${o.message}`;else if("string"==typeof o)a+=` | cause: ${o}`;else if(null!=o)try{a+=` | cause: ${JSON.stringify(o)}`}catch(e){a+=" | cause: [unserializable]"}m("error","Error:",a)};var b;let N=null!==(b="5464f5ff80645bf551138116c319240b")?b:"";const w=(()=>{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)}})(),T=[],C=new Set;let P=null;function _(e,t){return{event:e,properties:Object.assign({token:N,distinct_id:w,time:Math.floor(Date.now()/1e3)},t)}}function D(){return c(this,void 0,void 0,(function*(){if(0===T.length||!N)return;const e=T.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&&null===P&&(P=setTimeout((()=>{P=null,D()}),3e4))}function A(e){C.has(e)||(C.add(e),T.push(_("method_called",{method:e})),$())}"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&(null!==P&&(clearTimeout(P),P=null),D())}));const B="CLEAR_SENT_MESSAGES",G="PING",I="PONG";let L;if("test"===process.env.NODE_ENV)try{L=require("react-dom").flushSync}catch(b){}const x=(o,a={},c="hook")=>{const{sourceName:i,cleaningInterval:l=1e3,keepLatestMessage:d=!1,registeredTypes:m=[],namespace:b="",deduplicationTTL:N=3e5,cleanupDebounceMs:w=0,batchingDelayMs:C=20,excludedBatchMessageTypes:P=[],onMessage:D,telemetry:x=!0}=a,[k,O]=e([]),[R,j]=e([]),[F,U]=e(null),[J,q]=e(!1),z=t(null),V=t(new Map),W=t(null),H=t(null),K=t([]),Q=t(!1),X=t(D);X.current=D;const Y=n((()=>i||`tab-${u()}`),[i]),Z=n((()=>({CLEAR_SENT_MESSAGES:h(B,o,b),PING:h(G,o,b),PONG:h(I,o,b)})),[o,b]),ee=n((()=>b?`${o}-${b}`:o),[o,b]),te=t(m);te.current=m,r((()=>{if(!x)return;const e=[];var t;void 0!==i&&e.push("sourceName"),1e3!==l&&e.push("cleaningInterval"),d&&e.push("keepLatestMessage"),m.length>0&&e.push("registeredTypes"),b&&e.push("namespace"),3e5!==N&&e.push("deduplicationTTL"),w>0&&e.push("cleanupDebounceMs"),20!==C&&e.push("batchingDelayMs"),P.length>0&&e.push("excludedBatchMessageTypes"),void 0!==D&&e.push("onMessage"),t={entry:c,options_used:e,onmessage_shape:void 0===D?"none":"function"==typeof D?"function":"map",batching_enabled:C>0,browser_supported:"undefined"!=typeof BroadcastChannel},T.push(_("channel_init",t)),$()}),[]);const ne=s((()=>{O((e=>e.filter((e=>!p(e)))))}),[]),re=t(w>0?((e,t)=>{let n,r=null,s=null;const o=(...o)=>{s=o,null!==r&&clearTimeout(r),r=setTimeout((()=>{r=null,null!==s&&(n=e(...s),s=null)}),t)};return o.cancel=()=>{null!==r&&(clearTimeout(r),r=null,s=null)},o.flush=()=>(null!==r&&(clearTimeout(r),r=null,null!==s&&(n=e(...s),s=null)),n),o})(ne,w):Object.assign(ne,{cancel:()=>{}})).current,se=s((e=>{U(e),setTimeout((()=>U(null)),3e3)}),[]),oe=s(((e=300)=>{if(x&&A("ping"),J)return E.inProgress(),Promise.resolve([]);if(!z.current){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return S({action:"ping",channelName:ee,originalError:e}),se(e),Promise.resolve([])}L?L((()=>q(!0))):q(!0);const t=new Set;return W.current=t,z.current.postMessage(g(Z.PING,null,Y)),new Promise((n=>{setTimeout((()=>{q(!1),W.current===t&&(W.current=null),n(Array.from(t))}),e)}))}),[Z.PING,Y,se,J,L]),ae=s(((e,t,n={})=>{x&&A("postMessage");const r=z.current;if(!r){const t="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return S({action:"postMessage",channelName:ee,type:e,originalError:t}),void se(t)}const s=g(e,t,Y,n);if(!C||C<0||P.includes(e))try{r.postMessage(s)}catch(t){const n="Failed to send message";S({action:"postMessage",channelName:ee,type:e,originalError:n}),se(n),Q.current=!0}else K.current.push(s),H.current||(H.current=setTimeout((()=>{if(Q.current)return K.current=[],void(H.current=null);try{r.postMessage(K.current)}catch(t){const n="Failed to send message";S({action:"postMessage",channelName:ee,type:e,originalError:n}),se(n),Q.current=!0}K.current=[],H.current=null}),C));v.sent(s),j((e=>[...e,s]))}),[Y,se,C,P]),ce=s(((e={})=>{x&&A("clearReceivedMessages");const t=Boolean(e.ids&&e.ids.length||e.types&&e.types.length||e.sources&&e.sources.length);O((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||v.allReceivedCleared()}),[]),ie=s(((e={})=>{var t,n,r;x&&A("clearSentMessages");const{ids:s=[],types:o=[],sync:a=!1}=null!=e?e:{};j((e=>s.length>0||o.length>0?e.filter((e=>{if(e.source!==Y)return!0;const t=0===s.length||s.includes(e.id),n=0===o.length||o.includes(e.type);return!(t&&n)})):[])),0===s.length&&0===o.length&&v.allSentCleared(),a&&(null===(t=z.current)||void 0===t||t.postMessage(g(Z.CLEAR_SENT_MESSAGES,{ids:null!==(n=e.ids)&&void 0!==n?n:[],types:null!==(r=e.types)&&void 0!==r?r:[]},Y)))}),[Y,Z.CLEAR_SENT_MESSAGES]),le=s(((e={})=>{x&&A("getLatestMessage");const{source:t,type:n}=e;for(let e=k.length-1;e>=0;e--){const r=k[e],s=!t||r.source===t,o=!n||r.type===n;if(s&&o)return r}return null}),[k]),ue=s((e=>{var t,n;try{const r=e.data;if(v.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===Y)return;if(f(r)){if(r.type===Z.CLEAR_SENT_MESSAGES){const{ids:e=[],types:t=[]}=r.message||{};return void O((n=>[...n.filter((n=>{if(n.source!==r.source)return!0;const s=0===e.length||e.includes(n.id),o=0===t.length||t.includes(n.type);return!(s&&o)}))]))}if(r.type===Z.PING)return void(null===(t=z.current)||void 0===t||t.postMessage(g(Z.PONG,null,Y)));if(r.type===Z.PONG){const e=r.source,t=W.current;return void(t&&!1===t.has(e)&&t.add(e))}}if(te.current.length>0&&!te.current.includes(r.type))return void v.ignored(r.type);if(p(r))return void v.expired(r.id);const s=Date.now(),o=V.current.get(r.id);if(o&&s-o<N)return void v.duplicate(r.id);V.current.set(r.id,s),O((e=>d?[r]:[...e,r]));try{const e=X.current;"function"==typeof e?e(r):e&&(null===(n=e[r.type])||void 0===n||n.call(e,r))}catch(e){S({action:"onMessage",channelName:ee,originalError:e instanceof Error?e.message:String(e)})}}catch(e){const t="Error processing broadcast message";S({action:"handleMessage",channelName:ee,originalError:t}),se(t)}}),[Y,d,se,Z,N]),de=s((()=>{x&&A("closeChannel");const e=z.current;e&&"function"==typeof e.close&&(e.removeEventListener("message",ue),e.close(),y.closed(ee),z.current=null)}),[ue,ee]);return r((()=>{if("undefined"==typeof BroadcastChannel){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return S({action:"useBroadcastChannel",channelName:ee,originalError:e}),x&&(T.push(_("browser_unsupported",{})),$()),void se(e)}let e=null;try{e=new BroadcastChannel(ee)}catch(e){const t="Failed to create BroadcastChannel";return S({action:"useBroadcastChannel",channelName:ee,originalError:e instanceof Error?e:String(e)}),void se(t)}return z.current=e,y.created(ee),e.addEventListener("message",(e=>{Array.isArray(e.data)?e.data.forEach((e=>{ue({data:e})})):ue(e)})),()=>{de()}}),[ee,ue,se]),r((()=>{if(l<=0)return;const e=setInterval((()=>{M.started();const e=k.length;re(),M.completed(e-k.length)}),l);return()=>{var t;clearInterval(e),w>0&&(null===(t=re.cancel)||void 0===t||t.call(re))}}),[l,re,w]),r((()=>{const e=setInterval((()=>{const e=Date.now();for(const[t,n]of V.current.entries())e-n>=N&&V.current.delete(t)}),6e4);return()=>clearInterval(e)}),[N]),r((()=>()=>{if(K.current.length>0&&z.current&&!Q.current){try{z.current.postMessage(K.current)}catch(e){const t="Failed to send message";S({action:"useBroadcastChannel",channelName:ee,originalError:e instanceof Error?e:String(e)}),se(t)}K.current=[],setTimeout((()=>{}),0)}H.current&&(clearTimeout(H.current),H.current=null),Q.current=!1}),[]),{channelName:ee,messages:k,sentMessages:R,isPingInProgress:J,ping:oe,postMessage:ae,clearReceivedMessages:ce,clearSentMessages:ie,getLatestMessage:le,error:F,closeChannel:de}},k=o(void 0),O=({children:e,channelName:t,options:n})=>{const r=x(t,n,"provider");return i(k.Provider,{value:r,children:e})},R=()=>{const e=a(k);if(!e)throw new Error("useBroadcastProvider must be used within a BroadcastProvider");return e};export{O as BroadcastProvider,x as useBroadcastChannel,R as useBroadcastProvider};
|
|
1
|
+
import{useState as e,useRef as t,useMemo as n,useEffect as r,useCallback as s,createContext as o,useContext as a}from"react";import{__awaiter as c}from"tslib";import{jsx as i}from"react/jsx-runtime";const l="__INTERNAL__",u=()=>Math.random().toString(36).substr(2,9),d=(e,t)=>{const n=`${u()}-${e}-${t}`;return btoa(n).replace(/=+$/,"")},p=e=>!!e.expirationDate&&e.expirationDate<Date.now(),g=(e,t,n,r={})=>{var s;const o=Date.now();return{id:d(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}},h=(e,t,n="")=>{const r=btoa(`react-broadcast-sync:${e}:${`${t}-${n}`}`);return`${l}:${e}:${r}`},f=e=>e&&"object"==typeof e&&"string"==typeof e.type&&e.type.startsWith(`${l}:`)&&"string"==typeof e.source,m=(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||"")}},y={created:e=>m("info","Channel created:",e),closed:e=>m("info","Channel closed:",e)},v={sent:e=>m("info","Message sent:",e),received:e=>m("info","Message received:",e),cleared:e=>m("info","Message cleared:",e),expired:e=>m("info","Message expired:",e),duplicate:e=>m("warn","Duplicate message ignored:",e),allSentCleared:()=>m("info","All sent messages cleared"),allReceivedCleared:()=>m("info","All received messages cleared"),ignored:e=>m("info","Message ignored due to type filter:",e)},E={inProgress:()=>m("warn","Ping already in progress. Skipping call.")},M={started:()=>m("info","Cleanup started"),completed:e=>m("info","Cleanup completed:",e)},S=e=>{const{action:t,channelName:n,type:r,source:s,originalError:o}=e;let a=`${t}`;if(n&&(a+=` | channel: ${n}`),r&&(a+=` | type: ${r}`),s&&(a+=` | source: ${s}`),o instanceof Error)a+=` | cause: ${o.message}`;else if("string"==typeof o)a+=` | cause: ${o}`;else if(null!=o)try{a+=` | cause: ${JSON.stringify(o)}`}catch(e){a+=" | cause: [unserializable]"}m("error","Error:",a)};var b;let N=null!==(b="5464f5ff80645bf551138116c319240b")?b:"";const w=(()=>{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)}})(),T=[],C=new Set;let P=null;function _(e,t){return{event:e,properties:Object.assign({token:N,distinct_id:w,time:Math.floor(Date.now()/1e3)},t)}}function D(){return c(this,void 0,void 0,(function*(){if(0===T.length||!N)return;const e=T.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&&null===P&&(P=setTimeout((()=>{P=null,D()}),3e4))}function A(e){C.has(e)||(C.add(e),T.push(_("method_called",{method:e})),$())}"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&(null!==P&&(clearTimeout(P),P=null),D())}));const B="CLEAR_SENT_MESSAGES",G="PING",I="PONG";let L;if("test"===process.env.NODE_ENV)try{L=require("react-dom").flushSync}catch(b){}const x=(o,a={},c="hook")=>{const{sourceName:i,cleaningInterval:l=1e3,keepLatestMessage:d=!1,registeredTypes:m=[],namespace:b="",deduplicationTTL:N=3e5,cleanupDebounceMs:w=0,batchingDelayMs:C=20,excludedBatchMessageTypes:P=[],onMessage:D,telemetry:x=!1}=a,[k,O]=e([]),[R,j]=e([]),[F,U]=e(null),[J,q]=e(!1),z=t(null),V=t(new Map),W=t(null),H=t(null),K=t([]),Q=t(!1),X=t(D);X.current=D;const Y=n((()=>i||`tab-${u()}`),[i]),Z=n((()=>({CLEAR_SENT_MESSAGES:h(B,o,b),PING:h(G,o,b),PONG:h(I,o,b)})),[o,b]),ee=n((()=>b?`${o}-${b}`:o),[o,b]),te=t(m);te.current=m,r((()=>{if(!x)return;const e=[];var t;void 0!==i&&e.push("sourceName"),1e3!==l&&e.push("cleaningInterval"),d&&e.push("keepLatestMessage"),m.length>0&&e.push("registeredTypes"),b&&e.push("namespace"),3e5!==N&&e.push("deduplicationTTL"),w>0&&e.push("cleanupDebounceMs"),20!==C&&e.push("batchingDelayMs"),P.length>0&&e.push("excludedBatchMessageTypes"),void 0!==D&&e.push("onMessage"),t={entry:c,options_used:e,onmessage_shape:void 0===D?"none":"function"==typeof D?"function":"map",batching_enabled:C>0,browser_supported:"undefined"!=typeof BroadcastChannel},T.push(_("channel_init",t)),$()}),[]);const ne=s((()=>{O((e=>e.filter((e=>!p(e)))))}),[]),re=t(w>0?((e,t)=>{let n,r=null,s=null;const o=(...o)=>{s=o,null!==r&&clearTimeout(r),r=setTimeout((()=>{r=null,null!==s&&(n=e(...s),s=null)}),t)};return o.cancel=()=>{null!==r&&(clearTimeout(r),r=null,s=null)},o.flush=()=>(null!==r&&(clearTimeout(r),r=null,null!==s&&(n=e(...s),s=null)),n),o})(ne,w):Object.assign(ne,{cancel:()=>{}})).current,se=s((e=>{U(e),setTimeout((()=>U(null)),3e3)}),[]),oe=s(((e=300)=>{if(x&&A("ping"),J)return E.inProgress(),Promise.resolve([]);if(!z.current){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return S({action:"ping",channelName:ee,originalError:e}),se(e),Promise.resolve([])}L?L((()=>q(!0))):q(!0);const t=new Set;return W.current=t,z.current.postMessage(g(Z.PING,null,Y)),new Promise((n=>{setTimeout((()=>{q(!1),W.current===t&&(W.current=null),n(Array.from(t))}),e)}))}),[Z.PING,Y,se,J,L]),ae=s(((e,t,n={})=>{x&&A("postMessage");const r=z.current;if(!r){const t="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return S({action:"postMessage",channelName:ee,type:e,originalError:t}),void se(t)}const s=g(e,t,Y,n);if(!C||C<0||P.includes(e))try{r.postMessage(s)}catch(t){const n="Failed to send message";S({action:"postMessage",channelName:ee,type:e,originalError:n}),se(n),Q.current=!0}else K.current.push(s),H.current||(H.current=setTimeout((()=>{if(Q.current)return K.current=[],void(H.current=null);try{r.postMessage(K.current)}catch(t){const n="Failed to send message";S({action:"postMessage",channelName:ee,type:e,originalError:n}),se(n),Q.current=!0}K.current=[],H.current=null}),C));v.sent(s),j((e=>[...e,s]))}),[Y,se,C,P]),ce=s(((e={})=>{x&&A("clearReceivedMessages");const t=Boolean(e.ids&&e.ids.length||e.types&&e.types.length||e.sources&&e.sources.length);O((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||v.allReceivedCleared()}),[]),ie=s(((e={})=>{var t,n,r;x&&A("clearSentMessages");const{ids:s=[],types:o=[],sync:a=!1}=null!=e?e:{};j((e=>s.length>0||o.length>0?e.filter((e=>{if(e.source!==Y)return!0;const t=0===s.length||s.includes(e.id),n=0===o.length||o.includes(e.type);return!(t&&n)})):[])),0===s.length&&0===o.length&&v.allSentCleared(),a&&(null===(t=z.current)||void 0===t||t.postMessage(g(Z.CLEAR_SENT_MESSAGES,{ids:null!==(n=e.ids)&&void 0!==n?n:[],types:null!==(r=e.types)&&void 0!==r?r:[]},Y)))}),[Y,Z.CLEAR_SENT_MESSAGES]),le=s(((e={})=>{x&&A("getLatestMessage");const{source:t,type:n}=e;for(let e=k.length-1;e>=0;e--){const r=k[e],s=!t||r.source===t,o=!n||r.type===n;if(s&&o)return r}return null}),[k]),ue=s((e=>{var t,n;try{const r=e.data;if(v.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===Y)return;if(f(r)){if(r.type===Z.CLEAR_SENT_MESSAGES){const{ids:e=[],types:t=[]}=r.message||{};return void O((n=>[...n.filter((n=>{if(n.source!==r.source)return!0;const s=0===e.length||e.includes(n.id),o=0===t.length||t.includes(n.type);return!(s&&o)}))]))}if(r.type===Z.PING)return void(null===(t=z.current)||void 0===t||t.postMessage(g(Z.PONG,null,Y)));if(r.type===Z.PONG){const e=r.source,t=W.current;return void(t&&!1===t.has(e)&&t.add(e))}}if(te.current.length>0&&!te.current.includes(r.type))return void v.ignored(r.type);if(p(r))return void v.expired(r.id);const s=Date.now(),o=V.current.get(r.id);if(o&&s-o<N)return void v.duplicate(r.id);V.current.set(r.id,s),O((e=>d?[r]:[...e,r]));try{const e=X.current;"function"==typeof e?e(r):e&&(null===(n=e[r.type])||void 0===n||n.call(e,r))}catch(e){S({action:"onMessage",channelName:ee,originalError:e instanceof Error?e.message:String(e)})}}catch(e){const t="Error processing broadcast message";S({action:"handleMessage",channelName:ee,originalError:t}),se(t)}}),[Y,d,se,Z,N]),de=s((()=>{x&&A("closeChannel");const e=z.current;e&&"function"==typeof e.close&&(e.removeEventListener("message",ue),e.close(),y.closed(ee),z.current=null)}),[ue,ee]);return r((()=>{if("undefined"==typeof BroadcastChannel){const e="BroadcastChannel is not supported in this browser. Please check browser compatibility.";return S({action:"useBroadcastChannel",channelName:ee,originalError:e}),x&&(T.push(_("browser_unsupported",{})),$()),void se(e)}let e=null;try{e=new BroadcastChannel(ee)}catch(e){const t="Failed to create BroadcastChannel";return S({action:"useBroadcastChannel",channelName:ee,originalError:e instanceof Error?e:String(e)}),void se(t)}return z.current=e,y.created(ee),e.addEventListener("message",(e=>{Array.isArray(e.data)?e.data.forEach((e=>{ue({data:e})})):ue(e)})),()=>{de()}}),[ee,ue,se]),r((()=>{if(l<=0)return;const e=setInterval((()=>{M.started();const e=k.length;re(),M.completed(e-k.length)}),l);return()=>{var t;clearInterval(e),w>0&&(null===(t=re.cancel)||void 0===t||t.call(re))}}),[l,re,w]),r((()=>{const e=setInterval((()=>{const e=Date.now();for(const[t,n]of V.current.entries())e-n>=N&&V.current.delete(t)}),6e4);return()=>clearInterval(e)}),[N]),r((()=>()=>{if(K.current.length>0&&z.current&&!Q.current){try{z.current.postMessage(K.current)}catch(e){const t="Failed to send message";S({action:"useBroadcastChannel",channelName:ee,originalError:e instanceof Error?e:String(e)}),se(t)}K.current=[],setTimeout((()=>{}),0)}H.current&&(clearTimeout(H.current),H.current=null),Q.current=!1}),[]),{channelName:ee,messages:k,sentMessages:R,isPingInProgress:J,ping:oe,postMessage:ae,clearReceivedMessages:ce,clearSentMessages:ie,getLatestMessage:le,error:F,closeChannel:de}},k=o(void 0),O=({children:e,channelName:t,options:n})=>{const r=x(t,n,"provider");return i(k.Provider,{value:r,children:e})},R=()=>{const e=a(k);if(!e)throw new Error("useBroadcastProvider must be used within a BroadcastProvider");return e};export{O as BroadcastProvider,x as useBroadcastChannel,R as useBroadcastProvider};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.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","Provider","value","useBroadcastProvider","useContext"],"mappings":"uMAEA,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,iBAA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QAAU,GAE9B3C,YAAW,QAAU,EACvB,CACIuC,EAAmBI,UACrBnC,aAAa+B,EAAmBI,SAChCJ,EAAmBI,QAAU,MAE/BF,EAAiBE,SAAU,IAE5B,IAEI,CACLpH,YAAa0H,GACbvB,WACAG,eACAG,mBACA2C,QACAK,eACAO,yBACAM,qBACAI,oBACA3J,QACAsK,kBChjBEa,EAA0BC,OAA4CtM,GAQ/DuM,EAAsDA,EACjEC,WACArM,cACAP,cAEA,MAAM6M,EAA0B/G,EAAoBvF,EAAaP,EAAS,YAE1E,OACE8M,EAACL,EAAwBM,SAAQ,CAACC,MAAOH,EAAuBD,SAC7DA,KAKMK,EAAuBA,KAClC,MAAMxK,EAAUyK,EAAWT,GAC3B,IAAKhK,EACH,MAAM,IAAIG,MAAM,gEAElB,OAAOH"}
|
|
1
|
+
{"version":3,"file":"index.esm.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","Provider","value","useBroadcastProvider","useContext"],"mappings":"uMAEA,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,eAE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B,CAAC9F,IAEJ+B,GAAU,IACD,KAEL,GAAIX,EAAoBG,QAAQpD,OAAS,GAAK2C,EAAQS,UAAYF,EAAiBE,QAAS,CAC1F,IACET,EAAQS,QAAQqC,YAAYxC,EAAoBG,QACjD,CAAC,MAAO2C,GACP,MAAMhJ,EAAQ,yBACdC,EAAY,CACVmB,OAAQ,sBACRnC,YAAa0H,GACbtF,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,GACbvB,WACAG,eACAG,mBACA2C,QACAK,eACAO,yBACAM,qBACAI,oBACA3J,QACAsK,kBClkBEa,EAA0BC,OAA4CtM,GAuB/DuM,EAAsDA,EACjEC,WACArM,cACAP,cAEA,MAAM6M,EAA0B/G,EAAoBvF,EAAaP,EAAS,YAE1E,OACE8M,EAACL,EAAwBM,SAAQ,CAACC,MAAOH,EAAuBD,SAC7DA,KAUMK,EAAuBA,KAClC,MAAMxK,EAAUyK,EAAWT,GAC3B,IAAKhK,EACH,MAAM,IAAIG,MAAM,gEAElB,OAAOH"}
|
package/dist/types/types.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ export interface BroadcastOptions {
|
|
|
14
14
|
namespace?: string;
|
|
15
15
|
/** TTL for deduplication in milliseconds (default: 5 minutes) */
|
|
16
16
|
deduplicationTTL?: number;
|
|
17
|
-
/** Debounce time for messages cleanup in milliseconds (default:
|
|
17
|
+
/** Debounce time for messages cleanup in milliseconds (default: 0, no debounce) */
|
|
18
18
|
cleanupDebounceMs?: number;
|
|
19
19
|
/** Delay in milliseconds for batching messages (default: 20) */
|
|
20
20
|
batchingDelayMs?: number;
|
|
@@ -32,18 +32,16 @@ export interface BroadcastOptions {
|
|
|
32
32
|
*/
|
|
33
33
|
onMessage?: MessageCallback | OnMessageMap;
|
|
34
34
|
/**
|
|
35
|
-
* Allow the package to collect anonymous usage statistics (default:
|
|
35
|
+
* Allow the package to collect anonymous usage statistics (default: false).
|
|
36
36
|
*
|
|
37
|
-
*
|
|
38
|
-
* which options are in use, which
|
|
39
|
-
* or provider entry point is used.
|
|
40
|
-
*
|
|
41
|
-
* ever collected. The session ID is randomly generated on every page load
|
|
42
|
-
* and is never persisted to storage.
|
|
37
|
+
* Telemetry is off unless explicitly enabled. When enabled, structural
|
|
38
|
+
* signals are sent to the maintainer: which options are in use, which
|
|
39
|
+
* methods are called, and whether the hook or provider entry point is used.
|
|
40
|
+
* No channel names, source names, or message content are sent.
|
|
43
41
|
*
|
|
44
|
-
* Set to `
|
|
42
|
+
* Set to `true` to opt in:
|
|
45
43
|
* ```tsx
|
|
46
|
-
* useBroadcastChannel('my-channel', { telemetry:
|
|
44
|
+
* useBroadcastChannel('my-channel', { telemetry: true });
|
|
47
45
|
* ```
|
|
48
46
|
*
|
|
49
47
|
* See TELEMETRY.md in the package repository for full details.
|
package/llms.txt
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
# react-broadcast-sync
|
|
2
|
+
|
|
3
|
+
> React hook and provider for cross-tab messaging over BroadcastChannel, with helpers for manually syncing state between tabs (no automatic state replication).
|
|
4
|
+
|
|
5
|
+
Version 2.0.0. Install: `npm install react-broadcast-sync`. Same origin only. Generated from README.md by scripts/generate-llms-txt.mjs; do not edit by hand.
|
|
6
|
+
|
|
7
|
+
## Syncing Shared State (filters, settings)
|
|
8
|
+
|
|
9
|
+
`messages` is an event log of what other tabs sent, not the current state. To keep a piece of state
|
|
10
|
+
(for example dashboard filters) in sync, update local state and send one message from the handler,
|
|
11
|
+
and apply incoming messages with `onMessage`:
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
function Dashboard() {
|
|
15
|
+
const [filters, setFilters] = useState({ status: 'all' });
|
|
16
|
+
|
|
17
|
+
const { postMessage } = useBroadcastChannel('dashboard', {
|
|
18
|
+
// sourceName is optional: a unique one is generated for each tab.
|
|
19
|
+
// Do not build it inline with crypto.randomUUID(): it would change on every render.
|
|
20
|
+
onMessage: {
|
|
21
|
+
'filters-update': msg => setFilters(msg.message),
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const updateFilters = (next: typeof filters) => {
|
|
26
|
+
setFilters(next);
|
|
27
|
+
postMessage('filters-update', next);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
return <FilterBar value={filters} onChange={updateFilters} />;
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Do not call `postMessage` from a `useEffect` on state that you also set from incoming messages.
|
|
35
|
+
Each tab re-broadcasts what it receives, the tabs ping-pong, and they can end up with different
|
|
36
|
+
values. Deduplication is by message ID, so it does not stop this.
|
|
37
|
+
|
|
38
|
+
### New tabs do not receive past messages
|
|
39
|
+
|
|
40
|
+
Messages are not replayed. A tab opened later only sees messages sent after it opened, and
|
|
41
|
+
`keepLatestMessage` and `getLatestMessage` do not change that. To give a new tab the current state,
|
|
42
|
+
let it ask for it and let an existing tab answer:
|
|
43
|
+
|
|
44
|
+
```tsx
|
|
45
|
+
const { postMessage } = useBroadcastChannel('dashboard', {
|
|
46
|
+
sourceName: sourceName, // unique per tab
|
|
47
|
+
onMessage: {
|
|
48
|
+
'filters-update': msg => setFilters(msg.message),
|
|
49
|
+
'state-request': () => postMessage('filters-update', filtersRef.current),
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Ask once when this tab mounts
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
postMessage('state-request', null);
|
|
56
|
+
}, []);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Keep the current value in a ref (`filtersRef.current = filters`) so the `state-request` handler
|
|
60
|
+
always answers with the latest state. If no other tab is open, nothing answers and the tab keeps its
|
|
61
|
+
default state.
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## API Reference
|
|
66
|
+
|
|
67
|
+
### `useBroadcastChannel` Hook
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
const {
|
|
71
|
+
channelName,
|
|
72
|
+
messages,
|
|
73
|
+
sentMessages,
|
|
74
|
+
postMessage,
|
|
75
|
+
clearReceivedMessages,
|
|
76
|
+
clearSentMessages,
|
|
77
|
+
error,
|
|
78
|
+
} = useBroadcastChannel(channelName, options);
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
#### Options
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
interface BroadcastOptions {
|
|
85
|
+
sourceName?: string; // Custom name for the message source. Must be unique per tab: a tab ignores messages from its own sourceName
|
|
86
|
+
cleaningInterval?: number; // Interval in ms for cleaning expired messages (default: 1000)
|
|
87
|
+
keepLatestMessage?: boolean; // Keep only the latest message (default: false)
|
|
88
|
+
registeredTypes?: string[]; // List of allowed message types
|
|
89
|
+
namespace?: string; // Channel namespace for isolation
|
|
90
|
+
deduplicationTTL?: number; // Time in ms to keep message IDs for deduplication (default: 5 minutes)
|
|
91
|
+
cleanupDebounceMs?: number; // Debounce time in ms for cleanup operations (default: 0)
|
|
92
|
+
batchingDelayMs?: number; // Delay in ms to batch outgoing messages (default: 20). If > 0, messages are batched and sent together.
|
|
93
|
+
excludedBatchMessageTypes?: string[]; // Message types to always send immediately, never batched (default: []).
|
|
94
|
+
onMessage?: MessageCallback | OnMessageMap; // Callback(s) fired when a received message passes all filters (default: undefined).
|
|
95
|
+
telemetry?: boolean; // Privacy-first: off by default. Pass true to opt in.
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
#### Default Values
|
|
100
|
+
|
|
101
|
+
| Option | Default Value | Description |
|
|
102
|
+
| --------------------------- | ------------- | -------------------------------------------- |
|
|
103
|
+
| `sourceName` | `undefined` | Auto-generated if not provided |
|
|
104
|
+
| `cleaningInterval` | `1000` | 1 second between cleanup runs |
|
|
105
|
+
| `keepLatestMessage` | `false` | Keep all messages by default |
|
|
106
|
+
| `registeredTypes` | `[]` | Accept all message types by default |
|
|
107
|
+
| `namespace` | `''` | No namespace by default |
|
|
108
|
+
| `deduplicationTTL` | `300000` | 5 minutes (5 × 60 × 1000 ms) |
|
|
109
|
+
| `cleanupDebounceMs` | `0` | No debounce by default |
|
|
110
|
+
| `batchingDelayMs` | `20` | Batch delay in ms (0 = off) |
|
|
111
|
+
| `excludedBatchMessageTypes` | `[]` | Types never batched |
|
|
112
|
+
| `onMessage` | `undefined` | Callback(s) for received messages |
|
|
113
|
+
| `telemetry` | `false` | Anonymous usage stats. Pass `true` to opt in |
|
|
114
|
+
|
|
115
|
+
#### Return Value
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
interface BroadcastActions {
|
|
119
|
+
channelName: string; // The resolved channel name (includes namespace)
|
|
120
|
+
messages: BroadcastMessage[]; // Received messages
|
|
121
|
+
sentMessages: BroadcastMessage[]; // Messages sent by this instance
|
|
122
|
+
postMessage: (type: string, content: any, options?: SendMessageOptions) => void;
|
|
123
|
+
clearReceivedMessages: (opts?: { ids?: string[]; types?: string[]; sources?: string[] }) => void;
|
|
124
|
+
clearSentMessages: (opts?: { ids?: string[]; types?: string[]; sync?: boolean }) => void;
|
|
125
|
+
getLatestMessage: (opts?: { type?: string; source?: string }) => BroadcastMessage | null;
|
|
126
|
+
closeChannel: () => void;
|
|
127
|
+
error: string | null; // Current error state
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### `useBroadcastChannel(channelName, options?)`
|
|
132
|
+
|
|
133
|
+
Returns an object with:
|
|
134
|
+
|
|
135
|
+
| Property | Type | Description |
|
|
136
|
+
| ------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
137
|
+
| `channelName` | `string` | The resolved channel name (includes namespace) |
|
|
138
|
+
| `messages` | `BroadcastMessage[]` | All received messages from other tabs |
|
|
139
|
+
| `sentMessages` | `BroadcastMessage[]` | Messages sent from this tab |
|
|
140
|
+
| `postMessage()` | `function` | Send a message to all tabs |
|
|
141
|
+
| `clearReceivedMessages()` | `function` | Clear received messages. No filters ⇒ clear all. With filters, a message is deleted only if it matches **every** provided filter (`ids`, `types`, `sources`). Empty arrays act as wildcards. |
|
|
142
|
+
| `clearSentMessages()` | `function` | Clear messages this tab sent (same matching rules). Pass `sync: true` to broadcast the clear to other tabs. |
|
|
143
|
+
| `getLatestMessage()` | `function` | Get the latest message matching optional filters (`type`, `source`). Returns the most recent message that matches, or `null` if none. |
|
|
144
|
+
| `ping(timeoutMs?)` | `function` | Ping other tabs on the channel and collect their source names. `timeoutMs` (default: 300ms) controls how long to wait for responses before resolving. Returns a Promise of string array. |
|
|
145
|
+
| `isPingInProgress` | `boolean` | `true` while a ping is active, otherwise `false`. |
|
|
146
|
+
| `closeChannel()` | `function` | Explicitly closes the broadcast channel and removes event listeners. Safe to call multiple times. |
|
|
147
|
+
| `error` | `string \| null` | Any runtime error from the channel |
|
|
148
|
+
|
|
149
|
+
#### Clearing examples
|
|
150
|
+
|
|
151
|
+
```tsx
|
|
152
|
+
// Clear everything we've received
|
|
153
|
+
clearReceivedMessages();
|
|
154
|
+
|
|
155
|
+
// Clear all messages we sent and broadcast the clear to other tabs
|
|
156
|
+
clearSentMessages({ sync: true });
|
|
157
|
+
|
|
158
|
+
// Clear by id or by type (OR inside each array)
|
|
159
|
+
clearReceivedMessages({ ids: ['123'] }); // id match
|
|
160
|
+
clearReceivedMessages({ types: ['alert', 'chat'] }); // type match
|
|
161
|
+
|
|
162
|
+
// Combine filters (logical AND between filters)
|
|
163
|
+
// Removes messages whose id is '123' AND type is 'alert'
|
|
164
|
+
clearSentMessages({ ids: ['123'], types: ['alert'] });
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
#### Send Options:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
interface SendMessageOptions {
|
|
171
|
+
expirationDuration?: number; // TTL in ms
|
|
172
|
+
expirationDate?: number; // Exact expiry timestamp
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
#### Message Format:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
interface BroadcastMessage {
|
|
180
|
+
id: string;
|
|
181
|
+
type: string;
|
|
182
|
+
message: any;
|
|
183
|
+
timestamp: number;
|
|
184
|
+
source: string;
|
|
185
|
+
expirationDate?: number;
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
#### Getting the Latest Message
|
|
190
|
+
|
|
191
|
+
You can use `getLatestMessage` to retrieve the most recent message received, optionally filtered by `type` and/or `source`. If no options are provided, it returns the latest message of any kind. If no message matches, it returns `null`.
|
|
192
|
+
|
|
193
|
+
**Signature:**
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
getLatestMessage(options?: { type?: string; source?: string }): BroadcastMessage | null
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**Examples:**
|
|
200
|
+
|
|
201
|
+
```tsx
|
|
202
|
+
// Get the latest message of any type/source
|
|
203
|
+
const latest = getLatestMessage();
|
|
204
|
+
|
|
205
|
+
// Get the latest message of a specific type
|
|
206
|
+
const latestAlert = getLatestMessage({ type: 'alert' });
|
|
207
|
+
|
|
208
|
+
// Get the latest message from a specific source
|
|
209
|
+
const latestFromTab = getLatestMessage({ source: 'tab-123' });
|
|
210
|
+
|
|
211
|
+
// Get the latest message of a specific type from a specific source
|
|
212
|
+
const latestInfoFromTab = getLatestMessage({ type: 'info', source: 'tab-123' });
|
|
213
|
+
|
|
214
|
+
// Check if there are any messages of a type
|
|
215
|
+
if (getLatestMessage({ type: 'notification' })) {
|
|
216
|
+
// ...
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
**Behavior:**
|
|
221
|
+
|
|
222
|
+
- If no messages are present, returns `null`.
|
|
223
|
+
- If no message matches the filter, returns `null`.
|
|
224
|
+
- If multiple messages match, returns the most recently received one.
|
|
225
|
+
|
|
226
|
+
#### Ping & Active Source Detection
|
|
227
|
+
|
|
228
|
+
`useBroadcastChannel` provides a `ping` method and an `isPingInProgress` state for discovering active sources (tabs) on the same channel.
|
|
229
|
+
|
|
230
|
+
- **`ping(timeoutMs?: number): Promise<string[]>`**: Broadcasts a ping and collects responses from other tabs within the timeout. Returns an array of source names (excluding your own).
|
|
231
|
+
- **`isPingInProgress: boolean`**: Indicates if a ping is currently in progress.
|
|
232
|
+
|
|
233
|
+
**Example:**
|
|
234
|
+
|
|
235
|
+
```tsx
|
|
236
|
+
const { ping, isPingInProgress } = useBroadcastChannel('my-channel', {
|
|
237
|
+
sourceName: 'my-tab',
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
// To discover other active sources:
|
|
241
|
+
const activeSources = await ping(300); // e.g., ['tab-2', 'tab-3']
|
|
242
|
+
|
|
243
|
+
// To show loading state:
|
|
244
|
+
if (isPingInProgress) {
|
|
245
|
+
// Show spinner or status
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
#### Closing the Channel Explicitly
|
|
250
|
+
|
|
251
|
+
You can use `closeChannel` to explicitly close the underlying BroadcastChannel and remove all event listeners. This is useful if you want to clean up resources before the component unmounts, or to stop all cross-tab communication on demand. Note that the channel will automatically close and all event listeners will be removed when the component unmounts, so this method is mainly useful for manual cleanup.
|
|
252
|
+
|
|
253
|
+
**Signature:**
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
closeChannel(): void
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
**Example:**
|
|
260
|
+
|
|
261
|
+
```tsx
|
|
262
|
+
const { closeChannel } = useBroadcastChannel('my-channel');
|
|
263
|
+
|
|
264
|
+
// ... later, when you want to stop all communication:
|
|
265
|
+
closeChannel();
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
**Notes:**
|
|
269
|
+
|
|
270
|
+
- After calling `closeChannel`, the channel is closed and will not send or receive any more messages.
|
|
271
|
+
- It is safe to call `closeChannel` multiple times (idempotent).
|
|
272
|
+
- You do not need to call this for normal React unmounting; the hook will clean up automatically. Use it for explicit/manual cleanup only.
|
|
273
|
+
|
|
274
|
+
#### `onMessage` Callbacks
|
|
275
|
+
|
|
276
|
+
`onMessage` lets you react to incoming messages imperatively — without polling `messages` state or using `useEffect`. The callback fires after the message is added to state and only for messages that pass all active filters (`registeredTypes`, expiry, deduplication, self-filter). Internal protocol messages (PING, PONG, CLEAR_SENT_MESSAGES) never trigger it.
|
|
277
|
+
|
|
278
|
+
**Two supported shapes:**
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
// 1. A single catch-all function — fires for every accepted message type
|
|
282
|
+
type MessageCallback = (msg: BroadcastMessage) => void;
|
|
283
|
+
|
|
284
|
+
// 2. A map from message type → one handler function
|
|
285
|
+
type OnMessageMap = { [type: string]: (msg: BroadcastMessage) => void };
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
**Catch-all example:**
|
|
289
|
+
|
|
290
|
+
```tsx
|
|
291
|
+
const { postMessage } = useBroadcastChannel('my-channel', {
|
|
292
|
+
onMessage: msg => {
|
|
293
|
+
console.log('received', msg.type, msg.message);
|
|
294
|
+
},
|
|
295
|
+
});
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
**Per-type map example:**
|
|
299
|
+
|
|
300
|
+
```tsx
|
|
301
|
+
useBroadcastChannel('my-channel', {
|
|
302
|
+
onMessage: {
|
|
303
|
+
error: msg => showToast(`Error: ${msg.message.text}`),
|
|
304
|
+
success: msg => celebrate(),
|
|
305
|
+
log: msg => console.log('[log]', msg.message),
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
**Behavior:**
|
|
311
|
+
|
|
312
|
+
- Fires for messages from **other** tabs only — self-messages are always ignored before this point.
|
|
313
|
+
- Fires **after** `messages` state is updated — both the callback argument and `messages[messages.length - 1]` will be the same object.
|
|
314
|
+
- A type not listed in the map causes no error — it is silently skipped.
|
|
315
|
+
- If the callback throws, the error is caught and debug-logged. Message state is **not** affected.
|
|
316
|
+
- Changing `onMessage` between renders is safe — the latest callback is always used with no stale closure risk.
|
|
317
|
+
- Works with batched messages: each message in a batch triggers its own callback call.
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
#### `telemetry` Option
|
|
322
|
+
|
|
323
|
+
**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.
|
|
324
|
+
|
|
325
|
+
**What is collected:**
|
|
326
|
+
|
|
327
|
+
- Which `BroadcastOptions` keys are present (not their values)
|
|
328
|
+
- The shape of `onMessage` (`none` / `function` / `map`)
|
|
329
|
+
- Whether batching is enabled
|
|
330
|
+
- Whether `BroadcastChannel` is supported in the browser
|
|
331
|
+
- Which action methods (`postMessage`, `ping`, etc.) are called at least once per session
|
|
332
|
+
- Hook vs. provider entry point
|
|
333
|
+
|
|
334
|
+
**What is never collected:**
|
|
335
|
+
|
|
336
|
+
- Channel names, source names, message content, or message types
|
|
337
|
+
- Any application user identifiers in the event payload (Mixpanel may process IP addresses from request metadata)
|
|
338
|
+
|
|
339
|
+
Telemetry is **off by default**. Pass `telemetry: true` to opt in for a channel:
|
|
340
|
+
|
|
341
|
+
```tsx
|
|
342
|
+
useBroadcastChannel('my-channel', { telemetry: true });
|
|
343
|
+
// or
|
|
344
|
+
<BroadcastProvider channelName="my-channel" options={{ telemetry: true }} />;
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
**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.
|
|
348
|
+
|
|
349
|
+
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.
|
|
350
|
+
|
|
351
|
+
See [TELEMETRY.md](./TELEMETRY.md) for the full legal notice.
|
|
352
|
+
|
|
353
|
+
---
|
|
354
|
+
|
|
355
|
+
## Gotchas
|
|
356
|
+
|
|
357
|
+
- **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.
|
|
358
|
+
- **`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.
|
|
359
|
+
- **`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`.
|
|
360
|
+
- **Deduplication is by message ID**, not content (see [Message Deduplication](#message-deduplication)).
|
|
361
|
+
- **Same origin only:** `BroadcastChannel` does not cross origins, and a tab does not receive its own messages.
|
|
362
|
+
- **Telemetry is off by default:** pass `telemetry: true` to opt in (see [Telemetry](#telemetry)).
|
|
363
|
+
|
|
364
|
+
## Links
|
|
365
|
+
|
|
366
|
+
- [README](https://github.com/IdanShalem/react-broadcast-sync#readme)
|
|
367
|
+
- [Telemetry notice](https://github.com/IdanShalem/react-broadcast-sync/blob/main/TELEMETRY.md)
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-broadcast-sync",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "React hook and provider for cross-tab messaging over BroadcastChannel, with helpers for manually syncing state between tabs (no automatic state replication).",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
"type": "module",
|
|
10
10
|
"files": [
|
|
11
11
|
"dist",
|
|
12
|
+
"llms.txt",
|
|
13
|
+
"skills",
|
|
12
14
|
"README.md",
|
|
13
15
|
"LICENSE",
|
|
14
16
|
"TELEMETRY.md"
|
|
@@ -31,6 +33,8 @@
|
|
|
31
33
|
"release": "semantic-release",
|
|
32
34
|
"lint-staged": "lint-staged",
|
|
33
35
|
"prepack": "npm run build",
|
|
36
|
+
"generate:llms": "node scripts/generate-llms-txt.mjs",
|
|
37
|
+
"check:llms": "node scripts/generate-llms-txt.mjs --check",
|
|
34
38
|
"verify:telemetry": "node scripts/verify-telemetry-token.mjs",
|
|
35
39
|
"dev:integration": "vite integration/app --port 5199 --strictPort",
|
|
36
40
|
"test:integration": "playwright test"
|
|
@@ -71,11 +75,20 @@
|
|
|
71
75
|
},
|
|
72
76
|
"keywords": [
|
|
73
77
|
"react",
|
|
78
|
+
"react-hooks",
|
|
74
79
|
"hooks",
|
|
75
80
|
"broadcastchannel",
|
|
81
|
+
"broadcast-channel",
|
|
76
82
|
"sync",
|
|
83
|
+
"state-sync",
|
|
77
84
|
"cross-tab",
|
|
78
|
-
"
|
|
85
|
+
"multi-tab",
|
|
86
|
+
"tabs",
|
|
87
|
+
"state-management",
|
|
88
|
+
"localstorage-alternative",
|
|
89
|
+
"message-ttl",
|
|
90
|
+
"typescript",
|
|
91
|
+
"real-time"
|
|
79
92
|
],
|
|
80
93
|
"author": "Idan Shalem <idanshalem25@gmail.com>",
|
|
81
94
|
"license": "MIT",
|