1globalThis.EventTarget&&globalThis.Event||console.error("\n PartySocket requires a global 'EventTarget' class to be available!\n You can polyfill this global by adding this to your code before any partysocket imports: \n \n ```\n import 'partysocket/event-target-polyfill';\n ```\n Please file an issue at https://github.com/partykit/partykit if you're still having trouble.\n");var e=class extends Event{message;error;constructor(e,t){super("error",t),this.message=e.message,this.error=e}},t=class extends Event{code;reason;wasClean=!0;constructor(e=1e3,t="",s){super("close",s),this.code=e,this.reason=t}},s=(Event,e),o=t;var r="undefined"!=typeof process&&void 0!==process.versions?.node,n="undefined"!=typeof navigator&&"ReactNative"===navigator.product,i=r||n?function(s){return"data"in s?new MessageEvent(s.type,s):"code"in s||"reason"in s?new t(s.code||1999,s.reason||"unknown reason",s):"error"in s?new e(s.error,s):new Event(s.type,s)}:function(e){return new e.constructor(e.type,e)},a={maxReconnectionDelay:1e4,minReconnectionDelay:3e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:Number.POSITIVE_INFINITY,maxEnqueuedMessages:Number.POSITIVE_INFINITY,startClosed:!1,debug:!1},h=!1;function c(){}var u=class e extends EventTarget{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType="blob";_closeCalled=!1;_didWarnAboutClosedSend=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(e,t,s={}){super(),this._url=e,this._protocols=t,this._options=s,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return e.CONNECTING}get OPEN(){return e.OPEN}get CLOSING(){return e.CLOSING}get CLOSED(){return e.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((e,t)=>("string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._closeCalled?e.CLOSED:this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED&&this._ws.readyState!==this.CLOSING?this._disconnect(e,t):this._debug("close: already closing or closed"):this._debug("close enqueued: no ws instance")}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._didWarnAboutClosedSend=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.readyState!==this.CLOSING?(this._disconnect(e,t),this._connect()):this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)return this._debug("send",e),this._ws.send(e),!0;this._closeCalled&&!this._didWarnAboutClosedSend&&(this._didWarnAboutClosedSend=!0,console.warn("ReconnectingWebSocket: send() was called after close(). The message has been buffered, but it will only be delivered if reconnect() is called on this socket. If this socket has been discarded, the message is lost â this usually means a stale socket reference is being used."));const{maxEnqueuedMessages:t=a.maxEnqueuedMessages}=this._options;return this._messageQueue.length<t&&(this._debug("enqueue",e),this._messageQueue.push(e)),!1}drainQueuedMessages(){const e=this._messageQueue;return this._messageQueue=[],e}_debug(...e){this._options.debug&&this._debugLogger("RWS>",...e)}_getNextDelay(){const{reconnectionDelayGrowFactor:e=a.reconnectionDelayGrowFactor,minReconnectionDelay:t=a.minReconnectionDelay,maxReconnectionDelay:s=a.maxReconnectionDelay}=this._options;let o=0;return this._retryCount>0&&(o=t*e**(this._retryCount-1),o>s&&(o=s)),this._debug("next delay",o),o}_wait(){return new Promise(e=>{setTimeout(e,this._getNextDelay())})}_getNextProtocols(e){if(!e)return Promise.resolve(null);if("string"==typeof e||Array.isArray(e))return Promise.resolve(e);if("function"==typeof e){const t=e();if(!t)return Promise.resolve(null);if("string"==typeof t||Array.isArray(t))return Promise.resolve(t);if(t.then)return t}throw Error("Invalid protocols")}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;
1const{maxRetries:e=a.maxRetries,connectionTimeout:t=a.connectionTimeout}=this._options;if(this._retryCount>=e)return this._debug("max retries reached",this._retryCount,">=",e),void(this._connectLock=!1);this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>Promise.all([this._getNextUrl(this._url),this._getNextProtocols(this._protocols||null)])).then(([e,s])=>{if(this._closeCalled)return void(this._connectLock=!1);this._options.WebSocket||"undefined"!=typeof WebSocket||h||(console.error("â¼ï¸ No WebSocket implementation available. You should define options.WebSocket. \n\nFor example, if you're using node.js, run `npm install ws`, and then in your code:\n\nimport PartySocket from 'partysocket';\nimport WS from 'ws';\n\nconst partysocket = new PartySocket({\n host: \"127.0.0.1:1999\",\n room: \"test-room\",\n WebSocket: WS\n});\n\n"),h=!0);const o=this._options.WebSocket||WebSocket;this._debug("connect",{url:e,protocols:s}),this._ws=s?new o(e,s):new o(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),t)}).catch(e=>{this._connectLock=!1,this._handleError(new s(Error(e.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new s(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.readyState!==this.OPEN&&this._ws.readyState!==this.CONNECTING||this._ws.close(e,t),this._handleClose(new o(e,t,this))}catch(s){}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=e=>{this._debug("open event");const{minUptime:t=a.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),t),function(e,t){if(!e)throw new Error(t)}(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(e=>{this._ws?.send(e)}),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(i(e))};_handleMessage=e=>{this._debug("message event"),this.onmessage&&this.onmessage(e),this.dispatchEvent(i(e))};_handleError=e=>{this._debug("error event",e.message),this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._debug("exec error listeners"),this.dispatchEvent(i(e)),this._connect()};_handleClose=e=>{this._debug("close event"),this._clearTimeouts(),this._options.shouldReconnectOnClose&&!this._options.shouldReconnectOnClose(e)&&(this._shouldReconnect=!1),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(i(e))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError),this._ws.addEventListener("error",c))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}},l=e=>null!==e[1]&&void 0!==e[1];function d(e,t,s={}){const{host:o,path:r,protocol:n,room:i,party:a,basePath:h,prefix:c,query:u}=e;let d=o.replace(/^(http|https|ws|wss):\/\//,"");if(d.endsWith("/")&&(d=d.slice(0,-1)),r?.startsWith("/"))throw new Error("path must not start with a slash");const _=a??"main",p=r?`/${r}`:"",m=n||(d.startsWith("localhost:")||d.startsWith("127.0.0.1:")||d.startsWith("192.168.")||d.startsWith("10.")||d.startsWith("172.")&&d.split(".")[1]>="16"&&d.split(".")[1]<="31"||d.startsWith("[::ffff:7f00:1]:")?t:`${t}s`),g=`${m}://${d}/${h||`${c||"parties"}/${_}/${i}`}${p}`,y=(e={})=>`${g}?${new URLSearchParams([...Object.entries(s),...Object.entries(e).filter(l)])}`,w="function"==typeof u?async()=>y(await u()):y(u);return{host:d,path:p,room:i,name:_,protocol:m,partyUrl:g,urlProvider:w}}var _=class extends u{_pk;_pkurl;name;room;host;path;basePath;constructor(e){const t=p(e);if(super(t.urlProvider,t.protocols,t.socketOptions),this.partySocketOptions=e,this.setWSProperties(t),!e.startClosed&&!this.room&&!this.basePath)throw this.close(),new Error("Either room or basePath must be provided to connect. Use startClosed: true to create a socket and set them via updateProperties before calling reconnect().");e.disableNameValidation||(e.party?.includes("/")&&console.warn(`PartySocket: party name "${e.party}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`),e.room?.includes("/")&&console.warn(`PartySocket: room name "${e.room}" contains forward slash which may cause routing issues. Consider using a name without forward slashes or set disableNameValidation: true to bypass this warning.`))}updateProperties(e){const t=p({...this.partySocketOptions,...e,host:e.host??this.host,room:e.room??this.room,path:e.path??this.path,basePath:e.basePath??this.basePath});this._url=t.urlProvider,this._protocols=t.protocols,this._options=t.socketOptions,this.setWSProperties(t)}setWSProperties(e){const{_pk:t,_pkurl:s,name:o,room:r,host:n,path:i,basePath:a}=e;this._pk=t,this._pkurl=s,this.name=o,this.room=r,this.host=n,this.path=i,this.basePath=a}reconnect(e,t){if(!this.host)throw new Error("The host must be set before connecting, use `updateProperties` method to set it or pass it to the constructor.");if(!this.room&&!this.basePath)throw new Error("The room (or basePath) must be set before connecting, use `updateProperties` method to set it or pass it to the constructor.");super.reconnect(e,t)}get id(){return this._pk}get roomUrl(){return this._pkurl}static async fetch(e,t){const s=d(e,"http"),o="string"==typeof s.urlProvider?s.urlProvider:await s.urlProvider();return(e.fetch??fetch)(o,t)}};function p(e){const{id:t,host:s,path:o,party:r,room:n,protocol:i,query:a,protocols:h,...c}=e,u=t||function(){if(crypto?.randomUUID)return crypto.randomUUID();let e=Date.now(),t=performance?.now&&1e3*performance.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let o=16*Math.random();return e>0?(o=(e+o)%16|0,e=Math.floor(e/16)):(o=(t+o)%16|0,t=Math.floor(t/16)),("x"===s?o:3&o|8).toString(16)})}(),l=d(e,"ws",{_pk:u});return{_pk:u,_pkurl:l.partyUrl,name:l.name,room:l.room,host:l.host,path:l.path,basePath:e.basePath,protocols:h,socketOptions:c,urlProvider:l.urlProvider}}export{_ as PartySocket,_ as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.