Current section

Files

Jump to
combo priv static live_reloader.min.js
Raw

priv/static/live_reloader.min.js

var Combo=Combo||{};Combo.LiveReloader=(()=>{var V=Object.create;var k=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty;var ie=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),se=(e,t)=>{for(var i in t)k(e,i,{get:t[i],enumerable:!0})},U=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Z(t))!te.call(e,n)&&n!==i&&k(e,n,{get:()=>t[n],enumerable:!(s=Y(t,n))||s.enumerable});return e};var ne=(e,t,i)=>(i=e!=null?V(ee(e)):{},U(t||!e||!e.__esModule?k(i,"default",{value:e,enumerable:!0}):i,e)),re=e=>U(k({},"__esModule",{value:!0}),e);var W=ie((We,J)=>{var de="Expected a function",I=NaN,pe="[object Symbol]",ge=/^\s+|\s+$/g,me=/^[-+]0x[0-9a-f]+$/i,be=/^0b[01]+$/i,Te=/^0o[0-7]+$/i,ve=parseInt,Ce=typeof global=="object"&&global&&global.Object===Object&&global,ye=typeof self=="object"&&self&&self.Object===Object&&self,Se=Ce||ye||Function("return this")(),Re=Object.prototype,Ee=Re.toString,ke=Math.max,je=Math.min,H=function(){return Se.Date.now()};function we(e,t,i){var s,n,r,o,a,h,l=0,d=!1,f=!1,C=!0;if(typeof e!="function")throw new TypeError(de);t=F(t)||0,N(i)&&(d=!!i.leading,f="maxWait"in i,r=f?ke(F(i.maxWait)||0,t):r,C="trailing"in i?!!i.trailing:C);function y(c){var b=s,S=n;return s=n=void 0,l=c,o=e.apply(S,b),o}function q(c){return l=c,a=setTimeout(E,t),d?y(c):o}function X(c){var b=c-h,S=c-l,M=t-b;return f?je(M,r-S):M}function $(c){var b=c-h,S=c-l;return h===void 0||b>=t||b<0||f&&S>=r}function E(){var c=H();if($(c))return P(c);a=setTimeout(E,X(c))}function P(c){return a=void 0,C&&s?y(c):(s=n=void 0,o)}function K(){a!==void 0&&clearTimeout(a),l=0,s=h=n=a=void 0}function Q(){return a===void 0?o:P(H())}function L(){var c=H(),b=$(c);if(s=arguments,n=this,h=c,b){if(a===void 0)return q(h);if(f)return a=setTimeout(E,t),y(h)}return a===void 0&&(a=setTimeout(E,t)),o}return L.cancel=K,L.flush=Q,L}function N(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function Ae(e){return!!e&&typeof e=="object"}function Le(e){return typeof e=="symbol"||Ae(e)&&Ee.call(e)==pe}function F(e){if(typeof e=="number")return e;if(Le(e))return I;if(N(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=N(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(ge,"");var i=be.test(e);return i||Te.test(e)?ve(e.slice(2),i?2:8):me.test(e)?I:+e}J.exports=we});var $e={};se($e,{default:()=>Be});var oe=typeof self!="undefined"?self:null,v=typeof window!="undefined"?window:null,p=oe||v||globalThis,ae="2.0.0",g={connecting:0,open:1,closing:2,closed:3},he=1e4,le=1e3,u={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},m={close:"combo_close",error:"combo_error",join:"combo_join",reply:"combo_reply",leave:"combo_leave"},_={longpoll:"longpoll",websocket:"websocket"},ce={complete:4},O="base64url.bearer.combo.",R=e=>typeof e=="function"?e:function(){return e},A=class{static request(e,t,i,s,n,r,o){if(p.XDomainRequest){let a=new p.XDomainRequest;return this.xdomainRequest(a,e,t,s,n,r,o)}else if(p.XMLHttpRequest){let a=new p.XMLHttpRequest;return this.xhrRequest(a,e,t,i,s,n,r,o)}else{if(p.fetch&&p.AbortController)return this.fetchRequest(e,t,i,s,n,r,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,t,i,s,n,r,o){let a={method:e,headers:i,body:s},h=null;if(n){h=new AbortController;let l=setTimeout(()=>h.abort(),n);a.signal=h.signal}return p.fetch(t,a).then(l=>l.text()).then(l=>this.parseJSON(l)).then(l=>o&&o(l)).catch(l=>{l.name==="AbortError"&&r?r():o&&o(null)}),h}static xdomainRequest(e,t,i,s,n,r,o){return e.timeout=n,e.open(t,i),e.onload=()=>{let a=this.parseJSON(e.responseText);o&&o(a)},r&&(e.ontimeout=r),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,i,s,n,r,o,a){e.open(t,i,!0),e.timeout=r;for(let[h,l]of Object.entries(s))e.setRequestHeader(h,l);return e.onerror=()=>a&&a(null),e.onreadystatechange=()=>{if(e.readyState===ce.complete&&a){let h=this.parseJSON(e.responseText);a(h)}},o&&(e.ontimeout=o),e.send(n),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch(t){return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let n=t?`${t}[${s}]`:s,r=e[s];typeof r=="object"?i.push(this.serialize(r,n)):i.push(encodeURIComponent(n)+"="+encodeURIComponent(r))}return i.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}},j=class{constructor(e,t,i,s){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},x=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},fe=class{constructor(e,t,i){this.state=u.closed,this.topic=e,this.params=R(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new j(this,m.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new x(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=u.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=u.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=u.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=u.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new j(this,m.leave,R({}),this.timeout).send(),this.state=u.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(m.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(m.close,e)}onError(e){return this.on(m.error,t=>e(t))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter(i=>!(i.event===e&&(typeof t=="undefined"||t===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new j(this,e,function(){return t},i);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=u.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(m.close,"leave")},i=new j(this,m.leave,R({}),e);return i.receive("ok",()=>t()).receive("timeout",()=>t()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}isMember(e,t,i,s){return this.topic!==e?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=u.joining,this.joinPush.resend(e))}trigger(e,t,i,s){let n=this.onMessage(e,t,i,s);if(t&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===e);for(let o=0;o<r.length;o++)r[o].callback(n,i,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===u.closed}isErrored(){return this.state===u.errored}isJoined(){return this.state===u.joined}isJoining(){return this.state===u.joining}isLeaving(){return this.state===u.leaving}},ue=e=>{let t="",i=new Uint8Array(e),s=i.byteLength;for(let n=0;n<s;n++)t+=String.fromCharCode(i[n]);return btoa(t)},T=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(O)&&(this.authToken=atob(t[1].slice(O.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=g.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+_.websocket),"$1/"+_.longpoll)}endpointURL(){return A.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=g.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===g.open||this.readyState===g.connecting}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Combo-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:i,token:s,messages:n}=t;if(i===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else i=0;switch(i){case 200:n.forEach(r=>{setTimeout(()=>this.onmessage({data:r}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=g.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${i}`)}})}send(e){typeof e!="string"&&(e=ue(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(`
`),()=>this.onerror("timeout"),t=>{this.awaitingBatchAck=!1,!t||t.status!==200?(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,t,i){for(let n of this.reqs)n.abort();this.readyState=g.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent!="undefined"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,i,s,n){let r,o=()=>{this.reqs.delete(r),s()};r=A.request(e,this.endpointURL(),t,i,this.timeout,o,a=>{this.reqs.delete(r),this.isActive()&&n(a)}),this.reqs.add(r)}},w={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let i=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(i))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[i,s,n,r,o]=JSON.parse(e);return t({join_ref:i,ref:s,topic:n,event:r,payload:o})}},binaryEncode(e){let{join_ref:t,ref:i,event:s,topic:n,payload:r}=e,o=this.META_LENGTH+t.length+i.length+n.length+s.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),h=new DataView(a),l=0;h.setUint8(l++,this.KINDS.push),h.setUint8(l++,t.length),h.setUint8(l++,i.length),h.setUint8(l++,n.length),h.setUint8(l++,s.length),Array.from(t,f=>h.setUint8(l++,f.charCodeAt(0))),Array.from(i,f=>h.setUint8(l++,f.charCodeAt(0))),Array.from(n,f=>h.setUint8(l++,f.charCodeAt(0))),Array.from(s,f=>h.setUint8(l++,f.charCodeAt(0)));var d=new Uint8Array(a.byteLength+r.byteLength);return d.set(new Uint8Array(a),0),d.set(new Uint8Array(r),a.byteLength),d.buffer},binaryDecode(e){let t=new DataView(e),i=t.getUint8(0),s=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=i.decode(e.slice(o,o+s));o=o+s;let h=i.decode(e.slice(o,o+n));o=o+n;let l=i.decode(e.slice(o,o+r));o=o+r;let d=e.slice(o,e.byteLength);return{join_ref:a,ref:null,topic:h,event:l,payload:d}},decodeReply(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,h=i.decode(e.slice(a,a+s));a=a+s;let l=i.decode(e.slice(a,a+n));a=a+n;let d=i.decode(e.slice(a,a+r));a=a+r;let f=i.decode(e.slice(a,a+o));a=a+o;let C=e.slice(a,e.byteLength),y={status:f,response:C};return{join_ref:h,ref:l,topic:d,event:m.reply,payload:y}},decodeBroadcast(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=this.HEADER_LENGTH+2,o=i.decode(e.slice(r,r+s));r=r+s;let a=i.decode(e.slice(r,r+n));r=r+n;let h=e.slice(r,e.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:h}}},D=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||he,this.transport=t.transport||p.WebSocket||T,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||p&&p.sessionStorage,this.establishedConnections=0,this.defaultEncoder=w.encode.bind(w),this.defaultDecoder=w.decode.bind(w),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.transport!==T?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;v&&v.addEventListener&&(v.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),i=this.connectClock)}),v.addEventListener("pageshow",s=>{i===this.connectClock&&(i=null,this.connect())})),v.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))}),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=s=>t.rejoinAfterMs?t.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>t.reconnectAfterMs?t.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(s,n,r)=>{console.log(`${s}: ${n}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=R(t.params||{}),this.endPoint=`${e}/${_.websocket}`,this.vsn=t.vsn||ae,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new x(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(()=>this.connect())},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return T}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=A.appendParams(A.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=R(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==T?this.connectWithFallback(T,this.longPollFallbackMs):this.transportConnect())}log(e,t,i){this.logger&&this.logger(e,t,i)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"combo",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(n=>{n.ref===t&&(this.off([s]),e(Date.now()-i))});return!0}transportName(e){switch(e){case T:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["combo",`${O}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let i=!1,s=!0,n,r,o=this.transportName(e),a=h=>{this.log("transport",`falling back to ${o}...`,h),this.off([n,r]),s=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`combo:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,t),r=this.onError(h=>{this.log("transport","error",h),s&&!i&&(clearTimeout(this.fallbackTimer),a(h))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!s){let h=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`combo:fallback:${h}`,"true"),this.log("transport",`established ${h} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,t),this.ping(h=>{this.log("transport","connected to primary after",h),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transportName(this.transport)} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,e])=>e())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),le,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,i||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,i=1){if(i===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,i+1)},150*i)}waitForSocketClosed(e,t,i=1){if(i===5||e.readyState===g.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,i+1)},150*i)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{});let t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&t!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,i])=>i(e))}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,s])=>{s(e,t,i)}),(t===this.transport||i>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(m.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case g.connecting:return"connecting";case g.open:return"open";case g.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([i])=>e.indexOf(i)===-1)}channel(e,t={}){let i=new fe(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:s,ref:n,join_ref:r}=e;this.log("push",`${t} ${i} (${r}, ${n})`,s)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"combo",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:i,event:s,payload:n,ref:r,join_ref:o}=t;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${n.status||""} ${i} ${s} ${r&&"("+r+")"||""}`,n);for(let a=0;a<this.channels.length;a++){let h=this.channels[a];h.isMember(i,s,n,o)&&h.trigger(s,n,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,h]=this.stateChangeCallbacks.message[a];h(t)}})}leaveOpenTopic(e){let t=this.channels.find(i=>i.topic===e&&(i.isJoined()||i.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};var z=ne(W(),1);function G(e){let t=Math.round(Date.now()/1e3).toString(),i=e.replace(/(&|\?)vsn=\d*/,"");return i+(i.includes("?")?"&":"?")+"vsn="+t}function _e(e){let t=document.createElement("style"),i=()=>{e.parentNode!==null&&e.parentNode.removeChild(e)},n=(e.textContent||e.innerHTML).replace(/@import\s+(?:url\()?['"]?([^'"\)]+)['"]?\)?/g,(r,o)=>{let a=G(o);return r.includes("url(")?`@import url("${a}")`:`@import "${a}"`});return t.onerror=i,t.onload=i,e.setAttribute("data-pending-removal",""),t.setAttribute("type","text/css"),t.textContent=n,e.parentNode.insertBefore(t,e.nextSibling),t}function Oe(e){let t=document.createElement("link"),i=()=>{e.parentNode!==null&&e.parentNode.removeChild(e)};return t.onerror=i,t.onload=i,e.setAttribute("data-pending-removal",""),t.setAttribute("rel","stylesheet"),t.setAttribute("type","text/css"),t.setAttribute("href",G(e.href)),e.parentNode.insertBefore(t,e.nextSibling),t}function He(){navigator.userAgent.toLowerCase().includes("chrome")&&setTimeout(()=>document.body.offsetHeight,25)}function Ne(e,t){let i={type:"full_reload",priority:9,fun:()=>{window[e].location.reload()}};return{css:t?i:{type:"hot_reload",priority:1,fun:()=>{let n=window.parent.document.querySelectorAll("link[rel=stylesheet]:not([data-no-reload]):not([data-pending-removal])");Array.from(n).filter(o=>o.href).forEach(o=>Oe(o));let r=window.parent.document.querySelectorAll("style:not([data-no-reload]):not([data-pending-removal])");Array.from(r).filter(o=>o.textContent.includes("@import")).forEach(o=>_e(o)),He()}},__default__:i}}var B=class{constructor(t,i,s,n){this.enabledOnce=!1,this.reloadQueue=[],this.socket=new D(t),this.debouncedReload=(0,z.default)(this.reload,i),this.reloadStrategies=Ne(s,n),this.channel=this.socket.channel("combo:live_reloader",{}),this.socket.onOpen(()=>{this.enabledOnce||(this.enabledOnce=!0,["complete","loaded","interactive"].includes(parent.document.readyState)?this.dispatchConnected():parent.addEventListener("load",()=>this.dispatchConnected()))}),this.channel.on("reload",r=>{let{type:o}=r;this.scheduleReload(o)})}enable(){this.channel.join(),this.socket.connect()}disable(){this.channel.leave(),this.socket.disconnect(),this.enabledOnce=!1,this.reloadQueue=[]}dispatchConnected(){parent.dispatchEvent(new CustomEvent("combo:live_reloader:connected",{detail:this}))}scheduleReload(t){this.reloadQueue.push(t),this.debouncedReload()}reload(){let i=this.reloadQueue.map(r=>this.getReloadStrategy(r)).reduce((r,o)=>o.priority>r.priority?o:r),{type:s,fun:n}=i;s=="full_reload"&&this.channel.off("reload"),n(),this.reloadQueue=[]}getReloadStrategy(t){return this.reloadStrategies[t]||this.reloadStrategies.__default__}},Be=B;return re($e);})();
//# sourceMappingURL=live_reloader.min.js.map