turbo-rails 2.0.14 → 2.0.16
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.
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 7de922709135b46c78da967fc906370e96bace376d0c03b205b5b7fb0bf0c1db
|
4
|
+
data.tar.gz: 36c2463b1a996f8d225a3ba33eb73bb07d2c34eccf8316a4670cebca2ed1c90b
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 88303af9181adb99632e23da782c7ab7063c7ce194271b3b9dbf92d89d1e1d2cd3cf1a88147f38ca957d74f7ff310cbf455e3c636cf705ef76cc46b6583b84b1
|
7
|
+
data.tar.gz: '02446187359ca3060de17e6bc435f159d5d5aa98afee83280487372bf63a70b901a44314119119ee9ff4947fba8b93d971d6f143815240cbd0bed9dcd5a7d69e'
|
@@ -5490,8 +5490,8 @@ window.Turbo = Turbo$1;
|
|
5490
5490
|
addEventListener("turbo:before-fetch-request", encodeMethodIntoRequestBody);
|
5491
5491
|
|
5492
5492
|
var adapters = {
|
5493
|
-
logger:
|
5494
|
-
WebSocket:
|
5493
|
+
logger: typeof console !== "undefined" ? console : undefined,
|
5494
|
+
WebSocket: typeof WebSocket !== "undefined" ? WebSocket : undefined
|
5495
5495
|
};
|
5496
5496
|
|
5497
5497
|
var logger = {
|
@@ -5533,12 +5533,11 @@ class ConnectionMonitor {
|
|
5533
5533
|
isRunning() {
|
5534
5534
|
return this.startedAt && !this.stoppedAt;
|
5535
5535
|
}
|
5536
|
-
|
5536
|
+
recordMessage() {
|
5537
5537
|
this.pingedAt = now();
|
5538
5538
|
}
|
5539
5539
|
recordConnect() {
|
5540
5540
|
this.reconnectAttempts = 0;
|
5541
|
-
this.recordPing();
|
5542
5541
|
delete this.disconnectedAt;
|
5543
5542
|
logger.log("ConnectionMonitor recorded connect");
|
5544
5543
|
}
|
@@ -5737,6 +5736,7 @@ Connection.prototype.events = {
|
|
5737
5736
|
return;
|
5738
5737
|
}
|
5739
5738
|
const {identifier: identifier, message: message, reason: reason, reconnect: reconnect, type: type} = JSON.parse(event.data);
|
5739
|
+
this.monitor.recordMessage();
|
5740
5740
|
switch (type) {
|
5741
5741
|
case message_types.welcome:
|
5742
5742
|
if (this.triedToReconnect()) {
|
@@ -5752,7 +5752,7 @@ Connection.prototype.events = {
|
|
5752
5752
|
});
|
5753
5753
|
|
5754
5754
|
case message_types.ping:
|
5755
|
-
return
|
5755
|
+
return null;
|
5756
5756
|
|
5757
5757
|
case message_types.confirmation:
|
5758
5758
|
this.subscriptions.confirmSubscription(identifier);
|
@@ -25,5 +25,5 @@ Copyright © 2025 37signals LLC
|
|
25
25
|
|
26
26
|
——
|
27
27
|
Suppress this warning by adding a "data-turbo-suppress-warning" attribute to: %s
|
28
|
-
`,e.outerHTML);e=e.parentElement}})(),window.Turbo={...qt,StreamActions:Nt},At();var Vt=Object.freeze({__proto__:null,FetchEnctype:J,FetchMethod:z,FetchRequest:X,FetchResponse:V,FrameElement:r,FrameLoadingStyle:s,FrameRenderer:ge,PageRenderer:dt,PageSnapshot:Te,StreamActions:Nt,StreamElement:Dt,StreamSourceElement:xt,cache:yt,clearCache:kt,config:F,connectStreamSource:Tt,disconnectStreamSource:Ct,fetch:$,fetchEnctypeFromString:G,fetchMethodFromString:j,isSafe:K,navigator:Et,registerAdapter:Rt,renderStreamMessage:Pt,session:wt,setConfirmMethod:Ft,setFormMode:It,setProgressBarDelay:Mt,start:At,visit:Lt});let Wt;async function Ut(){return Wt||_t($t().then(_t))}function _t(e){return Wt=e}async function $t(){const{createConsumer:e}=await Promise.resolve().then((function(){return ps}));return e()}async function jt(e,t){const{subscriptions:s}=await Ut();return s.create(e,t)}var zt=Object.freeze({__proto__:null,getConsumer:Ut,setConsumer:_t,createConsumer:$t,subscribeTo:jt});function Gt(e){return e&&"object"==typeof e?e instanceof Date||e instanceof RegExp?e:Array.isArray(e)?e.map(Gt):Object.keys(e).reduce((function(t,s){return t[s[0].toLowerCase()+s.slice(1).replace(/([A-Z]+)/g,(function(e,t){return"_"+t.toLowerCase()}))]=Gt(e[s]),t}),{}):e}class Jt extends HTMLElement{static observedAttributes=["channel","signed-stream-name"];async connectedCallback(){Tt(this),this.subscription=await jt(this.channel,{received:this.dispatchMessageEvent.bind(this),connected:this.subscriptionConnected.bind(this),disconnected:this.subscriptionDisconnected.bind(this)})}disconnectedCallback(){Ct(this),this.subscription&&this.subscription.unsubscribe(),this.subscriptionDisconnected()}attributeChangedCallback(){this.subscription&&(this.disconnectedCallback(),this.connectedCallback())}dispatchMessageEvent(e){const t=new MessageEvent("message",{data:e});return this.dispatchEvent(t)}subscriptionConnected(){this.setAttribute("connected","")}subscriptionDisconnected(){this.removeAttribute("connected")}get channel(){return{channel:this.getAttribute("channel"),signed_stream_name:this.getAttribute("signed-stream-name"),...Gt({...this.dataset})}}}void 0===customElements.get("turbo-cable-stream-source")&&customElements.define("turbo-cable-stream-source",Jt),window.Turbo=Vt,addEventListener("turbo:before-fetch-request",(function(e){if(e.target instanceof HTMLFormElement){const{target:t,detail:{fetchOptions:s}}=e;t.addEventListener("turbo:submit-start",(({detail:{formSubmission:{submitter:e}}})=>{const r=function(e){return e instanceof FormData||e instanceof URLSearchParams}(s.body)?s.body:new URLSearchParams,i=function(e,t,s){const r=function(e){return e instanceof HTMLButtonElement||e instanceof HTMLInputElement?"_method"===e.name?e.value:e.hasAttribute("formmethod")?e.formMethod:null:null}(e),i=t.get("_method"),n=s.getAttribute("method")||"get";return"string"==typeof r?r:"string"==typeof i?i:n}(e,r,t);/get/i.test(i)||(/post/i.test(i)?r.delete("_method"):r.set("_method",i),s.method="post")}),{once:!0})}}));var Xt={logger:self.console,WebSocket:self.WebSocket},Kt={log(...e){this.enabled&&(e.push(Date.now()),Xt.logger.log("[ActionCable]",...e))}};const Qt=()=>(new Date).getTime(),Yt=e=>(Qt()-e)/1e3;class Zt{constructor(e){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=e,this.reconnectAttempts=0}start(){this.isRunning()||(this.startedAt=Qt(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),Kt.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`))}stop(){this.isRunning()&&(this.stoppedAt=Qt(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),Kt.log("ConnectionMonitor stopped"))}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=Qt()}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,Kt.log("ConnectionMonitor recorded connect")}recordDisconnect(){this.disconnectedAt=Qt(),Kt.log("ConnectionMonitor recorded disconnect")}startPolling(){this.stopPolling(),this.poll()}stopPolling(){clearTimeout(this.pollTimeout)}poll(){this.pollTimeout=setTimeout((()=>{this.reconnectIfStale(),this.poll()}),this.getPollInterval())}getPollInterval(){const{staleThreshold:e,reconnectionBackoffRate:t}=this.constructor;return 1e3*e*Math.pow(1+t,Math.min(this.reconnectAttempts,10))*(1+(0===this.reconnectAttempts?1:t)*Math.random())}reconnectIfStale(){this.connectionIsStale()&&(Kt.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${Yt(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?Kt.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${Yt(this.disconnectedAt)} s`):(Kt.log("ConnectionMonitor reopening"),this.connection.reopen()))}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return Yt(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&Yt(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){"visible"===document.visibilityState&&setTimeout((()=>{!this.connectionIsStale()&&this.connection.isOpen()||(Kt.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen())}),200)}}Zt.staleThreshold=6,Zt.reconnectionBackoffRate=.15;var es=Zt,ts={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]};const{message_types:ss,protocols:rs}=ts,is=rs.slice(0,rs.length-1),ns=[].indexOf;class os{constructor(e){this.open=this.open.bind(this),this.consumer=e,this.subscriptions=this.consumer.subscriptions,this.monitor=new es(this),this.disconnected=!0}send(e){return!!this.isOpen()&&(this.webSocket.send(JSON.stringify(e)),!0)}open(){if(this.isActive())return Kt.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{const e=[...rs,...this.consumer.subprotocols||[]];return Kt.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${e}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new Xt.WebSocket(this.consumer.url,e),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:e}={allowReconnect:!0}){if(e||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(Kt.log(`Reopening WebSocket, current state is ${this.getState()}`),!this.isActive())return this.open();try{return this.close()}catch(e){Kt.log("Failed to reopen WebSocket",e)}finally{Kt.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay)}}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return ns.call(is,this.getProtocol())>=0}isState(...e){return ns.call(e,this.getState())>=0}getState(){if(this.webSocket)for(let e in Xt.WebSocket)if(Xt.WebSocket[e]===this.webSocket.readyState)return e.toLowerCase();return null}installEventHandlers(){for(let e in this.events){const t=this.events[e].bind(this);this.webSocket[`on${e}`]=t}}uninstallEventHandlers(){for(let e in this.events)this.webSocket[`on${e}`]=function(){}}}os.reopenDelay=500,os.prototype.events={message(e){if(!this.isProtocolSupported())return;const{identifier:t,message:s,reason:r,reconnect:i,type:n}=JSON.parse(e.data);switch(n){case ss.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case ss.disconnect:return Kt.log(`Disconnecting. Reason: ${r}`),this.close({allowReconnect:i});case ss.ping:return this.monitor.recordPing();case ss.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case ss.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",s)}},open(){if(Kt.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return Kt.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(e){if(Kt.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){Kt.log("WebSocket onerror event")}};var as=os;class cs{constructor(e,t={},s){this.consumer=e,this.identifier=JSON.stringify(t),function(e,t){if(null!=t)for(let s in t){const r=t[s];e[s]=r}}(this,s)}perform(e,t={}){return t.action=e,this.send(t)}send(e){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(e)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}}var ls=class{constructor(e){this.subscriptions=e,this.pendingSubscriptions=[]}guarantee(e){-1==this.pendingSubscriptions.indexOf(e)?(Kt.log(`SubscriptionGuarantor guaranteeing ${e.identifier}`),this.pendingSubscriptions.push(e)):Kt.log(`SubscriptionGuarantor already guaranteeing ${e.identifier}`),this.startGuaranteeing()}forget(e){Kt.log(`SubscriptionGuarantor forgetting ${e.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter((t=>t!==e))}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing()}stopGuaranteeing(){clearTimeout(this.retryTimeout)}retrySubscribing(){this.retryTimeout=setTimeout((()=>{this.subscriptions&&"function"==typeof this.subscriptions.subscribe&&this.pendingSubscriptions.map((e=>{Kt.log(`SubscriptionGuarantor resubscribing ${e.identifier}`),this.subscriptions.subscribe(e)}))}),500)}};class hs{constructor(e){this.consumer=e,this.guarantor=new ls(this),this.subscriptions=[]}create(e,t){const s="object"==typeof e?e:{channel:e},r=new cs(this.consumer,s,t);return this.add(r)}add(e){return this.subscriptions.push(e),this.consumer.ensureActiveConnection(),this.notify(e,"initialized"),this.subscribe(e),e}remove(e){return this.forget(e),this.findAll(e.identifier).length||this.sendCommand(e,"unsubscribe"),e}reject(e){return this.findAll(e).map((e=>(this.forget(e),this.notify(e,"rejected"),e)))}forget(e){return this.guarantor.forget(e),this.subscriptions=this.subscriptions.filter((t=>t!==e)),e}findAll(e){return this.subscriptions.filter((t=>t.identifier===e))}reload(){return this.subscriptions.map((e=>this.subscribe(e)))}notifyAll(e,...t){return this.subscriptions.map((s=>this.notify(s,e,...t)))}notify(e,t,...s){let r;return r="string"==typeof e?this.findAll(e):[e],r.map((e=>"function"==typeof e[t]?e[t](...s):void 0))}subscribe(e){this.sendCommand(e,"subscribe")&&this.guarantor.guarantee(e)}confirmSubscription(e){Kt.log(`Subscription confirmed ${e}`),this.findAll(e).map((e=>this.guarantor.forget(e)))}sendCommand(e,t){const{identifier:s}=e;return this.consumer.send({command:t,identifier:s})}}class ds{constructor(e){this._url=e,this.subscriptions=new hs(this),this.connection=new as(this),this.subprotocols=[]}get url(){return us(this._url)}send(e){return this.connection.send(e)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(e){this.subprotocols=[...this.subprotocols,e]}}function us(e){if("function"==typeof e&&(e=e()),e&&!/^wss?:/i.test(e)){const t=document.createElement("a");return t.href=e,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}return e}function ms(e){const t=document.head.querySelector(`meta[name='action-cable-${e}']`);if(t)return t.getAttribute("content")}var ps=Object.freeze({__proto__:null,Connection:as,ConnectionMonitor:es,Consumer:ds,INTERNAL:ts,Subscription:cs,Subscriptions:hs,SubscriptionGuarantor:ls,adapters:Xt,createWebSocketURL:us,logger:Kt,createConsumer:function(e=ms("url")||ts.default_mount_path){return new ds(e)},getConfig:ms});export{Vt as Turbo,zt as cable};
|
28
|
+
`,e.outerHTML);e=e.parentElement}})(),window.Turbo={...qt,StreamActions:Nt},At();var Vt=Object.freeze({__proto__:null,FetchEnctype:J,FetchMethod:z,FetchRequest:X,FetchResponse:V,FrameElement:r,FrameLoadingStyle:s,FrameRenderer:ge,PageRenderer:dt,PageSnapshot:Te,StreamActions:Nt,StreamElement:Dt,StreamSourceElement:xt,cache:yt,clearCache:kt,config:F,connectStreamSource:Tt,disconnectStreamSource:Ct,fetch:$,fetchEnctypeFromString:G,fetchMethodFromString:j,isSafe:K,navigator:Et,registerAdapter:Rt,renderStreamMessage:Pt,session:wt,setConfirmMethod:Ft,setFormMode:It,setProgressBarDelay:Mt,start:At,visit:Lt});let Wt;async function Ut(){return Wt||_t($t().then(_t))}function _t(e){return Wt=e}async function $t(){const{createConsumer:e}=await Promise.resolve().then((function(){return ps}));return e()}async function jt(e,t){const{subscriptions:s}=await Ut();return s.create(e,t)}var zt=Object.freeze({__proto__:null,getConsumer:Ut,setConsumer:_t,createConsumer:$t,subscribeTo:jt});function Gt(e){return e&&"object"==typeof e?e instanceof Date||e instanceof RegExp?e:Array.isArray(e)?e.map(Gt):Object.keys(e).reduce((function(t,s){return t[s[0].toLowerCase()+s.slice(1).replace(/([A-Z]+)/g,(function(e,t){return"_"+t.toLowerCase()}))]=Gt(e[s]),t}),{}):e}class Jt extends HTMLElement{static observedAttributes=["channel","signed-stream-name"];async connectedCallback(){Tt(this),this.subscription=await jt(this.channel,{received:this.dispatchMessageEvent.bind(this),connected:this.subscriptionConnected.bind(this),disconnected:this.subscriptionDisconnected.bind(this)})}disconnectedCallback(){Ct(this),this.subscription&&this.subscription.unsubscribe(),this.subscriptionDisconnected()}attributeChangedCallback(){this.subscription&&(this.disconnectedCallback(),this.connectedCallback())}dispatchMessageEvent(e){const t=new MessageEvent("message",{data:e});return this.dispatchEvent(t)}subscriptionConnected(){this.setAttribute("connected","")}subscriptionDisconnected(){this.removeAttribute("connected")}get channel(){return{channel:this.getAttribute("channel"),signed_stream_name:this.getAttribute("signed-stream-name"),...Gt({...this.dataset})}}}void 0===customElements.get("turbo-cable-stream-source")&&customElements.define("turbo-cable-stream-source",Jt),window.Turbo=Vt,addEventListener("turbo:before-fetch-request",(function(e){if(e.target instanceof HTMLFormElement){const{target:t,detail:{fetchOptions:s}}=e;t.addEventListener("turbo:submit-start",(({detail:{formSubmission:{submitter:e}}})=>{const r=function(e){return e instanceof FormData||e instanceof URLSearchParams}(s.body)?s.body:new URLSearchParams,i=function(e,t,s){const r=function(e){return e instanceof HTMLButtonElement||e instanceof HTMLInputElement?"_method"===e.name?e.value:e.hasAttribute("formmethod")?e.formMethod:null:null}(e),i=t.get("_method"),n=s.getAttribute("method")||"get";return"string"==typeof r?r:"string"==typeof i?i:n}(e,r,t);/get/i.test(i)||(/post/i.test(i)?r.delete("_method"):r.set("_method",i),s.method="post")}),{once:!0})}}));var Xt={logger:"undefined"!=typeof console?console:void 0,WebSocket:"undefined"!=typeof WebSocket?WebSocket:void 0},Kt={log(...e){this.enabled&&(e.push(Date.now()),Xt.logger.log("[ActionCable]",...e))}};const Qt=()=>(new Date).getTime(),Yt=e=>(Qt()-e)/1e3;class Zt{constructor(e){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=e,this.reconnectAttempts=0}start(){this.isRunning()||(this.startedAt=Qt(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),Kt.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`))}stop(){this.isRunning()&&(this.stoppedAt=Qt(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),Kt.log("ConnectionMonitor stopped"))}isRunning(){return this.startedAt&&!this.stoppedAt}recordMessage(){this.pingedAt=Qt()}recordConnect(){this.reconnectAttempts=0,delete this.disconnectedAt,Kt.log("ConnectionMonitor recorded connect")}recordDisconnect(){this.disconnectedAt=Qt(),Kt.log("ConnectionMonitor recorded disconnect")}startPolling(){this.stopPolling(),this.poll()}stopPolling(){clearTimeout(this.pollTimeout)}poll(){this.pollTimeout=setTimeout((()=>{this.reconnectIfStale(),this.poll()}),this.getPollInterval())}getPollInterval(){const{staleThreshold:e,reconnectionBackoffRate:t}=this.constructor;return 1e3*e*Math.pow(1+t,Math.min(this.reconnectAttempts,10))*(1+(0===this.reconnectAttempts?1:t)*Math.random())}reconnectIfStale(){this.connectionIsStale()&&(Kt.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${Yt(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?Kt.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${Yt(this.disconnectedAt)} s`):(Kt.log("ConnectionMonitor reopening"),this.connection.reopen()))}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return Yt(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&Yt(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){"visible"===document.visibilityState&&setTimeout((()=>{!this.connectionIsStale()&&this.connection.isOpen()||(Kt.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen())}),200)}}Zt.staleThreshold=6,Zt.reconnectionBackoffRate=.15;var es=Zt,ts={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]};const{message_types:ss,protocols:rs}=ts,is=rs.slice(0,rs.length-1),ns=[].indexOf;class os{constructor(e){this.open=this.open.bind(this),this.consumer=e,this.subscriptions=this.consumer.subscriptions,this.monitor=new es(this),this.disconnected=!0}send(e){return!!this.isOpen()&&(this.webSocket.send(JSON.stringify(e)),!0)}open(){if(this.isActive())return Kt.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{const e=[...rs,...this.consumer.subprotocols||[]];return Kt.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${e}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new Xt.WebSocket(this.consumer.url,e),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:e}={allowReconnect:!0}){if(e||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(Kt.log(`Reopening WebSocket, current state is ${this.getState()}`),!this.isActive())return this.open();try{return this.close()}catch(e){Kt.log("Failed to reopen WebSocket",e)}finally{Kt.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay)}}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return ns.call(is,this.getProtocol())>=0}isState(...e){return ns.call(e,this.getState())>=0}getState(){if(this.webSocket)for(let e in Xt.WebSocket)if(Xt.WebSocket[e]===this.webSocket.readyState)return e.toLowerCase();return null}installEventHandlers(){for(let e in this.events){const t=this.events[e].bind(this);this.webSocket[`on${e}`]=t}}uninstallEventHandlers(){for(let e in this.events)this.webSocket[`on${e}`]=function(){}}}os.reopenDelay=500,os.prototype.events={message(e){if(!this.isProtocolSupported())return;const{identifier:t,message:s,reason:r,reconnect:i,type:n}=JSON.parse(e.data);switch(this.monitor.recordMessage(),n){case ss.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case ss.disconnect:return Kt.log(`Disconnecting. Reason: ${r}`),this.close({allowReconnect:i});case ss.ping:return null;case ss.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case ss.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",s)}},open(){if(Kt.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return Kt.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(e){if(Kt.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){Kt.log("WebSocket onerror event")}};var as=os;class cs{constructor(e,t={},s){this.consumer=e,this.identifier=JSON.stringify(t),function(e,t){if(null!=t)for(let s in t){const r=t[s];e[s]=r}}(this,s)}perform(e,t={}){return t.action=e,this.send(t)}send(e){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(e)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}}var ls=class{constructor(e){this.subscriptions=e,this.pendingSubscriptions=[]}guarantee(e){-1==this.pendingSubscriptions.indexOf(e)?(Kt.log(`SubscriptionGuarantor guaranteeing ${e.identifier}`),this.pendingSubscriptions.push(e)):Kt.log(`SubscriptionGuarantor already guaranteeing ${e.identifier}`),this.startGuaranteeing()}forget(e){Kt.log(`SubscriptionGuarantor forgetting ${e.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter((t=>t!==e))}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing()}stopGuaranteeing(){clearTimeout(this.retryTimeout)}retrySubscribing(){this.retryTimeout=setTimeout((()=>{this.subscriptions&&"function"==typeof this.subscriptions.subscribe&&this.pendingSubscriptions.map((e=>{Kt.log(`SubscriptionGuarantor resubscribing ${e.identifier}`),this.subscriptions.subscribe(e)}))}),500)}};class hs{constructor(e){this.consumer=e,this.guarantor=new ls(this),this.subscriptions=[]}create(e,t){const s="object"==typeof e?e:{channel:e},r=new cs(this.consumer,s,t);return this.add(r)}add(e){return this.subscriptions.push(e),this.consumer.ensureActiveConnection(),this.notify(e,"initialized"),this.subscribe(e),e}remove(e){return this.forget(e),this.findAll(e.identifier).length||this.sendCommand(e,"unsubscribe"),e}reject(e){return this.findAll(e).map((e=>(this.forget(e),this.notify(e,"rejected"),e)))}forget(e){return this.guarantor.forget(e),this.subscriptions=this.subscriptions.filter((t=>t!==e)),e}findAll(e){return this.subscriptions.filter((t=>t.identifier===e))}reload(){return this.subscriptions.map((e=>this.subscribe(e)))}notifyAll(e,...t){return this.subscriptions.map((s=>this.notify(s,e,...t)))}notify(e,t,...s){let r;return r="string"==typeof e?this.findAll(e):[e],r.map((e=>"function"==typeof e[t]?e[t](...s):void 0))}subscribe(e){this.sendCommand(e,"subscribe")&&this.guarantor.guarantee(e)}confirmSubscription(e){Kt.log(`Subscription confirmed ${e}`),this.findAll(e).map((e=>this.guarantor.forget(e)))}sendCommand(e,t){const{identifier:s}=e;return this.consumer.send({command:t,identifier:s})}}class ds{constructor(e){this._url=e,this.subscriptions=new hs(this),this.connection=new as(this),this.subprotocols=[]}get url(){return us(this._url)}send(e){return this.connection.send(e)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(e){this.subprotocols=[...this.subprotocols,e]}}function us(e){if("function"==typeof e&&(e=e()),e&&!/^wss?:/i.test(e)){const t=document.createElement("a");return t.href=e,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}return e}function ms(e){const t=document.head.querySelector(`meta[name='action-cable-${e}']`);if(t)return t.getAttribute("content")}var ps=Object.freeze({__proto__:null,Connection:as,ConnectionMonitor:es,Consumer:ds,INTERNAL:ts,Subscription:cs,Subscriptions:hs,SubscriptionGuarantor:ls,adapters:Xt,createWebSocketURL:us,logger:Kt,createConsumer:function(e=ms("url")||ts.default_mount_path){return new ds(e)},getConfig:ms});export{Vt as Turbo,zt as cable};
|
29
29
|
//# sourceMappingURL=turbo.min.js.map
|