@thatopen/services 0.28.2 → 0.29.1

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/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var On=Object.create;var Ot=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty;var bs=n=>{throw TypeError(n)};var $n=(n,e,t)=>e in n?Ot(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var xn=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of An(e))!Cn.call(n,r)&&r!==t&&Ot(n,r,{get:()=>e[r],enumerable:!(s=kn(e,r))||s.enumerable});return n};var ot=(n,e,t)=>(t=n!=null?On(Rn(n)):{},xn(e||!n||!n.__esModule?Ot(t,"default",{value:n,enumerable:!0}):t,n));var B=(n,e,t)=>$n(n,typeof e!="symbol"?e+"":e,t),kt=(n,e,t)=>e.has(n)||bs("Cannot "+t);var u=(n,e,t)=>(kt(n,e,"read from private field"),t?t.call(n):e.get(n)),S=(n,e,t)=>e.has(n)?bs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),R=(n,e,t,s)=>(kt(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),h=(n,e,t)=>(kt(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=Object.create(null);ne.open="0";ne.close="1";ne.ping="2";ne.pong="3";ne.message="4";ne.upgrade="5";ne.noop="6";const ut=Object.create(null);Object.keys(ne).forEach(n=>{ut[ne[n]]=n});const Bt={type:"error",data:"parser error"},Ds=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",js=typeof ArrayBuffer=="function",qs=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,os=({type:n,data:e},t,s)=>Ds&&e instanceof Blob?t?s(e):vs(e,s):js&&(e instanceof ArrayBuffer||qs(e))?t?s(e):vs(new Blob([e]),s):s(ne[n]+(e||"")),vs=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function Es(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let At;function Nn(n,e){if(Ds&&n.data instanceof Blob)return n.data.arrayBuffer().then(Es).then(e);if(js&&(n.data instanceof ArrayBuffer||qs(n.data)))return e(Es(n.data));os(n,!1,t=>{At||(At=new TextEncoder),e(At.encode(t))})}const Ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Je=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<Ts.length;n++)Je[Ts.charCodeAt(n)]=n;const Pn=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,a,l;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const d=new ArrayBuffer(e),c=new Uint8Array(d);for(s=0;s<t;s+=4)i=Je[n.charCodeAt(s)],o=Je[n.charCodeAt(s+1)],a=Je[n.charCodeAt(s+2)],l=Je[n.charCodeAt(s+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Bn=typeof ArrayBuffer=="function",as=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ms(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Fn(n.substring(1),e)}:ut[t]?n.length>1?{type:ut[t],data:n.substring(1)}:{type:ut[t]}:Bt},Fn=(n,e)=>{if(Bn){const t=Pn(n);return Ms(t,e)}else return{base64:!0,data:n}},Ms=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Us="",Ln=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{os(i,!1,a=>{s[o]=a,++r===t&&e(s.join(Us))})})},Dn=(n,e)=>{const t=n.split(Us),s=[];for(let r=0;r<t.length;r++){const i=as(t[r],e);if(s.push(i),i.type==="error")break}return s};function jn(){return new TransformStream({transform(n,e){Nn(n,t=>{const s=t.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let Rt;function at(n){return n.reduce((e,t)=>e+t.length,0)}function ct(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let r=0;r<e;r++)t[r]=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 qn(n,e){Rt||(Rt=new TextDecoder);const t=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(s===0){if(at(t)<1)break;const l=ct(t,1);i=(l[0]&128)===128,r=l[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(at(t)<2)break;const l=ct(t,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),s=3}else if(s===2){if(at(t)<8)break;const l=ct(t,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Bt);break}r=c*Math.pow(2,32)+d.getUint32(4),s=3}else{if(at(t)<r)break;const l=ct(t,r);a.enqueue(as(i?l:Rt.decode(l),e)),s=0}if(r===0||r>n){a.enqueue(Bt);break}}}})}const Vs=4;function C(n){if(n)return Mn(n)}function Mn(n){for(var e in C.prototype)n[e]=C.prototype[e];return n}C.prototype.on=C.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};C.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};C.prototype.off=C.prototype.removeListener=C.prototype.removeAllListeners=C.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,r=0;r<t.length;r++)if(s=t[r],s===e||s.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+n],this};C.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,r=t.length;s<r;++s)t[s].apply(this,e)}return this};C.prototype.emitReserved=C.prototype.emit;C.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};C.prototype.hasListeners=function(n){return!!this.listeners(n).length};const _t=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),H=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Un="arraybuffer";function Hs(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Vn=H.setTimeout,Hn=H.clearTimeout;function It(n,e){e.useNativeTimers?(n.setTimeoutFn=Vn.bind(H),n.clearTimeoutFn=Hn.bind(H)):(n.setTimeoutFn=H.setTimeout.bind(H),n.clearTimeoutFn=H.clearTimeout.bind(H))}const Gn=1.33;function Jn(n){return typeof n=="string"?Wn(n):Math.ceil((n.byteLength||n.size)*Gn)}function Wn(n){let e=0,t=0;for(let s=0,r=n.length;s<r;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 Gs(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Yn(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function zn(n){let e={},t=n.split("&");for(let s=0,r=t.length;s<r;s++){let i=t[s].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class Kn extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class cs extends C{constructor(e){super(),this.writable=!1,It(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 Kn(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=as(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&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Yn(e);return t.length?"?"+t:""}}class Xn extends cs{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)};Dn(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,Ln(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]=Gs()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Js=!1;try{Js=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Qn=Js;function Zn(){}class er extends Xn{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",(r,i)=>{this.onError("xhr post error",r,i)})}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 se extends C{constructor(e,t,s){super(),this.createRequest=e,It(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=Hs(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 r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}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 r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.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(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=se.requestsCount++,se.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=Zn,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete se.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()}}se.requestsCount=0;se.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",_s);else if(typeof addEventListener=="function"){const n="onpagehide"in H?"pagehide":"unload";addEventListener(n,_s,!1)}}function _s(){for(let n in se.requests)se.requests.hasOwnProperty(n)&&se.requests[n].abort()}const tr=function(){const n=Ws({xdomain:!1});return n&&n.responseType!==null}();class sr extends er{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=tr&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new se(Ws,this.uri(),e)}}function Ws(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Qn))return new XMLHttpRequest}catch{}if(!e)try{return new H[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ys=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class nr extends cs{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ys?{}:Hs(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(r){return this.emitReserved("error",r)}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],r=t===e.length-1;os(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&_t(()=>{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]=Gs()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Ct=H.WebSocket||H.MozWebSocket;class rr extends nr{createSocket(e,t,s){return Ys?new Ct(e,t,s):t?new Ct(e,t):new Ct(e)}doWrite(e,t){this.ws.send(t)}}class ir extends cs{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=qn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=jn();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:a,value:l})=>{a||(this.onPacket(l),i())}).catch(a=>{})};i();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],r=t===e.length-1;this._writer.write(s).then(()=>{r&&_t(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const or={websocket:rr,webtransport:ir,polling:sr},ar=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,cr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ft(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 r=ar.exec(n||""),i={},o=14;for(;o--;)i[cr[o]]=r[o]||"";return t!=-1&&s!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=hr(i,i.path),i.queryKey=lr(i,i.query),i}function hr(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 lr(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const Lt=typeof addEventListener=="function"&&typeof removeEventListener=="function",ft=[];Lt&&addEventListener("offline",()=>{ft.forEach(n=>n())},!1);class we extends C{constructor(e,t){if(super(),this.binaryType=Un,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=Ft(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=Ft(t.host).host);It(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 r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=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=zn(this.opts.query)),Lt&&(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"})},ft.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=Vs,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&&we.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",we.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 r=this.writeBuffer[s].data;if(r&&(t+=Jn(r)),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,_t(()=>{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,r){if(typeof t=="function"&&(r=t,t=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:e,data:t,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),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(we.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(),Lt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=ft.indexOf(this._offlineEventListener);s!==-1&&ft.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}we.protocol=Vs;class dr extends we{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;we.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!s)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;we.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const T=new Error("probe error");T.transport=t.name,this.emitReserved("upgradeError",T)}}))};function i(){s||(s=!0,c(),t.close(),t=null)}const o=m=>{const T=new Error("probe error: "+m);T.transport=t.name,i(),this.emitReserved("upgradeError",T)};function a(){o("transport closed")}function l(){o("socket closed")}function d(m){t&&m.name!==t.name&&i()}const c=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",l),this.once("upgrading",d),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 ur=class extends dr{constructor(e,t={}){const s=typeof e=="object",r=s?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>or[i]).filter(i=>!!i)),super(s?r:e,r)}};function fr(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=Ft(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 i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(t&&t.port===s.port?"":":"+s.port),s}const pr=typeof ArrayBuffer=="function",mr=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,zs=Object.prototype.toString,yr=typeof Blob=="function"||typeof Blob<"u"&&zs.call(Blob)==="[object BlobConstructor]",gr=typeof File=="function"||typeof File<"u"&&zs.call(File)==="[object FileConstructor]";function hs(n){return pr&&(n instanceof ArrayBuffer||mr(n))||yr&&n instanceof Blob||gr&&n instanceof File}function pt(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(pt(n[t]))return!0;return!1}if(hs(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return pt(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&pt(n[t]))return!0;return!1}function wr(n){const e=[],t=n.data,s=n;return s.data=Dt(t,e),s.attachments=e.length,{packet:s,buffers:e}}function Dt(n,e){if(!n)return n;if(hs(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]=Dt(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]=Dt(n[s],e));return t}return n}function br(n,e){return n.data=jt(n.data,e),delete n.attachments,n}function jt(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]=jt(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=jt(n[t],e));return n}const vr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var E;(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"})(E||(E={}));class Er{constructor(e){this.replacer=e}encode(e){return(e.type===E.EVENT||e.type===E.ACK)&&pt(e)?this.encodeAsBinary({type:e.type===E.EVENT?E.BINARY_EVENT:E.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===E.BINARY_EVENT||e.type===E.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=wr(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class ls extends C{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}: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===E.BINARY_EVENT;s||t.type===E.BINARY_ACK?(t.type=s?E.EVENT:E.ACK,this.reconstructor=new Tr(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(hs(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(E[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===E.BINARY_EVENT||s.type===E.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!_r(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=a}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(i,t)}else s.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=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(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(ls.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case E.CONNECT:return Is(t);case E.DISCONNECT:return t===void 0;case E.CONNECT_ERROR:return typeof t=="string"||Is(t);case E.EVENT:case E.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&vr.indexOf(t[0])===-1);case E.ACK:case E.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Tr{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=br(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const _r=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Is(n){return Object.prototype.toString.call(n)==="[object Object]"}const Ir=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ls,Encoder:Er,get PacketType(){return E}},Symbol.toStringTag,{value:"Module"}));function Y(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Sr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ks extends C{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=[Y(e,"open",this.onopen.bind(this)),Y(e,"packet",this.onpacket.bind(this)),Y(e,"error",this.onerror.bind(this)),Y(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,r,i;if(Sr.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:E.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const c=this.ids++,m=t.pop();this._registerAckCallback(c,m),o.id=c}const a=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=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"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,r)=>{const i=(o,a)=>o?r(o):s(a);i.withError=!0,t.push(i),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((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),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:E.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 E.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 E.EVENT:case E.BINARY_EVENT:this.onevent(e);break;case E.ACK:case E.BINARY_ACK:this.onack(e);break;case E.DISCONNECT:this.ondisconnect();break;case E.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(...r){s||(s=!0,t.packet({type:E.ACK,id:e,data:r}))}}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._drainQueue(!0),this.emitReserved("connect")}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:E.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 Le(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}Le.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};Le.prototype.reset=function(){this.attempts=0};Le.prototype.setMin=function(n){this.ms=n};Le.prototype.setMax=function(n){this.max=n};Le.prototype.setJitter=function(n){this.jitter=n};class qt extends C{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,It(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 Le({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||Ir;this.encoder=new r.Encoder,this.decoder=new r.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 ur(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=Y(t,"open",function(){s.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Y(t,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),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(Y(e,"ping",this.onping.bind(this)),Y(e,"data",this.ondata.bind(this)),Y(e,"error",this.onerror.bind(this)),Y(e,"close",this.onclose.bind(this)),Y(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){_t(()=>{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 Ks(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(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):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 Ge={};function Ke(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=fr(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=Ge[r]&&i in Ge[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new qt(s,e):(Ge[r]||(Ge[r]=new qt(s,e)),l=Ge[r]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(Ke,{Manager:qt,Socket:Ks,io:Ke,connect:Ke});const Xe="thatopen/document@1",Mt="document.json",Xs=["pdf","txt","md","json","csv","tsv","frag"],Ss=()=>`v-${Date.now()}`;function ht(n){return String(n._id??n.id??"")}var Oe,Qs,Ut;class ds{constructor(e,t){S(this,Oe);this.client=e,this.projectId=t}async list(){const e=await this.client.listFolders({projectId:this.projectId});return(await Promise.all(e.map(async s=>{const r=ht(s),i=await this.descriptor(r);return i?{folderId:r,descriptor:i}:null}))).filter(s=>s!==null)}async fromFile(e,t){const s=await this.client.getFile(e),r=String(s.name??""),i=Os(r,s.fileExtension),o=(t==null?void 0:t.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,s.folderId?String(s.folderId):void 0,this.projectId),l=ht(a);await this.client.updateFile(e,{parentFolderId:l});const d=[],c=await h(this,Oe,Qs).call(this,s);if(c)try{const A=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:Os(String(A.name??""),A.fileExtension)})}catch{}((t==null?void 0:t.selfView)??Xs.includes(i))&&d.push({fileId:e,format:i});const T={schema:Xe,name:o,native:{fileId:e,format:i},views:d};return await this.setDescriptor(l,T),{folderId:l,descriptor:T}}async descriptor(e){const t=await h(this,Oe,Ut).call(this,e);if(!t)return null;const r=await(await this.client.downloadFile(t.id)).text();if(!r.trim())return null;let i;try{i=JSON.parse(r)}catch{return null}return Or(i)}async view(e,t){const s=await this.descriptor(e);if(!s)return null;for(const r of t){const i=s.views.find(o=>o.format===r);if(i)return i}return null}async addView(e,t){const s=await this.descriptor(e);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.views=[...s.views.filter(r=>r.format!==t.format),t],await this.setDescriptor(e,s)}async setDescriptor(e,t){const s={...t,schema:Xe,views:t.views??[]},r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await h(this,Oe,Ut).call(this,e);if(i){await this.client.updateFile(i.id,{file:r,versionTag:Ss()});return}await this.client.createFile({file:r,name:Mt,versionTag:Ss(),parentFolderId:e,projectId:this.projectId})}}Oe=new WeakSet,Qs=async function(e){const t=[...e.versions??[]].sort((s,r)=>String(r.createdAt??"").localeCompare(String(s.createdAt??"")));for(const s of t)try{const r=await this.client.getFileVersionMetadata(ht(e),s.tag),i=r==null?void 0:r.derivedFileId;if(typeof i=="string"&&i)return i}catch{}},Ut=async function(e){const s=(await this.client.listFiles({folderId:e})).find(r=>String(r.name??"")===Mt);return s?{id:ht(s)}:void 0};function Os(n,e){const t=(e??"").replace(/^\./,"").toLowerCase();if(t)return t;const s=n.lastIndexOf(".");return s>0?n.slice(s+1).toLowerCase():""}function Or(n){if(!n||typeof n!="object")return null;const e=n;if(e.schema!==Xe||typeof e.name!="string")return null;const t=Array.isArray(e.views)?e.views.filter(i=>!!i&&typeof i=="object"&&typeof i.fileId=="string"&&typeof i.format=="string"):[],s=e.native,r=!!s&&typeof s=="object"&&typeof s.fileId=="string"&&typeof s.format=="string";return{schema:Xe,name:e.name,...r?{native:{fileId:s.fileId,format:s.format}}:{},views:t}}class Vt extends Error{constructor(e,t){super(`The document history advanced while this version was being prepared: expected head ${e}, found ${t??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=e,this.actualGuid=t,this.name="StaleHistoryError"}}const ks="bimterop",Ht="revitflow_history.json",Re="revitflow_ops.json",As="revitflow/ops@1",Zs="revitflow_model.frag",en="revitflow_",kr="bimterop-locks-anchor",lt=()=>`v-${Date.now()}`;function tn(n,e){return n.filter(t=>String(t.parentId??"")===e)}function Rs(n){const e=n==null?void 0:n.hiddenFileId;if(typeof e!="string"||!e)throw new Error("The hidden-file upload answered without a hiddenFileId.");return e}function te(n){return String(n._id??n.id??"")}var W,Qe,Gt;class sn{constructor(e,t){S(this,Qe);S(this,W);this.client=e,this.projectId=t}async docs(){const e=await h(this,Qe,Gt).call(this);if(!e)return[];const t=await this.client.listFolders({parentFolderId:e,projectId:this.projectId}),s=[];for(const r of tn(t,e)){const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:te(r)})).map(m=>String(m.name??"")),d=l.find(m=>m===Zs)??l.find(m=>m.endsWith(".frag")&&!m.startsWith(en)),c=l.includes(Ht)||l.includes(Re)||!!d;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:te(r),modelName:d,...c?{}:{empty:!0}})}return s}doc(e,t){return new nn(this.client,this,e,t)}async rootFolderId(e=!1){if(u(this,W))return u(this,W);const t=await h(this,Qe,Gt).call(this);if(t)return t;if(!e)return;const s=await this.client.createFolder(ks,void 0,this.projectId);return R(this,W,te(s)),u(this,W)}}W=new WeakMap,Qe=new WeakSet,Gt=async function(){if(u(this,W))return u(this,W);const t=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===ks&&!s.parentId);return t&&R(this,W,te(t)),u(this,W)};var ae,p,oe,Ce,ee,Jt,We,ue,Wt,mt,Ye,yt,Yt,rn;class nn{constructor(e,t,s,r){S(this,p);S(this,ae);this.client=e,this.project=t,this.source=s,this.docId=r}async timeline(){const e=await h(this,p,mt).call(this);return us((e==null?void 0:e.commits)??[])}async latest(){const e=await this.timeline();return e.length?e[e.length-1]:null}async delta(e){if(!e.deltaId)throw new Error(`Version ${e.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(e.deltaId)).blob()}async model(){const e=await h(this,p,ue).call(this);if(!e)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(e.id)).blob()}async modelParts(e){const t=await this.timeline();if(t.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const s=e==null?void 0:e.at,r=s?t.findIndex(c=>c.guid===s):t.length-1;if(r<0)throw new Error(`No version ${s} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(t[c].full){i=c;break}const o=await h(this,p,ue).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=t[i],l=t.slice(r+1).some(c=>c.full),d=t.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},removedUniqueIds:c.changes.filter(m=>m.type==="delete").map(m=>m.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!l,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:t[r].guid}}async folderId(){return await h(this,p,ee).call(this,!1)}async descriptor(){return await u(this,p,oe).descriptor(await h(this,p,ee).call(this,!1))}async view(e){const t=await h(this,p,ee).call(this,!1),s=await u(this,p,oe).descriptor(t);if(s){for(const i of e){const o=s.views.find(a=>a.format===i);if(o)return o}return null}if(!e.includes("frag"))return null;const r=await h(this,p,ue).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(e){const t=await h(this,p,ee).call(this,!0);if(await u(this,p,oe).descriptor(t)){await u(this,p,oe).addView(t,e);return}const r=await h(this,p,ue).call(this);await u(this,p,oe).setDescriptor(t,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??u(this,p,Ce),views:[e]})}async ensureDescriptor(){const e=await h(this,p,ee).call(this,!1),t=await u(this,p,oe).descriptor(e);if(t)return t;const s=await h(this,p,ue).call(this);if(!s)return null;const r={name:s.name.replace(/\.frag$/,""),views:[{fileId:s.id,format:"frag"}]};return await u(this,p,oe).setDescriptor(e,r),await u(this,p,oe).descriptor(e)}async ownership(){const e=await h(this,p,We).call(this,kr);if(!e)return[];const t=await this.client.getHiddenFilesByParent(e.id),s=await Promise.all(t.map(async o=>{try{const a=te(o),l=await this.client.downloadHiddenFile(a),d=JSON.parse(await l.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(c=>typeof c=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of s)if(o)for(const a of o.keys){if(!a||r.has(a))continue;r.add(a);const l=i.get(o.owner)??[];l.push(a),i.set(o.owner,l)}return[...i.entries()].map(([o,a])=>({owner:o,elements:a}))}async sync(e){var a;const t=await h(this,p,ee).call(this,!0);let s=await h(this,p,mt).call(this)??{model:this.docId,commits:[]};const r=Cs(s.commits);if(e.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==e.expectedLatestGuid)throw new Vt(e.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Et(),...r?{parents:[r.guid]}:{},author:e.author,source:e.source,timestamp:new Date().toISOString(),...e.message?{message:e.message}:{},...e.userId?{userId:e.userId}:{},...(a=e.appliedOps)!=null&&a.length?{appliedOps:e.appliedOps}:{},changes:e.changes,counts:Ar(e.changes)};if(e.model&&(await h(this,p,rn).call(this,t,e.model),i.full=!0),e.delta){const l=await h(this,p,ue).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const d=await this.client.createHiddenFile(e.delta,l.id);i.deltaId=Rs(d)}const o=await h(this,p,mt).call(this);if(o){s=o;const l=Cs(s.commits);if(e.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==e.expectedLatestGuid)throw new Vt(e.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return s.commits.push(i),await h(this,p,yt).call(this,t,Ht,s),i}async suggestions(){const e=await h(this,p,Ye).call(this);return(e==null?void 0:e.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(e=>e.state==="pending")}async suggest(e){const t=await h(this,p,ee).call(this,!0),s=await h(this,p,Ye).call(this)??{schema:As,ops:[]},r=await h(this,p,We).call(this,Re),i={opId:e.opId??Et(),to:e.to??this.source,title:e.title,verb:e.verb,author:e.author,createdAt:new Date().toISOString(),state:"pending",...e.targets!==void 0?{targets:e.targets}:{},...e.batchId?{batchId:e.batchId}:{},...e.userId?{userId:e.userId}:{},...e.baseCommitGuid?{baseCommitGuid:e.baseCommitGuid}:{}};if(e.payload){const a=r??await h(this,p,Yt).call(this,t,Re,s),l=await this.client.createHiddenFile(e.payload,a.id);i.fragId=Rs(l)}const o=await h(this,p,Ye).call(this)??s;return o.schema??(o.schema=As),o.ops.push(i),await h(this,p,yt).call(this,t,Re,o),i}async suggestionPayload(e){if(!e.fragId)throw new Error(`Suggestion ${e.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(e.fragId)).blob()}async resolveSuggestion(e,t){const s=await h(this,p,ee).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await h(this,p,Ye).call(this),i=r==null?void 0:r.ops.find(o=>o.opId===e);if(!r||!i)throw new Error(`No suggestion ${e} in this document's queue.`);return Object.assign(i,t),await h(this,p,yt).call(this,s,Re,r),i}}ae=new WeakMap,p=new WeakSet,oe=function(){return new ds(this.client,this.project.projectId)},Ce=function(){return`${this.source}-${this.docId}`},ee=async function(e){if(u(this,ae))return u(this,ae);const t=await this.project.rootFolderId(e);if(!t)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=await this.client.listFolders({parentFolderId:t,projectId:this.project.projectId}),r=tn(s,t).find(o=>String(o.name??"")===u(this,p,Ce));if(r)return R(this,ae,te(r)),u(this,ae);if(!e)throw new Error(`Document ${u(this,p,Ce)} does not exist in this project.`);const i=await this.client.createFolder(u(this,p,Ce),t,this.project.projectId);return R(this,ae,te(i)),u(this,ae)},Jt=async function(){const e=await h(this,p,ee).call(this,!1);return(await this.client.listFiles({folderId:e})).map(s=>({id:te(s),name:String(s.name??"")}))},We=async function(e){try{return(await h(this,p,Jt).call(this)).find(t=>t.name===e)}catch{return}},ue=async function(){try{const e=await h(this,p,Jt).call(this);return e.find(t=>t.name===Zs)??e.find(t=>t.name.endsWith(".frag")&&!t.name.startsWith(en))}catch{return}},Wt=async function(e){const t=await h(this,p,We).call(this,e);if(!t)return;const r=await(await this.client.downloadFile(t.id)).text();if(r.trim())return JSON.parse(r)},mt=function(){return h(this,p,Wt).call(this,Ht)},Ye=function(){return h(this,p,Wt).call(this,Re)},yt=async function(e,t,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await h(this,p,We).call(this,t);return i?(await this.client.updateFile(i.id,{file:r,versionTag:lt()}),i):await h(this,p,Yt).call(this,e,t,s)},Yt=async function(e,t,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:r,name:t,versionTag:lt(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:te(o??i),name:t}},rn=async function(e,t){const s=await h(this,p,ue).call(this);if(s)return await this.client.updateFile(s.id,{file:t,versionTag:lt()}),s;const r=`${u(this,p,Ce)}.frag`,i=await this.client.createFile({file:t,name:r,versionTag:lt(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:te(o??i),name:r}};function Ar(n){const e={added:0,modified:0,removed:0};for(const t of n)t.type==="create"?e.added++:t.type==="delete"?e.removed++:e.modified++;return e}function us(n){var l;if(n.length<=1)return n.forEach((d,c)=>d.ordinal=c),[...n];const e=new Map(n.map(d=>[d.guid,d])),t=new Map,s=[];for(const d of n){const c=(l=d.parents)==null?void 0:l[0];if(c&&e.has(c)){const m=t.get(c)??[];m.push(d),t.set(c,m)}else s.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));s.sort(r);const i=[],o=[...s].reverse(),a=new Set;for(;o.length;){const d=o.pop();if(a.has(d.guid))continue;a.add(d.guid),i.push(d);const c=(t.get(d.guid)??[]).sort(r);for(let m=c.length-1;m>=0;m--)o.push(c[m])}for(const d of n)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function Cs(n){const e=us(n);return e[e.length-1]}function Et(){const n=globalThis.crypto;return n!=null&&n.randomUUID?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var pe,Ze,zt;class on{constructor(e){S(this,Ze);S(this,pe,new Map);this.client=e}register(e){if(u(this,pe).has(e.name))throw new Error(`A recipe named "${e.name}" is already registered.`);u(this,pe).set(e.name,e)}list(e){return[...u(this,pe).values()].filter(s=>(!(e!=null&&e.to)||s.to===e.to)&&(!(e!=null&&e.input)||s.inputs.includes(e.input)))}get(e){return u(this,pe).get(e)}async plan(e,t){const{base:s,opId:r,result:i}=await h(this,Ze,zt).call(this,e,t);return{opId:r,projectId:t.projectId,target:t.target,...s!=null&&s.guid?{baseCommitGuid:s.guid}:{},result:i}}async queue(e,t){return{suggestion:await this.client.history(e.projectId).doc(e.target.source,e.target.docId).suggest({opId:e.opId,title:e.result.title,verb:e.result.verb,author:t.author,payload:e.result.payload,targets:e.result.targets,userId:t.userId,baseCommitGuid:e.baseCommitGuid}),result:e.result}}async run(e,t){const{targetDoc:s,base:r,opId:i,result:o}=await h(this,Ze,zt).call(this,e,t);return{suggestion:await s.suggest({opId:i,title:o.title,verb:o.verb,author:t.author,payload:o.payload,targets:o.targets,userId:t.userId,baseCommitGuid:r==null?void 0:r.guid}),result:o}}}pe=new WeakMap,Ze=new WeakSet,zt=async function(e,t){const s=u(this,pe).get(e);if(!s)throw new Error(`No recipe named "${e}" is registered.`);if(s.to!==t.target.source)throw new Error(`Recipe "${e}" writes ${s.to}, but the target document belongs to ${t.target.source}.`);const r=this.client.history(t.projectId).doc(t.target.source,t.target.docId),i=await r.latest(),o=Et(),a=await s.run({client:this.client,projectId:t.projectId,targetDoc:r,opId:o,input:t.input,settings:t.settings??{}});return{recipe:s,targetDoc:r,base:i,opId:o,result:a}};const Kt=100;function Rr(n){try{const e=JSON.parse(n);if(e&&typeof e=="object"){const t=e;return{message:typeof t.message=="string"?t.message:void 0,code:typeof t.code=="string"?t.code:void 0,details:t.details}}}catch{}return{}}function Cr(n){if(!n||typeof n!="object")return;const e=n.retryAfter;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}class St extends Error{constructor(t,s,r,i){const o=Rr(r);super(o.message??`${s||"Request failed"} (${t})`);B(this,"status");B(this,"code");B(this,"details");B(this,"body");B(this,"retryAfter");this.name="RequestError",this.status=t,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??Cr(o.details)}}const Z="item/folder",b="item",de="processor",$r="npm-registry",ie="hidden",$t="FILE",xt="TOOL",Nt="APP",xr=500,$s=3e4,Nr=.25,Pr=n=>new Promise(e=>setTimeout(e,n));function Br(n){var r,i;const e=(i=(r=n.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!e)return;const t=Number(e);if(Number.isFinite(t))return Math.max(0,t);const s=Date.parse(e);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function Fr(n){return n instanceof St?n.status===429||n.status>=500:!0}function Lr(n,e){const t=Math.min(xr*2**e,$s),s=t*Nr*Math.random(),r=n instanceof St&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,$s)+s:t+s}var f,Xt,w,fe,et,ze,gt,wt,Qt,Zt,an;const gs=class gs{constructor(e,t,s){S(this,f);B(this,"apiUrl");B(this,"accessToken");B(this,"wsUrl");B(this,"retries");B(this,"useBearer");B(this,"builtInGlobals",null);B(this,"localServerUrl",null);B(this,"context");S(this,et);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=s||{};let a=t;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=e,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:e,apiUrl:t},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(e){const t=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new gs(t.accessToken,t.apiUrl,{...e,useBearer:!0});return s.context=t,s}setRetries(e){this.retries=e}setBuiltInGlobals(e){this.builtInGlobals=e}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(e,t,s){return h(this,f,w).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await h(this,f,w).call(this,"GET",`${Z}/${t}/items`,{query:{itemType:$t,archived:s}}):await h(this,f,w).call(this,"GET",`${b}`,{query:{itemType:$t,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await h(this,f,Zt).call(this,e,t)}async createFile(e){return await h(this,f,wt).call(this,e,$t)}async updateFile(e,t){return await h(this,f,Qt).call(this,e,t)}async archiveFile(e){return await h(this,f,w).call(this,"DELETE",`${b}/${e}`)}async recoverFile(e){return await h(this,f,w).call(this,"PUT",`${b}/${e}/recover`)}async downloadFile(e,t){return await h(this,f,gt).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await h(this,f,w).call(this,"GET",`${b}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await h(this,f,w).call(this,"PUT",`${b}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await h(this,f,w).call(this,"DELETE",`${b}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await h(this,f,ze).call(this,e,async r=>(await h(this,f,w).call(this,"POST",`${b}/batch/version-metadata`,{body:JSON.stringify({entries:r,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(e){const{archived:t,parentFolderId:s,projectId:r}=e||{};return await h(this,f,w).call(this,"GET",Z,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await h(this,f,w).call(this,"GET",`${Z}/${e}`)}async getFoldersBatch(e){return await h(this,f,ze).call(this,e,async t=>(await h(this,f,w).call(this,"POST",`${b}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await h(this,f,w).call(this,"POST",Z,{body:JSON.stringify({name:e,...t&&{parentId:t},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(e,t){const{name:s}=t;return await h(this,f,w).call(this,"PUT",`${Z}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await h(this,f,w).call(this,"DELETE",`${Z}/${e}`)}async recoverFolder(e){return await h(this,f,w).call(this,"PUT",`${Z}/${e}/recover`)}async downloadFolder(e){return await h(this,f,fe).call(this,`${Z}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await h(this,f,w).call(this,"GET",`${Z}/${t}/items`,{query:{itemType:xt,...s&&{ShowVersions:s}}}):await h(this,f,w).call(this,"GET",`${b}`,{query:{itemType:xt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await h(this,f,Zt).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await h(this,f,wt).call(this,e,xt,t)}async updateComponent(e,t){const{componentProps:s}=t;return await h(this,f,Qt).call(this,e,t,s)}async downloadComponent(e,t){return await h(this,f,gt).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await h(this,f,fe).call(this,`${b}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await h(this,f,w).call(this,"DELETE",`${b}/${e}`)}async recoverComponent(e){return await h(this,f,w).call(this,"PUT",`${b}/${e}/recover`)}async getBuiltInComponent(e){return await(await h(this,f,fe).call(this,`built-in/${e}/bundle`)).text()}async initBuiltInComponent(e,t,s){const r=await this.getBuiltInComponent(e.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(m=>i[m]),d=new Function(...o,`${r}
2
- return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;t.get(c)}async initBuiltInComponents(e,...t){await Promise.all(t.map(s=>this.initBuiltInComponent(s,e)))}async setup(e,...t){var o,a;const s=e.OBC,r=e.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return r.Manager.init(),this.setBuiltInGlobals(e),await this.initBuiltInComponents(i,...t),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(e,t){var s,r;(r=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||r.call(s,e,t)}async listApps(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await h(this,f,w).call(this,"GET",`${Z}/${t}/items`,{query:{itemType:Nt,...s&&{ShowVersions:s}}}):await h(this,f,w).call(this,"GET",`${b}`,{query:{itemType:Nt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await h(this,f,wt).call(this,e,Nt,t)}async downloadApp(e,t){return await h(this,f,gt).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await h(this,f,fe).call(this,`${b}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await h(this,f,w).call(this,"DELETE",`${b}/${e}`)}async getNpmCredentials(){return await h(this,f,w).call(this,"GET",`${$r}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${de}/${e}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await h(this,f,w).call(this,"POST",`${de}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${de}/progress/${e}/abort`,s=await fetch(t,{method:"POST"});if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await h(this,f,w).call(this,"POST",`${de}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${de}/${e}/progress${s}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await h(this,f,w).call(this,"GET",`${de}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${de}/progress/${e}`,s=await fetch(t);if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await h(this,f,w).call(this,"GET",`${de}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl??this.wsUrl,r=await Ke(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:e})),r.on("execution",i=>{t(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(e){return new ds(this,e)}history(e){return new sn(this,e)}get recipes(){return u(this,et)??R(this,et,new on(this)),u(this,et)}async createHiddenFile(e,t,s){const r=new FormData;return r.append("file",e),r.append("parentItemId",t),s!=null&&r.append("tag",s),await h(this,f,w).call(this,"POST",`${b}/${ie}`,{body:r})}async createHiddenFilesBatch(e,t,s){const r=new FormData;for(const i of e)r.append("files",i);return r.append("parentItemId",t),s!=null&&r.append("tag",s),await h(this,f,w).call(this,"POST",`${b}/${ie}/batch`,{body:r})}async deleteHiddenFile(e){return await h(this,f,w).call(this,"DELETE",`${b}/${ie}/${e}`)}async getHiddenFile(e){return await h(this,f,w).call(this,"GET",`${b}/${ie}/${e}`)}async downloadHiddenFile(e){return await h(this,f,fe).call(this,`${b}/${ie}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await h(this,f,w).call(this,"GET",`${b}/${ie}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await h(this,f,ze).call(this,e,async s=>(await h(this,f,w).call(this,"POST",`${b}/${ie}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...t!=null&&{expiresIn:t}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(e,t){return await h(this,f,w).call(this,"GET",`${b}/${e}/${ie}`,{...t!=null&&{query:{tag:t}}})}async deleteHiddenFilesByParent(e){return await h(this,f,w).call(this,"DELETE",`${b}/${e}/${ie}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await h(this,f,w).call(this,"PUT",`${b}/${e}/icon`,{body:s})}async getItemIcon(e){return await h(this,f,fe).call(this,`${b}/${e}/icon`)}async removeItemIcon(e){return await h(this,f,w).call(this,"DELETE",`${b}/${e}/icon`)}async updateItem(e,t){return await h(this,f,w).call(this,"PUT",`${b}/${e}`,{body:JSON.stringify(t),contentType:"application/json"})}async createVersion(e,t,s,r,i){const o=new FormData;return o.append("file",t),o.append("versionTag",s),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await h(this,f,w).call(this,"POST",`${b}/${e}/version`,{body:o})}async listVersions(e,t={}){return await h(this,f,w).call(this,"GET",`${b}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await h(this,f,ze).call(this,e,async r=>(await h(this,f,w).call(this,"POST",`${b}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(e,t){return await h(this,f,w).call(this,"PUT",`${b}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await h(this,f,w).call(this,"PUT",`${b}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await h(this,f,w).call(this,"DELETE",`${b}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};f=new WeakSet,Xt=function(e){return`${this.apiUrl}/${e}`},w=async function(e,t,s){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=s||{},c=h(this,f,Xt).call(this,t),m=h(this,f,an).call(this,i),T=await this.resolveAccessToken(),A={...m,...this.useBearer?{}:{accessToken:T}};try{const _=await fetch(c+"?"+new URLSearchParams(A).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${T}`}},...r&&{body:r}});if(!_.ok){const v=await _.text().then(N=>N).catch(()=>"");throw new St(_.status,_.statusText,v,Br(_))}return l==="blob"?await _.blob():_.json().then(v=>v).catch(()=>{})}catch(_){const v=a??this.retries;if(v>0&&Fr(_)){const N=d??0;return await Pr(Lr(_,N)),await h(this,f,w).call(this,e,t,{...s,retries:v-1,retryAttempt:N+1})}throw _}},fe=async function(e,t){const{query:s}=t||{},r=h(this,f,Xt).call(this,e),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},et=new WeakMap,ze=async function(e,t){if(!e.length)return[];const s=[];for(let i=0;i<e.length;i+=Kt)s.push(e.slice(i,i+Kt));return(await Promise.all(s.map(t))).flat()},gt=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await h(this,f,fe).call(this,`${b}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},wt=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=e,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",t),o&&c.append("folderId",o),a&&c.append("projectId",a),s&&c.append("extraProps",JSON.stringify(s)),d&&c.append("metadata",JSON.stringify(d)),await h(this,f,w).call(this,"POST",b,{body:c})},Qt=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=t;let d,c;if(a){const m=new FormData;m.append("file",a),i&&m.append("versionTag",i),s&&m.append("extraProps",JSON.stringify(s)),l&&m.append("metadata",JSON.stringify(l)),c=await h(this,f,w).call(this,"POST",`${b}/${e}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},T=JSON.stringify(m);d=await h(this,f,w).call(this,"PUT",`${b}/${e}`,{body:T,contentType:"application/json"})}return{item:d,version:c}},Zt=async function(e,t){const{showVersions:s=!1}=t||{};return await h(this,f,w).call(this,"GET",`${b}/${e}`,{query:{showVersions:s}})},an=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let Tt=gs;function cn(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const e=t=>{t.source===window.parent&&n(t.data)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}}}const es="channel:",Dr=1e4;function bt(n){try{n()}catch(e){console.error("[channel] a listener threw:",e)}}var ce,U,V,xe,Ne,Pe,L,ts,ss,$e;class fs{constructor(e,t){S(this,L);S(this,ce,!1);S(this,U,[]);S(this,V,[]);S(this,xe,new Set);S(this,Ne,new Set);S(this,Pe,new Set);this.transport=e,this.controls=t}get joined(){return u(this,ce)}get peers(){return u(this,U)}join(){return u(this,ce)?Promise.resolve():h(this,L,ts).call(this,"joined",this.controls.join)}leave(){return!u(this,ce)&&!u(this,V).some(e=>e.want==="joined")?Promise.resolve():h(this,L,ts).call(this,"left",this.controls.leave)}onChange(e){return u(this,xe).add(e),()=>void u(this,xe).delete(e)}onPeerJoined(e){return u(this,Ne).add(e),()=>void u(this,Ne).delete(e)}onPeerLeft(e){return u(this,Pe).add(e),()=>void u(this,Pe).delete(e)}applyJoined(){R(this,ce,!0),h(this,L,ss).call(this,"joined"),h(this,L,$e).call(this)}applyLeft(){R(this,ce,!1),R(this,U,[]),h(this,L,ss).call(this,"left"),h(this,L,$e).call(this)}applyPeers(e){R(this,U,e),h(this,L,$e).call(this)}applyPeerJoined(e){!u(this,ce)||u(this,U).some(t=>t.from===e.from)||(R(this,U,[...u(this,U),e]),u(this,Ne).forEach(t=>bt(()=>t(e))),h(this,L,$e).call(this))}applyPeerLeft(e){const t=u(this,U).find(s=>s.from===e);t&&(R(this,U,u(this,U).filter(s=>s.from!==e)),u(this,Pe).forEach(s=>bt(()=>s(t))),h(this,L,$e).call(this))}failPending(e){const t=u(this,V);return R(this,V,[]),t.forEach(s=>{clearTimeout(s.timer),s.reject(e)}),t.length>0}post(e){this.transport.post(e)}}ce=new WeakMap,U=new WeakMap,V=new WeakMap,xe=new WeakMap,Ne=new WeakMap,Pe=new WeakMap,L=new WeakSet,ts=function(e,t){return new Promise((s,r)=>{const i={want:e,resolve:s,reject:r,timer:setTimeout(()=>{R(this,V,u(this,V).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${e==="joined"?"joining":"leaving"} in time.`))},Dr)};u(this,V).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...t})})},ss=function(e){const t=u(this,V).filter(s=>s.want===e);R(this,V,u(this,V).filter(s=>s.want!==e)),t.forEach(s=>{clearTimeout(s.timer),s.resolve()})},$e=function(){u(this,xe).forEach(e=>bt(e))};var Be;class hn extends fs{constructor(t){super(t,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});S(this,Be,new Map)}on(t,s){const r=u(this,Be).get(t)??new Set;return r.add(s),u(this,Be).set(t,r),()=>void r.delete(s)}send(t,s){if(t.startsWith(es))throw new Error(`Message types starting with '${es}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:t,payload:s}})}accepts(t){return t===void 0||t==="collab"}async handle(t){const s=u(this,Be).get(t.type);if(!(s!=null&&s.size))return{handled:!1};const r=dn(t);return s.forEach(i=>bt(()=>i(t.payload,r))),{handled:!0}}}Be=new WeakMap;var me;class ln extends fs{constructor(t,s){super(t,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});S(this,me,new Map);this.kind=s}on(t,s){if(u(this,me).has(t))throw new Error(`"${t}" already has a handler in this room. Remove it first.`);return u(this,me).set(t,s),()=>void u(this,me).delete(t)}accepts(t,s){return t!==void 0&&t!=="external"?!1:this.kind===void 0||t===void 0||this.kind===s}get hasHandlers(){return u(this,me).size>0}async handle(t){const s=u(this,me).get(t.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(t.payload,dn(t))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}me=new WeakMap;function dn(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function jr(n){const e=n;if((e==null?void 0:e.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const t=e.message;return!t||typeof t.type!="string"?null:{type:t.type,requestId:typeof t.requestId=="string"?t.requestId:void 0,payload:t.payload,at:typeof t.at=="number"?t.at:Date.now(),from:typeof t.from=="string"?t.from:"",scope:t.scope==="collab"||t.scope==="external"?t.scope:void 0,kind:typeof t.kind=="string"?t.kind:void 0}}var Se,tt,he,ye,ge,$,ns,vt,fn,pn,mn,rs;class un{constructor(e){S(this,$);S(this,Se);S(this,tt);S(this,he);S(this,ye,new Map);S(this,ge,new Set);R(this,Se,e),R(this,tt,e.listen(t=>void h(this,$,fn).call(this,t)))}collab(){return u(this,he)??R(this,he,new hn(u(this,Se))),u(this,he)}external(e){const t=e??"";let s=u(this,ye).get(t);return s||(s=new ln(u(this,Se),e),u(this,ye).set(t,s)),s}dispose(){u(this,tt).call(this)}}Se=new WeakMap,tt=new WeakMap,he=new WeakMap,ye=new WeakMap,ge=new WeakMap,$=new WeakSet,ns=function(){return[...u(this,he)?[u(this,he)]:[],...u(this,ye).values()]},vt=function(e,t){if(e==="collab")return u(this,he);if(e==="external")return u(this,ye).get(typeof t=="string"?t:"")},fn=async function(e){const t=jr(e);if(t){if(t.type.startsWith(es)){h(this,$,pn).call(this,t);return}await h(this,$,mn).call(this,t)}},pn=function(e){var s,r,i;const t=e.payload??{};switch(e.type){case"channel:joined":(s=h(this,$,vt).call(this,t.scope,t.kind))==null||s.applyJoined();break;case"channel:left":(r=h(this,$,vt).call(this,t.scope,t.kind))==null||r.applyLeft();break;case"channel:peers":(i=h(this,$,vt).call(this,t.scope,t.kind))==null||i.applyPeers(t.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!t.from)break;const o=t.scope==="collab"?[u(this,he)]:[...u(this,ye).values()].filter(a=>a.accepts("external",t.kind));for(const a of o)e.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:t.from,kind:t.kind}):a==null||a.applyPeerLeft(t.from);break}case"channel:error":{const o=new Error(String(e.payload));h(this,$,ns).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",e.payload);break}}},mn=async function(e){const t=h(this,$,ns).call(this).filter(i=>i.accepts(e.scope,e.kind));let s=!1;for(const i of t){const o=await i.handle(e);o.handled&&(s=!0,e.requestId&&h(this,$,rs).call(this,e.requestId,o))}e.requestId&&e.scope==="external"&&t.length>0&&!s&&h(this,$,rs).call(this,e.requestId,{handled:!0,error:`No handler for "${e.type}".`})},rs=function(e,t){u(this,ge).has(e)||(u(this,ge).add(e),u(this,ge).size>500&&u(this,ge).delete(u(this,ge).values().next().value),u(this,Se).post({type:"APP_CHANNEL_PUBLISH",message:{type:t.error===void 0?"reply":"reply-error",requestId:e,payload:t.error===void 0?t.value:{error:t.error}}}))};const Ie="project",Ae="notifications";var Fe,st;const ws=class ws extends Tt{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});S(this,Fe);S(this,st);typeof t=="function"&&R(this,Fe,t)}async resolveAccessToken(){return u(this,Fe)?await u(this,Fe).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new ws(s.accessToken,s.apiUrl,t);return r.context=s,r}get channel(){return u(this,st)??R(this,st,new un(cn())),u(this,st)}async listProjects(){return await this.request("GET",Ie)}async getProject(t){return await this.request("GET",`${Ie}/${t}`)}async getProjectData(t){return await this.request("GET",`${Ie}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${Ie}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${Ie}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",Ae,{query:{...(t==null?void 0:t.cursor)!==void 0&&{cursor:t.cursor},...(t==null?void 0:t.limit)!==void 0&&{limit:String(t.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${Ae}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${Ae}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Ae}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Ae}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${Ae}/subscriptions/${t}`)}async subscribeToAutomation(t,s,r){return await this.request("POST",`${Ie}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,r){return await this.request("PATCH",`${Ie}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),r=Ke(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return r.on("notification.created",i=>t({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>t({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>t({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};Fe=new WeakMap,st=new WeakMap;let is=ws;async function ps(n){const[e,t]=await qr(),s=t.Model.getRootAsModel(new e.ByteBuffer(await Mr(n)));let r={};try{r=JSON.parse(s.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<s.guidsLength();a++){const l=s.guidsItems(a),d=s.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<s.attributesLength();a++){const l=s.localIds(a);if(l===null)continue;const d={},c=s.attributes(a);for(let m=0;m<((c==null?void 0:c.dataLength())??0);m++){const T=c.data(m);if(T)try{const[A,_]=JSON.parse(T);d[A]=_}catch{}}o.push({localId:l,guid:i.get(l)??null,category:s.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function qr(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(n){throw new Error(`readFrag needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` resolvable (in Node, fragments also pulls its own imports, e.g. web-ifc). (${n instanceof Error?n.message:String(n)})`)}}async function Mr(n){const e=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const Ur="flow:",Vr="flow:op",Hr="flow:source",yn="revitflow/op@2",xs="REVITFLOWCHANGE",Ns="REVITFLOWOPERATION";class ms{constructor(e){B(this,"changes",[]);this.target=e}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(e,t={}){return this.changes.push({op:"add",attrs:this.pack(e,t)}),this}set(e,t,s={}){return this.requireId(e,"set"),this.changes.push({op:"set",item:e,attrs:this.pack(t,s)}),this}remove(e){return this.requireId(e,"remove"),this.changes.push({op:"remove",item:e,attrs:{}}),this}get summary(){const e=new Set(this.changes.map(t=>t.op));return e.size===1?[...e][0]:"mixed"}async build(e){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const t={schema:yn,opId:e,batchId:this.batchId??e,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[s,r]=await Gr();return Jr(this.flatbuffer(s,r,e,JSON.stringify(t)))}pack(e,t){const s={};for(const[r,i]of Object.entries(e??{}))r.startsWith(Ur)||(s[r]=String(i));return t.position&&(s.Position=t.position.map(Ps).join(",")),t.rotationDeg!==void 0&&(s.Rotation=Ps(t.rotationDeg)),t.source&&(s[Hr]=t.source),s}requireId(e,t){if(!e||!e.trim())throw new Error(`A '${t}' has to name the item it acts on.`)}flatbuffer(e,t,s,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=t,c=new e.Builder(1024),m=this.changes.length,T=new Uint32Array(m);let A=1;for(let I=0;I<m;I++)T[I]=A++;const _=A++,v=I=>(I(c,0),c.endVector()),N=o.createShellsVector(c,[]),be=o.createCircleExtrusionsVector(c,[]),G=v(o.startSamplesVector),z=v(o.startRepresentationsVector),De=v(o.startMaterialsVector),K=v(o.startLocalTransformsVector),k=v(o.startGlobalTransformsVector),j=o.createMeshesItemsVector(c,[]),X=o.createMaterialIdsVector(c,[]),ve=o.createRepresentationIdsVector(c,[]),Ee=o.createSampleIdsVector(c,[]),Te=o.createLocalTransformIdsVector(c,[]),je=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,k),o.addShells(c,N),o.addRepresentations(c,z),o.addSamples(c,G),o.addLocalTransforms(c,K),o.addMaterials(c,De),o.addCircleExtrusions(c,be),o.addMeshesItems(c,j),o.addRepresentationIds(c,ve),o.addSampleIds(c,Ee),o.addMaterialIds(c,X),o.addLocalTransformIds(c,Te),o.addGlobalTransformIds(c,je);const qe=o.endMeshes(c),_e=c.createString(r),Me=new Set,ke=[];for(const I of this.changes){const F=[],re={[Vr]:I.op,...I.attrs};for(const[q,J]of Object.entries(re)){const Q=JSON.stringify([q,J,"IFCTEXT"]);Me.add(Q),F.push(c.createString(Q))}ke.push(i.createAttribute(c,i.createDataVector(c,F)))}{const I=JSON.stringify(["Name",s,"IFCLABEL"]);Me.add(I);const F=i.createDataVector(c,[c.createString(I)]);ke.push(i.createAttribute(c,F))}const nt=a.createAttributesVector(c,ke),rt=a.createUniqueAttributesVector(c,[...Me].map(I=>c.createString(I))),Ue=this.changes.map(()=>c.createString(xs));Ue.push(c.createString(Ns));const it=a.createCategoriesVector(c,Ue),Ve=[],He=[];this.changes.forEach((I,F)=>{I.item&&(Ve.push(c.createString(I.item)),He.push(T[F]))});const g=a.createGuidsVector(c,Ve),y=a.createGuidsItemsVector(c,He),O=a.createLocalIdsVector(c,[...T,_]),x=this.changes.map((I,F)=>l.createSpatialStructure(c,T[F],c.createString(xs),0)),P=l.createSpatialStructure(c,_,c.createString(Ns),l.createChildrenVector(c,x)),D=c.createString(s);a.startModel(c),a.addMeshes(c,qe),a.addMetadata(c,_e),a.addAttributes(c,nt),a.addUniqueAttributes(c,rt),a.addLocalIds(c,O),a.addCategories(c,it),a.addGuidsItems(c,y),a.addGuids(c,g),a.addGuid(c,D),a.addSpatialStructure(c,P),a.addMaxLocalId(c,A);const le=a.endModel(c);return a.finishModelBuffer(c,le),c.asUint8Array()}}async function Gr(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(n){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${n instanceof Error?n.message:String(n)})`)}}function Ps(n){return Number.isFinite(n)?String(n):"0"}async function Jr(n){const e=new Blob([n]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const Wr="Element",Yr="Carried",gn=1/.3048;function zr(n){const e=[];for(const t of n)for(const s of[Wr,Yr]){const r=t.attrs[s];if(r)try{const i=JSON.parse(r);for(const o of Array.isArray(i)?i:[i]){const a=o;typeof(a==null?void 0:a.id)!="string"||typeof(a==null?void 0:a.kind)!="string"||e.push({id:a.id,kind:a.kind,params:a.params??{},item:t})}}catch{}}return e}function dt(n,e){const t=n.params[e];if(typeof t!="string")return null;try{return JSON.parse(t)}catch{return null}}function Kr(n){const e=new Map;for(const t of n){if(t.kind!=="datum"||t.params.of!=="level")continue;const s=t.params.named,r=t.params.at;typeof s=="string"&&typeof r=="number"&&e.set(t.id,{name:s,at:r})}return e}function Xr(n){const e=new Map;for(const t of n){if(!t.kind.endsWith("Style"))continue;const s=t.params.name;typeof s=="string"&&e.set(s,t)}return e}async function wn(n,e){const t=new Map,s=(await n.targetDoc.suggestions()).filter(r=>{var i;return r.author===e&&r.state==="applied"&&r.fragId&&(((i=r.affectedIds)==null?void 0:i.length)??0)>0}).sort((r,i)=>String(r.createdAt).localeCompare(String(i.createdAt)));for(const r of s)try{const i=await n.targetDoc.suggestionPayload(r),{items:o}=await ps(new Uint8Array(await i.arrayBuffer())),a=o.filter(d=>d.attrs["flow:op"]),l=r.affectedIds??[];for(let d=0;d<a.length&&d<l.length;d++){const c=a[d].attrs["flow:source"];c&&(a[d].attrs["flow:op"]==="remove"?t.delete(c):t.set(c,l[d]))}}catch{}return t}async function bn(n,e){if(!(e!=null&&e.fileId))throw new Error("Choose the model file to read.");const t=new Uint8Array(await(await n.client.downloadFile(e.fileId)).arrayBuffer());return{picked:e,contents:await ps(t)}}const Pt={levels:"-2000240",walls:"-2000011",floors:"-2000032"},Bs=180/Math.PI;function Fs(n){if(typeof n!="string")return null;const e=n.indexOf(":");return e<=0||e===n.length-1?null:{family:n.slice(0,e),type:n.slice(e+1)}}const M=n=>String(n);function vn(n){return async e=>{var ke,nt,rt,Ue,it,Ve,He;const{picked:t,contents:s}=await bn(e,e.input),r=zr(s.items);if(r.length===0)throw new Error(n==="ifc"?`"${t.name}" carries no platform records: it was imported without the editable converter. Process the IFC with the editable converter first; a plain import only has IFC attributes, and guessing geometry is not this recipe.`:`"${t.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:i,trustStyleNames:o,includeInstances:a}=e.settings,l=e.settings.createLevels!==!1;if(a&&!o)throw new Error("Free-standing instances can only be proposed by their style names: turn trustStyleNames on.");const d=Kr(r),c=Xr(r),m=`recipe:${n}-to-revit`,T=await wn(e,m),A=await e.targetDoc.latest(),_=new ms({project:e.projectId,document:e.targetDoc.docId,baseCommit:(A==null?void 0:A.version)??0,author:m}),v=gn,N=g=>`${t.fileId}:${g}`,be=new Set;let G=0;const z=(g,y,O)=>(be.add(g),T.has(g)?(G++,!1):(_.add(y,{...O,source:g}),!0)),De=g=>{const y=typeof g=="string"?c.get(g):void 0,O=y==null?void 0:y.params.thickness;return typeof O=="number"&&O>0?O*v:void 0};let K=0;if(l)for(const[g,y]of d)z(N(g),{CategoryId:Pt.levels,Name:y.name,Elevation:M(y.at*v)}),K++;let k=0,j=0;for(const g of r){if(g.kind!=="run"||g.params.of!=="wall")continue;const y=dt(g,"run"),O=((nt=(ke=y==null?void 0:y.run)==null?void 0:ke.line)==null?void 0:nt.curves)??[],x=typeof(y==null?void 0:y.base)=="number"?y.base:0,P=y==null?void 0:y.height,D=d.get(String((y==null?void 0:y.level)??g.params.level??"")),le=g.params.lookRef;if(typeof le!="string"||typeof P!="number"||!D){j++;continue}O.forEach((I,F)=>{if(I.kind!=="segment"||!I.from||!I.to){j++;return}const re=(D.at+x)*v,q=`${M(I.from[0]*v)},${M(I.from[1]*v)},${M(re)};${M(I.to[0]*v)},${M(I.to[1]*v)},${M(re)}`,J={CategoryId:Pt.walls,Type:le,LocationLine:q,Level:D.name,BaseOffset:M(x*v),Height:M(P*v)},Q=De(le);Q&&(J["Type.Width"]=M(Q)),z(`${N(g.id)}#${F}`,J)&&k++})}let X=0,ve=0;for(const g of r){if(g.kind!=="extrusion"||g.params.of!=="slab")continue;const y=dt(g,"extrusion"),O=typeof g.params.base=="number"?g.params.base:0,x=d.get(String((y==null?void 0:y.level)??g.params.level??"")),P=g.params.lookRef,D=q=>{if(!(q!=null&&q.length))return null;const J=[];for(const Q of q){if(Q.kind!=="segment"||!Q.from)return null;J.push(Q.from[0]*v,Q.from[1]*v,O*v)}return J.length>=9?J:null},le=D((Ue=(rt=y==null?void 0:y.profile)==null?void 0:rt.outline)==null?void 0:Ue.curves);if(typeof P!="string"||!x||!le){ve++;continue}const I=[le];for(const q of((it=y==null?void 0:y.profile)==null?void 0:it.holes)??[]){const J=D(q==null?void 0:q.curves);J&&I.push(J)}const F={CategoryId:Pt.floors,Type:P,Profile:JSON.stringify(I),Level:x.name},re=De(P);re&&(F["Type.Width"]=M(re)),re&&(F.HeightOffset=M(O*v+re)),z(N(g.id),F)&&X++}let Ee=0;for(const g of r){if(g.kind!=="member"||g.params.of!=="column")continue;const y=dt(g,"member"),O=y==null?void 0:y.start;if(!O||O.length!==3)continue;const x=o?Fs(g.params.lookRef):null;if(o&&!x||!x&&!i)continue;const P=x??{family:i.family,type:i.type},D=d.get(String((y==null?void 0:y.level)??""));z(N(g.id),{...i&&!x?{CategoryId:i.categoryId}:{},Family:P.family,Type:P.type,...D?{Level:D.name}:{}},{position:[O[0]*v,O[1]*v,O[2]*v],rotationDeg:(Number((y==null?void 0:y.roll)??0)||0)*Bs})&&Ee++}let Te=0,je=0;for(const g of r){if(g.kind!=="familyInstance")continue;if(g.params.host){je++;continue}if(!a)continue;const y=dt(g,"instance"),O=(Ve=y==null?void 0:y.placement)==null?void 0:Ve.at;if(!O||O.length!==3)continue;const x=Fs(g.params.type);if(!x)continue;const P=(He=y==null?void 0:y.placement)==null?void 0:He.right,D=P?Math.atan2(P[1],P[0])*Bs:0;z(N(g.id),{Family:x.family,Type:x.type},{position:[O[0]*v,O[1]*v,O[2]*v],rotationDeg:D})&&Te++}let qe=0;for(const g of r)(g.kind==="stair"||g.kind==="footing"||g.kind==="ramp"||g.kind==="extrusion"&&g.params.of!=="slab"||g.kind==="run"&&g.params.of!=="wall")&&qe++;let _e=0;for(const[g,y]of T)!g.startsWith(`${t.fileId}:`)||be.has(g)||(_.remove(y),_e++);if(_.length===0)throw new Error(`Nothing new to ask for: "${t.name}" holds ${G} element(s) this recipe already made, ${je+qe} waiting on the applier, and nothing is left to remove.`);const Me=[K?`${K} level(s)`:"",k?`${k} wall(s)`:"",X?`${X} floor(s)`:"",Ee?`${Ee} column(s)`:"",Te?`${Te} instance(s)`:"",_e?`${_e} gone`:""].filter(Boolean);return{title:`${n==="ifc"?"IFC":"Model"} to Revit: ${Me.join(", ")}`,verb:_.summary,targets:_.length,payload:new Blob([await _.build(e.opId)]),ruleTallies:[{read:d.size,proposed:K},{read:k+j,proposed:k},{read:X+ve,proposed:X},{read:Ee,proposed:Ee},{read:Te,proposed:Te},{read:_e,proposed:_e},{read:je+qe,proposed:0}]}}}const Qr={type:"object",properties:{columnType:{type:"object",title:"Column type","x-existing":{of:"family-type",from:"target",where:{CategoryId:"-2001330"}}},trustStyleNames:{type:"boolean",title:"Use the model's own style names as Family:Type",default:!1},includeInstances:{type:"boolean",title:"Also propose free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},Zr=[{reads:"Levels (datums)",proposes:"The same level on the target, ensured by name"},{reads:"Wall runs, one per straight segment",proposes:"A native wall: curve, type (made from its width when missing), level, height"},{reads:"Slabs with their boundary",proposes:"A native floor from the profile, holes included"},{reads:"Column records (members)",proposes:"A Revit column at each, on its level"},{reads:"Free-standing family instances (when turned on)",proposes:"A new instance of the same-named type, placed and turned"},{reads:"Things this recipe made whose record is gone",proposes:"That element removed"},{reads:"Hosted doors/windows, stairs, roofs, footings, curtain pieces",proposes:"Nothing yet - each waits on the applier or the converter growing"}],En=`
1
+ "use strict";var Ln=Object.create;var Ft=Object.defineProperty;var Dn=Object.getOwnPropertyDescriptor;var jn=Object.getOwnPropertyNames;var qn=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var ks=n=>{throw TypeError(n)};var Un=(n,e,t)=>e in n?Ft(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Vn=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jn(e))!Mn.call(n,r)&&r!==t&&Ft(n,r,{get:()=>e[r],enumerable:!(s=Dn(e,r))||s.enumerable});return n};var ft=(n,e,t)=>(t=n!=null?Ln(qn(n)):{},Vn(e||!n||!n.__esModule?Ft(t,"default",{value:n,enumerable:!0}):t,n));var L=(n,e,t)=>Un(n,typeof e!="symbol"?e+"":e,t),Pt=(n,e,t)=>e.has(n)||ks("Cannot "+t);var u=(n,e,t)=>(Pt(n,e,"read from private field"),t?t.call(n):e.get(n)),S=(n,e,t)=>e.has(n)?ks("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),C=(n,e,t,s)=>(Pt(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),l=(n,e,t)=>(Pt(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re=Object.create(null);re.open="0";re.close="1";re.ping="2";re.pong="3";re.message="4";re.upgrade="5";re.noop="6";const vt=Object.create(null);Object.keys(re).forEach(n=>{vt[re[n]]=n});const Ut={type:"error",data:"parser error"},Ys=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",zs=typeof ArrayBuffer=="function",Ks=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ms=({type:n,data:e},t,s)=>Ys&&e instanceof Blob?t?s(e):Rs(e,s):zs&&(e instanceof ArrayBuffer||Ks(e))?t?s(e):Rs(new Blob([e]),s):s(re[n]+(e||"")),Rs=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function Cs(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Bt;function Hn(n,e){if(Ys&&n.data instanceof Blob)return n.data.arrayBuffer().then(Cs).then(e);if(zs&&(n.data instanceof ArrayBuffer||Ks(n.data)))return e(Cs(n.data));ms(n,!1,t=>{Bt||(Bt=new TextEncoder),e(Bt.encode(t))})}const $s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<$s.length;n++)Xe[$s.charCodeAt(n)]=n;const Gn=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,a,h;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const d=new ArrayBuffer(e),c=new Uint8Array(d);for(s=0;s<t;s+=4)i=Xe[n.charCodeAt(s)],o=Xe[n.charCodeAt(s+1)],a=Xe[n.charCodeAt(s+2)],h=Xe[n.charCodeAt(s+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|h&63;return d},Jn=typeof ArrayBuffer=="function",ys=(n,e)=>{if(typeof n!="string")return{type:"message",data:Xs(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Wn(n.substring(1),e)}:vt[t]?n.length>1?{type:vt[t],data:n.substring(1)}:{type:vt[t]}:Ut},Wn=(n,e)=>{if(Jn){const t=Gn(n);return Xs(t,e)}else return{base64:!0,data:n}},Xs=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Qs="",Yn=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{ms(i,!1,a=>{s[o]=a,++r===t&&e(s.join(Qs))})})},zn=(n,e)=>{const t=n.split(Qs),s=[];for(let r=0;r<t.length;r++){const i=ys(t[r],e);if(s.push(i),i.type==="error")break}return s};function Kn(){return new TransformStream({transform(n,e){Hn(n,t=>{const s=t.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let Lt;function pt(n){return n.reduce((e,t)=>e+t.length,0)}function mt(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let r=0;r<e;r++)t[r]=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 Xn(n,e){Lt||(Lt=new TextDecoder);const t=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(s===0){if(pt(t)<1)break;const h=mt(t,1);i=(h[0]&128)===128,r=h[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(pt(t)<2)break;const h=mt(t,2);r=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),s=3}else if(s===2){if(pt(t)<8)break;const h=mt(t,8),d=new DataView(h.buffer,h.byteOffset,h.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Ut);break}r=c*Math.pow(2,32)+d.getUint32(4),s=3}else{if(pt(t)<r)break;const h=mt(t,r);a.enqueue(ys(i?h:Lt.decode(h),e)),s=0}if(r===0||r>n){a.enqueue(Ut);break}}}})}const Zs=4;function $(n){if(n)return Qn(n)}function Qn(n){for(var e in $.prototype)n[e]=$.prototype[e];return n}$.prototype.on=$.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};$.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};$.prototype.off=$.prototype.removeListener=$.prototype.removeAllListeners=$.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,r=0;r<t.length;r++)if(s=t[r],s===e||s.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+n],this};$.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,r=t.length;s<r;++s)t[s].apply(this,e)}return this};$.prototype.emitReserved=$.prototype.emit;$.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};$.prototype.hasListeners=function(n){return!!this.listeners(n).length};const $t=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),J=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Zn="arraybuffer";function en(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const er=J.setTimeout,tr=J.clearTimeout;function xt(n,e){e.useNativeTimers?(n.setTimeoutFn=er.bind(J),n.clearTimeoutFn=tr.bind(J)):(n.setTimeoutFn=J.setTimeout.bind(J),n.clearTimeoutFn=J.clearTimeout.bind(J))}const sr=1.33;function nr(n){return typeof n=="string"?rr(n):Math.ceil((n.byteLength||n.size)*sr)}function rr(n){let e=0,t=0;for(let s=0,r=n.length;s<r;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 tn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ir(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function or(n){let e={},t=n.split("&");for(let s=0,r=t.length;s<r;s++){let i=t[s].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class ar extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class gs extends ${constructor(e){super(),this.writable=!1,xt(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 ar(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=ys(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&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=ir(e);return t.length?"?"+t:""}}class cr extends gs{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)};zn(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,Yn(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]=tn()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let sn=!1;try{sn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const lr=sn;function hr(){}class dr extends cr{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",(r,i)=>{this.onError("xhr post error",r,i)})}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 ne extends ${constructor(e,t,s){super(),this.createRequest=e,xt(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=en(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 r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}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 r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.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(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ne.requestsCount++,ne.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=hr,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ne.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()}}ne.requestsCount=0;ne.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",xs);else if(typeof addEventListener=="function"){const n="onpagehide"in J?"pagehide":"unload";addEventListener(n,xs,!1)}}function xs(){for(let n in ne.requests)ne.requests.hasOwnProperty(n)&&ne.requests[n].abort()}const ur=function(){const n=nn({xdomain:!1});return n&&n.responseType!==null}();class fr extends dr{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=ur&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ne(nn,this.uri(),e)}}function nn(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||lr))return new XMLHttpRequest}catch{}if(!e)try{return new J[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const rn=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class pr extends gs{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=rn?{}:en(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(r){return this.emitReserved("error",r)}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],r=t===e.length-1;ms(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&$t(()=>{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]=tn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Dt=J.WebSocket||J.MozWebSocket;class mr extends pr{createSocket(e,t,s){return rn?new Dt(e,t,s):t?new Dt(e,t):new Dt(e)}doWrite(e,t){this.ws.send(t)}}class yr extends gs{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=Xn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Kn();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:a,value:h})=>{a||(this.onPacket(h),i())}).catch(a=>{})};i();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],r=t===e.length-1;this._writer.write(s).then(()=>{r&&$t(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const gr={websocket:mr,webtransport:yr,polling:fr},wr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,vr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Vt(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 r=wr.exec(n||""),i={},o=14;for(;o--;)i[vr[o]]=r[o]||"";return t!=-1&&s!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=br(i,i.path),i.queryKey=Er(i,i.query),i}function br(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 Er(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const Ht=typeof addEventListener=="function"&&typeof removeEventListener=="function",bt=[];Ht&&addEventListener("offline",()=>{bt.forEach(n=>n())},!1);class we extends ${constructor(e,t){if(super(),this.binaryType=Zn,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=Vt(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=Vt(t.host).host);xt(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 r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=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=or(this.opts.query)),Ht&&(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"})},bt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=Zs,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&&we.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",we.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 r=this.writeBuffer[s].data;if(r&&(t+=nr(r)),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,$t(()=>{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,r){if(typeof t=="function"&&(r=t,t=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:e,data:t,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),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(we.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(),Ht&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=bt.indexOf(this._offlineEventListener);s!==-1&&bt.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}we.protocol=Zs;class Tr extends we{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;we.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",y=>{if(!s)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;we.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const T=new Error("probe error");T.transport=t.name,this.emitReserved("upgradeError",T)}}))};function i(){s||(s=!0,c(),t.close(),t=null)}const o=y=>{const T=new Error("probe error: "+y);T.transport=t.name,i(),this.emitReserved("upgradeError",T)};function a(){o("transport closed")}function h(){o("socket closed")}function d(y){t&&y.name!==t.name&&i()}const c=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",a),this.off("close",h),this.off("upgrading",d)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",h),this.once("upgrading",d),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 _r=class extends Tr{constructor(e,t={}){const s=typeof e=="object",r=s?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>gr[i]).filter(i=>!!i)),super(s?r:e,r)}};function Ir(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=Vt(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 i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(t&&t.port===s.port?"":":"+s.port),s}const Sr=typeof ArrayBuffer=="function",Ar=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,on=Object.prototype.toString,Or=typeof Blob=="function"||typeof Blob<"u"&&on.call(Blob)==="[object BlobConstructor]",kr=typeof File=="function"||typeof File<"u"&&on.call(File)==="[object FileConstructor]";function ws(n){return Sr&&(n instanceof ArrayBuffer||Ar(n))||Or&&n instanceof Blob||kr&&n instanceof File}function Et(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(Et(n[t]))return!0;return!1}if(ws(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Et(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Et(n[t]))return!0;return!1}function Rr(n){const e=[],t=n.data,s=n;return s.data=Gt(t,e),s.attachments=e.length,{packet:s,buffers:e}}function Gt(n,e){if(!n)return n;if(ws(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]=Gt(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]=Gt(n[s],e));return t}return n}function Cr(n,e){return n.data=Jt(n.data,e),delete n.attachments,n}function Jt(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]=Jt(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Jt(n[t],e));return n}const $r=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var E;(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"})(E||(E={}));class xr{constructor(e){this.replacer=e}encode(e){return(e.type===E.EVENT||e.type===E.ACK)&&Et(e)?this.encodeAsBinary({type:e.type===E.EVENT?E.BINARY_EVENT:E.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===E.BINARY_EVENT||e.type===E.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=Rr(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class vs extends ${constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}: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===E.BINARY_EVENT;s||t.type===E.BINARY_ACK?(t.type=s?E.EVENT:E.ACK,this.reconstructor=new Nr(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(ws(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(E[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===E.BINARY_EVENT||s.type===E.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Fr(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=a}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(i,t)}else s.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=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(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(vs.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case E.CONNECT:return Ns(t);case E.DISCONNECT:return t===void 0;case E.CONNECT_ERROR:return typeof t=="string"||Ns(t);case E.EVENT:case E.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&$r.indexOf(t[0])===-1);case E.ACK:case E.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Nr{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=Cr(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Fr=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Ns(n){return Object.prototype.toString.call(n)==="[object Object]"}const Pr=Object.freeze(Object.defineProperty({__proto__:null,Decoder:vs,Encoder:xr,get PacketType(){return E}},Symbol.toStringTag,{value:"Module"}));function z(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Br=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class an extends ${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=[z(e,"open",this.onopen.bind(this)),z(e,"packet",this.onpacket.bind(this)),z(e,"error",this.onerror.bind(this)),z(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,r,i;if(Br.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:E.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const c=this.ids++,y=t.pop();this._registerAckCallback(c,y),o.id=c}const a=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,h=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._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 r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=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"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,r)=>{const i=(o,a)=>o?r(o):s(a);i.withError=!0,t.push(i),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((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),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:E.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 E.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 E.EVENT:case E.BINARY_EVENT:this.onevent(e);break;case E.ACK:case E.BINARY_ACK:this.onack(e);break;case E.DISCONNECT:this.ondisconnect();break;case E.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(...r){s||(s=!0,t.packet({type:E.ACK,id:e,data:r}))}}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._drainQueue(!0),this.emitReserved("connect")}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:E.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 Ue(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}Ue.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};Ue.prototype.reset=function(){this.attempts=0};Ue.prototype.setMin=function(n){this.ms=n};Ue.prototype.setMax=function(n){this.max=n};Ue.prototype.setJitter=function(n){this.jitter=n};class Wt extends ${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,xt(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 Ue({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||Pr;this.encoder=new r.Encoder,this.decoder=new r.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 _r(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=z(t,"open",function(){s.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=z(t,"error",i);if(this._timeout!==!1){const a=this._timeout,h=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(r),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(z(e,"ping",this.onping.bind(this)),z(e,"data",this.ondata.bind(this)),z(e,"error",this.onerror.bind(this)),z(e,"close",this.onclose.bind(this)),z(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){$t(()=>{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 an(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(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):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 Ke={};function st(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=Ir(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=Ke[r]&&i in Ke[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let h;return a?h=new Wt(s,e):(Ke[r]||(Ke[r]=new Wt(s,e)),h=Ke[r]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(st,{Manager:Wt,Socket:an,io:st,connect:st});const nt="thatopen/document@1",Yt="document.json",cn=["pdf","txt","md","json","csv","tsv","frag"],Fs=()=>`v-${Date.now()}`;function yt(n){return String(n._id??n.id??"")}var ve,ln,Tt;class bs{constructor(e,t){S(this,ve);this.client=e,this.projectId=t}async list(){const e=await this.client.listFolders({projectId:this.projectId});return(await Promise.all(e.map(async s=>{const r=yt(s),i=await this.descriptor(r);return i?{folderId:r,descriptor:i}:null}))).filter(s=>s!==null)}async fromFile(e,t){const s=await this.client.getFile(e),r=String(s.name??""),i=Bs(r,s.fileExtension),o=(t==null?void 0:t.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,s.folderId?String(s.folderId):void 0,this.projectId),h=yt(a);await this.client.updateFile(e,{parentFolderId:h});const d=[],c=await l(this,ve,ln).call(this,s);if(c)try{const R=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:h}),d.push({fileId:c,format:Bs(String(R.name??""),R.fileExtension)})}catch{}((t==null?void 0:t.selfView)??cn.includes(i))&&d.push({fileId:e,format:i});const T={schema:nt,name:o,native:{fileId:e,format:i},views:d};return await this.setDescriptor(h,T),{folderId:h,descriptor:T}}async descriptor(e){const t=await l(this,ve,Tt).call(this,e);if(!t)return null;const r=await(await this.client.downloadFile(t.id)).text();if(!r.trim())return null;let i;try{i=JSON.parse(r)}catch{return null}return qr(i)}async view(e,t){const s=await this.descriptor(e);if(!s)return null;for(const r of t){const i=s.views.find(o=>o.format===r);if(i)return i}return null}async addView(e,t){const s=await this.descriptor(e);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.views=[...s.views.filter(r=>r.format!==t.format),t],await this.setDescriptor(e,s)}async setDescriptor(e,t){const s={...t,schema:nt,views:t.views??[]},r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await l(this,ve,Tt).call(this,e);if(i){await this.client.updateFile(i.id,{file:r,versionTag:Fs()});return}await this.client.createFile({file:r,name:Yt,versionTag:Fs(),parentFolderId:e,projectId:this.projectId})}drafts(e){return new hn(this.client,()=>l(this,ve,Tt).call(this,e))}}ve=new WeakSet,ln=async function(e){const t=[...e.versions??[]].sort((s,r)=>String(r.createdAt??"").localeCompare(String(s.createdAt??"")));for(const s of t)try{const r=await this.client.getFileVersionMetadata(yt(e),s.tag),i=r==null?void 0:r.derivedFileId;if(typeof i=="string"&&i)return i}catch{}},Tt=async function(e){const s=(await this.client.listFiles({folderId:e})).find(r=>String(r.name??"")===Yt);return s?{id:yt(s)}:void 0};const zt="draft:",Ne="TODRAFT1";var se,Qe,Kt;class hn{constructor(e,t){S(this,se);this.client=e,this.holder=t}async list(){const e=await this.holder();if(!e)return[];const t=new Map;for(const s of await l(this,se,Qe).call(this,e.id)){const r=t.get(s.userId);(!r||s.savedAt>r.savedAt)&&t.set(s.userId,{userId:s.userId,savedAt:s.savedAt})}return[...t.values()].sort((s,r)=>+r.savedAt-+s.savedAt)}async get(e){const t=await this.holder();if(!t)return null;const r=(await l(this,se,Qe).call(this,t.id)).filter(h=>!(e!=null&&e.userId)||h.userId===e.userId).sort((h,d)=>+d.savedAt-+h.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await jr(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(e,t){const s=await this.holder();if(!s)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Lr(t.userId),i=(await l(this,se,Qe).call(this,s.id)).filter(h=>h.userId===t.userId),a=(await this.client.createHiddenFile(await Dr(e,t.meta??{}),s.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await l(this,se,Kt).call(this,i.map(h=>h.hiddenId)),{userId:t.userId,savedAt:Ps(a)}}async delete(e){const t=await this.holder();if(!t)return;const s=(await l(this,se,Qe).call(this,t.id)).filter(r=>r.userId===e.userId);await l(this,se,Kt).call(this,s.map(r=>r.hiddenId))}}se=new WeakSet,Qe=async function(e){return(await this.client.getHiddenFilesByParent(e)).filter(s=>typeof s.tag=="string"&&s.tag.startsWith(zt)).map(s=>{const r=String(s._id);return{hiddenId:r,userId:s.tag.slice(zt.length),savedAt:Ps(r)}})},Kt=async function(e){for(const t of e)try{await this.client.deleteHiddenFile(t)}catch{}};function Lr(n){const e=`${zt}${n}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(e))throw new Error(`A draft cannot be tagged for user "${n}": ids must be letters, digits or :._- and short.`);return e}function Ps(n){const e=parseInt(n.slice(0,8),16);return new Date(Number.isFinite(e)?e*1e3:0)}async function Dr(n,e){const t=new TextEncoder().encode(JSON.stringify(e)),s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,t.length,!0),new Blob([new TextEncoder().encode(Ne),s,t,n])}async function jr(n){const e=new Uint8Array(await n.slice(0,Ne.length+4).arrayBuffer());if(new TextDecoder().decode(e.slice(0,Ne.length))!==Ne)return{meta:{},blob:n};const t=new DataView(e.buffer).getUint32(Ne.length,!0),s=Ne.length+4,r=await n.slice(s,s+t).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:n.slice(s+t)}}function Bs(n,e){const t=(e??"").replace(/^\./,"").toLowerCase();if(t)return t;const s=n.lastIndexOf(".");return s>0?n.slice(s+1).toLowerCase():""}function qr(n){if(!n||typeof n!="object")return null;const e=n;if(e.schema!==nt||typeof e.name!="string")return null;const t=Array.isArray(e.views)?e.views.filter(i=>!!i&&typeof i=="object"&&typeof i.fileId=="string"&&typeof i.format=="string"):[],s=e.native,r=!!s&&typeof s=="object"&&typeof s.fileId=="string"&&typeof s.format=="string";return{schema:nt,name:e.name,...r?{native:{fileId:s.fileId,format:s.format}}:{},views:t}}class Xt extends Error{constructor(e,t){super(`The document history advanced while this version was being prepared: expected head ${e}, found ${t??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=e,this.actualGuid=t,this.name="StaleHistoryError"}}const Ls="bimterop",Qt="revitflow_history.json",Fe="revitflow_ops.json",Ds="revitflow/ops@1",dn="revitflow_model.frag",un="revitflow_",Mr="bimterop-locks-anchor",gt=()=>`v-${Date.now()}`;function fn(n,e){return n.filter(t=>String(t.parentId??"")===e)}function js(n){const e=n==null?void 0:n.hiddenFileId;if(typeof e!="string"||!e)throw new Error("The hidden-file upload answered without a hiddenFileId.");return e}function te(n){return String(n._id??n.id??"")}var Y,rt,Zt;class pn{constructor(e,t){S(this,rt);S(this,Y);this.client=e,this.projectId=t}async docs(){const e=await l(this,rt,Zt).call(this);if(!e)return[];const t=await this.client.listFolders({parentFolderId:e,projectId:this.projectId}),s=[];for(const r of fn(t,e)){const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const h=(await this.client.listFiles({folderId:te(r)})).map(y=>String(y.name??"")),d=h.find(y=>y===dn)??h.find(y=>y.endsWith(".frag")&&!y.startsWith(un)),c=h.includes(Qt)||h.includes(Fe)||!!d;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:te(r),modelName:d,...c?{}:{empty:!0}})}return s}doc(e,t){return new mn(this.client,this,e,t)}async rootFolderId(e=!1){if(u(this,Y))return u(this,Y);const t=await l(this,rt,Zt).call(this);if(t)return t;if(!e)return;const s=await this.client.createFolder(Ls,void 0,this.projectId);return C(this,Y,te(s)),u(this,Y)}}Y=new WeakMap,rt=new WeakSet,Zt=async function(){if(u(this,Y))return u(this,Y);const t=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===Ls&&!s.parentId);return t&&C(this,Y,te(t)),u(this,Y)};var ce,p,ae,Pe,ee,es,Ze,ue,ts,_t,et,It,ss,yn;class mn{constructor(e,t,s,r){S(this,p);S(this,ce);this.client=e,this.project=t,this.source=s,this.docId=r}async timeline(){const e=await l(this,p,_t).call(this);return Es((e==null?void 0:e.commits)??[])}async latest(){const e=await this.timeline();return e.length?e[e.length-1]:null}async delta(e){if(!e.deltaId)throw new Error(`Version ${e.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(e.deltaId)).blob()}async model(){const e=await l(this,p,ue).call(this);if(!e)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(e.id)).blob()}async modelParts(e){const t=await this.timeline();if(t.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const s=e==null?void 0:e.at,r=s?t.findIndex(c=>c.guid===s):t.length-1;if(r<0)throw new Error(`No version ${s} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(t[c].full){i=c;break}const o=await l(this,p,ue).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=t[i],h=t.slice(r+1).some(c=>c.full),d=t.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},removedUniqueIds:c.changes.filter(y=>y.type==="delete").map(y=>y.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!h,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:t[r].guid}}async folderId(){return await l(this,p,ee).call(this,!1)}async descriptor(){return await u(this,p,ae).descriptor(await l(this,p,ee).call(this,!1))}async view(e){const t=await l(this,p,ee).call(this,!1),s=await u(this,p,ae).descriptor(t);if(s){for(const i of e){const o=s.views.find(a=>a.format===i);if(o)return o}return null}if(!e.includes("frag"))return null;const r=await l(this,p,ue).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(e){const t=await l(this,p,ee).call(this,!0);if(await u(this,p,ae).descriptor(t)){await u(this,p,ae).addView(t,e);return}const r=await l(this,p,ue).call(this);await u(this,p,ae).setDescriptor(t,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??u(this,p,Pe),views:[e]})}async ensureDescriptor(){const e=await l(this,p,ee).call(this,!1),t=await u(this,p,ae).descriptor(e);if(t)return t;const s=await l(this,p,ue).call(this);if(!s)return null;const r={name:s.name.replace(/\.frag$/,""),views:[{fileId:s.id,format:"frag"}]};return await u(this,p,ae).setDescriptor(e,r),await u(this,p,ae).descriptor(e)}async ownership(){const e=await l(this,p,Ze).call(this,Mr);if(!e)return[];const t=await this.client.getHiddenFilesByParent(e.id),s=await Promise.all(t.map(async o=>{try{const a=te(o),h=await this.client.downloadHiddenFile(a),d=JSON.parse(await h.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(c=>typeof c=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of s)if(o)for(const a of o.keys){if(!a||r.has(a))continue;r.add(a);const h=i.get(o.owner)??[];h.push(a),i.set(o.owner,h)}return[...i.entries()].map(([o,a])=>({owner:o,elements:a}))}async sync(e){var a;const t=await l(this,p,ee).call(this,!0);let s=await l(this,p,_t).call(this)??{model:this.docId,commits:[]};const r=qs(s.commits);if(e.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==e.expectedLatestGuid)throw new Xt(e.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Rt(),...r?{parents:[r.guid]}:{},author:e.author,source:e.source,timestamp:new Date().toISOString(),...e.message?{message:e.message}:{},...e.userId?{userId:e.userId}:{},...(a=e.appliedOps)!=null&&a.length?{appliedOps:e.appliedOps}:{},changes:e.changes,counts:Ur(e.changes)};if(e.model&&(await l(this,p,yn).call(this,t,e.model),i.full=!0),e.delta){const h=await l(this,p,ue).call(this);if(!h)throw new Error("A delta needs the model file to hang from: sync a full model first.");const d=await this.client.createHiddenFile(e.delta,h.id);i.deltaId=js(d)}const o=await l(this,p,_t).call(this);if(o){s=o;const h=qs(s.commits);if(e.expectedLatestGuid!==void 0&&(h==null?void 0:h.guid)!==e.expectedLatestGuid)throw new Xt(e.expectedLatestGuid,h==null?void 0:h.guid);h&&!i.parents&&(i.parents=[h.guid])}return s.commits.push(i),await l(this,p,It).call(this,t,Qt,s),i}async suggestions(){const e=await l(this,p,et).call(this);return(e==null?void 0:e.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(e=>e.state==="pending")}async suggest(e){const t=await l(this,p,ee).call(this,!0),s=await l(this,p,et).call(this)??{schema:Ds,ops:[]},r=await l(this,p,Ze).call(this,Fe),i={opId:e.opId??Rt(),to:e.to??this.source,title:e.title,verb:e.verb,author:e.author,createdAt:new Date().toISOString(),state:"pending",...e.targets!==void 0?{targets:e.targets}:{},...e.batchId?{batchId:e.batchId}:{},...e.userId?{userId:e.userId}:{},...e.baseCommitGuid?{baseCommitGuid:e.baseCommitGuid}:{}};if(e.payload){const a=r??await l(this,p,ss).call(this,t,Fe,s),h=await this.client.createHiddenFile(e.payload,a.id);i.fragId=js(h)}const o=await l(this,p,et).call(this)??s;return o.schema??(o.schema=Ds),o.ops.push(i),await l(this,p,It).call(this,t,Fe,o),i}async suggestionPayload(e){if(!e.fragId)throw new Error(`Suggestion ${e.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(e.fragId)).blob()}async resolveSuggestion(e,t){const s=await l(this,p,ee).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await l(this,p,et).call(this),i=r==null?void 0:r.ops.find(o=>o.opId===e);if(!r||!i)throw new Error(`No suggestion ${e} in this document's queue.`);return Object.assign(i,t),await l(this,p,It).call(this,s,Fe,r),i}}ce=new WeakMap,p=new WeakSet,ae=function(){return new bs(this.client,this.project.projectId)},Pe=function(){return`${this.source}-${this.docId}`},ee=async function(e){if(u(this,ce))return u(this,ce);const t=await this.project.rootFolderId(e);if(!t)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=await this.client.listFolders({parentFolderId:t,projectId:this.project.projectId}),r=fn(s,t).find(o=>String(o.name??"")===u(this,p,Pe));if(r)return C(this,ce,te(r)),u(this,ce);if(!e)throw new Error(`Document ${u(this,p,Pe)} does not exist in this project.`);const i=await this.client.createFolder(u(this,p,Pe),t,this.project.projectId);return C(this,ce,te(i)),u(this,ce)},es=async function(){const e=await l(this,p,ee).call(this,!1);return(await this.client.listFiles({folderId:e})).map(s=>({id:te(s),name:String(s.name??"")}))},Ze=async function(e){try{return(await l(this,p,es).call(this)).find(t=>t.name===e)}catch{return}},ue=async function(){try{const e=await l(this,p,es).call(this);return e.find(t=>t.name===dn)??e.find(t=>t.name.endsWith(".frag")&&!t.name.startsWith(un))}catch{return}},ts=async function(e){const t=await l(this,p,Ze).call(this,e);if(!t)return;const r=await(await this.client.downloadFile(t.id)).text();if(r.trim())return JSON.parse(r)},_t=function(){return l(this,p,ts).call(this,Qt)},et=function(){return l(this,p,ts).call(this,Fe)},It=async function(e,t,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await l(this,p,Ze).call(this,t);return i?(await this.client.updateFile(i.id,{file:r,versionTag:gt()}),i):await l(this,p,ss).call(this,e,t,s)},ss=async function(e,t,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:r,name:t,versionTag:gt(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:te(o??i),name:t}},yn=async function(e,t){const s=await l(this,p,ue).call(this);if(s)return await this.client.updateFile(s.id,{file:t,versionTag:gt()}),s;const r=`${u(this,p,Pe)}.frag`,i=await this.client.createFile({file:t,name:r,versionTag:gt(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:te(o??i),name:r}};function Ur(n){const e={added:0,modified:0,removed:0};for(const t of n)t.type==="create"?e.added++:t.type==="delete"?e.removed++:e.modified++;return e}function Es(n){var h;if(n.length<=1)return n.forEach((d,c)=>d.ordinal=c),[...n];const e=new Map(n.map(d=>[d.guid,d])),t=new Map,s=[];for(const d of n){const c=(h=d.parents)==null?void 0:h[0];if(c&&e.has(c)){const y=t.get(c)??[];y.push(d),t.set(c,y)}else s.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));s.sort(r);const i=[],o=[...s].reverse(),a=new Set;for(;o.length;){const d=o.pop();if(a.has(d.guid))continue;a.add(d.guid),i.push(d);const c=(t.get(d.guid)??[]).sort(r);for(let y=c.length-1;y>=0;y--)o.push(c[y])}for(const d of n)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function qs(n){const e=Es(n);return e[e.length-1]}function Rt(){const n=globalThis.crypto;return n!=null&&n.randomUUID?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var pe,it,ns;class gn{constructor(e){S(this,it);S(this,pe,new Map);this.client=e}register(e){if(u(this,pe).has(e.name))throw new Error(`A recipe named "${e.name}" is already registered.`);u(this,pe).set(e.name,e)}list(e){return[...u(this,pe).values()].filter(s=>(!(e!=null&&e.to)||s.to===e.to)&&(!(e!=null&&e.input)||s.inputs.includes(e.input)))}get(e){return u(this,pe).get(e)}async plan(e,t){const{base:s,opId:r,result:i}=await l(this,it,ns).call(this,e,t);return{opId:r,projectId:t.projectId,target:t.target,...s!=null&&s.guid?{baseCommitGuid:s.guid}:{},result:i}}async queue(e,t){return{suggestion:await this.client.history(e.projectId).doc(e.target.source,e.target.docId).suggest({opId:e.opId,title:e.result.title,verb:e.result.verb,author:t.author,payload:e.result.payload,targets:e.result.targets,userId:t.userId,baseCommitGuid:e.baseCommitGuid}),result:e.result}}async run(e,t){const{targetDoc:s,base:r,opId:i,result:o}=await l(this,it,ns).call(this,e,t);return{suggestion:await s.suggest({opId:i,title:o.title,verb:o.verb,author:t.author,payload:o.payload,targets:o.targets,userId:t.userId,baseCommitGuid:r==null?void 0:r.guid}),result:o}}}pe=new WeakMap,it=new WeakSet,ns=async function(e,t){const s=u(this,pe).get(e);if(!s)throw new Error(`No recipe named "${e}" is registered.`);if(s.to!==t.target.source)throw new Error(`Recipe "${e}" writes ${s.to}, but the target document belongs to ${t.target.source}.`);const r=this.client.history(t.projectId).doc(t.target.source,t.target.docId),i=await r.latest(),o=Rt(),a=await s.run({client:this.client,projectId:t.projectId,targetDoc:r,opId:o,input:t.input,settings:t.settings??{}});return{recipe:s,targetDoc:r,base:i,opId:o,result:a}};const rs=100;function Vr(n){try{const e=JSON.parse(n);if(e&&typeof e=="object"){const t=e;return{message:typeof t.message=="string"?t.message:void 0,code:typeof t.code=="string"?t.code:void 0,details:t.details}}}catch{}return{}}function Hr(n){if(!n||typeof n!="object")return;const e=n.retryAfter;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}class Nt extends Error{constructor(t,s,r,i){const o=Vr(r);super(o.message??`${s||"Request failed"} (${t})`);L(this,"status");L(this,"code");L(this,"details");L(this,"body");L(this,"retryAfter");this.name="RequestError",this.status=t,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??Hr(o.details)}}const Z="item/folder",v="item",de="processor",Gr="npm-registry",oe="hidden",jt="FILE",qt="TOOL",Mt="APP",Jr=500,Ms=3e4,Wr=.25,Yr=n=>new Promise(e=>setTimeout(e,n));function zr(n){var r,i;const e=(i=(r=n.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!e)return;const t=Number(e);if(Number.isFinite(t))return Math.max(0,t);const s=Date.parse(e);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function Kr(n){return n instanceof Nt?n.status===429||n.status>=500:!0}function Xr(n,e){const t=Math.min(Jr*2**e,Ms),s=t*Wr*Math.random(),r=n instanceof Nt&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,Ms)+s:t+s}var f,is,g,fe,ot,tt,St,At,os,as,wn;const As=class As{constructor(e,t,s){S(this,f);L(this,"apiUrl");L(this,"accessToken");L(this,"wsUrl");L(this,"retries");L(this,"useBearer");L(this,"builtInGlobals",null);L(this,"localServerUrl",null);L(this,"context");S(this,ot);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=s||{};let a=t;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=e,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:e,apiUrl:t},o){let h=o;h.charAt(h.length-1)==="/"&&(h=h.slice(0,-1)),this.localServerUrl=h}}static fromPlatformContext(e){const t=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new As(t.accessToken,t.apiUrl,{...e,useBearer:!0});return s.context=t,s}setRetries(e){this.retries=e}setBuiltInGlobals(e){this.builtInGlobals=e}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(e,t,s){return l(this,f,g).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await l(this,f,g).call(this,"GET",`${Z}/${t}/items`,{query:{itemType:jt,archived:s}}):await l(this,f,g).call(this,"GET",`${v}`,{query:{itemType:jt,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await l(this,f,as).call(this,e,t)}async createFile(e){return await l(this,f,At).call(this,e,jt)}async updateFile(e,t){return await l(this,f,os).call(this,e,t)}async archiveFile(e){return await l(this,f,g).call(this,"DELETE",`${v}/${e}`)}async recoverFile(e){return await l(this,f,g).call(this,"PUT",`${v}/${e}/recover`)}async downloadFile(e,t){return await l(this,f,St).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await l(this,f,g).call(this,"GET",`${v}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await l(this,f,g).call(this,"PUT",`${v}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await l(this,f,g).call(this,"DELETE",`${v}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await l(this,f,tt).call(this,e,async r=>(await l(this,f,g).call(this,"POST",`${v}/batch/version-metadata`,{body:JSON.stringify({entries:r,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(e){const{archived:t,parentFolderId:s,projectId:r}=e||{};return await l(this,f,g).call(this,"GET",Z,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await l(this,f,g).call(this,"GET",`${Z}/${e}`)}async getFoldersBatch(e){return await l(this,f,tt).call(this,e,async t=>(await l(this,f,g).call(this,"POST",`${v}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await l(this,f,g).call(this,"POST",Z,{body:JSON.stringify({name:e,...t&&{parentId:t},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(e,t){const{name:s}=t;return await l(this,f,g).call(this,"PUT",`${Z}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await l(this,f,g).call(this,"DELETE",`${Z}/${e}`)}async recoverFolder(e){return await l(this,f,g).call(this,"PUT",`${Z}/${e}/recover`)}async downloadFolder(e){return await l(this,f,fe).call(this,`${Z}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await l(this,f,g).call(this,"GET",`${Z}/${t}/items`,{query:{itemType:qt,...s&&{ShowVersions:s}}}):await l(this,f,g).call(this,"GET",`${v}`,{query:{itemType:qt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await l(this,f,as).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await l(this,f,At).call(this,e,qt,t)}async updateComponent(e,t){const{componentProps:s}=t;return await l(this,f,os).call(this,e,t,s)}async downloadComponent(e,t){return await l(this,f,St).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await l(this,f,fe).call(this,`${v}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await l(this,f,g).call(this,"DELETE",`${v}/${e}`)}async recoverComponent(e){return await l(this,f,g).call(this,"PUT",`${v}/${e}/recover`)}async getBuiltInComponent(e){return await(await l(this,f,fe).call(this,`built-in/${e}/bundle`)).text()}async initBuiltInComponent(e,t,s){const r=await this.getBuiltInComponent(e.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(y=>i[y]),d=new Function(...o,`${r}
2
+ return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;t.get(c)}async initBuiltInComponents(e,...t){await Promise.all(t.map(s=>this.initBuiltInComponent(s,e)))}async setup(e,...t){var o,a;const s=e.OBC,r=e.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return r.Manager.init(),this.setBuiltInGlobals(e),await this.initBuiltInComponents(i,...t),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(e,t){var s,r;(r=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||r.call(s,e,t)}async listApps(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await l(this,f,g).call(this,"GET",`${Z}/${t}/items`,{query:{itemType:Mt,...s&&{ShowVersions:s}}}):await l(this,f,g).call(this,"GET",`${v}`,{query:{itemType:Mt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await l(this,f,At).call(this,e,Mt,t)}async downloadApp(e,t){return await l(this,f,St).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await l(this,f,fe).call(this,`${v}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await l(this,f,g).call(this,"DELETE",`${v}/${e}`)}async getNpmCredentials(){return await l(this,f,g).call(this,"GET",`${Gr}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${de}/${e}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await l(this,f,g).call(this,"POST",`${de}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${de}/progress/${e}/abort`,s=await fetch(t,{method:"POST"});if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await l(this,f,g).call(this,"POST",`${de}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${de}/${e}/progress${s}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await l(this,f,g).call(this,"GET",`${de}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${de}/progress/${e}`,s=await fetch(t);if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await l(this,f,g).call(this,"GET",`${de}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl??this.wsUrl,r=await st(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:e})),r.on("execution",i=>{t(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(e){return new bs(this,e)}history(e){return new pn(this,e)}get recipes(){return u(this,ot)??C(this,ot,new gn(this)),u(this,ot)}async createHiddenFile(e,t,s){const r=new FormData;return r.append("file",e),r.append("parentItemId",t),s!=null&&r.append("tag",s),await l(this,f,g).call(this,"POST",`${v}/${oe}`,{body:r})}async createHiddenFilesBatch(e,t,s){const r=new FormData;for(const i of e)r.append("files",i);return r.append("parentItemId",t),s!=null&&r.append("tag",s),await l(this,f,g).call(this,"POST",`${v}/${oe}/batch`,{body:r})}async deleteHiddenFile(e){return await l(this,f,g).call(this,"DELETE",`${v}/${oe}/${e}`)}async getHiddenFile(e){return await l(this,f,g).call(this,"GET",`${v}/${oe}/${e}`)}async downloadHiddenFile(e){return await l(this,f,fe).call(this,`${v}/${oe}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await l(this,f,g).call(this,"GET",`${v}/${oe}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await l(this,f,tt).call(this,e,async s=>(await l(this,f,g).call(this,"POST",`${v}/${oe}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...t!=null&&{expiresIn:t}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(e,t){return await l(this,f,g).call(this,"GET",`${v}/${e}/${oe}`,{...t!=null&&{query:{tag:t}}})}async deleteHiddenFilesByParent(e){return await l(this,f,g).call(this,"DELETE",`${v}/${e}/${oe}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await l(this,f,g).call(this,"PUT",`${v}/${e}/icon`,{body:s})}async getItemIcon(e){return await l(this,f,fe).call(this,`${v}/${e}/icon`)}async removeItemIcon(e){return await l(this,f,g).call(this,"DELETE",`${v}/${e}/icon`)}async updateItem(e,t){return await l(this,f,g).call(this,"PUT",`${v}/${e}`,{body:JSON.stringify(t),contentType:"application/json"})}async createVersion(e,t,s,r,i){const o=new FormData;return o.append("file",t),o.append("versionTag",s),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await l(this,f,g).call(this,"POST",`${v}/${e}/version`,{body:o})}async listVersions(e,t={}){return await l(this,f,g).call(this,"GET",`${v}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await l(this,f,tt).call(this,e,async r=>(await l(this,f,g).call(this,"POST",`${v}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(e,t){return await l(this,f,g).call(this,"PUT",`${v}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await l(this,f,g).call(this,"PUT",`${v}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await l(this,f,g).call(this,"DELETE",`${v}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};f=new WeakSet,is=function(e){return`${this.apiUrl}/${e}`},g=async function(e,t,s){const{body:r,query:i,contentType:o,retries:a,responseType:h,retryAttempt:d}=s||{},c=l(this,f,is).call(this,t),y=l(this,f,wn).call(this,i),T=await this.resolveAccessToken(),R={...y,...this.useBearer?{}:{accessToken:T}};try{const _=await fetch(c+"?"+new URLSearchParams(R).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${T}`}},...r&&{body:r}});if(!_.ok){const b=await _.text().then(B=>B).catch(()=>"");throw new Nt(_.status,_.statusText,b,zr(_))}return h==="blob"?await _.blob():_.json().then(b=>b).catch(()=>{})}catch(_){const b=a??this.retries;if(b>0&&Kr(_)){const B=d??0;return await Yr(Xr(_,B)),await l(this,f,g).call(this,e,t,{...s,retries:b-1,retryAttempt:B+1})}throw _}},fe=async function(e,t){const{query:s}=t||{},r=l(this,f,is).call(this,e),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},ot=new WeakMap,tt=async function(e,t){if(!e.length)return[];const s=[];for(let i=0;i<e.length;i+=rs)s.push(e.slice(i,i+rs));return(await Promise.all(s.map(t))).flat()},St=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await l(this,f,fe).call(this,`${v}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},At=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:h,metadata:d}=e,c=new FormData;return c.append("file",h),c.append("name",r),c.append("versionTag",i),c.append("itemType",t),o&&c.append("folderId",o),a&&c.append("projectId",a),s&&c.append("extraProps",JSON.stringify(s)),d&&c.append("metadata",JSON.stringify(d)),await l(this,f,g).call(this,"POST",v,{body:c})},os=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:h}=t;let d,c;if(a){const y=new FormData;y.append("file",a),i&&y.append("versionTag",i),s&&y.append("extraProps",JSON.stringify(s)),h&&y.append("metadata",JSON.stringify(h)),c=await l(this,f,g).call(this,"POST",`${v}/${e}/version`,{body:y})}if(r||o){const y={...r&&{name:r},...o&&{folderId:o}},T=JSON.stringify(y);d=await l(this,f,g).call(this,"PUT",`${v}/${e}`,{body:T,contentType:"application/json"})}return{item:d,version:c}},as=async function(e,t){const{showVersions:s=!1}=t||{};return await l(this,f,g).call(this,"GET",`${v}/${e}`,{query:{showVersions:s}})},wn=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let Ct=As;function vn(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const e=t=>{t.source===window.parent&&n(t.data)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}}}const cs="channel:",Qr=1e4;function Ot(n){try{n()}catch(e){console.error("[channel] a listener threw:",e)}}var le,H,G,Le,De,je,M,ls,hs,Be;class Ts{constructor(e,t){S(this,M);S(this,le,!1);S(this,H,[]);S(this,G,[]);S(this,Le,new Set);S(this,De,new Set);S(this,je,new Set);this.transport=e,this.controls=t}get joined(){return u(this,le)}get peers(){return u(this,H)}join(){return u(this,le)?Promise.resolve():l(this,M,ls).call(this,"joined",this.controls.join)}leave(){return!u(this,le)&&!u(this,G).some(e=>e.want==="joined")?Promise.resolve():l(this,M,ls).call(this,"left",this.controls.leave)}onChange(e){return u(this,Le).add(e),()=>void u(this,Le).delete(e)}onPeerJoined(e){return u(this,De).add(e),()=>void u(this,De).delete(e)}onPeerLeft(e){return u(this,je).add(e),()=>void u(this,je).delete(e)}applyJoined(){C(this,le,!0),l(this,M,hs).call(this,"joined"),l(this,M,Be).call(this)}applyLeft(){C(this,le,!1),C(this,H,[]),l(this,M,hs).call(this,"left"),l(this,M,Be).call(this)}applyPeers(e){C(this,H,e),l(this,M,Be).call(this)}applyPeerJoined(e){!u(this,le)||u(this,H).some(t=>t.from===e.from)||(C(this,H,[...u(this,H),e]),u(this,De).forEach(t=>Ot(()=>t(e))),l(this,M,Be).call(this))}applyPeerLeft(e){const t=u(this,H).find(s=>s.from===e);t&&(C(this,H,u(this,H).filter(s=>s.from!==e)),u(this,je).forEach(s=>Ot(()=>s(t))),l(this,M,Be).call(this))}failPending(e){const t=u(this,G);return C(this,G,[]),t.forEach(s=>{clearTimeout(s.timer),s.reject(e)}),t.length>0}post(e){this.transport.post(e)}}le=new WeakMap,H=new WeakMap,G=new WeakMap,Le=new WeakMap,De=new WeakMap,je=new WeakMap,M=new WeakSet,ls=function(e,t){return new Promise((s,r)=>{const i={want:e,resolve:s,reject:r,timer:setTimeout(()=>{C(this,G,u(this,G).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${e==="joined"?"joining":"leaving"} in time.`))},Qr)};u(this,G).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...t})})},hs=function(e){const t=u(this,G).filter(s=>s.want===e);C(this,G,u(this,G).filter(s=>s.want!==e)),t.forEach(s=>{clearTimeout(s.timer),s.resolve()})},Be=function(){u(this,Le).forEach(e=>Ot(e))};var qe;class bn extends Ts{constructor(t){super(t,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});S(this,qe,new Map)}on(t,s){const r=u(this,qe).get(t)??new Set;return r.add(s),u(this,qe).set(t,r),()=>void r.delete(s)}send(t,s){if(t.startsWith(cs))throw new Error(`Message types starting with '${cs}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:t,payload:s}})}accepts(t){return t===void 0||t==="collab"}async handle(t){const s=u(this,qe).get(t.type);if(!(s!=null&&s.size))return{handled:!1};const r=Tn(t);return s.forEach(i=>Ot(()=>i(t.payload,r))),{handled:!0}}}qe=new WeakMap;var me;class En extends Ts{constructor(t,s){super(t,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});S(this,me,new Map);this.kind=s}on(t,s){if(u(this,me).has(t))throw new Error(`"${t}" already has a handler in this room. Remove it first.`);return u(this,me).set(t,s),()=>void u(this,me).delete(t)}accepts(t,s){return t!==void 0&&t!=="external"?!1:this.kind===void 0||t===void 0||this.kind===s}get hasHandlers(){return u(this,me).size>0}async handle(t){const s=u(this,me).get(t.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(t.payload,Tn(t))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}me=new WeakMap;function Tn(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function Zr(n){const e=n;if((e==null?void 0:e.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const t=e.message;return!t||typeof t.type!="string"?null:{type:t.type,requestId:typeof t.requestId=="string"?t.requestId:void 0,payload:t.payload,at:typeof t.at=="number"?t.at:Date.now(),from:typeof t.from=="string"?t.from:"",scope:t.scope==="collab"||t.scope==="external"?t.scope:void 0,kind:typeof t.kind=="string"?t.kind:void 0}}var ke,at,he,ye,ge,N,ds,kt,In,Sn,An,us;class _n{constructor(e){S(this,N);S(this,ke);S(this,at);S(this,he);S(this,ye,new Map);S(this,ge,new Set);C(this,ke,e),C(this,at,e.listen(t=>void l(this,N,In).call(this,t)))}collab(){return u(this,he)??C(this,he,new bn(u(this,ke))),u(this,he)}external(e){const t=e??"";let s=u(this,ye).get(t);return s||(s=new En(u(this,ke),e),u(this,ye).set(t,s)),s}dispose(){u(this,at).call(this)}}ke=new WeakMap,at=new WeakMap,he=new WeakMap,ye=new WeakMap,ge=new WeakMap,N=new WeakSet,ds=function(){return[...u(this,he)?[u(this,he)]:[],...u(this,ye).values()]},kt=function(e,t){if(e==="collab")return u(this,he);if(e==="external")return u(this,ye).get(typeof t=="string"?t:"")},In=async function(e){const t=Zr(e);if(t){if(t.type.startsWith(cs)){l(this,N,Sn).call(this,t);return}await l(this,N,An).call(this,t)}},Sn=function(e){var s,r,i;const t=e.payload??{};switch(e.type){case"channel:joined":(s=l(this,N,kt).call(this,t.scope,t.kind))==null||s.applyJoined();break;case"channel:left":(r=l(this,N,kt).call(this,t.scope,t.kind))==null||r.applyLeft();break;case"channel:peers":(i=l(this,N,kt).call(this,t.scope,t.kind))==null||i.applyPeers(t.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!t.from)break;const o=t.scope==="collab"?[u(this,he)]:[...u(this,ye).values()].filter(a=>a.accepts("external",t.kind));for(const a of o)e.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:t.from,kind:t.kind}):a==null||a.applyPeerLeft(t.from);break}case"channel:error":{const o=new Error(String(e.payload));l(this,N,ds).call(this).map(h=>h.failPending(o)).some(Boolean)||console.error("[channel] error:",e.payload);break}}},An=async function(e){const t=l(this,N,ds).call(this).filter(i=>i.accepts(e.scope,e.kind));let s=!1;for(const i of t){const o=await i.handle(e);o.handled&&(s=!0,e.requestId&&l(this,N,us).call(this,e.requestId,o))}e.requestId&&e.scope==="external"&&t.length>0&&!s&&l(this,N,us).call(this,e.requestId,{handled:!0,error:`No handler for "${e.type}".`})},us=function(e,t){u(this,ge).has(e)||(u(this,ge).add(e),u(this,ge).size>500&&u(this,ge).delete(u(this,ge).values().next().value),u(this,ke).post({type:"APP_CHANNEL_PUBLISH",message:{type:t.error===void 0?"reply":"reply-error",requestId:e,payload:t.error===void 0?t.value:{error:t.error}}}))};const Oe="project",$e="notifications";var Me,ct;const Os=class Os extends Ct{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});S(this,Me);S(this,ct);typeof t=="function"&&C(this,Me,t)}async resolveAccessToken(){return u(this,Me)?await u(this,Me).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Os(s.accessToken,s.apiUrl,t);return r.context=s,r}get channel(){return u(this,ct)??C(this,ct,new _n(vn())),u(this,ct)}async listProjects(){return await this.request("GET",Oe)}async getProject(t){return await this.request("GET",`${Oe}/${t}`)}async getProjectData(t){return await this.request("GET",`${Oe}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${Oe}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${Oe}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",$e,{query:{...(t==null?void 0:t.cursor)!==void 0&&{cursor:t.cursor},...(t==null?void 0:t.limit)!==void 0&&{limit:String(t.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${$e}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${$e}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${$e}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${$e}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${$e}/subscriptions/${t}`)}async subscribeToAutomation(t,s,r){return await this.request("POST",`${Oe}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,r){return await this.request("PATCH",`${Oe}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),r=st(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return r.on("notification.created",i=>t({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>t({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>t({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};Me=new WeakMap,ct=new WeakMap;let fs=Os;async function _s(n){const[e,t]=await ei(),s=t.Model.getRootAsModel(new e.ByteBuffer(await ti(n)));let r={};try{r=JSON.parse(s.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<s.guidsLength();a++){const h=s.guidsItems(a),d=s.guids(a);h!==null&&d&&i.set(h,d)}const o=[];for(let a=0;a<s.attributesLength();a++){const h=s.localIds(a);if(h===null)continue;const d={},c=s.attributes(a);for(let y=0;y<((c==null?void 0:c.dataLength())??0);y++){const T=c.data(y);if(T)try{const[R,_]=JSON.parse(T);d[R]=_}catch{}}o.push({localId:h,guid:i.get(h)??null,category:s.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function ei(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(n){throw new Error(`readFrag needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` resolvable (in Node, fragments also pulls its own imports, e.g. web-ifc). (${n instanceof Error?n.message:String(n)})`)}}async function ti(n){const e=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const si="flow:",ni="flow:op",ri="flow:source",On="revitflow/op@2",Us="REVITFLOWCHANGE",Vs="REVITFLOWOPERATION";class Is{constructor(e){L(this,"changes",[]);this.target=e}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(e,t={}){return this.changes.push({op:"add",attrs:this.pack(e,t)}),this}set(e,t,s={}){return this.requireId(e,"set"),this.changes.push({op:"set",item:e,attrs:this.pack(t,s)}),this}remove(e){return this.requireId(e,"remove"),this.changes.push({op:"remove",item:e,attrs:{}}),this}get summary(){const e=new Set(this.changes.map(t=>t.op));return e.size===1?[...e][0]:"mixed"}async build(e){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const t={schema:On,opId:e,batchId:this.batchId??e,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[s,r]=await ii();return oi(this.flatbuffer(s,r,e,JSON.stringify(t)))}pack(e,t){const s={};for(const[r,i]of Object.entries(e??{}))r.startsWith(si)||(s[r]=String(i));return t.position&&(s.Position=t.position.map(Hs).join(",")),t.rotationDeg!==void 0&&(s.Rotation=Hs(t.rotationDeg)),t.source&&(s[ri]=t.source),s}requireId(e,t){if(!e||!e.trim())throw new Error(`A '${t}' has to name the item it acts on.`)}flatbuffer(e,t,s,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:h,Transform:d}=t,c=new e.Builder(1024),y=this.changes.length,T=new Uint32Array(y);let R=1;for(let O=0;O<y;O++)T[O]=R++;const _=R++,b=O=>(O(c,0),c.endVector()),B=o.createShellsVector(c,[]),be=o.createCircleExtrusionsVector(c,[]),W=b(o.startSamplesVector),K=b(o.startRepresentationsVector),Ve=b(o.startMaterialsVector),X=b(o.startLocalTransformsVector),k=b(o.startGlobalTransformsVector),U=o.createMeshesItemsVector(c,[]),Q=o.createMaterialIdsVector(c,[]),Ee=o.createRepresentationIdsVector(c,[]),Te=o.createSampleIdsVector(c,[]),_e=o.createLocalTransformIdsVector(c,[]),He=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,k),o.addShells(c,B),o.addRepresentations(c,K),o.addSamples(c,W),o.addLocalTransforms(c,X),o.addMaterials(c,Ve),o.addCircleExtrusions(c,be),o.addMeshesItems(c,U),o.addRepresentationIds(c,Ee),o.addSampleIds(c,Te),o.addMaterialIds(c,Q),o.addLocalTransformIds(c,_e),o.addGlobalTransformIds(c,He);const Ge=o.endMeshes(c),Ie=c.createString(r),Je=new Set,Re=[];for(const O of this.changes){const x=[],Ce={[ni]:O.op,...O.attrs};for(const[Se,ie]of Object.entries(Ce)){const V=JSON.stringify([Se,ie,"IFCTEXT"]);Je.add(V),x.push(c.createString(V))}Re.push(i.createAttribute(c,i.createDataVector(c,x)))}{const O=JSON.stringify(["Name",s,"IFCLABEL"]);Je.add(O);const x=i.createDataVector(c,[c.createString(O)]);Re.push(i.createAttribute(c,x))}const lt=a.createAttributesVector(c,Re),ht=a.createUniqueAttributesVector(c,[...Je].map(O=>c.createString(O))),We=this.changes.map(()=>c.createString(Us));We.push(c.createString(Vs));const dt=a.createCategoriesVector(c,We),Ye=[],ze=[];this.changes.forEach((O,x)=>{O.item&&(Ye.push(c.createString(O.item)),ze.push(T[x]))});const ut=a.createGuidsVector(c,Ye),m=a.createGuidsItemsVector(c,ze),w=a.createLocalIdsVector(c,[...T,_]),I=this.changes.map((O,x)=>h.createSpatialStructure(c,T[x],c.createString(Us),0)),A=h.createSpatialStructure(c,_,c.createString(Vs),h.createChildrenVector(c,I)),F=c.createString(s);a.startModel(c),a.addMeshes(c,Ge),a.addMetadata(c,Ie),a.addAttributes(c,lt),a.addUniqueAttributes(c,ht),a.addLocalIds(c,w),a.addCategories(c,dt),a.addGuidsItems(c,m),a.addGuids(c,ut),a.addGuid(c,F),a.addSpatialStructure(c,A),a.addMaxLocalId(c,R);const D=a.endModel(c);return a.finishModelBuffer(c,D),c.asUint8Array()}}async function ii(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(n){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${n instanceof Error?n.message:String(n)})`)}}function Hs(n){return Number.isFinite(n)?String(n):"0"}async function oi(n){const e=new Blob([n]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const ai="Element",ci="Carried",kn=1/.3048;function li(n){const e=[];for(const t of n)for(const s of[ai,ci]){const r=t.attrs[s];if(r)try{const i=JSON.parse(r);for(const o of Array.isArray(i)?i:[i]){const a=o;typeof(a==null?void 0:a.id)!="string"||typeof(a==null?void 0:a.kind)!="string"||e.push({id:a.id,kind:a.kind,params:a.params??{},item:t})}}catch{}}return e}function wt(n,e){const t=n.params[e];if(typeof t!="string")return null;try{return JSON.parse(t)}catch{return null}}function hi(n){const e=new Map;for(const t of n){if(t.kind!=="datum"||t.params.of!=="level")continue;const s=t.params.named,r=t.params.at;typeof s=="string"&&typeof r=="number"&&e.set(t.id,{name:s,at:r})}return e}function di(n){const e=new Map;for(const t of n){if(!t.kind.endsWith("Style"))continue;const s=t.params.name;typeof s=="string"&&e.set(s,t)}return e}async function Rn(n,e){const t=new Map,s=(await n.targetDoc.suggestions()).filter(r=>{var i;return r.author===e&&r.state==="applied"&&r.fragId&&(((i=r.affectedIds)==null?void 0:i.length)??0)>0}).sort((r,i)=>String(r.createdAt).localeCompare(String(i.createdAt)));for(const r of s)try{const i=await n.targetDoc.suggestionPayload(r),{items:o}=await _s(new Uint8Array(await i.arrayBuffer())),a=o.filter(d=>d.attrs["flow:op"]),h=r.affectedIds??[];for(let d=0;d<a.length&&d<h.length;d++){const c=a[d].attrs["flow:source"];c&&(a[d].attrs["flow:op"]==="remove"?t.delete(c):t.set(c,h[d]))}}catch{}return t}async function Cn(n,e){if(!(e!=null&&e.fileId))throw new Error("Choose the model file to read.");const t=new Uint8Array(await(await n.client.downloadFile(e.fileId)).arrayBuffer());return{picked:e,contents:await _s(t)}}const xe={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300"};function ps(n){const e=n.item.attrs.Name;if(typeof e!="string")return null;const t=e.indexOf(":"),s=e.lastIndexOf(":");if(t<=0||s<=t)return null;const r=e.slice(t+1,s).trim();return r?{family:e.slice(0,t).trim(),type:r}:null}function ui(n){const e=ps(n),t=n.item.attrs.PredefinedType;return e?/escalera|stair|landing|descansillo/i.test(e.family)||t==="LANDING"||/plataforma|^pad\b|building pad/i.test(e.family)?"other":/cubierta|roof/i.test(e.family)||t==="ROOF"?"roof":/cimentaci|foundation/i.test(e.family)||t==="BASESLAB"?"foundation":"floor":"floor"}const Gs=180/Math.PI;function Js(n){if(typeof n!="string")return null;const e=n.indexOf(":");return e<=0||e===n.length-1?null:{family:n.slice(0,e),type:n.slice(e+1)}}const q=n=>String(n);function $n(n){return async e=>{var Re,lt,ht,We,dt,Ye,ze,ut;const{picked:t,contents:s}=await Cn(e,e.input),r=li(s.items);if(r.length===0)throw new Error(n==="ifc"?`"${t.name}" carries no platform records: it was imported without the editable converter. Process the IFC with the editable converter first; a plain import only has IFC attributes, and guessing geometry is not this recipe.`:`"${t.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:i,trustStyleNames:o,includeInstances:a}=e.settings,h=e.settings.createLevels!==!1;if(a&&!o)throw new Error("Free-standing instances can only be proposed by their style names: turn trustStyleNames on.");const d=hi(r),c=di(r),y=`recipe:${n}-to-revit`,T=await Rn(e,y),R=await e.targetDoc.latest(),_=new Is({project:e.projectId,document:e.targetDoc.docId,baseCommit:(R==null?void 0:R.version)??0,author:y}),b=kn,B=m=>`${t.fileId}:${m}`,be=new Set;let W=0;const K=(m,w,I)=>(be.add(m),T.has(m)?(W++,!1):(_.add(w,{...I,source:m}),!0)),Ve=m=>{const w=typeof m=="string"?c.get(m):void 0,I=w==null?void 0:w.params.thickness;return typeof I=="number"&&I>0?I*b:void 0};let X=0;if(h)for(const[m,w]of d)K(B(m),{CategoryId:xe.levels,Name:w.name,Elevation:q(w.at*b)}),X++;let k=0,U=0;for(const m of r){if(m.kind!=="run"||m.params.of!=="wall")continue;const w=wt(m,"run"),I=((lt=(Re=w==null?void 0:w.run)==null?void 0:Re.line)==null?void 0:lt.curves)??[],A=typeof(w==null?void 0:w.base)=="number"?w.base:0,F=w==null?void 0:w.height,D=d.get(String((w==null?void 0:w.level)??m.params.level??"")),O=m.params.lookRef;if(typeof O!="string"||typeof F!="number"||!D){U++;continue}I.forEach((x,Ce)=>{var Ae;if(x.kind!=="segment"||!x.from||!x.to){U++;return}const Se=(D.at+A)*b,ie=`${q(x.from[0]*b)},${q(x.from[1]*b)},${q(Se)};${q(x.to[0]*b)},${q(x.to[1]*b)},${q(Se)}`,V={CategoryId:xe.walls,Type:((Ae=ps(m))==null?void 0:Ae.type)??O,LocationLine:ie,Level:D.name,BaseOffset:q(A*b),Height:q(F*b)},P=d.get(String(m.params.topLevel??""));P&&(V.TopLevel=P.name,V.TopOffset=q((D.at+A+F-P.at)*b));const j=Ve(O);j&&(V["Type.Width"]=q(j)),K(`${B(m.id)}#${Ce}`,V)&&k++})}let Q=0,Ee=0;for(const m of r){const w=m.params.of;if(m.kind!=="extrusion"||w!=="slab"&&w!=="roof"&&w!=="covering")continue;const I=w==="covering"?"ceiling":w==="roof"?"roof":ui(m);if(I==="other")continue;const A=wt(m,"extrusion"),F=typeof m.params.base=="number"?m.params.base:0,D=d.get(String((A==null?void 0:A.level)??m.params.level??"")),O=m.params.lookRef,x=P=>{if(!(P!=null&&P.length))return null;const j=[];for(const Ae of P){if(Ae.kind!=="segment"||!Ae.from)return null;j.push(Ae.from[0]*b,Ae.from[1]*b,F*b)}return j.length>=9?j:null},Ce=x((We=(ht=A==null?void 0:A.profile)==null?void 0:ht.outline)==null?void 0:We.curves);if(typeof O!="string"||!D||!Ce){Ee++;continue}const Se=[Ce];for(const P of((dt=A==null?void 0:A.profile)==null?void 0:dt.holes)??[]){const j=x(P==null?void 0:P.curves);j&&Se.push(j)}const ie={CategoryId:I==="roof"?xe.roofs:I==="ceiling"?xe.ceilings:I==="foundation"?xe.structuralFoundations:xe.floors,Type:((Ye=ps(m))==null?void 0:Ye.type)??O,Profile:JSON.stringify(Se),Level:D.name},V=Ve(O);if(V&&(ie["Type.Width"]=q(V)),I==="roof"||I==="ceiling"){ie.BaseOffset=q(F*b);const P=A==null?void 0:A.slopes;I==="roof"&&Array.isArray(P)&&P.some(j=>typeof j=="number")&&(ie.Slopes=JSON.stringify(P.map(j=>typeof j=="number"?j:null)))}else V&&(ie.HeightOffset=q(F*b+V));K(B(m.id),ie)&&Q++}let Te=0;for(const m of r){if(m.kind!=="member"||m.params.of!=="column")continue;const w=wt(m,"member"),I=w==null?void 0:w.start;if(!I||I.length!==3)continue;const A=o?Js(m.params.lookRef):null;if(o&&!A||!A&&!i)continue;const F=A??{family:i.family,type:i.type},D=d.get(String((w==null?void 0:w.level)??""));K(B(m.id),{...i&&!A?{CategoryId:i.categoryId}:{},Family:F.family,Type:F.type,...D?{Level:D.name}:{}},{position:[I[0]*b,I[1]*b,I[2]*b],rotationDeg:(Number((w==null?void 0:w.roll)??0)||0)*Gs})&&Te++}let _e=0,He=0;for(const m of r){if(m.kind!=="familyInstance")continue;if(m.params.host){He++;continue}if(!a)continue;const w=wt(m,"instance"),I=(ze=w==null?void 0:w.placement)==null?void 0:ze.at;if(!I||I.length!==3)continue;const A=Js(m.params.type);if(!A)continue;const F=(ut=w==null?void 0:w.placement)==null?void 0:ut.right,D=F?Math.atan2(F[1],F[0])*Gs:0;K(B(m.id),{Family:A.family,Type:A.type},{position:[I[0]*b,I[1]*b,I[2]*b],rotationDeg:D})&&_e++}let Ge=0;for(const m of r)(m.kind==="stair"||m.kind==="footing"||m.kind==="ramp"||m.kind==="extrusion"&&m.params.of!=="slab"||m.kind==="run"&&m.params.of!=="wall")&&Ge++;let Ie=0;for(const[m,w]of T)!m.startsWith(`${t.fileId}:`)||be.has(m)||(_.remove(w),Ie++);if(_.length===0)throw new Error(`Nothing new to ask for: "${t.name}" holds ${W} element(s) this recipe already made, ${He+Ge} waiting on the applier, and nothing is left to remove.`);const Je=[X?`${X} level(s)`:"",k?`${k} wall(s)`:"",Q?`${Q} floor(s)`:"",Te?`${Te} column(s)`:"",_e?`${_e} instance(s)`:"",Ie?`${Ie} gone`:""].filter(Boolean);return{title:`${n==="ifc"?"IFC":"Model"} to Revit: ${Je.join(", ")}`,verb:_.summary,targets:_.length,payload:new Blob([await _.build(e.opId)]),ruleTallies:[{read:d.size,proposed:X},{read:k+U,proposed:k},{read:Q+Ee,proposed:Q},{read:Te,proposed:Te},{read:_e,proposed:_e},{read:Ie,proposed:Ie},{read:He+Ge,proposed:0}]}}}const fi={type:"object",properties:{columnType:{type:"object",title:"Column type","x-existing":{of:"family-type",from:"target",where:{CategoryId:"-2001330"}}},trustStyleNames:{type:"boolean",title:"Use the model's own style names as Family:Type",default:!1},includeInstances:{type:"boolean",title:"Also propose free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},pi=[{reads:"Levels (datums)",proposes:"The same level on the target, ensured by name"},{reads:"Wall runs, one per straight segment",proposes:"A native wall: curve, type (made from its width when missing), level, height"},{reads:"Slabs with their boundary",proposes:"A native floor from the profile, holes included"},{reads:"Column records (members)",proposes:"A Revit column at each, on its level"},{reads:"Free-standing family instances (when turned on)",proposes:"A new instance of the same-named type, placed and turned"},{reads:"Things this recipe made whose record is gone",proposes:"That element removed"},{reads:"Hosted doors/windows, stairs, roofs, footings, curtain pieces",proposes:"Nothing yet - each waits on the applier or the converter growing"}],xn=`
3
3
  ## What it does
4
4
 
5
5
  It reads the platform's records out of a .frag and asks a Revit document for
@@ -38,13 +38,13 @@ Records are metres and radians, Z up; proposals are written in Revit's feet
38
38
  and degrees. Types are matched exactly by name; Revit refuses the whole
39
39
  request when a loadable type is missing (system types are created from their
40
40
  width instead).
41
- `,ys={name:"frag-to-revit",title:"Platform model to Revit",description:"Turns the platform records of a .frag - levels, walls, floors, columns, instances - into change requests for a Revit document.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},runtime:"browser",settingsSchema:Qr,rules:Zr,doc:En,run:vn("frag")},Tn={...ys,name:"ifc-to-revit",title:"IFC to Revit",description:"Turns an IFC - through the frag the platform converted it into - into native Revit change requests: levels, walls, floors, columns, instances.",inputs:["ifc-model"],doc:`
41
+ `,Ss={name:"frag-to-revit",title:"Platform model to Revit",description:"Turns the platform records of a .frag - levels, walls, floors, columns, instances - into change requests for a Revit document.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},runtime:"browser",settingsSchema:fi,rules:pi,doc:xn,run:$n("frag")},Nn={...Ss,name:"ifc-to-revit",title:"IFC to Revit",description:"Turns an IFC - through the frag the platform converted it into - into native Revit change requests: levels, walls, floors, columns, instances.",inputs:["ifc-model"],doc:`
42
42
  ## Point it at the converted frag
43
43
 
44
44
  It reads the .frag your IFC was PROCESSED into (the IFC document's view). A
45
45
  plain IFC import carries only IFC attributes and is refused by name - the
46
46
  editable converter is what gives an IFC real records.
47
- `+En,run:vn("ifc")},ei={millimeters:.001,millimetres:.001,mm:.001,centimeters:.01,centimetres:.01,cm:.01,meters:1,metres:1,m:1,inches:.0254,in:.0254,feet:.3048,ft:.3048},_n="rhino-to-revit",Ls=`recipe:${_n}`;function ti(n){const e=(n.attrs.Position??"").split(",").map(t=>Number(t.trim()));return e.length!==3||e.some(t=>!Number.isFinite(t))?null:[e[0],e[1],e[2]]}const In={name:_n,title:"Rhino to Revit",description:"Turns the placed objects of a Rhino layer into change requests for Revit instances of a chosen type.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},runtime:"browser",settingsSchema:{type:"object",properties:{layer:{type:"string",title:"Rhino layer","x-existing":{of:"layer",from:"source"}},instanceType:{type:"object",title:"Revit type","x-existing":{of:"family-type",from:"target"}}},required:["layer","instanceType"]},rules:[{reads:"Objects on the chosen layer with no instance yet",proposes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",proposes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",proposes:"That instance removed"},{reads:"Everything on other layers",proposes:"Nothing"}],doc:`
47
+ `+xn,run:$n("ifc")},mi={millimeters:.001,millimetres:.001,mm:.001,centimeters:.01,centimetres:.01,cm:.01,meters:1,metres:1,m:1,inches:.0254,in:.0254,feet:.3048,ft:.3048},Fn="rhino-to-revit",Ws=`recipe:${Fn}`;function yi(n){const e=(n.attrs.Position??"").split(",").map(t=>Number(t.trim()));return e.length!==3||e.some(t=>!Number.isFinite(t))?null:[e[0],e[1],e[2]]}const Pn={name:Fn,title:"Rhino to Revit",description:"Turns the placed objects of a Rhino layer into change requests for Revit instances of a chosen type.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},runtime:"browser",settingsSchema:{type:"object",properties:{layer:{type:"string",title:"Rhino layer","x-existing":{of:"layer",from:"source"}},instanceType:{type:"object",title:"Revit type","x-existing":{of:"family-type",from:"target"}}},required:["layer","instanceType"]},rules:[{reads:"Objects on the chosen layer with no instance yet",proposes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",proposes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",proposes:"That instance removed"},{reads:"Everything on other layers",proposes:"Nothing"}],doc:`
48
48
  ## What it does
49
49
 
50
50
  It reads a model published from Rhino and asks a Revit document for instances
@@ -73,5 +73,5 @@ requests; it keeps nothing of its own.
73
73
  Where an object becomes an instance, Revit decides the level: the nearest one
74
74
  at or below the point. For a level-based family the level wins over the
75
75
  point's height.
76
- `,async run(n){var K;const{picked:e,contents:t}=await bn(n,n.input),{layer:s,instanceType:r}=n.settings;if(!s||!r)throw new Error("Choose the layer and the Revit type.");const i=(K=t.metadata)==null?void 0:K.data,o=i==null?void 0:i.units,a=typeof o=="string"?ei[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${e.name}" does not say what units its data is in${o?` ("${String(o)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const l=String((i==null?void 0:i.axes)??"z-up").toLowerCase();if(l!=="z-up")throw new Error(`"${e.name}" declares its data as "${l}"; this recipe only converts Z up.`);const d=a*gn,c=await wn(n,Ls),m=await n.targetDoc.latest(),T=new ms({project:n.projectId,document:n.targetDoc.docId,baseCommit:(m==null?void 0:m.version)??0,author:Ls});let A=0,_=0,v=0;const N=new Set,be=[];for(const k of t.items){if(!k.guid||Object.keys(k.attrs).length===0)continue;if((k.attrs.Layer??"")!==s){v++;continue}const j=ti(k);if(!j)continue;N.add(k.guid);const X=[j[0]*d,j[1]*d,j[2]*d],ve=c.get(k.guid);ve?be.push({instance:ve,object:k.guid,position:X}):(T.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:X,source:k.guid}),A++)}for(const k of be)T.set(k.instance,{},{position:k.position,source:k.object}),_++;let G=0;for(const[k,j]of c)N.has(k)||(T.remove(j),G++);const z=A+_+G;if(z===0)throw new Error(`Nothing to ask for: layer "${s}" of "${e.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[A?`${A} new`:"",_?`${_} moved`:"",G?`${G} gone`:""].filter(Boolean).join(", ")}`,verb:T.summary,targets:z,payload:new Blob([await T.build(n.opId)]),ruleTallies:[{read:A,proposed:A},{read:_,proposed:_},{read:G,proposed:G},{read:v,proposed:0}]}}},Sn=[In,Tn,ys];function si(n){for(const e of Sn)n.recipes.register(e)}const ni={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},ri={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},ii={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},oi={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ai={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},ci={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},hi={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},li={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},di={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},ui={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=ri;exports.ChannelClient=un;exports.ChannelRoom=fs;exports.ClashesManager=ii;exports.CollabRoom=hn;exports.DOCUMENT_FILE=Mt;exports.DOCUMENT_SCHEMA=Xe;exports.EngineServicesClient=Tt;exports.ExternalRoom=ln;exports.FileList=oi;exports.FlowDoc=nn;exports.GISManager=ai;exports.GitHistoryManager=ci;exports.HelloWorld=hi;exports.METADATA_LIMITS=ni;exports.OP_SCHEMA=yn;exports.OperationBuilder=ms;exports.PlatformClient=is;exports.ProjectDocuments=ds;exports.ProjectHistory=sn;exports.ProjectManager=li;exports.Recipes=on;exports.RequestError=St;exports.SELF_VIEWING_FORMATS=Xs;exports.STORAGE_BATCH_MAX=Kt;exports.StaleHistoryError=Vt;exports.TopicsManager=di;exports.UIManager=ui;exports.builtinRecipes=Sn;exports.fragToRevit=ys;exports.ifcToRevit=Tn;exports.mintGuid=Et;exports.orderByGraph=us;exports.readFrag=ps;exports.registerBuiltinRecipes=si;exports.rhinoToRevit=In;exports.windowTransport=cn;
76
+ `,async run(n){var X;const{picked:e,contents:t}=await Cn(n,n.input),{layer:s,instanceType:r}=n.settings;if(!s||!r)throw new Error("Choose the layer and the Revit type.");const i=(X=t.metadata)==null?void 0:X.data,o=i==null?void 0:i.units,a=typeof o=="string"?mi[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${e.name}" does not say what units its data is in${o?` ("${String(o)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const h=String((i==null?void 0:i.axes)??"z-up").toLowerCase();if(h!=="z-up")throw new Error(`"${e.name}" declares its data as "${h}"; this recipe only converts Z up.`);const d=a*kn,c=await Rn(n,Ws),y=await n.targetDoc.latest(),T=new Is({project:n.projectId,document:n.targetDoc.docId,baseCommit:(y==null?void 0:y.version)??0,author:Ws});let R=0,_=0,b=0;const B=new Set,be=[];for(const k of t.items){if(!k.guid||Object.keys(k.attrs).length===0)continue;if((k.attrs.Layer??"")!==s){b++;continue}const U=yi(k);if(!U)continue;B.add(k.guid);const Q=[U[0]*d,U[1]*d,U[2]*d],Ee=c.get(k.guid);Ee?be.push({instance:Ee,object:k.guid,position:Q}):(T.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:Q,source:k.guid}),R++)}for(const k of be)T.set(k.instance,{},{position:k.position,source:k.object}),_++;let W=0;for(const[k,U]of c)B.has(k)||(T.remove(U),W++);const K=R+_+W;if(K===0)throw new Error(`Nothing to ask for: layer "${s}" of "${e.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[R?`${R} new`:"",_?`${_} moved`:"",W?`${W} gone`:""].filter(Boolean).join(", ")}`,verb:T.summary,targets:K,payload:new Blob([await T.build(n.opId)]),ruleTallies:[{read:R,proposed:R},{read:_,proposed:_},{read:W,proposed:W},{read:b,proposed:0}]}}},Bn=[Pn,Nn,Ss];function gi(n){for(const e of Bn)n.recipes.register(e)}const wi={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},vi={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},bi={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Ei={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Ti={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},_i={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Ii={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Si={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Ai={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Oi={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=vi;exports.ChannelClient=_n;exports.ChannelRoom=Ts;exports.ClashesManager=bi;exports.CollabRoom=bn;exports.DOCUMENT_FILE=Yt;exports.DOCUMENT_SCHEMA=nt;exports.DocumentDrafts=hn;exports.EngineServicesClient=Ct;exports.ExternalRoom=En;exports.FileList=Ei;exports.FlowDoc=mn;exports.GISManager=Ti;exports.GitHistoryManager=_i;exports.HelloWorld=Ii;exports.METADATA_LIMITS=wi;exports.OP_SCHEMA=On;exports.OperationBuilder=Is;exports.PlatformClient=fs;exports.ProjectDocuments=bs;exports.ProjectHistory=pn;exports.ProjectManager=Si;exports.Recipes=gn;exports.RequestError=Nt;exports.SELF_VIEWING_FORMATS=cn;exports.STORAGE_BATCH_MAX=rs;exports.StaleHistoryError=Xt;exports.TopicsManager=Ai;exports.UIManager=Oi;exports.builtinRecipes=Bn;exports.fragToRevit=Ss;exports.ifcToRevit=Nn;exports.mintGuid=Rt;exports.orderByGraph=Es;exports.readFrag=_s;exports.registerBuiltinRecipes=gi;exports.rhinoToRevit=Pn;exports.windowTransport=vn;
77
77
  //# sourceMappingURL=index.cjs.js.map