@thatopen/services 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Tn=Object.create;var ot=Object.defineProperty;var _n=Object.getOwnPropertyDescriptor;var In=Object.getOwnPropertyNames;var Sn=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty;var ss=n=>{throw TypeError(n)};var On=(n,e,t)=>e in n?ot(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var An=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of In(e))!kn.call(n,r)&&r!==t&&ot(n,r,{get:()=>e[r],enumerable:!(s=_n(e,r))||s.enumerable});return n};var qe=(n,e,t)=>(t=n!=null?Tn(Sn(n)):{},An(e||!n||!n.__esModule?ot(t,"default",{value:n,enumerable:!0}):t,n));var N=(n,e,t)=>On(n,typeof e!="symbol"?e+"":e,t),at=(n,e,t)=>e.has(n)||ss("Cannot "+t);var f=(n,e,t)=>(at(n,e,"read from private field"),t?t.call(n):e.get(n)),T=(n,e,t)=>e.has(n)?ss("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),k=(n,e,t,s)=>(at(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),c=(n,e,t)=>(at(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=Object.create(null);W.open="0";W.close="1";W.ping="2";W.pong="3";W.message="4";W.upgrade="5";W.noop="6";const Ge=Object.create(null);Object.keys(W).forEach(n=>{Ge[W[n]]=n});const pt={type:"error",data:"parser error"},Es=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ts=typeof ArrayBuffer=="function",_s=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,qt=({type:n,data:e},t,s)=>Es&&e instanceof Blob?t?s(e):ns(e,s):Ts&&(e instanceof ArrayBuffer||_s(e))?t?s(e):ns(new Blob([e]),s):s(W[n]+(e||"")),ns=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function rs(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let ct;function Rn(n,e){if(Es&&n.data instanceof Blob)return n.data.arrayBuffer().then(rs).then(e);if(Ts&&(n.data instanceof ArrayBuffer||_s(n.data)))return e(rs(n.data));qt(n,!1,t=>{ct||(ct=new TextEncoder),e(ct.encode(t))})}const is="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<is.length;n++)Ae[is.charCodeAt(n)]=n;const Cn=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 u=new ArrayBuffer(e),h=new Uint8Array(u);for(s=0;s<t;s+=4)i=Ae[n.charCodeAt(s)],o=Ae[n.charCodeAt(s+1)],a=Ae[n.charCodeAt(s+2)],l=Ae[n.charCodeAt(s+3)],h[r++]=i<<2|o>>4,h[r++]=(o&15)<<4|a>>2,h[r++]=(a&3)<<6|l&63;return u},$n=typeof ArrayBuffer=="function",Dt=(n,e)=>{if(typeof n!="string")return{type:"message",data:Is(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:xn(n.substring(1),e)}:Ge[t]?n.length>1?{type:Ge[t],data:n.substring(1)}:{type:Ge[t]}:pt},xn=(n,e)=>{if($n){const t=Cn(n);return Is(t,e)}else return{base64:!0,data:n}},Is=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Ss="",Nn=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{qt(i,!1,a=>{s[o]=a,++r===t&&e(s.join(Ss))})})},Pn=(n,e)=>{const t=n.split(Ss),s=[];for(let r=0;r<t.length;r++){const i=Dt(t[r],e);if(s.push(i),i.type==="error")break}return s};function Bn(){return new TransformStream({transform(n,e){Rn(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 ht;function De(n){return n.reduce((e,t)=>e+t.length,0)}function Me(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 Fn(n,e){ht||(ht=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(De(t)<1)break;const l=Me(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(De(t)<2)break;const l=Me(t,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),s=3}else if(s===2){if(De(t)<8)break;const l=Me(t,8),u=new DataView(l.buffer,l.byteOffset,l.length),h=u.getUint32(0);if(h>Math.pow(2,21)-1){a.enqueue(pt);break}r=h*Math.pow(2,32)+u.getUint32(4),s=3}else{if(De(t)<r)break;const l=Me(t,r);a.enqueue(Dt(i?l:ht.decode(l),e)),s=0}if(r===0||r>n){a.enqueue(pt);break}}}})}const ks=4;function O(n){if(n)return Ln(n)}function Ln(n){for(var e in O.prototype)n[e]=O.prototype[e];return n}O.prototype.on=O.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};O.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};O.prototype.off=O.prototype.removeListener=O.prototype.removeAllListeners=O.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};O.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};O.prototype.emitReserved=O.prototype.emit;O.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};O.prototype.hasListeners=function(n){return!!this.listeners(n).length};const tt=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")(),jn="arraybuffer";function Os(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const qn=j.setTimeout,Dn=j.clearTimeout;function st(n,e){e.useNativeTimers?(n.setTimeoutFn=qn.bind(j),n.clearTimeoutFn=Dn.bind(j)):(n.setTimeoutFn=j.setTimeout.bind(j),n.clearTimeoutFn=j.clearTimeout.bind(j))}const Mn=1.33;function Un(n){return typeof n=="string"?Vn(n):Math.ceil((n.byteLength||n.size)*Mn)}function Vn(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 As(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Gn(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Hn(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 Jn extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class Mt extends O{constructor(e){super(),this.writable=!1,st(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 Jn(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=Dt(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=Gn(e);return t.length?"?"+t:""}}class Wn extends Mt{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)};Pn(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,Nn(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]=As()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Rs=!1;try{Rs=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Yn=Rs;function Kn(){}class zn extends Wn{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 J extends O{constructor(e,t,s){super(),this.createRequest=e,st(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=Os(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=J.requestsCount++,J.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=Kn,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete J.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()}}J.requestsCount=0;J.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",os);else if(typeof addEventListener=="function"){const n="onpagehide"in j?"pagehide":"unload";addEventListener(n,os,!1)}}function os(){for(let n in J.requests)J.requests.hasOwnProperty(n)&&J.requests[n].abort()}const Xn=function(){const n=Cs({xdomain:!1});return n&&n.responseType!==null}();class Qn extends zn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Xn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new J(Cs,this.uri(),e)}}function Cs(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Yn))return new XMLHttpRequest}catch{}if(!e)try{return new j[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const $s=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Zn extends Mt{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=$s?{}:Os(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;qt(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&tt(()=>{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]=As()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const lt=j.WebSocket||j.MozWebSocket;class er extends Zn{createSocket(e,t,s){return $s?new lt(e,t,s):t?new lt(e,t):new lt(e)}doWrite(e,t){this.ws.send(t)}}class tr extends Mt{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=Fn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Bn();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&&tt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const sr={websocket:er,webtransport:tr,polling:Qn},nr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mt(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=nr.exec(n||""),i={},o=14;for(;o--;)i[rr[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=ir(i,i.path),i.queryKey=or(i,i.query),i}function ir(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 or(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const yt=typeof addEventListener=="function"&&typeof removeEventListener=="function",He=[];yt&&addEventListener("offline",()=>{He.forEach(n=>n())},!1);class he extends O{constructor(e,t){if(super(),this.binaryType=jn,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=mt(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=mt(t.host).host);st(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=Hn(this.opts.query)),yt&&(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"})},He.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ks,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&&he.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",he.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+=Un(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,tt(()=>{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(he.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(),yt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=He.indexOf(this._offlineEventListener);s!==-1&&He.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}he.protocol=ks;class ar extends he{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;he.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;he.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(h(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=t.name,this.emitReserved("upgradeError",w)}}))};function i(){s||(s=!0,h(),t.close(),t=null)}const o=y=>{const w=new Error("probe error: "+y);w.transport=t.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function u(y){t&&y.name!==t.name&&i()}const h=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",a),this.off("close",l),this.off("upgrading",u)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",l),this.once("upgrading",u),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 cr=class extends ar{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=>sr[i]).filter(i=>!!i)),super(s?r:e,r)}};function hr(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=mt(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 lr=typeof ArrayBuffer=="function",dr=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,xs=Object.prototype.toString,ur=typeof Blob=="function"||typeof Blob<"u"&&xs.call(Blob)==="[object BlobConstructor]",fr=typeof File=="function"||typeof File<"u"&&xs.call(File)==="[object FileConstructor]";function Ut(n){return lr&&(n instanceof ArrayBuffer||dr(n))||ur&&n instanceof Blob||fr&&n instanceof File}function Je(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(Je(n[t]))return!0;return!1}if(Ut(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Je(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Je(n[t]))return!0;return!1}function pr(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(Ut(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 mr(n,e){return n.data=wt(n.data,e),delete n.attachments,n}function wt(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]=wt(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=wt(n[t],e));return n}const yr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var b;(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"})(b||(b={}));class gr{constructor(e){this.replacer=e}encode(e){return(e.type===b.EVENT||e.type===b.ACK)&&Je(e)?this.encodeAsBinary({type:e.type===b.EVENT?b.BINARY_EVENT:b.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===b.BINARY_EVENT||e.type===b.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=pr(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class Vt extends O{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===b.BINARY_EVENT;s||t.type===b.BINARY_ACK?(t.type=s?b.EVENT:b.ACK,this.reconstructor=new wr(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Ut(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(b[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===b.BINARY_EVENT||s.type===b.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(!br(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(Vt.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 b.CONNECT:return as(t);case b.DISCONNECT:return t===void 0;case b.CONNECT_ERROR:return typeof t=="string"||as(t);case b.EVENT:case b.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&yr.indexOf(t[0])===-1);case b.ACK:case b.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class wr{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=mr(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const br=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function as(n){return Object.prototype.toString.call(n)==="[object Object]"}const vr=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Vt,Encoder:gr,get PacketType(){return b}},Symbol.toStringTag,{value:"Module"}));function V(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Er=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ns extends O{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=[V(e,"open",this.onopen.bind(this)),V(e,"packet",this.onpacket.bind(this)),V(e,"error",this.onerror.bind(this)),V(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(Er.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:b.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const h=this.ids++,y=t.pop();this._registerAckCallback(h,y),o.id=h}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:b.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 b.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 b.EVENT:case b.BINARY_EVENT:this.onevent(e);break;case b.ACK:case b.BINARY_ACK:this.onack(e);break;case b.DISCONNECT:this.ondisconnect();break;case b.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:b.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:b.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 ke(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}ke.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};ke.prototype.reset=function(){this.attempts=0};ke.prototype.setMin=function(n){this.ms=n};ke.prototype.setMax=function(n){this.max=n};ke.prototype.setJitter=function(n){this.jitter=n};class bt extends O{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,st(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 ke({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||vr;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 cr(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=V(t,"open",function(){s.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=V(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(V(e,"ping",this.onping.bind(this)),V(e,"data",this.ondata.bind(this)),V(e,"error",this.onerror.bind(this)),V(e,"close",this.onclose.bind(this)),V(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){tt(()=>{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 Ns(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 Oe={};function xe(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=hr(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=Oe[r]&&i in Oe[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new bt(s,e):(Oe[r]||(Oe[r]=new bt(s,e)),l=Oe[r]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(xe,{Manager:bt,Socket:Ns,io:xe,connect:xe});const Ne="thatopen/document@1",vt="document.json",Ps=["pdf","txt","md","json","csv","tsv","frag"],cs=()=>`v-${Date.now()}`;function Ue(n){return String(n._id??n.id??"")}var fe,Bs,Et;class Gt{constructor(e,t){T(this,fe);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=Ue(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=hs(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=Ue(a);await this.client.updateFile(e,{parentFolderId:l});const u=[],h=await c(this,fe,Bs).call(this,s);if(h)try{const I=await this.client.getFile(h);await this.client.updateFile(h,{parentFolderId:l}),u.push({fileId:h,format:hs(String(I.name??""),I.fileExtension)})}catch{}((t==null?void 0:t.selfView)??Ps.includes(i))&&u.push({fileId:e,format:i});const w={schema:Ne,name:o,native:{fileId:e,format:i},views:u};return await this.setDescriptor(l,w),{folderId:l,descriptor:w}}async descriptor(e){const t=await c(this,fe,Et).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 Tr(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:Ne,views:t.views??[]},r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await c(this,fe,Et).call(this,e);if(i){await this.client.updateFile(i.id,{file:r,versionTag:cs()});return}await this.client.createFile({file:r,name:vt,versionTag:cs(),parentFolderId:e,projectId:this.projectId})}}fe=new WeakSet,Bs=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(Ue(e),s.tag),i=r==null?void 0:r.derivedFileId;if(typeof i=="string"&&i)return i}catch{}},Et=async function(e){const s=(await this.client.listFiles({folderId:e})).find(r=>String(r.name??"")===vt);return s?{id:Ue(s)}:void 0};function hs(n,e){const t=(e??"").replace(/^\./,"").toLowerCase();if(t)return t;const s=n.lastIndexOf(".");return s>0?n.slice(s+1).toLowerCase():""}function Tr(n){if(!n||typeof n!="object")return null;const e=n;if(e.schema!==Ne||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:Ne,name:e.name,...r?{native:{fileId:s.fileId,format:s.format}}:{},views:t}}class Tt 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",_t="revitflow_history.json",ye="revitflow_ops.json",ds="revitflow/ops@1",Fs="revitflow_model.frag",Ls="revitflow_",_r="bimterop-locks-anchor",Ve=()=>`v-${Date.now()}`;function js(n,e){return n.filter(t=>String(t.parentId??"")===e)}function H(n){return String(n._id??n.id??"")}var U,Pe,It;class qs{constructor(e,t){T(this,Pe);T(this,U);this.client=e,this.projectId=t}async docs(){const e=await c(this,Pe,It).call(this);if(!e)return[];const t=await this.client.listFolders({parentFolderId:e,projectId:this.projectId}),s=[];for(const r of js(t,e)){const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:H(r)})).map(y=>String(y.name??"")),u=l.find(y=>y===Fs)??l.find(y=>y.endsWith(".frag")&&!y.startsWith(Ls)),h=l.includes(_t)||l.includes(ye)||!!u;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:H(r),modelName:u,...h?{}:{empty:!0}})}return s}doc(e,t){return new Ds(this.client,this,e,t)}async rootFolderId(e=!1){if(f(this,U))return f(this,U);const t=await c(this,Pe,It).call(this);if(t)return t;if(!e)return;const s=await this.client.createFolder(ls,void 0,this.projectId);return k(this,U,H(s)),f(this,U)}}U=new WeakMap,Pe=new WeakSet,It=async function(){if(f(this,U))return f(this,U);const t=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===ls&&!s.parentId);return t&&k(this,U,H(t)),f(this,U)};var X,p,ge,we,z,St,Re,be,kt,We,Ce,Ye,Ot,Ms;class Ds{constructor(e,t,s,r){T(this,p);T(this,X);this.client=e,this.project=t,this.source=s,this.docId=r}async timeline(){const e=await c(this,p,We).call(this);return Ht((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 c(this,p,be).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 folderId(){return await c(this,p,z).call(this,!1)}async descriptor(){return await f(this,p,ge).descriptor(await c(this,p,z).call(this,!1))}async view(e){const t=await c(this,p,z).call(this,!1),s=await f(this,p,ge).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 c(this,p,be).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(e){const t=await c(this,p,z).call(this,!0);if(await f(this,p,ge).descriptor(t)){await f(this,p,ge).addView(t,e);return}const r=await c(this,p,be).call(this);await f(this,p,ge).setDescriptor(t,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??f(this,p,we),views:[e]})}async ownership(){const e=await c(this,p,Re).call(this,_r);if(!e)return[];const t=await this.client.getHiddenFilesByParent(e.id),s=await Promise.all(t.map(async o=>{try{const a=H(o),l=await this.client.downloadHiddenFile(a),u=JSON.parse(await l.text());return!u||typeof u!="object"||!("revitflowlock"in u)||!Array.isArray(u.keys)?null:{owner:String(u.user??""),keys:u.keys.filter(h=>typeof h=="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 c(this,p,z).call(this,!0);let s=await c(this,p,We).call(this)??{model:this.docId,commits:[]};const r=us(s.commits);if(e.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==e.expectedLatestGuid)throw new Tt(e.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Ze(),...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:Ir(e.changes)};if(e.model&&(await c(this,p,Ms).call(this,t,e.model),i.full=!0),e.delta){const l=await c(this,p,be).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const u=await this.client.createHiddenFile(e.delta,l.id);i.deltaId=String(u._id??u.id)}const o=await c(this,p,We).call(this);if(o){s=o;const l=us(s.commits);if(e.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==e.expectedLatestGuid)throw new Tt(e.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return s.commits.push(i),await c(this,p,Ye).call(this,t,_t,s),i}async suggestions(){const e=await c(this,p,Ce).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 c(this,p,z).call(this,!0),s=await c(this,p,Ce).call(this)??{schema:ds,ops:[]},r=await c(this,p,Re).call(this,ye),i={opId:e.opId??Ze(),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 c(this,p,Ot).call(this,t,ye,s),l=await this.client.createHiddenFile(e.payload,a.id);i.fragId=String(l._id??l.id)}const o=await c(this,p,Ce).call(this)??s;return o.schema??(o.schema=ds),o.ops.push(i),await c(this,p,Ye).call(this,t,ye,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 c(this,p,z).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await c(this,p,Ce).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 c(this,p,Ye).call(this,s,ye,r),i}}X=new WeakMap,p=new WeakSet,ge=function(){return new Gt(this.client,this.project.projectId)},we=function(){return`${this.source}-${this.docId}`},z=async function(e){if(f(this,X))return f(this,X);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=js(s,t).find(o=>String(o.name??"")===f(this,p,we));if(r)return k(this,X,H(r)),f(this,X);if(!e)throw new Error(`Document ${f(this,p,we)} does not exist in this project.`);const i=await this.client.createFolder(f(this,p,we),t,this.project.projectId);return k(this,X,H(i)),f(this,X)},St=async function(){const e=await c(this,p,z).call(this,!1);return(await this.client.listFiles({folderId:e})).map(s=>({id:H(s),name:String(s.name??"")}))},Re=async function(e){try{return(await c(this,p,St).call(this)).find(t=>t.name===e)}catch{return}},be=async function(){try{const e=await c(this,p,St).call(this);return e.find(t=>t.name===Fs)??e.find(t=>t.name.endsWith(".frag")&&!t.name.startsWith(Ls))}catch{return}},kt=async function(e){const t=await c(this,p,Re).call(this,e);if(!t)return;const r=await(await this.client.downloadFile(t.id)).text();if(r.trim())return JSON.parse(r)},We=function(){return c(this,p,kt).call(this,_t)},Ce=function(){return c(this,p,kt).call(this,ye)},Ye=async function(e,t,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await c(this,p,Re).call(this,t);return i?(await this.client.updateFile(i.id,{file:r,versionTag:Ve()}),i):await c(this,p,Ot).call(this,e,t,s)},Ot=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:Ve(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:H(o??i),name:t}},Ms=async function(e,t){const s=await c(this,p,be).call(this);if(s)return await this.client.updateFile(s.id,{file:t,versionTag:Ve()}),s;const r=`${f(this,p,we)}.frag`,i=await this.client.createFile({file:t,name:r,versionTag:Ve(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:H(o??i),name:r}};function Ir(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 Ht(n){var l;if(n.length<=1)return n.forEach((u,h)=>u.ordinal=h),[...n];const e=new Map(n.map(u=>[u.guid,u])),t=new Map,s=[];for(const u of n){const h=(l=u.parents)==null?void 0:l[0];if(h&&e.has(h)){const y=t.get(h)??[];y.push(u),t.set(h,y)}else s.push(u)}const r=(u,h)=>String(u.timestamp).localeCompare(String(h.timestamp));s.sort(r);const i=[],o=[...s].reverse(),a=new Set;for(;o.length;){const u=o.pop();if(a.has(u.guid))continue;a.add(u.guid),i.push(u);const h=(t.get(u.guid)??[]).sort(r);for(let y=h.length-1;y>=0;y--)o.push(h[y])}for(const u of n)a.has(u.guid)||i.push(u);return i.forEach((u,h)=>u.ordinal=h),i}function us(n){const e=Ht(n);return e[e.length-1]}function Ze(){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 ie,Be,At;class Us{constructor(e){T(this,Be);T(this,ie,new Map);this.client=e}register(e){if(f(this,ie).has(e.name))throw new Error(`A recipe named "${e.name}" is already registered.`);f(this,ie).set(e.name,e)}list(e){return[...f(this,ie).values()].filter(s=>(!(e!=null&&e.to)||s.to===e.to)&&(!(e!=null&&e.input)||s.inputs.includes(e.input)))}get(e){return f(this,ie).get(e)}async plan(e,t){const{base:s,opId:r,result:i}=await c(this,Be,At).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 c(this,Be,At).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}}}ie=new WeakMap,Be=new WeakSet,At=async function(e,t){const s=f(this,ie).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=Ze(),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 Rt=100;function Sr(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 kr(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=Sr(r);super(o.message??`${s||"Request failed"} (${t})`);N(this,"status");N(this,"code");N(this,"details");N(this,"body");N(this,"retryAfter");this.name="RequestError",this.status=t,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??kr(o.details)}}const G="item/folder",g="item",ne="processor",Or="npm-registry",K="hidden",dt="FILE",ut="TOOL",ft="APP",Ar=500,fs=3e4,Rr=.25,Cr=n=>new Promise(e=>setTimeout(e,n));function $r(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 xr(n){return n instanceof nt?n.status===429||n.status>=500:!0}function Nr(n,e){const t=Math.min(Ar*2**e,fs),s=t*Rr*Math.random(),r=n instanceof nt&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,fs)+s:t+s}var d,Ct,m,re,Fe,$e,Ke,ze,$t,xt,Vs;const zt=class zt{constructor(e,t,s){T(this,d);N(this,"apiUrl");N(this,"accessToken");N(this,"wsUrl");N(this,"retries");N(this,"useBearer");N(this,"builtInGlobals",null);N(this,"localServerUrl",null);N(this,"context");T(this,Fe);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 zt(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 c(this,d,m).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await c(this,d,m).call(this,"GET",`${G}/${t}/items`,{query:{itemType:dt,archived:s}}):await c(this,d,m).call(this,"GET",`${g}`,{query:{itemType:dt,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await c(this,d,xt).call(this,e,t)}async createFile(e){return await c(this,d,ze).call(this,e,dt)}async updateFile(e,t){return await c(this,d,$t).call(this,e,t)}async archiveFile(e){return await c(this,d,m).call(this,"DELETE",`${g}/${e}`)}async recoverFile(e){return await c(this,d,m).call(this,"PUT",`${g}/${e}/recover`)}async downloadFile(e,t){return await c(this,d,Ke).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await c(this,d,m).call(this,"GET",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await c(this,d,m).call(this,"PUT",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await c(this,d,m).call(this,"DELETE",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await c(this,d,$e).call(this,e,async r=>(await c(this,d,m).call(this,"POST",`${g}/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 c(this,d,m).call(this,"GET",G,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await c(this,d,m).call(this,"GET",`${G}/${e}`)}async getFoldersBatch(e){return await c(this,d,$e).call(this,e,async t=>(await c(this,d,m).call(this,"POST",`${g}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await c(this,d,m).call(this,"POST",G,{body:JSON.stringify({name:e,...t&&{parentId:t},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(e,t){const{name:s}=t;return await c(this,d,m).call(this,"PUT",`${G}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await c(this,d,m).call(this,"DELETE",`${G}/${e}`)}async recoverFolder(e){return await c(this,d,m).call(this,"PUT",`${G}/${e}/recover`)}async downloadFolder(e){return await c(this,d,re).call(this,`${G}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await c(this,d,m).call(this,"GET",`${G}/${t}/items`,{query:{itemType:ut,...s&&{ShowVersions:s}}}):await c(this,d,m).call(this,"GET",`${g}`,{query:{itemType:ut,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await c(this,d,xt).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await c(this,d,ze).call(this,e,ut,t)}async updateComponent(e,t){const{componentProps:s}=t;return await c(this,d,$t).call(this,e,t,s)}async downloadComponent(e,t){return await c(this,d,Ke).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,d,re).call(this,`${g}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await c(this,d,m).call(this,"DELETE",`${g}/${e}`)}async recoverComponent(e){return await c(this,d,m).call(this,"PUT",`${g}/${e}/recover`)}async getBuiltInComponent(e){return await(await c(this,d,re).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]),u=new Function(...o,`${r}
2
- return main;`)(...a),h=(u==null?void 0:u.componentDefinition)??u;t.get(h)}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 c(this,d,m).call(this,"GET",`${G}/${t}/items`,{query:{itemType:ft,...s&&{ShowVersions:s}}}):await c(this,d,m).call(this,"GET",`${g}`,{query:{itemType:ft,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await c(this,d,ze).call(this,e,ft,t)}async downloadApp(e,t){return await c(this,d,Ke).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,d,re).call(this,`${g}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await c(this,d,m).call(this,"DELETE",`${g}/${e}`)}async getNpmCredentials(){return await c(this,d,m).call(this,"GET",`${Or}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${ne}/${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 c(this,d,m).call(this,"POST",`${ne}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${ne}/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 c(this,d,m).call(this,"POST",`${ne}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${ne}/${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 c(this,d,m).call(this,"GET",`${ne}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${ne}/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 c(this,d,m).call(this,"GET",`${ne}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl??this.wsUrl,r=await xe(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 Gt(this,e)}history(e){return new qs(this,e)}get recipes(){return f(this,Fe)??k(this,Fe,new Us(this)),f(this,Fe)}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 c(this,d,m).call(this,"POST",`${g}/${K}`,{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 c(this,d,m).call(this,"POST",`${g}/${K}/batch`,{body:r})}async deleteHiddenFile(e){return await c(this,d,m).call(this,"DELETE",`${g}/${K}/${e}`)}async getHiddenFile(e){return await c(this,d,m).call(this,"GET",`${g}/${K}/${e}`)}async downloadHiddenFile(e){return await c(this,d,re).call(this,`${g}/${K}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await c(this,d,m).call(this,"GET",`${g}/${K}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await c(this,d,$e).call(this,e,async s=>(await c(this,d,m).call(this,"POST",`${g}/${K}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...t!=null&&{expiresIn:t}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(e,t){return await c(this,d,m).call(this,"GET",`${g}/${e}/${K}`,{...t!=null&&{query:{tag:t}}})}async deleteHiddenFilesByParent(e){return await c(this,d,m).call(this,"DELETE",`${g}/${e}/${K}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await c(this,d,m).call(this,"PUT",`${g}/${e}/icon`,{body:s})}async getItemIcon(e){return await c(this,d,re).call(this,`${g}/${e}/icon`)}async removeItemIcon(e){return await c(this,d,m).call(this,"DELETE",`${g}/${e}/icon`)}async updateItem(e,t){return await c(this,d,m).call(this,"PUT",`${g}/${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 c(this,d,m).call(this,"POST",`${g}/${e}/version`,{body:o})}async listVersions(e,t={}){return await c(this,d,m).call(this,"GET",`${g}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await c(this,d,$e).call(this,e,async r=>(await c(this,d,m).call(this,"POST",`${g}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(e,t){return await c(this,d,m).call(this,"PUT",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await c(this,d,m).call(this,"PUT",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await c(this,d,m).call(this,"DELETE",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};d=new WeakSet,Ct=function(e){return`${this.apiUrl}/${e}`},m=async function(e,t,s){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:u}=s||{},h=c(this,d,Ct).call(this,t),y=c(this,d,Vs).call(this,i),w=await this.resolveAccessToken(),I={...y,...this.useBearer?{}:{accessToken:w}};try{const _=await fetch(h+"?"+new URLSearchParams(I).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${w}`}},...r&&{body:r}});if(!_.ok){const S=await _.text().then(x=>x).catch(()=>"");throw new nt(_.status,_.statusText,S,$r(_))}return l==="blob"?await _.blob():_.json().then(S=>S).catch(()=>{})}catch(_){const S=a??this.retries;if(S>0&&xr(_)){const x=u??0;return await Cr(Nr(_,x)),await c(this,d,m).call(this,e,t,{...s,retries:S-1,retryAttempt:x+1})}throw _}},re=async function(e,t){const{query:s}=t||{},r=c(this,d,Ct).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}`}}})},Fe=new WeakMap,$e=async function(e,t){if(!e.length)return[];const s=[];for(let i=0;i<e.length;i+=Rt)s.push(e.slice(i,i+Rt));return(await Promise.all(s.map(t))).flat()},Ke=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,d,re).call(this,`${g}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},ze=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:u}=e,h=new FormData;return h.append("file",l),h.append("name",r),h.append("versionTag",i),h.append("itemType",t),o&&h.append("folderId",o),a&&h.append("projectId",a),s&&h.append("extraProps",JSON.stringify(s)),u&&h.append("metadata",JSON.stringify(u)),await c(this,d,m).call(this,"POST",g,{body:h})},$t=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=t;let u,h;if(a){const y=new FormData;y.append("file",a),i&&y.append("versionTag",i),s&&y.append("extraProps",JSON.stringify(s)),l&&y.append("metadata",JSON.stringify(l)),h=await c(this,d,m).call(this,"POST",`${g}/${e}/version`,{body:y})}if(r||o){const y={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(y);u=await c(this,d,m).call(this,"PUT",`${g}/${e}`,{body:w,contentType:"application/json"})}return{item:u,version:h}},xt=async function(e,t){const{showVersions:s=!1}=t||{};return await c(this,d,m).call(this,"GET",`${g}/${e}`,{query:{showVersions:s}})},Vs=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let et=zt;function Gs(){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 Nt="channel:",Pr=1e4;function Xe(n){try{n()}catch(e){console.error("[channel] a listener threw:",e)}}var Q,F,L,Ee,Te,_e,P,Pt,Bt,ve;class Jt{constructor(e,t){T(this,P);T(this,Q,!1);T(this,F,[]);T(this,L,[]);T(this,Ee,new Set);T(this,Te,new Set);T(this,_e,new Set);this.transport=e,this.controls=t}get joined(){return f(this,Q)}get peers(){return f(this,F)}join(){return f(this,Q)?Promise.resolve():c(this,P,Pt).call(this,"joined",this.controls.join)}leave(){return!f(this,Q)&&!f(this,L).some(e=>e.want==="joined")?Promise.resolve():c(this,P,Pt).call(this,"left",this.controls.leave)}onChange(e){return f(this,Ee).add(e),()=>void f(this,Ee).delete(e)}onPeerJoined(e){return f(this,Te).add(e),()=>void f(this,Te).delete(e)}onPeerLeft(e){return f(this,_e).add(e),()=>void f(this,_e).delete(e)}applyJoined(){k(this,Q,!0),c(this,P,Bt).call(this,"joined"),c(this,P,ve).call(this)}applyLeft(){k(this,Q,!1),k(this,F,[]),c(this,P,Bt).call(this,"left"),c(this,P,ve).call(this)}applyPeers(e){k(this,F,e),c(this,P,ve).call(this)}applyPeerJoined(e){!f(this,Q)||f(this,F).some(t=>t.from===e.from)||(k(this,F,[...f(this,F),e]),f(this,Te).forEach(t=>Xe(()=>t(e))),c(this,P,ve).call(this))}applyPeerLeft(e){const t=f(this,F).find(s=>s.from===e);t&&(k(this,F,f(this,F).filter(s=>s.from!==e)),f(this,_e).forEach(s=>Xe(()=>s(t))),c(this,P,ve).call(this))}failPending(e){const t=f(this,L);return k(this,L,[]),t.forEach(s=>{clearTimeout(s.timer),s.reject(e)}),t.length>0}post(e){this.transport.post(e)}}Q=new WeakMap,F=new WeakMap,L=new WeakMap,Ee=new WeakMap,Te=new WeakMap,_e=new WeakMap,P=new WeakSet,Pt=function(e,t){return new Promise((s,r)=>{const i={want:e,resolve:s,reject:r,timer:setTimeout(()=>{k(this,L,f(this,L).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${e==="joined"?"joining":"leaving"} in time.`))},Pr)};f(this,L).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...t})})},Bt=function(e){const t=f(this,L).filter(s=>s.want===e);k(this,L,f(this,L).filter(s=>s.want!==e)),t.forEach(s=>{clearTimeout(s.timer),s.resolve()})},ve=function(){f(this,Ee).forEach(e=>Xe(e))};var Ie;class Hs extends Jt{constructor(t){super(t,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});T(this,Ie,new Map)}on(t,s){const r=f(this,Ie).get(t)??new Set;return r.add(s),f(this,Ie).set(t,r),()=>void r.delete(s)}send(t,s){if(t.startsWith(Nt))throw new Error(`Message types starting with '${Nt}' 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=f(this,Ie).get(t.type);if(!(s!=null&&s.size))return{handled:!1};const r=Ws(t);return s.forEach(i=>Xe(()=>i(t.payload,r))),{handled:!0}}}Ie=new WeakMap;var oe;class Js extends Jt{constructor(t,s){super(t,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});T(this,oe,new Map);this.kind=s}on(t,s){if(f(this,oe).has(t))throw new Error(`"${t}" already has a handler in this room. Remove it first.`);return f(this,oe).set(t,s),()=>void f(this,oe).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 f(this,oe).size>0}async handle(t){const s=f(this,oe).get(t.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(t.payload,Ws(t))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}oe=new WeakMap;function Ws(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function Br(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 ue,Le,Z,ae,ce,R,Ft,Qe,Ks,zs,Xs,Lt;class Ys{constructor(e){T(this,R);T(this,ue);T(this,Le);T(this,Z);T(this,ae,new Map);T(this,ce,new Set);k(this,ue,e),k(this,Le,e.listen(t=>void c(this,R,Ks).call(this,t)))}collab(){return f(this,Z)??k(this,Z,new Hs(f(this,ue))),f(this,Z)}external(e){const t=e??"";let s=f(this,ae).get(t);return s||(s=new Js(f(this,ue),e),f(this,ae).set(t,s)),s}dispose(){f(this,Le).call(this)}}ue=new WeakMap,Le=new WeakMap,Z=new WeakMap,ae=new WeakMap,ce=new WeakMap,R=new WeakSet,Ft=function(){return[...f(this,Z)?[f(this,Z)]:[],...f(this,ae).values()]},Qe=function(e,t){if(e==="collab")return f(this,Z);if(e==="external")return f(this,ae).get(typeof t=="string"?t:"")},Ks=async function(e){const t=Br(e);if(t){if(t.type.startsWith(Nt)){c(this,R,zs).call(this,t);return}await c(this,R,Xs).call(this,t)}},zs=function(e){var s,r,i;const t=e.payload??{};switch(e.type){case"channel:joined":(s=c(this,R,Qe).call(this,t.scope,t.kind))==null||s.applyJoined();break;case"channel:left":(r=c(this,R,Qe).call(this,t.scope,t.kind))==null||r.applyLeft();break;case"channel:peers":(i=c(this,R,Qe).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"?[f(this,Z)]:[...f(this,ae).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));c(this,R,Ft).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",e.payload);break}}},Xs=async function(e){const t=c(this,R,Ft).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&&c(this,R,Lt).call(this,e.requestId,o))}e.requestId&&e.scope==="external"&&t.length>0&&!s&&c(this,R,Lt).call(this,e.requestId,{handled:!0,error:`No handler for "${e.type}".`})},Lt=function(e,t){f(this,ce).has(e)||(f(this,ce).add(e),f(this,ce).size>500&&f(this,ce).delete(f(this,ce).values().next().value),f(this,ue).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 de="project",me="notifications";var Se,je;const Xt=class Xt extends et{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});T(this,Se);T(this,je);typeof t=="function"&&k(this,Se,t)}async resolveAccessToken(){return f(this,Se)?await f(this,Se).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Xt(s.accessToken,s.apiUrl,t);return r.context=s,r}get channel(){return f(this,je)??k(this,je,new Ys(Gs())),f(this,je)}async listProjects(){return await this.request("GET",de)}async getProject(t){return await this.request("GET",`${de}/${t}`)}async getProjectData(t){return await this.request("GET",`${de}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${de}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${de}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",me,{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",`${me}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${me}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${me}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${me}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${me}/subscriptions/${t}`)}async subscribeToAutomation(t,s,r){return await this.request("POST",`${de}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,r){return await this.request("PATCH",`${de}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),r=xe(`${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()}};Se=new WeakMap,je=new WeakMap;let jt=Xt;async function Wt(n){const[e,t]=await Fr(),s=t.Model.getRootAsModel(new e.ByteBuffer(await Lr(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),u=s.guids(a);l!==null&&u&&i.set(l,u)}const o=[];for(let a=0;a<s.attributesLength();a++){const l=s.localIds(a);if(l===null)continue;const u={},h=s.attributes(a);for(let y=0;y<((h==null?void 0:h.dataLength())??0);y++){const w=h.data(y);if(w)try{const[I,_]=JSON.parse(w);u[I]=_}catch{}}o.push({localId:l,guid:i.get(l)??null,category:s.categories(a)??null,attrs:u})}return{metadata:r,items:o}}async function Fr(){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 Lr(n){const e=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const jr="flow:",qr="flow:op",Dr="flow:source",Qs="revitflow/op@2",ps="REVITFLOWCHANGE",ms="REVITFLOWOPERATION";class Yt{constructor(e){N(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:Qs,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 Mr();return Ur(this.flatbuffer(s,r,e,JSON.stringify(t)))}pack(e,t){const s={};for(const[r,i]of Object.entries(e??{}))r.startsWith(jr)||(s[r]=String(i));return t.position&&(s.Position=t.position.map(ys).join(",")),t.rotationDeg!==void 0&&(s.Rotation=ys(t.rotationDeg)),t.source&&(s[Dr]=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:u}=t,h=new e.Builder(1024),y=this.changes.length,w=new Uint32Array(y);let I=1;for(let C=0;C<y;C++)w[C]=I++;const _=I++,S=C=>(C(h,0),h.endVector()),x=o.createShellsVector(h,[]),ee=o.createCircleExtrusionsVector(h,[]),q=S(o.startSamplesVector),le=S(o.startRepresentationsVector),te=S(o.startMaterialsVector),pe=S(o.startLocalTransformsVector),A=S(o.startGlobalTransformsVector),D=o.createMeshesItemsVector(h,[]),E=o.createMaterialIdsVector(h,[]),v=o.createRepresentationIdsVector(h,[]),$=o.createSampleIdsVector(h,[]),M=o.createLocalTransformIdsVector(h,[]),B=o.createGlobalTransformIdsVector(h,[]);o.startMeshes(h),o.addCoordinates(h,u.createTransform(h,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(h,A),o.addShells(h,x),o.addRepresentations(h,le),o.addSamples(h,q),o.addLocalTransforms(h,pe),o.addMaterials(h,te),o.addCircleExtrusions(h,ee),o.addMeshesItems(h,D),o.addRepresentationIds(h,v),o.addSampleIds(h,$),o.addMaterialIds(h,E),o.addLocalTransformIds(h,M),o.addGlobalTransformIds(h,B);const Y=o.endMeshes(h),cn=h.createString(r),rt=new Set,it=[];for(const C of this.changes){const se=[],bn={[qr]:C.op,...C.attrs};for(const[vn,En]of Object.entries(bn)){const ts=JSON.stringify([vn,En,"IFCTEXT"]);rt.add(ts),se.push(h.createString(ts))}it.push(i.createAttribute(h,i.createDataVector(h,se)))}{const C=JSON.stringify(["Name",s,"IFCLABEL"]);rt.add(C);const se=i.createDataVector(h,[h.createString(C)]);it.push(i.createAttribute(h,se))}const hn=a.createAttributesVector(h,it),ln=a.createUniqueAttributesVector(h,[...rt].map(C=>h.createString(C))),Qt=this.changes.map(()=>h.createString(ps));Qt.push(h.createString(ms));const dn=a.createCategoriesVector(h,Qt),Zt=[],es=[];this.changes.forEach((C,se)=>{C.item&&(Zt.push(h.createString(C.item)),es.push(w[se]))});const un=a.createGuidsVector(h,Zt),fn=a.createGuidsItemsVector(h,es),pn=a.createLocalIdsVector(h,[...w,_]),mn=this.changes.map((C,se)=>l.createSpatialStructure(h,w[se],h.createString(ps),0)),yn=l.createSpatialStructure(h,_,h.createString(ms),l.createChildrenVector(h,mn)),gn=h.createString(s);a.startModel(h),a.addMeshes(h,Y),a.addMetadata(h,cn),a.addAttributes(h,hn),a.addUniqueAttributes(h,ln),a.addLocalIds(h,pn),a.addCategories(h,dn),a.addGuidsItems(h,fn),a.addGuids(h,un),a.addGuid(h,gn),a.addSpatialStructure(h,yn),a.addMaxLocalId(h,I);const wn=a.endModel(h);return a.finishModelBuffer(h,wn),h.asUint8Array()}}async function Mr(){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 ys(n){return Number.isFinite(n)?String(n):"0"}async function Ur(n){const e=new Blob([n]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const Vr="Element",Gr="Carried",Zs=1/.3048;function Hr(n){const e=[];for(const t of n)for(const s of[Vr,Gr]){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 gs(n,e){const t=n.params[e];if(typeof t!="string")return null;try{return JSON.parse(t)}catch{return null}}function Jr(n){const e=new Map;for(const t of n){if(t.kind!=="datum"||t.params.of!=="level")continue;const s=t.params.named;typeof s=="string"&&e.set(t.id,s)}return e}async function en(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 Wt(new Uint8Array(await i.arrayBuffer())),a=o.filter(u=>u.attrs["flow:op"]),l=r.affectedIds??[];for(let u=0;u<a.length&&u<l.length;u++){const h=a[u].attrs["flow:source"];h&&(a[u].attrs["flow:op"]==="remove"?t.delete(h):t.set(h,l[u]))}}catch{}return t}async function tn(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 Wt(t)}}const ws=180/Math.PI;function bs(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)}}function sn(n){return async e=>{var A,D;const{picked:t,contents:s}=await tn(e,e.input),r=Hr(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;if(!i&&!o)throw new Error("Choose the Revit column type, or trust the model style names.");if(a&&!o)throw new Error("Free-standing instances can only be proposed by their style names: turn trustStyleNames on.");const l=Jr(r),u=`recipe:${n}-to-revit`,h=await en(e,u),y=await e.targetDoc.latest(),w=new Yt({project:e.projectId,document:e.targetDoc.docId,baseCommit:(y==null?void 0:y.version)??0,author:u}),I=Zs,_=E=>`${t.fileId}:${E.id}`;let S=0,x=0,ee=0;const q=new Set,le=(E,v,$,M)=>{const B=_(E);q.add(B);const Y=h.get(B);Y?w.set(Y,{},{position:$,rotationDeg:M,source:B}):w.add(v,{position:$,rotationDeg:M,source:B})};for(const E of r){if(E.kind==="member"&&E.params.of==="column"){const v=gs(E,"member"),$=v==null?void 0:v.start;if(!$||$.length!==3)continue;const M=o?bs(E.params.lookRef):null;if(o&&!M)continue;const B=M??{family:i.family,type:i.type},Y=l.get(String((v==null?void 0:v.level)??""));le(E,{...i&&!o?{CategoryId:i.categoryId}:{},Family:B.family,Type:B.type,...Y?{Level:Y}:{}},[$[0]*I,$[1]*I,$[2]*I],(Number((v==null?void 0:v.roll)??0)||0)*ws),S++;continue}if(a&&E.kind==="familyInstance"&&!E.params.host){const v=gs(E,"instance"),$=(A=v==null?void 0:v.placement)==null?void 0:A.at;if(!$||$.length!==3||v!=null&&v.host)continue;const M=bs(E.params.type);if(!M)continue;const B=(D=v==null?void 0:v.placement)==null?void 0:D.right,Y=B?Math.atan2(B[1],B[0])*ws:0;le(E,{Family:M.family,Type:M.type},[$[0]*I,$[1]*I,$[2]*I],Y),x++;continue}(E.kind==="run"||E.kind==="extrusion"||E.kind==="stair"||E.kind==="footing"||E.kind==="ramp")&&ee++}let te=0;for(const[E,v]of h)!E.startsWith(`${t.fileId}:`)||q.has(E)||(w.remove(v),te++);if(w.length===0)throw new Error(`Nothing the Revit applier can do yet: "${t.name}" has ${ee} element(s) with a body (walls, slabs, stairs…) and no column or free-standing instance. Those arrive as the applier grows.`);const pe=[S?`${S} column(s)`:"",x?`${x} instance(s)`:"",te?`${te} gone`:""].filter(Boolean);return{title:`${n==="ifc"?"IFC":"Model"} to Revit: ${pe.join(", ")}`,verb:w.summary,targets:w.length,payload:new Blob([await w.build(e.opId)]),ruleTallies:[{read:S,proposed:S},{read:x,proposed:x},{read:te,proposed:te},{read:ee,proposed:0}]}}}const Wr={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}}},Yr=[{reads:"Column records (members) with no proposal yet",proposes:"A new 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:"Walls, slabs, stairs and every element with a body",proposes:"Nothing yet — waits on the Revit applier growing"}],Kt={name:"frag-to-revit",title:"Platform model to Revit",description:"Turns the platform records of a .frag into change requests for a Revit document.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},runtime:"browser",settingsSchema:Wr,rules:Yr,doc:`
1
+ "use strict";var Tn=Object.create;var ot=Object.defineProperty;var _n=Object.getOwnPropertyDescriptor;var In=Object.getOwnPropertyNames;var Sn=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty;var ss=n=>{throw TypeError(n)};var An=(n,e,t)=>e in n?ot(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var On=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of In(e))!kn.call(n,r)&&r!==t&&ot(n,r,{get:()=>e[r],enumerable:!(s=_n(e,r))||s.enumerable});return n};var je=(n,e,t)=>(t=n!=null?Tn(Sn(n)):{},On(e||!n||!n.__esModule?ot(t,"default",{value:n,enumerable:!0}):t,n));var N=(n,e,t)=>An(n,typeof e!="symbol"?e+"":e,t),at=(n,e,t)=>e.has(n)||ss("Cannot "+t);var d=(n,e,t)=>(at(n,e,"read from private field"),t?t.call(n):e.get(n)),T=(n,e,t)=>e.has(n)?ss("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),k=(n,e,t,s)=>(at(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),h=(n,e,t)=>(at(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=Object.create(null);Y.open="0";Y.close="1";Y.ping="2";Y.pong="3";Y.message="4";Y.upgrade="5";Y.noop="6";const Ge=Object.create(null);Object.keys(Y).forEach(n=>{Ge[Y[n]]=n});const pt={type:"error",data:"parser error"},Es=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ts=typeof ArrayBuffer=="function",_s=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,jt=({type:n,data:e},t,s)=>Es&&e instanceof Blob?t?s(e):ns(e,s):Ts&&(e instanceof ArrayBuffer||_s(e))?t?s(e):ns(new Blob([e]),s):s(Y[n]+(e||"")),ns=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function rs(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let ct;function Rn(n,e){if(Es&&n.data instanceof Blob)return n.data.arrayBuffer().then(rs).then(e);if(Ts&&(n.data instanceof ArrayBuffer||_s(n.data)))return e(rs(n.data));jt(n,!1,t=>{ct||(ct=new TextEncoder),e(ct.encode(t))})}const is="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Oe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<is.length;n++)Oe[is.charCodeAt(n)]=n;const Cn=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 u=new ArrayBuffer(e),c=new Uint8Array(u);for(s=0;s<t;s+=4)i=Oe[n.charCodeAt(s)],o=Oe[n.charCodeAt(s+1)],a=Oe[n.charCodeAt(s+2)],l=Oe[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 u},$n=typeof ArrayBuffer=="function",Dt=(n,e)=>{if(typeof n!="string")return{type:"message",data:Is(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:xn(n.substring(1),e)}:Ge[t]?n.length>1?{type:Ge[t],data:n.substring(1)}:{type:Ge[t]}:pt},xn=(n,e)=>{if($n){const t=Cn(n);return Is(t,e)}else return{base64:!0,data:n}},Is=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Ss="",Nn=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{jt(i,!1,a=>{s[o]=a,++r===t&&e(s.join(Ss))})})},Pn=(n,e)=>{const t=n.split(Ss),s=[];for(let r=0;r<t.length;r++){const i=Dt(t[r],e);if(s.push(i),i.type==="error")break}return s};function Bn(){return new TransformStream({transform(n,e){Rn(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 ht;function De(n){return n.reduce((e,t)=>e+t.length,0)}function Me(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 Fn(n,e){ht||(ht=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(De(t)<1)break;const l=Me(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(De(t)<2)break;const l=Me(t,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),s=3}else if(s===2){if(De(t)<8)break;const l=Me(t,8),u=new DataView(l.buffer,l.byteOffset,l.length),c=u.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(pt);break}r=c*Math.pow(2,32)+u.getUint32(4),s=3}else{if(De(t)<r)break;const l=Me(t,r);a.enqueue(Dt(i?l:ht.decode(l),e)),s=0}if(r===0||r>n){a.enqueue(pt);break}}}})}const ks=4;function A(n){if(n)return Ln(n)}function Ln(n){for(var e in A.prototype)n[e]=A.prototype[e];return n}A.prototype.on=A.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};A.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};A.prototype.off=A.prototype.removeListener=A.prototype.removeAllListeners=A.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};A.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};A.prototype.emitReserved=A.prototype.emit;A.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};A.prototype.hasListeners=function(n){return!!this.listeners(n).length};const tt=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),q=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),qn="arraybuffer";function As(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const jn=q.setTimeout,Dn=q.clearTimeout;function st(n,e){e.useNativeTimers?(n.setTimeoutFn=jn.bind(q),n.clearTimeoutFn=Dn.bind(q)):(n.setTimeoutFn=q.setTimeout.bind(q),n.clearTimeoutFn=q.clearTimeout.bind(q))}const Mn=1.33;function Un(n){return typeof n=="string"?Vn(n):Math.ceil((n.byteLength||n.size)*Mn)}function Vn(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 Os(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Gn(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Hn(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 Jn extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class Mt extends A{constructor(e){super(),this.writable=!1,st(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 Jn(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=Dt(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=Gn(e);return t.length?"?"+t:""}}class Wn extends Mt{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)};Pn(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,Nn(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]=Os()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Rs=!1;try{Rs=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Yn=Rs;function Kn(){}class zn extends Wn{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 W extends A{constructor(e,t,s){super(),this.createRequest=e,st(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=As(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=W.requestsCount++,W.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=Kn,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete W.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()}}W.requestsCount=0;W.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",os);else if(typeof addEventListener=="function"){const n="onpagehide"in q?"pagehide":"unload";addEventListener(n,os,!1)}}function os(){for(let n in W.requests)W.requests.hasOwnProperty(n)&&W.requests[n].abort()}const Xn=function(){const n=Cs({xdomain:!1});return n&&n.responseType!==null}();class Qn extends zn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Xn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new W(Cs,this.uri(),e)}}function Cs(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Yn))return new XMLHttpRequest}catch{}if(!e)try{return new q[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const $s=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Zn extends Mt{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=$s?{}:As(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;jt(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&tt(()=>{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]=Os()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const lt=q.WebSocket||q.MozWebSocket;class er extends Zn{createSocket(e,t,s){return $s?new lt(e,t,s):t?new lt(e,t):new lt(e)}doWrite(e,t){this.ws.send(t)}}class tr extends Mt{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=Fn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Bn();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&&tt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const sr={websocket:er,webtransport:tr,polling:Qn},nr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mt(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=nr.exec(n||""),i={},o=14;for(;o--;)i[rr[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=ir(i,i.path),i.queryKey=or(i,i.query),i}function ir(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 or(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const yt=typeof addEventListener=="function"&&typeof removeEventListener=="function",He=[];yt&&addEventListener("offline",()=>{He.forEach(n=>n())},!1);class de extends A{constructor(e,t){if(super(),this.binaryType=qn,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=mt(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=mt(t.host).host);st(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=Hn(this.opts.query)),yt&&(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"})},He.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ks,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&&de.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",de.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+=Un(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,tt(()=>{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(de.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(),yt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=He.indexOf(this._offlineEventListener);s!==-1&&He.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}de.protocol=ks;class ar extends de{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;de.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;de.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 w=new Error("probe error");w.transport=t.name,this.emitReserved("upgradeError",w)}}))};function i(){s||(s=!0,c(),t.close(),t=null)}const o=m=>{const w=new Error("probe error: "+m);w.transport=t.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function u(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",u)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",l),this.once("upgrading",u),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 cr=class extends ar{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=>sr[i]).filter(i=>!!i)),super(s?r:e,r)}};function hr(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=mt(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 lr=typeof ArrayBuffer=="function",dr=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,xs=Object.prototype.toString,ur=typeof Blob=="function"||typeof Blob<"u"&&xs.call(Blob)==="[object BlobConstructor]",fr=typeof File=="function"||typeof File<"u"&&xs.call(File)==="[object FileConstructor]";function Ut(n){return lr&&(n instanceof ArrayBuffer||dr(n))||ur&&n instanceof Blob||fr&&n instanceof File}function Je(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(Je(n[t]))return!0;return!1}if(Ut(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Je(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Je(n[t]))return!0;return!1}function pr(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(Ut(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 mr(n,e){return n.data=wt(n.data,e),delete n.attachments,n}function wt(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]=wt(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=wt(n[t],e));return n}const yr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var b;(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"})(b||(b={}));class gr{constructor(e){this.replacer=e}encode(e){return(e.type===b.EVENT||e.type===b.ACK)&&Je(e)?this.encodeAsBinary({type:e.type===b.EVENT?b.BINARY_EVENT:b.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===b.BINARY_EVENT||e.type===b.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=pr(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class Vt extends A{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===b.BINARY_EVENT;s||t.type===b.BINARY_ACK?(t.type=s?b.EVENT:b.ACK,this.reconstructor=new wr(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Ut(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(b[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===b.BINARY_EVENT||s.type===b.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(!br(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(Vt.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 b.CONNECT:return as(t);case b.DISCONNECT:return t===void 0;case b.CONNECT_ERROR:return typeof t=="string"||as(t);case b.EVENT:case b.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&yr.indexOf(t[0])===-1);case b.ACK:case b.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class wr{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=mr(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const br=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function as(n){return Object.prototype.toString.call(n)==="[object Object]"}const vr=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Vt,Encoder:gr,get PacketType(){return b}},Symbol.toStringTag,{value:"Module"}));function V(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Er=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ns extends A{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=[V(e,"open",this.onopen.bind(this)),V(e,"packet",this.onpacket.bind(this)),V(e,"error",this.onerror.bind(this)),V(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(Er.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:b.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:b.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 b.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 b.EVENT:case b.BINARY_EVENT:this.onevent(e);break;case b.ACK:case b.BINARY_ACK:this.onack(e);break;case b.DISCONNECT:this.ondisconnect();break;case b.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:b.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:b.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 ke(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}ke.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};ke.prototype.reset=function(){this.attempts=0};ke.prototype.setMin=function(n){this.ms=n};ke.prototype.setMax=function(n){this.max=n};ke.prototype.setJitter=function(n){this.jitter=n};class bt extends A{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,st(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 ke({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||vr;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 cr(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=V(t,"open",function(){s.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=V(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(V(e,"ping",this.onping.bind(this)),V(e,"data",this.ondata.bind(this)),V(e,"error",this.onerror.bind(this)),V(e,"close",this.onclose.bind(this)),V(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){tt(()=>{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 Ns(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 Ae={};function xe(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=hr(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=Ae[r]&&i in Ae[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new bt(s,e):(Ae[r]||(Ae[r]=new bt(s,e)),l=Ae[r]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(xe,{Manager:bt,Socket:Ns,io:xe,connect:xe});const Ne="thatopen/document@1",vt="document.json",Ps=["pdf","txt","md","json","csv","tsv","frag"],cs=()=>`v-${Date.now()}`;function Ue(n){return String(n._id??n.id??"")}var me,Bs,Et;class Gt{constructor(e,t){T(this,me);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=Ue(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=hs(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=Ue(a);await this.client.updateFile(e,{parentFolderId:l});const u=[],c=await h(this,me,Bs).call(this,s);if(c)try{const I=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),u.push({fileId:c,format:hs(String(I.name??""),I.fileExtension)})}catch{}((t==null?void 0:t.selfView)??Ps.includes(i))&&u.push({fileId:e,format:i});const w={schema:Ne,name:o,native:{fileId:e,format:i},views:u};return await this.setDescriptor(l,w),{folderId:l,descriptor:w}}async descriptor(e){const t=await h(this,me,Et).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 Tr(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:Ne,views:t.views??[]},r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await h(this,me,Et).call(this,e);if(i){await this.client.updateFile(i.id,{file:r,versionTag:cs()});return}await this.client.createFile({file:r,name:vt,versionTag:cs(),parentFolderId:e,projectId:this.projectId})}}me=new WeakSet,Bs=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(Ue(e),s.tag),i=r==null?void 0:r.derivedFileId;if(typeof i=="string"&&i)return i}catch{}},Et=async function(e){const s=(await this.client.listFiles({folderId:e})).find(r=>String(r.name??"")===vt);return s?{id:Ue(s)}:void 0};function hs(n,e){const t=(e??"").replace(/^\./,"").toLowerCase();if(t)return t;const s=n.lastIndexOf(".");return s>0?n.slice(s+1).toLowerCase():""}function Tr(n){if(!n||typeof n!="object")return null;const e=n;if(e.schema!==Ne||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:Ne,name:e.name,...r?{native:{fileId:s.fileId,format:s.format}}:{},views:t}}class Tt 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",_t="revitflow_history.json",we="revitflow_ops.json",ds="revitflow/ops@1",Fs="revitflow_model.frag",Ls="revitflow_",_r="bimterop-locks-anchor",Ve=()=>`v-${Date.now()}`;function qs(n,e){return n.filter(t=>String(t.parentId??"")===e)}function J(n){return String(n._id??n.id??"")}var U,Pe,It;class js{constructor(e,t){T(this,Pe);T(this,U);this.client=e,this.projectId=t}async docs(){const e=await h(this,Pe,It).call(this);if(!e)return[];const t=await this.client.listFolders({parentFolderId:e,projectId:this.projectId}),s=[];for(const r of qs(t,e)){const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:J(r)})).map(m=>String(m.name??"")),u=l.find(m=>m===Fs)??l.find(m=>m.endsWith(".frag")&&!m.startsWith(Ls)),c=l.includes(_t)||l.includes(we)||!!u;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:J(r),modelName:u,...c?{}:{empty:!0}})}return s}doc(e,t){return new Ds(this.client,this,e,t)}async rootFolderId(e=!1){if(d(this,U))return d(this,U);const t=await h(this,Pe,It).call(this);if(t)return t;if(!e)return;const s=await this.client.createFolder(ls,void 0,this.projectId);return k(this,U,J(s)),d(this,U)}}U=new WeakMap,Pe=new WeakSet,It=async function(){if(d(this,U))return d(this,U);const t=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===ls&&!s.parentId);return t&&k(this,U,J(t)),d(this,U)};var Q,p,X,be,H,St,Re,ie,kt,We,Ce,Ye,At,Ms;class Ds{constructor(e,t,s,r){T(this,p);T(this,Q);this.client=e,this.project=t,this.source=s,this.docId=r}async timeline(){const e=await h(this,p,We).call(this);return Ht((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,ie).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,ie).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),u=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:u,at:t[r].guid}}async folderId(){return await h(this,p,H).call(this,!1)}async descriptor(){return await d(this,p,X).descriptor(await h(this,p,H).call(this,!1))}async view(e){const t=await h(this,p,H).call(this,!1),s=await d(this,p,X).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,ie).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(e){const t=await h(this,p,H).call(this,!0);if(await d(this,p,X).descriptor(t)){await d(this,p,X).addView(t,e);return}const r=await h(this,p,ie).call(this);await d(this,p,X).setDescriptor(t,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??d(this,p,be),views:[e]})}async ensureDescriptor(){const e=await h(this,p,H).call(this,!1),t=await d(this,p,X).descriptor(e);if(t)return t;const s=await h(this,p,ie).call(this);if(!s)return null;const r={name:s.name.replace(/\.frag$/,""),views:[{fileId:s.id,format:"frag"}]};return await d(this,p,X).setDescriptor(e,r),await d(this,p,X).descriptor(e)}async ownership(){const e=await h(this,p,Re).call(this,_r);if(!e)return[];const t=await this.client.getHiddenFilesByParent(e.id),s=await Promise.all(t.map(async o=>{try{const a=J(o),l=await this.client.downloadHiddenFile(a),u=JSON.parse(await l.text());return!u||typeof u!="object"||!("revitflowlock"in u)||!Array.isArray(u.keys)?null:{owner:String(u.user??""),keys:u.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,H).call(this,!0);let s=await h(this,p,We).call(this)??{model:this.docId,commits:[]};const r=us(s.commits);if(e.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==e.expectedLatestGuid)throw new Tt(e.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Ze(),...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:Ir(e.changes)};if(e.model&&(await h(this,p,Ms).call(this,t,e.model),i.full=!0),e.delta){const l=await h(this,p,ie).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const u=await this.client.createHiddenFile(e.delta,l.id);i.deltaId=String(u._id??u.id)}const o=await h(this,p,We).call(this);if(o){s=o;const l=us(s.commits);if(e.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==e.expectedLatestGuid)throw new Tt(e.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return s.commits.push(i),await h(this,p,Ye).call(this,t,_t,s),i}async suggestions(){const e=await h(this,p,Ce).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,H).call(this,!0),s=await h(this,p,Ce).call(this)??{schema:ds,ops:[]},r=await h(this,p,Re).call(this,we),i={opId:e.opId??Ze(),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,At).call(this,t,we,s),l=await this.client.createHiddenFile(e.payload,a.id);i.fragId=String(l._id??l.id)}const o=await h(this,p,Ce).call(this)??s;return o.schema??(o.schema=ds),o.ops.push(i),await h(this,p,Ye).call(this,t,we,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,H).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await h(this,p,Ce).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,Ye).call(this,s,we,r),i}}Q=new WeakMap,p=new WeakSet,X=function(){return new Gt(this.client,this.project.projectId)},be=function(){return`${this.source}-${this.docId}`},H=async function(e){if(d(this,Q))return d(this,Q);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=qs(s,t).find(o=>String(o.name??"")===d(this,p,be));if(r)return k(this,Q,J(r)),d(this,Q);if(!e)throw new Error(`Document ${d(this,p,be)} does not exist in this project.`);const i=await this.client.createFolder(d(this,p,be),t,this.project.projectId);return k(this,Q,J(i)),d(this,Q)},St=async function(){const e=await h(this,p,H).call(this,!1);return(await this.client.listFiles({folderId:e})).map(s=>({id:J(s),name:String(s.name??"")}))},Re=async function(e){try{return(await h(this,p,St).call(this)).find(t=>t.name===e)}catch{return}},ie=async function(){try{const e=await h(this,p,St).call(this);return e.find(t=>t.name===Fs)??e.find(t=>t.name.endsWith(".frag")&&!t.name.startsWith(Ls))}catch{return}},kt=async function(e){const t=await h(this,p,Re).call(this,e);if(!t)return;const r=await(await this.client.downloadFile(t.id)).text();if(r.trim())return JSON.parse(r)},We=function(){return h(this,p,kt).call(this,_t)},Ce=function(){return h(this,p,kt).call(this,we)},Ye=async function(e,t,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await h(this,p,Re).call(this,t);return i?(await this.client.updateFile(i.id,{file:r,versionTag:Ve()}),i):await h(this,p,At).call(this,e,t,s)},At=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:Ve(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:J(o??i),name:t}},Ms=async function(e,t){const s=await h(this,p,ie).call(this);if(s)return await this.client.updateFile(s.id,{file:t,versionTag:Ve()}),s;const r=`${d(this,p,be)}.frag`,i=await this.client.createFile({file:t,name:r,versionTag:Ve(),parentFolderId:e,projectId:this.project.projectId}),o=i.item;return{id:J(o??i),name:r}};function Ir(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 Ht(n){var l;if(n.length<=1)return n.forEach((u,c)=>u.ordinal=c),[...n];const e=new Map(n.map(u=>[u.guid,u])),t=new Map,s=[];for(const u of n){const c=(l=u.parents)==null?void 0:l[0];if(c&&e.has(c)){const m=t.get(c)??[];m.push(u),t.set(c,m)}else s.push(u)}const r=(u,c)=>String(u.timestamp).localeCompare(String(c.timestamp));s.sort(r);const i=[],o=[...s].reverse(),a=new Set;for(;o.length;){const u=o.pop();if(a.has(u.guid))continue;a.add(u.guid),i.push(u);const c=(t.get(u.guid)??[]).sort(r);for(let m=c.length-1;m>=0;m--)o.push(c[m])}for(const u of n)a.has(u.guid)||i.push(u);return i.forEach((u,c)=>u.ordinal=c),i}function us(n){const e=Ht(n);return e[e.length-1]}function Ze(){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 ae,Be,Ot;class Us{constructor(e){T(this,Be);T(this,ae,new Map);this.client=e}register(e){if(d(this,ae).has(e.name))throw new Error(`A recipe named "${e.name}" is already registered.`);d(this,ae).set(e.name,e)}list(e){return[...d(this,ae).values()].filter(s=>(!(e!=null&&e.to)||s.to===e.to)&&(!(e!=null&&e.input)||s.inputs.includes(e.input)))}get(e){return d(this,ae).get(e)}async plan(e,t){const{base:s,opId:r,result:i}=await h(this,Be,Ot).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,Be,Ot).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}}}ae=new WeakMap,Be=new WeakSet,Ot=async function(e,t){const s=d(this,ae).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=Ze(),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 Rt=100;function Sr(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 kr(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=Sr(r);super(o.message??`${s||"Request failed"} (${t})`);N(this,"status");N(this,"code");N(this,"details");N(this,"body");N(this,"retryAfter");this.name="RequestError",this.status=t,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??kr(o.details)}}const G="item/folder",g="item",re="processor",Ar="npm-registry",z="hidden",dt="FILE",ut="TOOL",ft="APP",Or=500,fs=3e4,Rr=.25,Cr=n=>new Promise(e=>setTimeout(e,n));function $r(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 xr(n){return n instanceof nt?n.status===429||n.status>=500:!0}function Nr(n,e){const t=Math.min(Or*2**e,fs),s=t*Rr*Math.random(),r=n instanceof nt&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,fs)+s:t+s}var f,Ct,y,oe,Fe,$e,Ke,ze,$t,xt,Vs;const zt=class zt{constructor(e,t,s){T(this,f);N(this,"apiUrl");N(this,"accessToken");N(this,"wsUrl");N(this,"retries");N(this,"useBearer");N(this,"builtInGlobals",null);N(this,"localServerUrl",null);N(this,"context");T(this,Fe);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 zt(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,y).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await h(this,f,y).call(this,"GET",`${G}/${t}/items`,{query:{itemType:dt,archived:s}}):await h(this,f,y).call(this,"GET",`${g}`,{query:{itemType:dt,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await h(this,f,xt).call(this,e,t)}async createFile(e){return await h(this,f,ze).call(this,e,dt)}async updateFile(e,t){return await h(this,f,$t).call(this,e,t)}async archiveFile(e){return await h(this,f,y).call(this,"DELETE",`${g}/${e}`)}async recoverFile(e){return await h(this,f,y).call(this,"PUT",`${g}/${e}/recover`)}async downloadFile(e,t){return await h(this,f,Ke).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await h(this,f,y).call(this,"GET",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await h(this,f,y).call(this,"PUT",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await h(this,f,y).call(this,"DELETE",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await h(this,f,$e).call(this,e,async r=>(await h(this,f,y).call(this,"POST",`${g}/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,y).call(this,"GET",G,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await h(this,f,y).call(this,"GET",`${G}/${e}`)}async getFoldersBatch(e){return await h(this,f,$e).call(this,e,async t=>(await h(this,f,y).call(this,"POST",`${g}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await h(this,f,y).call(this,"POST",G,{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,y).call(this,"PUT",`${G}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await h(this,f,y).call(this,"DELETE",`${G}/${e}`)}async recoverFolder(e){return await h(this,f,y).call(this,"PUT",`${G}/${e}/recover`)}async downloadFolder(e){return await h(this,f,oe).call(this,`${G}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await h(this,f,y).call(this,"GET",`${G}/${t}/items`,{query:{itemType:ut,...s&&{ShowVersions:s}}}):await h(this,f,y).call(this,"GET",`${g}`,{query:{itemType:ut,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await h(this,f,xt).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await h(this,f,ze).call(this,e,ut,t)}async updateComponent(e,t){const{componentProps:s}=t;return await h(this,f,$t).call(this,e,t,s)}async downloadComponent(e,t){return await h(this,f,Ke).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await h(this,f,oe).call(this,`${g}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await h(this,f,y).call(this,"DELETE",`${g}/${e}`)}async recoverComponent(e){return await h(this,f,y).call(this,"PUT",`${g}/${e}/recover`)}async getBuiltInComponent(e){return await(await h(this,f,oe).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]),u=new Function(...o,`${r}
2
+ return main;`)(...a),c=(u==null?void 0:u.componentDefinition)??u;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,y).call(this,"GET",`${G}/${t}/items`,{query:{itemType:ft,...s&&{ShowVersions:s}}}):await h(this,f,y).call(this,"GET",`${g}`,{query:{itemType:ft,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await h(this,f,ze).call(this,e,ft,t)}async downloadApp(e,t){return await h(this,f,Ke).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await h(this,f,oe).call(this,`${g}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await h(this,f,y).call(this,"DELETE",`${g}/${e}`)}async getNpmCredentials(){return await h(this,f,y).call(this,"GET",`${Ar}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${re}/${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,y).call(this,"POST",`${re}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${re}/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,y).call(this,"POST",`${re}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${re}/${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,y).call(this,"GET",`${re}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${re}/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,y).call(this,"GET",`${re}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl??this.wsUrl,r=await xe(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 Gt(this,e)}history(e){return new js(this,e)}get recipes(){return d(this,Fe)??k(this,Fe,new Us(this)),d(this,Fe)}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,y).call(this,"POST",`${g}/${z}`,{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,y).call(this,"POST",`${g}/${z}/batch`,{body:r})}async deleteHiddenFile(e){return await h(this,f,y).call(this,"DELETE",`${g}/${z}/${e}`)}async getHiddenFile(e){return await h(this,f,y).call(this,"GET",`${g}/${z}/${e}`)}async downloadHiddenFile(e){return await h(this,f,oe).call(this,`${g}/${z}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await h(this,f,y).call(this,"GET",`${g}/${z}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await h(this,f,$e).call(this,e,async s=>(await h(this,f,y).call(this,"POST",`${g}/${z}/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,y).call(this,"GET",`${g}/${e}/${z}`,{...t!=null&&{query:{tag:t}}})}async deleteHiddenFilesByParent(e){return await h(this,f,y).call(this,"DELETE",`${g}/${e}/${z}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await h(this,f,y).call(this,"PUT",`${g}/${e}/icon`,{body:s})}async getItemIcon(e){return await h(this,f,oe).call(this,`${g}/${e}/icon`)}async removeItemIcon(e){return await h(this,f,y).call(this,"DELETE",`${g}/${e}/icon`)}async updateItem(e,t){return await h(this,f,y).call(this,"PUT",`${g}/${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,y).call(this,"POST",`${g}/${e}/version`,{body:o})}async listVersions(e,t={}){return await h(this,f,y).call(this,"GET",`${g}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await h(this,f,$e).call(this,e,async r=>(await h(this,f,y).call(this,"POST",`${g}/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,y).call(this,"PUT",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await h(this,f,y).call(this,"PUT",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await h(this,f,y).call(this,"DELETE",`${g}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};f=new WeakSet,Ct=function(e){return`${this.apiUrl}/${e}`},y=async function(e,t,s){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:u}=s||{},c=h(this,f,Ct).call(this,t),m=h(this,f,Vs).call(this,i),w=await this.resolveAccessToken(),I={...m,...this.useBearer?{}:{accessToken:w}};try{const _=await fetch(c+"?"+new URLSearchParams(I).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${w}`}},...r&&{body:r}});if(!_.ok){const S=await _.text().then(x=>x).catch(()=>"");throw new nt(_.status,_.statusText,S,$r(_))}return l==="blob"?await _.blob():_.json().then(S=>S).catch(()=>{})}catch(_){const S=a??this.retries;if(S>0&&xr(_)){const x=u??0;return await Cr(Nr(_,x)),await h(this,f,y).call(this,e,t,{...s,retries:S-1,retryAttempt:x+1})}throw _}},oe=async function(e,t){const{query:s}=t||{},r=h(this,f,Ct).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}`}}})},Fe=new WeakMap,$e=async function(e,t){if(!e.length)return[];const s=[];for(let i=0;i<e.length;i+=Rt)s.push(e.slice(i,i+Rt));return(await Promise.all(s.map(t))).flat()},Ke=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await h(this,f,oe).call(this,`${g}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},ze=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:u}=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)),u&&c.append("metadata",JSON.stringify(u)),await h(this,f,y).call(this,"POST",g,{body:c})},$t=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=t;let u,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,y).call(this,"POST",`${g}/${e}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(m);u=await h(this,f,y).call(this,"PUT",`${g}/${e}`,{body:w,contentType:"application/json"})}return{item:u,version:c}},xt=async function(e,t){const{showVersions:s=!1}=t||{};return await h(this,f,y).call(this,"GET",`${g}/${e}`,{query:{showVersions:s}})},Vs=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let et=zt;function Gs(){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 Nt="channel:",Pr=1e4;function Xe(n){try{n()}catch(e){console.error("[channel] a listener threw:",e)}}var Z,F,L,Ee,Te,_e,P,Pt,Bt,ve;class Jt{constructor(e,t){T(this,P);T(this,Z,!1);T(this,F,[]);T(this,L,[]);T(this,Ee,new Set);T(this,Te,new Set);T(this,_e,new Set);this.transport=e,this.controls=t}get joined(){return d(this,Z)}get peers(){return d(this,F)}join(){return d(this,Z)?Promise.resolve():h(this,P,Pt).call(this,"joined",this.controls.join)}leave(){return!d(this,Z)&&!d(this,L).some(e=>e.want==="joined")?Promise.resolve():h(this,P,Pt).call(this,"left",this.controls.leave)}onChange(e){return d(this,Ee).add(e),()=>void d(this,Ee).delete(e)}onPeerJoined(e){return d(this,Te).add(e),()=>void d(this,Te).delete(e)}onPeerLeft(e){return d(this,_e).add(e),()=>void d(this,_e).delete(e)}applyJoined(){k(this,Z,!0),h(this,P,Bt).call(this,"joined"),h(this,P,ve).call(this)}applyLeft(){k(this,Z,!1),k(this,F,[]),h(this,P,Bt).call(this,"left"),h(this,P,ve).call(this)}applyPeers(e){k(this,F,e),h(this,P,ve).call(this)}applyPeerJoined(e){!d(this,Z)||d(this,F).some(t=>t.from===e.from)||(k(this,F,[...d(this,F),e]),d(this,Te).forEach(t=>Xe(()=>t(e))),h(this,P,ve).call(this))}applyPeerLeft(e){const t=d(this,F).find(s=>s.from===e);t&&(k(this,F,d(this,F).filter(s=>s.from!==e)),d(this,_e).forEach(s=>Xe(()=>s(t))),h(this,P,ve).call(this))}failPending(e){const t=d(this,L);return k(this,L,[]),t.forEach(s=>{clearTimeout(s.timer),s.reject(e)}),t.length>0}post(e){this.transport.post(e)}}Z=new WeakMap,F=new WeakMap,L=new WeakMap,Ee=new WeakMap,Te=new WeakMap,_e=new WeakMap,P=new WeakSet,Pt=function(e,t){return new Promise((s,r)=>{const i={want:e,resolve:s,reject:r,timer:setTimeout(()=>{k(this,L,d(this,L).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${e==="joined"?"joining":"leaving"} in time.`))},Pr)};d(this,L).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...t})})},Bt=function(e){const t=d(this,L).filter(s=>s.want===e);k(this,L,d(this,L).filter(s=>s.want!==e)),t.forEach(s=>{clearTimeout(s.timer),s.resolve()})},ve=function(){d(this,Ee).forEach(e=>Xe(e))};var Ie;class Hs extends Jt{constructor(t){super(t,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});T(this,Ie,new Map)}on(t,s){const r=d(this,Ie).get(t)??new Set;return r.add(s),d(this,Ie).set(t,r),()=>void r.delete(s)}send(t,s){if(t.startsWith(Nt))throw new Error(`Message types starting with '${Nt}' 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=d(this,Ie).get(t.type);if(!(s!=null&&s.size))return{handled:!1};const r=Ws(t);return s.forEach(i=>Xe(()=>i(t.payload,r))),{handled:!0}}}Ie=new WeakMap;var ce;class Js extends Jt{constructor(t,s){super(t,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});T(this,ce,new Map);this.kind=s}on(t,s){if(d(this,ce).has(t))throw new Error(`"${t}" already has a handler in this room. Remove it first.`);return d(this,ce).set(t,s),()=>void d(this,ce).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 d(this,ce).size>0}async handle(t){const s=d(this,ce).get(t.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(t.payload,Ws(t))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}ce=new WeakMap;function Ws(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function Br(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 pe,Le,ee,he,le,R,Ft,Qe,Ks,zs,Xs,Lt;class Ys{constructor(e){T(this,R);T(this,pe);T(this,Le);T(this,ee);T(this,he,new Map);T(this,le,new Set);k(this,pe,e),k(this,Le,e.listen(t=>void h(this,R,Ks).call(this,t)))}collab(){return d(this,ee)??k(this,ee,new Hs(d(this,pe))),d(this,ee)}external(e){const t=e??"";let s=d(this,he).get(t);return s||(s=new Js(d(this,pe),e),d(this,he).set(t,s)),s}dispose(){d(this,Le).call(this)}}pe=new WeakMap,Le=new WeakMap,ee=new WeakMap,he=new WeakMap,le=new WeakMap,R=new WeakSet,Ft=function(){return[...d(this,ee)?[d(this,ee)]:[],...d(this,he).values()]},Qe=function(e,t){if(e==="collab")return d(this,ee);if(e==="external")return d(this,he).get(typeof t=="string"?t:"")},Ks=async function(e){const t=Br(e);if(t){if(t.type.startsWith(Nt)){h(this,R,zs).call(this,t);return}await h(this,R,Xs).call(this,t)}},zs=function(e){var s,r,i;const t=e.payload??{};switch(e.type){case"channel:joined":(s=h(this,R,Qe).call(this,t.scope,t.kind))==null||s.applyJoined();break;case"channel:left":(r=h(this,R,Qe).call(this,t.scope,t.kind))==null||r.applyLeft();break;case"channel:peers":(i=h(this,R,Qe).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"?[d(this,ee)]:[...d(this,he).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,R,Ft).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",e.payload);break}}},Xs=async function(e){const t=h(this,R,Ft).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,R,Lt).call(this,e.requestId,o))}e.requestId&&e.scope==="external"&&t.length>0&&!s&&h(this,R,Lt).call(this,e.requestId,{handled:!0,error:`No handler for "${e.type}".`})},Lt=function(e,t){d(this,le).has(e)||(d(this,le).add(e),d(this,le).size>500&&d(this,le).delete(d(this,le).values().next().value),d(this,pe).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 fe="project",ge="notifications";var Se,qe;const Xt=class Xt extends et{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});T(this,Se);T(this,qe);typeof t=="function"&&k(this,Se,t)}async resolveAccessToken(){return d(this,Se)?await d(this,Se).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Xt(s.accessToken,s.apiUrl,t);return r.context=s,r}get channel(){return d(this,qe)??k(this,qe,new Ys(Gs())),d(this,qe)}async listProjects(){return await this.request("GET",fe)}async getProject(t){return await this.request("GET",`${fe}/${t}`)}async getProjectData(t){return await this.request("GET",`${fe}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${fe}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${fe}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",ge,{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",`${ge}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${ge}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${ge}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${ge}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${ge}/subscriptions/${t}`)}async subscribeToAutomation(t,s,r){return await this.request("POST",`${fe}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,r){return await this.request("PATCH",`${fe}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),r=xe(`${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()}};Se=new WeakMap,qe=new WeakMap;let qt=Xt;async function Wt(n){const[e,t]=await Fr(),s=t.Model.getRootAsModel(new e.ByteBuffer(await Lr(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),u=s.guids(a);l!==null&&u&&i.set(l,u)}const o=[];for(let a=0;a<s.attributesLength();a++){const l=s.localIds(a);if(l===null)continue;const u={},c=s.attributes(a);for(let m=0;m<((c==null?void 0:c.dataLength())??0);m++){const w=c.data(m);if(w)try{const[I,_]=JSON.parse(w);u[I]=_}catch{}}o.push({localId:l,guid:i.get(l)??null,category:s.categories(a)??null,attrs:u})}return{metadata:r,items:o}}async function Fr(){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 Lr(n){const e=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const qr="flow:",jr="flow:op",Dr="flow:source",Qs="revitflow/op@2",ps="REVITFLOWCHANGE",ms="REVITFLOWOPERATION";class Yt{constructor(e){N(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:Qs,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 Mr();return Ur(this.flatbuffer(s,r,e,JSON.stringify(t)))}pack(e,t){const s={};for(const[r,i]of Object.entries(e??{}))r.startsWith(qr)||(s[r]=String(i));return t.position&&(s.Position=t.position.map(ys).join(",")),t.rotationDeg!==void 0&&(s.Rotation=ys(t.rotationDeg)),t.source&&(s[Dr]=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:u}=t,c=new e.Builder(1024),m=this.changes.length,w=new Uint32Array(m);let I=1;for(let C=0;C<m;C++)w[C]=I++;const _=I++,S=C=>(C(c,0),c.endVector()),x=o.createShellsVector(c,[]),te=o.createCircleExtrusionsVector(c,[]),j=S(o.startSamplesVector),ue=S(o.startRepresentationsVector),se=S(o.startMaterialsVector),ye=S(o.startLocalTransformsVector),O=S(o.startGlobalTransformsVector),D=o.createMeshesItemsVector(c,[]),E=o.createMaterialIdsVector(c,[]),v=o.createRepresentationIdsVector(c,[]),$=o.createSampleIdsVector(c,[]),M=o.createLocalTransformIdsVector(c,[]),B=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,u.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,O),o.addShells(c,x),o.addRepresentations(c,ue),o.addSamples(c,j),o.addLocalTransforms(c,ye),o.addMaterials(c,se),o.addCircleExtrusions(c,te),o.addMeshesItems(c,D),o.addRepresentationIds(c,v),o.addSampleIds(c,$),o.addMaterialIds(c,E),o.addLocalTransformIds(c,M),o.addGlobalTransformIds(c,B);const K=o.endMeshes(c),cn=c.createString(r),rt=new Set,it=[];for(const C of this.changes){const ne=[],bn={[jr]:C.op,...C.attrs};for(const[vn,En]of Object.entries(bn)){const ts=JSON.stringify([vn,En,"IFCTEXT"]);rt.add(ts),ne.push(c.createString(ts))}it.push(i.createAttribute(c,i.createDataVector(c,ne)))}{const C=JSON.stringify(["Name",s,"IFCLABEL"]);rt.add(C);const ne=i.createDataVector(c,[c.createString(C)]);it.push(i.createAttribute(c,ne))}const hn=a.createAttributesVector(c,it),ln=a.createUniqueAttributesVector(c,[...rt].map(C=>c.createString(C))),Qt=this.changes.map(()=>c.createString(ps));Qt.push(c.createString(ms));const dn=a.createCategoriesVector(c,Qt),Zt=[],es=[];this.changes.forEach((C,ne)=>{C.item&&(Zt.push(c.createString(C.item)),es.push(w[ne]))});const un=a.createGuidsVector(c,Zt),fn=a.createGuidsItemsVector(c,es),pn=a.createLocalIdsVector(c,[...w,_]),mn=this.changes.map((C,ne)=>l.createSpatialStructure(c,w[ne],c.createString(ps),0)),yn=l.createSpatialStructure(c,_,c.createString(ms),l.createChildrenVector(c,mn)),gn=c.createString(s);a.startModel(c),a.addMeshes(c,K),a.addMetadata(c,cn),a.addAttributes(c,hn),a.addUniqueAttributes(c,ln),a.addLocalIds(c,pn),a.addCategories(c,dn),a.addGuidsItems(c,fn),a.addGuids(c,un),a.addGuid(c,gn),a.addSpatialStructure(c,yn),a.addMaxLocalId(c,I);const wn=a.endModel(c);return a.finishModelBuffer(c,wn),c.asUint8Array()}}async function Mr(){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 ys(n){return Number.isFinite(n)?String(n):"0"}async function Ur(n){const e=new Blob([n]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}const Vr="Element",Gr="Carried",Zs=1/.3048;function Hr(n){const e=[];for(const t of n)for(const s of[Vr,Gr]){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 gs(n,e){const t=n.params[e];if(typeof t!="string")return null;try{return JSON.parse(t)}catch{return null}}function Jr(n){const e=new Map;for(const t of n){if(t.kind!=="datum"||t.params.of!=="level")continue;const s=t.params.named;typeof s=="string"&&e.set(t.id,s)}return e}async function en(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 Wt(new Uint8Array(await i.arrayBuffer())),a=o.filter(u=>u.attrs["flow:op"]),l=r.affectedIds??[];for(let u=0;u<a.length&&u<l.length;u++){const c=a[u].attrs["flow:source"];c&&(a[u].attrs["flow:op"]==="remove"?t.delete(c):t.set(c,l[u]))}}catch{}return t}async function tn(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 Wt(t)}}const ws=180/Math.PI;function bs(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)}}function sn(n){return async e=>{var O,D;const{picked:t,contents:s}=await tn(e,e.input),r=Hr(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;if(!i&&!o)throw new Error("Choose the Revit column type, or trust the model style names.");if(a&&!o)throw new Error("Free-standing instances can only be proposed by their style names: turn trustStyleNames on.");const l=Jr(r),u=`recipe:${n}-to-revit`,c=await en(e,u),m=await e.targetDoc.latest(),w=new Yt({project:e.projectId,document:e.targetDoc.docId,baseCommit:(m==null?void 0:m.version)??0,author:u}),I=Zs,_=E=>`${t.fileId}:${E.id}`;let S=0,x=0,te=0;const j=new Set,ue=(E,v,$,M)=>{const B=_(E);j.add(B);const K=c.get(B);K?w.set(K,{},{position:$,rotationDeg:M,source:B}):w.add(v,{position:$,rotationDeg:M,source:B})};for(const E of r){if(E.kind==="member"&&E.params.of==="column"){const v=gs(E,"member"),$=v==null?void 0:v.start;if(!$||$.length!==3)continue;const M=o?bs(E.params.lookRef):null;if(o&&!M)continue;const B=M??{family:i.family,type:i.type},K=l.get(String((v==null?void 0:v.level)??""));ue(E,{...i&&!o?{CategoryId:i.categoryId}:{},Family:B.family,Type:B.type,...K?{Level:K}:{}},[$[0]*I,$[1]*I,$[2]*I],(Number((v==null?void 0:v.roll)??0)||0)*ws),S++;continue}if(a&&E.kind==="familyInstance"&&!E.params.host){const v=gs(E,"instance"),$=(O=v==null?void 0:v.placement)==null?void 0:O.at;if(!$||$.length!==3||v!=null&&v.host)continue;const M=bs(E.params.type);if(!M)continue;const B=(D=v==null?void 0:v.placement)==null?void 0:D.right,K=B?Math.atan2(B[1],B[0])*ws:0;ue(E,{Family:M.family,Type:M.type},[$[0]*I,$[1]*I,$[2]*I],K),x++;continue}(E.kind==="run"||E.kind==="extrusion"||E.kind==="stair"||E.kind==="footing"||E.kind==="ramp")&&te++}let se=0;for(const[E,v]of c)!E.startsWith(`${t.fileId}:`)||j.has(E)||(w.remove(v),se++);if(w.length===0)throw new Error(`Nothing the Revit applier can do yet: "${t.name}" has ${te} element(s) with a body (walls, slabs, stairs...) and no column or free-standing instance. Those arrive as the applier grows.`);const ye=[S?`${S} column(s)`:"",x?`${x} instance(s)`:"",se?`${se} gone`:""].filter(Boolean);return{title:`${n==="ifc"?"IFC":"Model"} to Revit: ${ye.join(", ")}`,verb:w.summary,targets:w.length,payload:new Blob([await w.build(e.opId)]),ruleTallies:[{read:S,proposed:S},{read:x,proposed:x},{read:se,proposed:se},{read:te,proposed:0}]}}}const Wr={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}}},Yr=[{reads:"Column records (members) with no proposal yet",proposes:"A new 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:"Walls, slabs, stairs and every element with a body",proposes:"Nothing yet - waits on the Revit applier growing"}],Kt={name:"frag-to-revit",title:"Platform model to Revit",description:"Turns the platform records of a .frag into change requests for a Revit document.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},runtime:"browser",settingsSchema:Wr,rules:Yr,doc:`
3
3
  ## What it does
4
4
 
5
5
  It reads a .frag made or edited on the platform and asks a Revit document for
@@ -18,18 +18,18 @@ the applier learns native creation for them.
18
18
  Run it again after the model changed and it asks only for the difference. It
19
19
  can only ever ask to remove what it asked for itself; elements a person made
20
20
  in Revit are invisible to it. What it made is read back from its own applied
21
- requests — it keeps nothing of its own.
21
+ requests - it keeps nothing of its own.
22
22
 
23
23
  ## Units and axes
24
24
 
25
25
  Records are metres, Z up; proposals are written in Revit's feet. Types are
26
26
  matched exactly by name; Revit refuses the whole request when one is missing.
27
- `,run:sn("frag")},nn={...Kt,name:"ifc-to-revit",title:"IFC to Revit",description:"Turns an IFC — through the frag the platform converted it into — into change requests for a Revit document.",inputs:["ifc-model"],doc:`
27
+ `,run:sn("frag")},nn={...Kt,name:"ifc-to-revit",title:"IFC to Revit",description:"Turns an IFC - through the frag the platform converted it into - into change requests for a Revit document.",inputs:["ifc-model"],doc:`
28
28
  ## What it does
29
29
 
30
30
  It reads the .frag your IFC was PROCESSED into (the IFC document's view) and
31
31
  asks a Revit document for the elements its records describe. Point it at that
32
- frag: a plain IFC import carries only IFC attributes and is refused by name —
32
+ frag: a plain IFC import carries only IFC attributes and is refused by name -
33
33
  the editable converter is what gives an IFC real records.
34
34
 
35
35
  ## What it can ask for today
@@ -43,7 +43,7 @@ the applier learns native creation for them.
43
43
 
44
44
  Run it again after a reconversion and it asks only for the difference. It can
45
45
  only ever ask to remove what it asked for itself. What it made is read back
46
- from its own applied requests — it keeps nothing of its own.
46
+ from its own applied requests - it keeps nothing of its own.
47
47
 
48
48
  ## Units and axes
49
49
 
@@ -62,7 +62,7 @@ accepts the request there.
62
62
  Run it again after the Rhino model changed and it asks only for the
63
63
  difference: new objects become new instances, moved objects move theirs, and
64
64
  an object that is gone asks for its instance to be removed. It can only ever
65
- ask to remove an instance it asked for itself — elements a person made in
65
+ ask to remove an instance it asked for itself - elements a person made in
66
66
  Revit are invisible to it. What it made is read back from its own applied
67
67
  requests; it keeps nothing of its own.
68
68
 
@@ -78,5 +78,5 @@ requests; it keeps nothing of its own.
78
78
  Where an object becomes an instance, Revit decides the level: the nearest one
79
79
  at or below the point. For a level-based family the level wins over the
80
80
  point's height.
81
- `,async run(n){var pe;const{picked:e,contents:t}=await tn(n,n.input),{layer:s,instanceType:r}=n.settings;if(!s||!r)throw new Error("Choose the layer and the Revit type.");const i=(pe=t.metadata)==null?void 0:pe.data,o=i==null?void 0:i.units,a=typeof o=="string"?Kr[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 u=a*Zs,h=await en(n,vs),y=await n.targetDoc.latest(),w=new Yt({project:n.projectId,document:n.targetDoc.docId,baseCommit:(y==null?void 0:y.version)??0,author:vs});let I=0,_=0,S=0;const x=new Set,ee=[];for(const A of t.items){if(!A.guid||Object.keys(A.attrs).length===0)continue;if((A.attrs.Layer??"")!==s){S++;continue}const D=zr(A);if(!D)continue;x.add(A.guid);const E=[D[0]*u,D[1]*u,D[2]*u],v=h.get(A.guid);v?ee.push({instance:v,object:A.guid,position:E}):(w.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:E,source:A.guid}),I++)}for(const A of ee)w.set(A.instance,{},{position:A.position,source:A.object}),_++;let q=0;for(const[A,D]of h)x.has(A)||(w.remove(D),q++);const le=I+_+q;if(le===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: ${[I?`${I} new`:"",_?`${_} moved`:"",q?`${q} gone`:""].filter(Boolean).join(", ")}`,verb:w.summary,targets:le,payload:new Blob([await w.build(n.opId)]),ruleTallies:[{read:I,proposed:I},{read:_,proposed:_},{read:q,proposed:q},{read:S,proposed:0}]}}},an=[on,nn,Kt];function Xr(n){for(const e of an)n.recipes.register(e)}const Qr={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Zr={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},ei={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},ti={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},si={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},ni={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},ri={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},ii={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},oi={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},ai={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Zr;exports.ChannelClient=Ys;exports.ChannelRoom=Jt;exports.ClashesManager=ei;exports.CollabRoom=Hs;exports.DOCUMENT_FILE=vt;exports.DOCUMENT_SCHEMA=Ne;exports.EngineServicesClient=et;exports.ExternalRoom=Js;exports.FileList=ti;exports.FlowDoc=Ds;exports.GISManager=si;exports.GitHistoryManager=ni;exports.HelloWorld=ri;exports.METADATA_LIMITS=Qr;exports.OP_SCHEMA=Qs;exports.OperationBuilder=Yt;exports.PlatformClient=jt;exports.ProjectDocuments=Gt;exports.ProjectHistory=qs;exports.ProjectManager=ii;exports.Recipes=Us;exports.RequestError=nt;exports.SELF_VIEWING_FORMATS=Ps;exports.STORAGE_BATCH_MAX=Rt;exports.StaleHistoryError=Tt;exports.TopicsManager=oi;exports.UIManager=ai;exports.builtinRecipes=an;exports.fragToRevit=Kt;exports.ifcToRevit=nn;exports.mintGuid=Ze;exports.orderByGraph=Ht;exports.readFrag=Wt;exports.registerBuiltinRecipes=Xr;exports.rhinoToRevit=on;exports.windowTransport=Gs;
81
+ `,async run(n){var ye;const{picked:e,contents:t}=await tn(n,n.input),{layer:s,instanceType:r}=n.settings;if(!s||!r)throw new Error("Choose the layer and the Revit type.");const i=(ye=t.metadata)==null?void 0:ye.data,o=i==null?void 0:i.units,a=typeof o=="string"?Kr[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 u=a*Zs,c=await en(n,vs),m=await n.targetDoc.latest(),w=new Yt({project:n.projectId,document:n.targetDoc.docId,baseCommit:(m==null?void 0:m.version)??0,author:vs});let I=0,_=0,S=0;const x=new Set,te=[];for(const O of t.items){if(!O.guid||Object.keys(O.attrs).length===0)continue;if((O.attrs.Layer??"")!==s){S++;continue}const D=zr(O);if(!D)continue;x.add(O.guid);const E=[D[0]*u,D[1]*u,D[2]*u],v=c.get(O.guid);v?te.push({instance:v,object:O.guid,position:E}):(w.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:E,source:O.guid}),I++)}for(const O of te)w.set(O.instance,{},{position:O.position,source:O.object}),_++;let j=0;for(const[O,D]of c)x.has(O)||(w.remove(D),j++);const ue=I+_+j;if(ue===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: ${[I?`${I} new`:"",_?`${_} moved`:"",j?`${j} gone`:""].filter(Boolean).join(", ")}`,verb:w.summary,targets:ue,payload:new Blob([await w.build(n.opId)]),ruleTallies:[{read:I,proposed:I},{read:_,proposed:_},{read:j,proposed:j},{read:S,proposed:0}]}}},an=[on,nn,Kt];function Xr(n){for(const e of an)n.recipes.register(e)}const Qr={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Zr={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},ei={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},ti={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},si={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},ni={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},ri={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},ii={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},oi={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},ai={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Zr;exports.ChannelClient=Ys;exports.ChannelRoom=Jt;exports.ClashesManager=ei;exports.CollabRoom=Hs;exports.DOCUMENT_FILE=vt;exports.DOCUMENT_SCHEMA=Ne;exports.EngineServicesClient=et;exports.ExternalRoom=Js;exports.FileList=ti;exports.FlowDoc=Ds;exports.GISManager=si;exports.GitHistoryManager=ni;exports.HelloWorld=ri;exports.METADATA_LIMITS=Qr;exports.OP_SCHEMA=Qs;exports.OperationBuilder=Yt;exports.PlatformClient=qt;exports.ProjectDocuments=Gt;exports.ProjectHistory=js;exports.ProjectManager=ii;exports.Recipes=Us;exports.RequestError=nt;exports.SELF_VIEWING_FORMATS=Ps;exports.STORAGE_BATCH_MAX=Rt;exports.StaleHistoryError=Tt;exports.TopicsManager=oi;exports.UIManager=ai;exports.builtinRecipes=an;exports.fragToRevit=Kt;exports.ifcToRevit=nn;exports.mintGuid=Ze;exports.orderByGraph=Ht;exports.readFrag=Wt;exports.registerBuiltinRecipes=Xr;exports.rhinoToRevit=on;exports.windowTransport=Gs;
82
82
  //# sourceMappingURL=index.cjs.js.map