subfork 0.1.1 → 0.2.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 +40 -25
- package/dist/badge.min.js +15 -0
- package/dist/subfork.min.js +2 -1
- package/dist/subfork.min.js.map +1 -0
- package/dist/subfork.mjs +2566 -0
- package/dist/subfork.mjs.map +1 -0
- package/package.json +25 -7
- package/dist/subfork.js +0 -442
- package/subfork.js +0 -442
package/README.md
CHANGED
|
@@ -5,51 +5,66 @@ Javascript client library used to connect to [Subfork](https://subfork.com) site
|
|
|
5
5
|
Usage:
|
|
6
6
|
|
|
7
7
|
```html
|
|
8
|
-
<script src="https://cdn.jsdelivr.net/npm/subfork/dist/subfork.min.js"></script>
|
|
8
|
+
<script src="https://cdn.jsdelivr.net/npm/subfork@latest/dist/subfork.min.js"></script>
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
To use the latest dev (unstable) release:
|
|
12
|
+
|
|
13
|
+
```html
|
|
14
|
+
<script src="https://code.fork.io/subfork.min.js"></script>
|
|
9
15
|
```
|
|
10
16
|
|
|
11
17
|
Instantiate [Subfork](https://subfork.com) client:
|
|
12
18
|
|
|
13
19
|
```javascript
|
|
14
|
-
const
|
|
20
|
+
const sf = new Subfork();
|
|
15
21
|
```
|
|
16
22
|
|
|
17
|
-
|
|
23
|
+
Subscribe to task events (requires user to be authenticated):
|
|
18
24
|
|
|
19
25
|
```javascript
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
on: {
|
|
23
|
-
"message": function(msg) {
|
|
24
|
-
console.log(msg);
|
|
25
|
-
},
|
|
26
|
-
}
|
|
26
|
+
sf.task("test").on("done", (e) => {
|
|
27
|
+
console.log("done:", e);
|
|
27
28
|
});
|
|
28
29
|
```
|
|
29
30
|
|
|
30
|
-
|
|
31
|
+
Create a test task with some data:
|
|
31
32
|
|
|
32
33
|
```javascript
|
|
33
|
-
|
|
34
|
-
console.log(
|
|
34
|
+
sf.task("test").create({ t: 2 }).then((resp) => {
|
|
35
|
+
console.log("task created:", resp);
|
|
35
36
|
});
|
|
36
37
|
```
|
|
37
38
|
|
|
38
|
-
|
|
39
|
+
## badge.js
|
|
39
40
|
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
Used for displaying [Subfork](https://subfork.com) attribution badge on sites.
|
|
42
|
+
|
|
43
|
+
Usage:
|
|
44
|
+
|
|
45
|
+
```html
|
|
46
|
+
<script src="https://cdn.jsdelivr.net/npm/subfork@latest/dist/badge.min.js"></script>
|
|
42
47
|
```
|
|
43
48
|
|
|
44
|
-
|
|
49
|
+
## Development
|
|
45
50
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
51
|
+
For testing updates to `subfork.js`, use the vite dev server:
|
|
52
|
+
|
|
53
|
+
Dependencies:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
$ npm i socket.io-client
|
|
57
|
+
$ npm i -D vite typescript
|
|
52
58
|
```
|
|
53
59
|
|
|
54
|
-
|
|
55
|
-
|
|
60
|
+
Building the targets:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
$ npm run build
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Running vite dev server:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
$ npm run dev
|
|
70
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
(function(){"use strict";(function(){function o(){const e=document.createElement("div");e.id="subfork-badge",e.className="attribution-badge";const t=document.createElement("img");t.src="https://subfork.com/static/logo.png",t.title="Built with Subfork",t.alt="Subfork",t.className="attribution-image",t.addEventListener("click",()=>{window.open("https://subfork.com","_blank")}),e.appendChild(t),document.body.appendChild(e);const n=document.createElement("style");n.textContent=`
|
|
2
|
+
.attribution-badge {
|
|
3
|
+
position: fixed;
|
|
4
|
+
bottom: 10px;
|
|
5
|
+
right: 10px;
|
|
6
|
+
background-color: rgba(0.2, 0.2, 0.25, 0.25);
|
|
7
|
+
padding: 5px 10px 2px 10px;
|
|
8
|
+
border-radius: 12px;
|
|
9
|
+
z-index: 1000;
|
|
10
|
+
}
|
|
11
|
+
.attribution-image {
|
|
12
|
+
width: 80px;
|
|
13
|
+
cursor: pointer;
|
|
14
|
+
}
|
|
15
|
+
`,document.head.appendChild(n)}document.addEventListener("DOMContentLoaded",o)})()})();
|
package/dist/subfork.min.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
const version="0.1.1",api_version="api",hostname=window.location.hostname,port=window.location.port,protocol=window.location.protocol,socket_script="https://code.subfork.com/socket.io.min.js",wait_time=100;var message,server,socket,socket_loaded=!1;async function sha256(t){const e=new TextEncoder("utf-8").encode(t),s=await window.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s)).map((t=>("00"+t.toString(16)).slice(-2))).join("")}function load_socket_library(t,e){if(socket_loaded)e(t);else{var s=document.createElement("script");s.src=socket_script,document.head.appendChild(s),s.onload=function(){socket_loaded=!0,e(t)}}}function wait_for(t,e){t()?e():window.setTimeout(wait_for.bind(null,t,e),100)}function build_url(t){return"/api/"+t}function is_local(){return!("http:"!==protocol||"localhost"!==hostname&&"0.0.0.0"!==hostname&&"127.0.0.1"!==hostname||"8000"!==port&&"8080"!==port)}function post_request(t,e={},s=null,o=!0){$.ajax({type:"POST",contentType:"application/json; charset=utf-8",url:t,async:o,data:JSON.stringify(e),success:function(t){s?s(t):console.debug("no callback")},dataType:"json"})}class Datatype{constructor(t){this.name=t}create(t,e=null){let s={collection:this.name,data:t,version:"0.1.1"};return post_request(build_url("data/create"),t=s,(function(t){e&&e(t)})),!1}delete(t,e=null){let s={collection:this.name,params:t,version:"0.1.1"};return post_request(build_url("data/delete"),s,(function(t){e&&e(t)})),!1}find(t,e=null,s=!1,o=!0){let a={collection:this.name,expand:s,params:t,version:"0.1.1"};return post_request(build_url("data/get"),a,(function(t){e&&e(t)}),o),!1}update(t,e,s=null){let o={collection:this.name,id:t,data:e,version:"0.1.1"};return post_request(build_url("data/update"),e=o,(function(t){s&&s(t)})),!1}}class SubforkEvent{constructor(t,e){this.name=t,this.type=e.type,this.message=e.message,this.event_data=e}data(){if("data"==this.type)return new Datatype(this.name)}task(){if("task"==this.type){let t=new SubforkTaskQueue(this.event_data.queue);return new SubforkTask(t,this.event_data.task)}}user(){if("user"==this.type)return new SubforkUser(queue,this.event_data.task)}}class SubforkTask{constructor(t,e){this.queue=t,this.data=e}get_error(){return this.data.error}get_results(){try{return JSON.parse(this.data.results)}catch{return this.data.results}}on(t,e){return this.queue.on(t,e)}}class SubforkTaskQueue{constructor(t,e){this.conn=t,this.name=e}create(t){var e=new SubforkTask(this,t);if(this.enqueue(e))return e}enqueue(t){let e={queue:this.name,data:t.data,version:"0.1.1"},s=!1;return post_request(build_url("task/create"),e,(function(t){t.success&&(s=!0)})),s}get(t){let e={queue:this.name,taskid:t,version:"0.1.1"};var s;return post_request(build_url("task/get"),e,(function(t){t.success?s=new SubforkTask(this,t.data):console.error(t.error)}),async=!1),s}on(t,e){let s=this.conn.session.sessionid+":task:"+this.name+":"+t;return socket.on(s,(function(s,o){let a=new SubforkEvent(t,s);e(a)})),!0}}class SubforkUser{constructor(t){this.data=t}}class SubforkCache{constructor(t){this.parent=t,this._cache={}}add(t,e,s){t in this._cache||(this._cache[t]={}),this._cache[t][e]=s}clear(){Object.keys(this._cache).forEach((t=>{delete this._cache[t]}))}del(t,e){t in this._cache&&e in this._cache[t]&&delete this._cache[t][e]}get(t,e){if(t in this._cache&&e in this._cache[t])return this._cache[t][e]}update(t,e){t in this._cache||(this._cache[t]={}),Object.assign(this._cache[t],e)}}class Subfork{constructor(t={}){this.cache=new SubforkCache(this),this.session={},this.set_config(t),this.connect()}set_config(t){this.config=t,this.config.host=this.config.host??window.location.hostname,this.config.port=this.config.port??window.location.port}connect(){this.session=this.get_session_data(),console.debug("sessionid",this.session.sessionid),load_socket_library(this.config.host,(function(t){socket=io("https://events.fork.io"),console.debug("connected to event server")}))}get_session_data(){let t={source:this.config.host,version:"api"},e={};return post_request(build_url("get_session_data"),t,(function(t){t.success&&t.data?e=t.data:console.error(t.error)}),!1),e}data(t){if(!this.cache.get("data",t)){var e=new Datatype(t);this.cache.add("data",t,e)}return this.cache.get("data",t)}is_connected(){return socket_loaded&&socket.connected}ready(t){wait_for((()=>window.socket),(()=>t()))}task(t){if(!this.cache.get("task",t)){var e=new SubforkTaskQueue(this,t);this.cache.add("task",t,e)}return this.cache.get("task",t)}user(t){if(!this.cache.get("user",t)){let s={username:t,version:"0.1.1"};var e;post_request(build_url("user/get"),s,(function(t){t.success&&(e=new SubforkUser(t.data))}),!1),this.cache.add("user",t,e)}return this.cache.get("user",t)}}
|
|
1
|
+
var Subfork=function(){"use strict";const p=Object.create(null);p.open="0",p.close="1",p.ping="2",p.pong="3",p.message="4",p.upgrade="5",p.noop="6";const S=Object.create(null);Object.keys(p).forEach(n=>{S[p[n]]=n});const P={type:"error",data:"parser error"},Q=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",j=typeof ArrayBuffer=="function",G=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,D=({type:n,data:e},t,s)=>Q&&e instanceof Blob?t?s(e):Z(e,s):j&&(e instanceof ArrayBuffer||G(e))?t?s(e):Z(new Blob([e]),s):s(p[n]+(e||"")),Z=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function ee(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let U;function _e(n,e){if(Q&&n.data instanceof Blob)return n.data.arrayBuffer().then(ee).then(e);if(j&&(n.data instanceof ArrayBuffer||G(n.data)))return e(ee(n.data));D(n,!1,t=>{U||(U=new TextEncoder),e(U.encode(t))})}const te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<te.length;n++)k[te.charCodeAt(n)]=n;const we=n=>{let e=n.length*.75,t=n.length,s,i=0,r,o,a,h;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const m=new ArrayBuffer(e),l=new Uint8Array(m);for(s=0;s<t;s+=4)r=k[n.charCodeAt(s)],o=k[n.charCodeAt(s+1)],a=k[n.charCodeAt(s+2)],h=k[n.charCodeAt(s+3)],l[i++]=r<<2|o>>4,l[i++]=(o&15)<<4|a>>2,l[i++]=(a&3)<<6|h&63;return m},be=typeof ArrayBuffer=="function",I=(n,e)=>{if(typeof n!="string")return{type:"message",data:se(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:ve(n.substring(1),e)}:S[t]?n.length>1?{type:S[t],data:n.substring(1)}:{type:S[t]}:P},ve=(n,e)=>{if(be){const t=we(n);return se(t,e)}else return{base64:!0,data:n}},se=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},ne="",Ee=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{D(r,!1,a=>{s[o]=a,++i===t&&e(s.join(ne))})})},ke=(n,e)=>{const t=n.split(ne),s=[];for(let i=0;i<t.length;i++){const r=I(t[i],e);if(s.push(r),r.type==="error")break}return s};function Te(){return new TransformStream({transform(n,e){_e(n,t=>{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let F;function O(n){return n.reduce((e,t)=>e+t.length,0)}function R(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)t[i]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),t}function Ae(n,e){F||(F=new TextDecoder);const t=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(s===0){if(O(t)<1)break;const h=R(t,1);r=(h[0]&128)===128,i=h[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(O(t)<2)break;const h=R(t,2);i=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),s=3}else if(s===2){if(O(t)<8)break;const h=R(t,8),m=new DataView(h.buffer,h.byteOffset,h.length),l=m.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(P);break}i=l*Math.pow(2,32)+m.getUint32(4),s=3}else{if(O(t)<i)break;const h=R(t,i);a.enqueue(I(r?h:F.decode(h),e)),s=0}if(i===0||i>n){a.enqueue(P);break}}}})}const ie=4;function u(n){if(n)return Se(n)}function Se(n){for(var e in u.prototype)n[e]=u.prototype[e];return n}u.prototype.on=u.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this},u.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this},u.prototype.off=u.prototype.removeListener=u.prototype.removeAllListeners=u.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+n],this},u.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,i=t.length;s<i;++s)t[s].apply(this,e)}return this},u.prototype.emitReserved=u.prototype.emit,u.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]},u.prototype.hasListeners=function(n){return!!this.listeners(n).length};const C=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),f=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Oe="arraybuffer";function mt(){}function re(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Re=f.setTimeout,Ce=f.clearTimeout;function B(n,e){e.useNativeTimers?(n.setTimeoutFn=Re.bind(f),n.clearTimeoutFn=Ce.bind(f)):(n.setTimeoutFn=f.setTimeout.bind(f),n.clearTimeoutFn=f.clearTimeout.bind(f))}const Be=1.33;function Ne(n){return typeof n=="string"?xe(n):Math.ceil((n.byteLength||n.size)*Be)}function xe(n){let e=0,t=0;for(let s=0,i=n.length;s<i;s++)e=n.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function oe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Le(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function qe(n){let e={},t=n.split("&");for(let s=0,i=t.length;s<i;s++){let r=t[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class Pe extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class V extends u{constructor(e){super(),this.writable=!1,B(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new Pe(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=I(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Le(e);return t.length?"?"+t:""}}class De extends V{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};ke(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Ee(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=oe()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let ae=!1;try{ae=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Ue=ae;function Ie(){}class Fe extends De{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class y extends u{constructor(e,t,s){super(),this.createRequest=e,B(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=re(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=y.requestsCount++,y.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Ie,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete y.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(y.requestsCount=0,y.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ce);else if(typeof addEventListener=="function"){const n="onpagehide"in f?"pagehide":"unload";addEventListener(n,ce,!1)}}function ce(){for(let n in y.requests)y.requests.hasOwnProperty(n)&&y.requests[n].abort()}const Ve=function(){const n=he({xdomain:!1});return n&&n.responseType!==null}();class Me extends Fe{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Ve&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new y(he,this.uri(),e)}}function he(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Ue))return new XMLHttpRequest}catch{}if(!e)try{return new f[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ue=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class $e extends V{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=ue?{}:re(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;D(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&C(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=oe()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const M=f.WebSocket||f.MozWebSocket;class He extends $e{createSocket(e,t,s){return ue?new M(e,t,s):t?new M(e,t):new M(e)}doWrite(e,t){this.ws.send(t)}}class We extends V{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Ae(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=Te();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:a,value:h})=>{a||(this.onPacket(h),r())}).catch(a=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&C(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Ke={websocket:He,webtransport:We,polling:Me},Ye=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ze=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function $(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=Ye.exec(n||""),r={},o=14;for(;o--;)r[ze[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Je(r,r.path),r.queryKey=Xe(r,r.query),r}function Je(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Xe(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const H=typeof addEventListener=="function"&&typeof removeEventListener=="function",N=[];H&&addEventListener("offline",()=>{N.forEach(n=>n())},!1);class _ extends u{constructor(e,t){if(super(),this.binaryType=Oe,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=$(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=$(t.host).host);B(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=qe(this.opts.query)),H&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},N.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ie,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&_.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",_.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+=Ne(i)),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,C(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(_.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),H&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=N.indexOf(this._offlineEventListener);s!==-1&&N.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}_.protocol=ie;class Qe extends _{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;_.priorWebsocketSuccess=!1;const i=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",b=>{if(!s)if(b.type==="pong"&&b.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;_.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const A=new Error("probe error");A.transport=t.name,this.emitReserved("upgradeError",A)}}))};function r(){s||(s=!0,l(),t.close(),t=null)}const o=b=>{const A=new Error("probe error: "+b);A.transport=t.name,r(),this.emitReserved("upgradeError",A)};function a(){o("transport closed")}function h(){o("socket closed")}function m(b){t&&b.name!==t.name&&r()}const l=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",a),this.off("close",h),this.off("upgrading",m)};t.once("open",i),t.once("error",o),t.once("close",a),this.once("close",h),this.once("upgrading",m),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let je=class extends Qe{constructor(e,t={}){const s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>Ke[i]).filter(i=>!!i)),super(e,s)}};function Ge(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=$(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const Ze=typeof ArrayBuffer=="function",et=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,fe=Object.prototype.toString,tt=typeof Blob=="function"||typeof Blob<"u"&&fe.call(Blob)==="[object BlobConstructor]",st=typeof File=="function"||typeof File<"u"&&fe.call(File)==="[object FileConstructor]";function W(n){return Ze&&(n instanceof ArrayBuffer||et(n))||tt&&n instanceof Blob||st&&n instanceof File}function x(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(x(n[t]))return!0;return!1}if(W(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return x(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&x(n[t]))return!0;return!1}function nt(n){const e=[],t=n.data,s=n;return s.data=K(t,e),s.attachments=e.length,{packet:s,buffers:e}}function K(n,e){if(!n)return n;if(W(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=K(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=K(n[s],e));return t}return n}function it(n,e){return n.data=Y(n.data,e),delete n.attachments,n}function Y(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=Y(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Y(n[t],e));return n}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ot=5;var c;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(c||(c={}));class at{constructor(e){this.replacer=e}encode(e){return(e.type===c.EVENT||e.type===c.ACK)&&x(e)?this.encodeAsBinary({type:e.type===c.EVENT?c.BINARY_EVENT:c.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===c.BINARY_EVENT||e.type===c.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=nt(e),s=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(s),i}}function le(n){return Object.prototype.toString.call(n)==="[object Object]"}class z extends u{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===c.BINARY_EVENT;s||t.type===c.BINARY_ACK?(t.type=s?c.EVENT:c.ACK,this.reconstructor=new ct(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(W(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(c[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===c.BINARY_EVENT||s.type===c.BINARY_ACK){const r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(r,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(z.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case c.CONNECT:return le(t);case c.DISCONNECT:return t===void 0;case c.CONNECT_ERROR:return typeof t=="string"||le(t);case c.EVENT:case c.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&rt.indexOf(t[0])===-1);case c.ACK:case c.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=it(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Object.freeze(Object.defineProperty({__proto__:null,Decoder:z,Encoder:at,get PacketType(){return c},protocol:ot},Symbol.toStringTag,{value:"Module"}));function d(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const ut=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class de extends u{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[d(e,"open",this.onopen.bind(this)),d(e,"packet",this.onpacket.bind(this)),d(e,"error",this.onerror.bind(this)),d(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,i,r;if(ut.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:c.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const l=this.ids++,b=t.pop();this._registerAckCallback(l,b),o.id=l}const a=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,h=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!a||(h?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},i),o=(...a)=>{this.io.clearTimeoutFn(r),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,a)=>o?i(o):s(a);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>s!==this._queue[0]?void 0:(i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:c.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case c.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case c.EVENT:case c.BINARY_EVENT:this.onevent(e);break;case c.ACK:case c.BINARY_ACK:this.onack(e);break;case c.DISCONNECT:this.ondisconnect();break;case c.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:c.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:c.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function E(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}E.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=Math.floor(e*10)&1?n+t:n-t}return Math.min(n,this.max)|0},E.prototype.reset=function(){this.attempts=0},E.prototype.setMin=function(n){this.ms=n},E.prototype.setMax=function(n){this.max=n},E.prototype.setJitter=function(n){this.jitter=n};class J extends u{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,B(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new E({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||ht;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new je(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=d(t,"open",function(){s.onopen(),e&&e()}),r=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=d(t,"error",r);if(this._timeout!==!1){const a=this._timeout,h=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},a);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(d(e,"ping",this.onping.bind(this)),d(e,"data",this.ondata.bind(this)),d(e,"error",this.onerror.bind(this)),d(e,"close",this.onclose.bind(this)),d(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){C(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new de(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const T={};function L(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=Ge(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=T[i]&&r in T[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let h;return a?h=new J(s,e):(T[i]||(T[i]=new J(s,e)),h=T[i]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(L,{Manager:J,Socket:de,io:L,connect:L});const v="0.2.0",pe="api",ft="https://events.subfork.com",lt=100;var g;function ye(n,e){n()?e():window.setTimeout(ye.bind(null,n,e),lt)}function dt(n,e){const t=(e||window.location.origin).replace(/\/+$/,""),s=String(pe).replace(/^\/+|\/+$/g,""),i=String(n).replace(/^\/+/,"");return`${t}/${s}/${i}`}function w(n,e={},t=null){return fetch(n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json; charset=utf-8",Accept:"application/json"},body:JSON.stringify(e??{})}).then(async s=>{let i;try{i=await s.json()}catch{i={success:!1,error:"bad json",status:s.status}}return!s.ok&&i&&typeof i.success>"u"&&(i.success=!1,i.status=s.status),t&&t(i),i}).catch(s=>{const i={success:!1,error:String(s)};return t&&t(i),i})}class ge{constructor(e,t){this.name=e,this.conn=t}create(e,t=null){let s={collection:this.name,data:e,version:v},i=this.conn.build_url("data/create");return w(i,s,t)}delete(e,t=null){let s={collection:this.name,params:e,version:v},i=this.conn.build_url("data/delete");return w(i,s,t)}find(e,t=null,s=!1){let i={collection:this.name,expand:s,params:e,version:v},r=this.conn.build_url("data/get");return w(r,i,t)}update(e,t,s=null){let i={collection:this.name,id:e,data:t,version:v},r=this.conn.build_url("data/update");return w(r,i,s)}}class pt{constructor(e,t,s){this.name=e,this.type=t.type,this.message=t.message,this.event_data=t,this.conn=s}data(){if(this.type=="data")return new ge(this.name,this.conn)}task(){if(this.type=="task"){let e=new me(this.conn,this.event_data.queue);return new q(e,this.event_data.task)}}user(){if(this.type=="user")return new X(this.event_data.user)}}class q{constructor(e,t){this.queue=e,this.data=t}get_error(){return this.data.error}get_results(){try{return JSON.parse(this.data.results)}catch{return this.data.results}}on(e,t){return this.queue.on(e,t)}}class me{constructor(e,t){this.conn=e,this.name=t}create(e){var t=new q(this,e);if(this.enqueue(t))return t}enqueue(e,t=null){let s={queue:this.name,data:e.data,version:v},i=this.conn.build_url("task/create");return w(i,s,t)}get(e,t=null){let s={queue:this.name,taskid:e,version:v},i=this.conn.build_url("task/get");return w(i,s,r=>{if(!r||!r.success){t&&t(null,r);return}const o=new q(this,r.data);t&&t(o,r)}).then(r=>r&&r.success?new q(this,r.data):null)}on(e,t){if(!g)return console.error("Socket is not initialized"),!1;const s=`task:${this.name}:${e}`;return console.debug("listening for event",s),g.on(s,i=>{const r=new pt(e,i,this.conn);t(r)}),!0}}class X{constructor(e){this.data=e}get(e){return this.data[e]}}class yt{constructor(e){this.parent=e,this._cache={}}add(e,t,s){e in this._cache||(this._cache[e]={}),this._cache[e][t]=s}clear(){Object.keys(this._cache).forEach(e=>{delete this._cache[e]})}del(e,t){e in this._cache&&t in this._cache[e]&&delete this._cache[e][t]}get(e,t){if(e in this._cache&&t in this._cache[e])return this._cache[e][t]}update(e,t){e in this._cache||(this._cache[e]={}),Object.assign(this._cache[e],t)}}class gt{constructor(e={}){this.cache=new yt(this),this.session={},this.set_config(e),this.connect()}set_config(e){this.config=e,this.config.host=this.config.host??window.location.hostname,this.config.port=this.config.port??window.location.port,this.config.apiBase=this.config.apiBase??window.location.origin,this.config.eventsUrl=this.config.eventsUrl??ft}build_url(e){return dt(e,this.config.apiBase)}async connect(){this.session=await this.get_session_data(),console.debug("session",this.session);const e=this.session&&this.session.token;return e?(g=L(this.config.eventsUrl,{transports:["websocket"],path:"/socket.io",auth:{token:e},withCredentials:!0}),g.on("connect",()=>console.debug("WS connected",g.id)),g.on("connect_error",t=>console.error("WS connect_error:",t&&t.message||t)),!0):(console.warn("No token was found in session; skipping WS connect"),!1)}async get_session_data(e=null){let t={source:this.config.host,version:pe},s=this.build_url("session");return w(s,t,i=>{i&&i.success&&i.data?e&&e(i.data,i):(console.error(i&&i.error),e&&e(null,i))}).then(i=>i&&i.success&&i.data?i.data:{})}data(e){return this.cache.get("data",e)||this.cache.add("data",e,new ge(e,this)),this.cache.get("data",e)}is_connected(){return!!(g&&g.connected)}ready(e){ye(()=>g&&g.connected,()=>e())}task(e){if(!this.cache.get("task",e)){var t=new me(this,e);this.cache.add("task",e,t)}return this.cache.get("task",e)}user(e,t=null){const s=this.cache.get("user",e);if(s)return t&&t(s,{success:!0,data:s.data}),Promise.resolve(s);let i={username:e,version:v},r=this.build_url("user/get");return w(r,i,o=>{if(o&&o.success){const a=new X(o.data);this.cache.add("user",e,a),t&&t(a,o)}else t&&t(null,o)}).then(o=>{if(o&&o.success){const a=new X(o.data);return this.cache.add("user",e,a),a}return null})}}return gt}();
|
|
2
|
+
//# sourceMappingURL=subfork.min.js.map
|