@thatopen/services 0.30.0 → 0.31.2
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/cli.js +8 -24
- package/dist/cli.js.map +1 -1
- package/dist/core/builtin-recipes/shapes-to-families.d.ts +3 -1
- package/dist/core/client.d.ts +0 -19
- package/dist/core/documents.d.ts +13 -2
- package/dist/index.cjs.js +5 -5
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +1331 -1276
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var xi=Object.create;var Fn=Object.defineProperty;var Ri=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Mi=Object.prototype.hasOwnProperty;var dr=s=>{throw TypeError(s)};var Fi=(s,t,e)=>t in s?Fn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Li=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ki(t))!Mi.call(s,r)&&r!==e&&Fn(s,r,{get:()=>t[r],enumerable:!(n=Ri(t,r))||n.enumerable});return s};var dn=(s,t,e)=>(e=s!=null?xi(Ni(s)):{},Li(t||!s||!s.__esModule?Fn(e,"default",{value:s,enumerable:!0}):e,s));var xt=(s,t,e)=>Fi(s,typeof t!="symbol"?t+"":t,e),Ln=(s,t,e)=>t.has(s)||dr("Cannot "+e);var m=(s,t,e)=>(Ln(s,t,"read from private field"),e?e.call(s):t.get(s)),z=(s,t,e)=>t.has(s)?dr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),rt=(s,t,e,n)=>(Ln(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),p=(s,t,e)=>(Ln(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Qt=Object.create(null);Qt.open="0";Qt.close="1";Qt.ping="2";Qt.pong="3";Qt.message="4";Qt.upgrade="5";Qt.noop="6";const mn=Object.create(null);Object.keys(Qt).forEach(s=>{mn[Qt[s]]=s});const Hn={type:"error",data:"parser error"},Rr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",kr=typeof ArrayBuffer=="function",Nr=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,vs=({type:s,data:t},e,n)=>Rr&&t instanceof Blob?e?n(t):fr(t,n):kr&&(t instanceof ArrayBuffer||Nr(t))?e?n(t):fr(new Blob([t]),n):n(Qt[s]+(t||"")),fr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function ur(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Pn;function Pi(s,t){if(Rr&&s.data instanceof Blob)return s.data.arrayBuffer().then(ur).then(t);if(kr&&(s.data instanceof ArrayBuffer||Nr(s.data)))return t(ur(s.data));vs(s,!1,e=>{Pn||(Pn=new TextEncoder),t(Pn.encode(e))})}const pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",We=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<pr.length;s++)We[pr.charCodeAt(s)]=s;const Bi=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,a,l;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(n=0;n<e;n+=4)i=We[s.charCodeAt(n)],o=We[s.charCodeAt(n+1)],a=We[s.charCodeAt(n+2)],l=We[s.charCodeAt(n+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Di=typeof ArrayBuffer=="function",bs=(s,t)=>{if(typeof s!="string")return{type:"message",data:Mr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:ji(s.substring(1),t)}:mn[e]?s.length>1?{type:mn[e],data:s.substring(1)}:{type:mn[e]}:Hn},ji=(s,t)=>{if(Di){const e=Bi(s);return Mr(e,t)}else return{base64:!0,data:s}},Mr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Fr="",Ui=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{vs(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Fr))})})},qi=(s,t)=>{const e=s.split(Fr),n=[];for(let r=0;r<e.length;r++){const i=bs(e[r],t);if(n.push(i),i.type==="error")break}return n};function Vi(){return new TransformStream({transform(s,t){Pi(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Bn;function fn(s){return s.reduce((t,e)=>t+e.length,0)}function un(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function Gi(s,t){Bn||(Bn=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(e.push(o);;){if(n===0){if(fn(e)<1)break;const l=un(e,1);i=(l[0]&128)===128,r=l[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(fn(e)<2)break;const l=un(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(fn(e)<8)break;const l=un(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Hn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(fn(e)<r)break;const l=un(e,r);a.enqueue(bs(i?l:Bn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Hn);break}}}})}const Lr=4;function Et(s){if(s)return Hi(s)}function Hi(s){for(var t in Et.prototype)s[t]=Et.prototype[t];return s}Et.prototype.on=Et.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};Et.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};Et.prototype.off=Et.prototype.removeListener=Et.prototype.removeAllListeners=Et.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};Et.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};Et.prototype.emitReserved=Et.prototype.emit;Et.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};Et.prototype.hasListeners=function(s){return!!this.listeners(s).length};const Cn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),jt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ji="arraybuffer";function Pr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Wi=jt.setTimeout,zi=jt.clearTimeout;function $n(s,t){t.useNativeTimers?(s.setTimeoutFn=Wi.bind(jt),s.clearTimeoutFn=zi.bind(jt)):(s.setTimeoutFn=jt.setTimeout.bind(jt),s.clearTimeoutFn=jt.clearTimeout.bind(jt))}const Yi=1.33;function Ki(s){return typeof s=="string"?Xi(s):Math.ceil((s.byteLength||s.size)*Yi)}function Xi(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function Br(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Qi(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function Zi(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class to extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Ts extends Et{constructor(t){super(),this.writable=!1,$n(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new to(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=bs(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_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(t){const e=Qi(t);return e.length?"?"+e:""}}class eo extends Ts{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};qi(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Ui(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Br()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Dr=!1;try{Dr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const no=Dr;function so(){}class ro extends eo{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class Xt extends Et{constructor(t,e,n){super(),this.createRequest=t,$n(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const e=Pr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=Xt.requestsCount++,Xt.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=so,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Xt.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Xt.requestsCount=0;Xt.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",mr);else if(typeof addEventListener=="function"){const s="onpagehide"in jt?"pagehide":"unload";addEventListener(s,mr,!1)}}function mr(){for(let s in Xt.requests)Xt.requests.hasOwnProperty(s)&&Xt.requests[s].abort()}const io=function(){const s=jr({xdomain:!1});return s&&s.responseType!==null}();class oo extends ro{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=io&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Xt(jr,this.uri(),t)}}function jr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||no))return new XMLHttpRequest}catch{}if(!t)try{return new jt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ur=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ao extends Ts{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Ur?{}:Pr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}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=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;vs(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&Cn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Br()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Dn=jt.WebSocket||jt.MozWebSocket;class co extends ao{createSocket(t,e,n){return Ur?new Dn(t,e,n):e?new Dn(t,e):new Dn(t)}doWrite(t,e){this.ws.send(e)}}class lo extends Ts{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=Gi(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=Vi();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.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(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&Cn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const ho={websocket:co,webtransport:lo,polling:oo},fo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,uo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Jn(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=fo.exec(s||""),i={},o=14;for(;o--;)i[uo[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,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=po(i,i.path),i.queryKey=mo(i,i.query),i}function po(s,t){const e=/\/{2,9}/g,n=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function mo(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const Wn=typeof addEventListener=="function"&&typeof removeEventListener=="function",gn=[];Wn&&addEventListener("offline",()=>{gn.forEach(s=>s())},!1);class Te extends Et{constructor(t,e){if(super(),this.binaryType=Ji,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const n=Jn(t);e.hostname=n.host,e.secure=n.protocol==="https"||n.protocol==="wss",e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Jn(e.host).host);$n(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),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},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Zi(this.opts.query)),Wn&&(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"})},gn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Lr,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Te.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Te.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+=Ki(r)),n>0&&e>this._maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Cn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Te.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){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(),Wn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=gn.indexOf(this._offlineEventListener);n!==-1&&gn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Te.protocol=Lr;class go extends Te{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;Te.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",y=>{if(!n)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Te.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const O=new Error("probe error");O.transport=e.name,this.emitReserved("upgradeError",O)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const o=y=>{const O=new Error("probe error: "+y);O.transport=e.name,i(),this.emitReserved("upgradeError",O)};function a(){o("transport closed")}function l(){o("socket closed")}function d(y){e&&y.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};e.once("open",r),e.once("error",o),e.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let yo=class extends go{constructor(t,e={}){const n=typeof t=="object",r=n?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>ho[i]).filter(i=>!!i)),super(n?r:t,r)}};function wo(s,t="",e){let n=s;e=e||typeof location<"u"&&location,s==null&&(s=e.protocol+"//"+e.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=e.protocol+s:s=e.host+s),/^(https?|wss?):\/\//.test(s)||(typeof e<"u"?s=e.protocol+"//"+s:s="https://"+s),n=Jn(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}const vo=typeof ArrayBuffer=="function",bo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,qr=Object.prototype.toString,To=typeof Blob=="function"||typeof Blob<"u"&&qr.call(Blob)==="[object BlobConstructor]",Eo=typeof File=="function"||typeof File<"u"&&qr.call(File)==="[object FileConstructor]";function Es(s){return vo&&(s instanceof ArrayBuffer||bo(s))||To&&s instanceof Blob||Eo&&s instanceof File}function yn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(yn(s[e]))return!0;return!1}if(Es(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return yn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&yn(s[e]))return!0;return!1}function Io(s){const t=[],e=s.data,n=s;return n.data=zn(e,t),n.attachments=t.length,{packet:n,buffers:t}}function zn(s,t){if(!s)return s;if(Es(s)){const e={_placeholder:!0,num:t.length};return t.push(s),e}else if(Array.isArray(s)){const e=new Array(s.length);for(let n=0;n<s.length;n++)e[n]=zn(s[n],t);return e}else if(typeof s=="object"&&!(s instanceof Date)){const e={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(e[n]=zn(s[n],t));return e}return s}function So(s,t){return s.data=Yn(s.data,t),delete s.attachments,s}function Yn(s,t){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<t.length)return t[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=Yn(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Yn(s[e],t));return s}const _o=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Y;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(Y||(Y={}));class Ao{constructor(t){this.replacer=t}encode(t){return(t.type===Y.EVENT||t.type===Y.ACK)&&yn(t)?this.encodeAsBinary({type:t.type===Y.EVENT?Y.BINARY_EVENT:Y.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===Y.BINARY_EVENT||t.type===Y.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Io(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class Is extends Et{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===Y.BINARY_EVENT;n||e.type===Y.BINARY_ACK?(e.type=n?Y.EVENT:Y.ACK,this.reconstructor=new Oo(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Es(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(Y[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Y.BINARY_EVENT||n.type===Y.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Co(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(Is.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case Y.CONNECT:return gr(e);case Y.DISCONNECT:return e===void 0;case Y.CONNECT_ERROR:return typeof e=="string"||gr(e);case Y.EVENT:case Y.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&_o.indexOf(e[0])===-1);case Y.ACK:case Y.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Oo{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=So(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Co=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function gr(s){return Object.prototype.toString.call(s)==="[object Object]"}const $o=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Is,Encoder:Ao,get PacketType(){return Y}},Symbol.toStringTag,{value:"Module"}));function Gt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const xo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Vr extends Et{constructor(t,e,n){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=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Gt(t,"open",this.onopen.bind(this)),Gt(t,"packet",this.onpacket.bind(this)),Gt(t,"error",this.onerror.bind(this)),Gt(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(xo.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:Y.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,y=e.pop();this._registerAckCallback(c,y),o.id=c}const a=(r=(n=this.io.engine)===null||n===void 0?void 0:n.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(t,e){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);e.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),e.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(o,a)=>o?r(o):n(a);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Y.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Y.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 Y.EVENT:case Y.BINARY_EVENT:this.onevent(t);break;case Y.ACK:case Y.BINARY_ACK:this.onack(t);break;case Y.DISCONNECT:this.ondisconnect();break;case Y.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:Y.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Y.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function je(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}je.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*s);s=Math.floor(t*10)&1?s+e:s-e}return Math.min(s,this.max)|0};je.prototype.reset=function(){this.attempts=0};je.prototype.setMin=function(s){this.ms=s};je.prototype.setMax=function(s){this.max=s};je.prototype.setJitter=function(s){this.jitter=s};class Kn extends Et{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,$n(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((n=e.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new je({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||$o;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new yo(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=Gt(e,"open",function(){n.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=Gt(e,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Gt(t,"ping",this.onping.bind(this)),Gt(t,"data",this.ondata.bind(this)),Gt(t,"error",this.onerror.bind(this)),Gt(t,"close",this.onclose.bind(this)),Gt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){Cn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Vr(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Ge={};function Xe(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=wo(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=Ge[r]&&i in Ge[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new Kn(n,t):(Ge[r]||(Ge[r]=new Kn(n,t)),l=Ge[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(Xe,{Manager:Kn,Socket:Vr,io:Xe,connect:Xe});class Xn extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const yr="bimterop",Qn="revitflow_history.json",Gr="revitflow_model.frag",Hr="revitflow_",Ro="bimterop-locks-anchor";function ko(s,t){return s.filter(e=>String(e.parentId??"")===t)}function No(s){const t=s==null?void 0:s.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Yt(s){return String(s._id??s.id??"")}var Vt,Se,ie,Ze,tn,Zn;class Ss{constructor(t,e){z(this,tn);z(this,Vt);z(this,Se,new Map);z(this,ie);z(this,Ze,0);this.client=t,this.projectId=e}async docs(){const t=await p(this,tn,Zn).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const r of e){if(r.archived)continue;const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:Yt(r)})).map(y=>String(y.name??"")),d=l.find(y=>y===Gr)??l.find(y=>y.endsWith(".frag")&&!y.startsWith(Hr)),c=l.includes(Qn)||!!d;n.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:Yt(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=m(this,Se).get(n);return r||(r=new ts(this.client,this,t,e),m(this,Se).set(n,r)),r}document(t){const e=`platform-${t}`;let n=m(this,Se).get(e);return n||(n=new ts(this.client,this,"platform",t,t),m(this,Se).set(e,n)),n}async childFolders(t,e=!1){return(e||!m(this,ie)||Date.now()-m(this,Ze)>3e4)&&(rt(this,Ze,Date.now()),rt(this,ie,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>ko(n,t))),m(this,ie).catch(()=>{rt(this,ie,void 0)})),m(this,ie)}forgetFolders(){rt(this,ie,void 0)}async rootFolderId(t=!1){if(m(this,Vt))return m(this,Vt);const e=await p(this,tn,Zn).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(yr,void 0,this.projectId);return rt(this,Vt,Yt(n)),m(this,Vt)}}Vt=new WeakMap,Se=new WeakMap,ie=new WeakMap,Ze=new WeakMap,tn=new WeakSet,Zn=async function(){if(m(this,Vt))return m(this,Vt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===yr&&!n.parentId);return e&&rt(this,Vt,Yt(e)),m(this,Vt)};var Wt,$,re,xe,pe,zt,en,es,wn,me,Jr,vn,Wr,zr,Yr;class ts{constructor(t,e,n,r,i){z(this,$);z(this,Wt);z(this,zt);z(this,en,0);this.client=t,this.project=e,this.source=n,this.docId=r,rt(this,Wt,i)}async timeline(){const t=await p(this,$,vn).call(this);return _s((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await p(this,$,me).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async modelParts(t){const e=await this.timeline();if(e.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const n=t==null?void 0:t.at,r=n?e.findIndex(c=>c.guid===n):e.length-1;if(r<0)throw new Error(`No version ${n} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(e[c].full){i=c;break}const o=await p(this,$,me).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=e[i],l=e.slice(r+1).some(c=>c.full),d=e.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(y=>y.type==="delete").map(y=>y.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!l,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:e[r].guid}}async folderId(){return await p(this,$,pe).call(this,!1)}async descriptor(){return await m(this,$,re).descriptor(await p(this,$,pe).call(this,!1))}async view(t){const e=await p(this,$,pe).call(this,!1),n=await m(this,$,re).descriptor(e);if(n){for(const i of t){const o=n.views.find(a=>a.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await p(this,$,me).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await p(this,$,pe).call(this,!0);if(await m(this,$,re).descriptor(e)){await m(this,$,re).addView(e,t);return}const r=await p(this,$,me).call(this);await m(this,$,re).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??m(this,$,xe),views:[t]})}async ensureDescriptor(){const t=await p(this,$,pe).call(this,!1),e=await m(this,$,re).descriptor(t);if(e)return e;const n=await p(this,$,me).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await m(this,$,re).setDescriptor(t,r),await m(this,$,re).descriptor(t)}async ownership(){const t=await p(this,$,wn).call(this,Ro);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async o=>{try{const a=Yt(o),l=await this.client.downloadHiddenFile(a),d=JSON.parse(await l.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(c=>typeof c=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of n)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(t){var a;const e=await p(this,$,pe).call(this,!0);let n=await p(this,$,vn).call(this)??{model:this.docId,commits:[]};const r=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Xn(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:As(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...t.kind?{kind:t.kind}:{},...t.file?{file:t.file}:{},...t.origin?{origin:t.origin}:{},...(a=t.origins)!=null&&a.length?{origins:t.origins}:{},changes:t.changes,counts:Mo(t.changes)};if(t.model&&(await p(this,$,Yr).call(this,e,t.model),i.full=!0),t.delta){const l=await p(this,$,me).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const d=await this.client.createHiddenFile(t.delta,l.id);i.deltaId=No(d)}const o=await p(this,$,vn).call(this);if(o){n=o;const l=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new Xn(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await p(this,$,Wr).call(this,e,Qn,n),i}}Wt=new WeakMap,$=new WeakSet,re=function(){return new Cs(this.client,this.project.projectId)},xe=function(){return`${this.source}-${this.docId}`},pe=async function(t){if(m(this,Wt))return m(this,Wt);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=o=>o.find(a=>String(a.name??"")===m(this,$,xe)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return rt(this,Wt,Yt(r)),m(this,Wt);if(!t)throw new Error(`Document ${m(this,$,xe)} does not exist in this project.`);const i=await this.client.createFolder(m(this,$,xe),e,this.project.projectId);return this.project.forgetFolders(),rt(this,Wt,Yt(i)),m(this,Wt)},zt=new WeakMap,en=new WeakMap,es=async function(){return(!m(this,zt)||Date.now()-m(this,en)>5e3)&&(rt(this,en,Date.now()),rt(this,zt,(async()=>{const t=await p(this,$,pe).call(this,!1);return(await this.client.listFiles({folderId:t})).map(n=>({id:Yt(n),name:String(n.name??"")}))})()),m(this,zt).catch(()=>{rt(this,zt,void 0)})),m(this,zt)},wn=async function(t){try{return(await p(this,$,es).call(this)).find(e=>e.name===t)}catch{return}},me=async function(){try{const t=await p(this,$,es).call(this);return t.find(e=>e.name===Gr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Hr))}catch{return}},Jr=async function(t){const e=await p(this,$,wn).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},vn=function(){return p(this,$,Jr).call(this,Qn)},Wr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,$,wn).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await p(this,$,zr).call(this,t,e,n)},zr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});rt(this,zt,void 0);const o=i.item;return{id:Yt(o??i),name:e}},Yr=async function(t,e){const n=await p(this,$,me).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${m(this,$,xe)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});rt(this,zt,void 0);const o=i.item;return{id:Yt(o??i),name:r}};function Mo(s){const t={added:0,modified:0,removed:0};for(const e of s)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function _s(s){var l;if(s.length<=1)return s.forEach((d,c)=>d.ordinal=c),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const c=(l=d.parents)==null?void 0:l[0];if(c&&t.has(c)){const y=e.get(c)??[];y.push(d),e.set(c,y)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],o=[...n].reverse(),a=new Set;for(;o.length;){const d=o.pop();if(a.has(d.guid))continue;a.add(d.guid),i.push(d);const c=(e.get(d.guid)??[]).sort(r);for(let y=c.length-1;y>=0;y--)o.push(c[y])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function wr(s){const t=_s(s);return t[t.length-1]}function As(){const s=globalThis.crypto;return s!=null&&s.randomUUID?s.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}const Os={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawings",icon:"tabler:layout-board"},reality:{label:"Reality capture",icon:"tabler:3d-cube-sphere"},generic:{label:"Generic",icon:"tabler:file"}},Fo={rvt:"bim",rfa:"bim",ifc:"bim",frag:"bim","3dm":"bim",nwd:"bim",dgn:"bim",dwg:"drawings",dxf:"drawings",las:"reality",laz:"reality",e57:"reality",ply:"reality",potree:"reality",splat:"reality",spz:"reality",ksplat:"reality"};function ns(s){var e;if(s.type&&s.type in Os)return s.type;const t=[(e=s.native)==null?void 0:e.format,...s.views.map(n=>n.format)];for(const n of t){const r=n?Fo[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const Qe="thatopen/document@1",bn="document.json",Kr=["pdf","txt","md","json","csv","tsv","frag"];function ne(s){return String(s._id??s.id??"")}var Nt,Xr,ss,Qr,Zr,Tn;class Cs{constructor(t,e){z(this,Nt);this.client=t,this.projectId=e}async list(t){const e=await p(this,Nt,Xr).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(ns(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=jn(r,n.fileExtension),o=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,n.folderId?String(n.folderId):void 0,this.projectId),l=ne(a);await this.client.updateFile(t,{parentFolderId:l});const d=[],c=await p(this,Nt,Qr).call(this,n);if(c)try{const b=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:jn(String(b.name??""),b.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Kr.includes(i))&&d.push({fileId:t,format:i});const O={schema:Qe,name:o,native:{fileId:t,format:i},views:d};return O.type=(e==null?void 0:e.type)??ns(O),await this.setDescriptor(l,O),await this.recordUpload(l,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:l,descriptor:O}}async recordUpload(t,e,n){const r=new Ss(this.client,this.projectId).document(t),i=(await r.timeline()).length===0;await r.sync({author:n||"unknown",source:"platform",kind:"upload",message:i?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??jn(e.name,void 0)},changes:[]})}async descriptor(t){const e=await p(this,Nt,Tn).call(this,t);return e?p(this,Nt,ss).call(this,e.id):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const r of e){const i=n.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.views=[...n.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,n)}async setType(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.type!==e&&await this.setDescriptor(t,{...n,type:e})}async setDescriptor(t,e){const n={...e,schema:Qe,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,Nt,Tn).call(this,t);if(i){await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:bn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new ti(this.client,()=>p(this,Nt,Tn).call(this,t))}}Nt=new WeakSet,Xr=async function(){const e=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===bn);return(await Promise.all(e.map(async r=>{const i=r,o=String(i.folderId??i.parentFolderId??"");if(!o)return null;const a=await p(this,Nt,ss).call(this,ne(r));return a?{folderId:o,descriptor:a}:null}))).filter(r=>r!==null)},ss=async function(t){const n=await(await this.client.downloadFile(t)).text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Do(r)},Qr=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const a=n.find(l=>ne(l)===ne(t));e=(a==null?void 0:a.versions)??[]}const r=await p(this,Nt,Zr).call(this,t,e);if(r)return r;const i=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!i)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const o=n.find(a=>String(a.name??"").toLowerCase()===`${i}.frag`&&!a.archived&&ne(a)!==ne(t));return o?ne(o):void 0},Zr=async function(t,e){const n=[...e].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")));for(const r of n)try{const i=await this.client.getFileVersionMetadata(ne(t),r.tag),o=i==null?void 0:i.derivedFileId;if(typeof o=="string"&&o)return o}catch{}},Tn=async function(t){const n=(await this.client.listFiles({folderId:t})).find(r=>String(r.name??"")===bn);return n?{id:ne(n)}:void 0};const rs="draft:",Re="TODRAFT1";var Kt,ze,is;class ti{constructor(t,e){z(this,Kt);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const n of await p(this,Kt,ze).call(this,t.id)){const r=e.get(n.userId);(!r||n.savedAt>r.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,r)=>+r.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const r=(await p(this,Kt,ze).call(this,e.id)).filter(l=>!(t!=null&&t.userId)||l.userId===t.userId).sort((l,d)=>+d.savedAt-+l.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await Bo(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(t,e){const n=await this.holder();if(!n)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Lo(e.userId),i=(await p(this,Kt,ze).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await Po(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await p(this,Kt,is).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:vr(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await p(this,Kt,ze).call(this,e.id)).filter(r=>r.userId===t.userId);await p(this,Kt,is).call(this,n.map(r=>r.hiddenId))}}Kt=new WeakSet,ze=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(rs)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(rs.length),savedAt:vr(r)}})},is=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Lo(s){const t=`${rs}${s}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(t))throw new Error(`A draft cannot be tagged for user "${s}": ids must be letters, digits or :._- and short.`);return t}function vr(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function Po(s,t){const e=new TextEncoder().encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e.length,!0),new Blob([new TextEncoder().encode(Re),n,e,s])}async function Bo(s){const t=new Uint8Array(await s.slice(0,Re.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,Re.length))!==Re)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(Re.length,!0),n=Re.length+4,r=await s.slice(n,n+e).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:s.slice(n+e)}}function jn(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Do(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Qe||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(o=>!!o&&typeof o=="object"&&typeof o.fileId=="string"&&typeof o.format=="string"):[],n=t.native,r=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",i=typeof t.type=="string"&&t.type in Os?t.type:void 0;return{schema:Qe,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const jo="flow:",Uo="flow:op",qo="flow:source",Vo="flow:host",$s="revitflow/op@2",br="REVITFLOWCHANGE",Tr="REVITFLOWOPERATION";class xn{constructor(t){xt(this,"changes",[]);this.target=t}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(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,n={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,n)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:$s,opId:t,batchId:this.batchId??t,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},[n,r]=await Go();return Ho(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(jo)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Er).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Er(e.rotationDeg)),e.source&&(n[qo]=e.source),e.host&&(n[Vo]=e.host),n}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,n,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=e,c=new t.Builder(1024),y=this.changes.length,O=new Uint32Array(y);let b=1;for(let bt=0;bt<y;bt++)O[bt]=b++;const B=b++,H=bt=>(bt(c,0),c.endVector()),G=o.createShellsVector(c,[]),F=o.createCircleExtrusionsVector(c,[]),D=H(o.startSamplesVector),u=H(o.startRepresentationsVector),L=H(o.startMaterialsVector),I=H(o.startLocalTransformsVector),j=H(o.startGlobalTransformsVector),st=o.createMeshesItemsVector(c,[]),Z=o.createMaterialIdsVector(c,[]),mt=o.createRepresentationIdsVector(c,[]),Rt=o.createSampleIdsVector(c,[]),Tt=o.createLocalTransformIdsVector(c,[]),Zt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,j),o.addShells(c,G),o.addRepresentations(c,u),o.addSamples(c,D),o.addLocalTransforms(c,I),o.addMaterials(c,L),o.addCircleExtrusions(c,F),o.addMeshesItems(c,st),o.addRepresentationIds(c,mt),o.addSampleIds(c,Rt),o.addMaterialIds(c,Z),o.addLocalTransformIds(c,Tt),o.addGlobalTransformIds(c,Zt);const Ee=o.endMeshes(c),te=c.createString(r),Q=new Set,J=[];for(const bt of this.changes){const Ut=[],Ae={[Uo]:bt.op,...bt.attrs};for(const[ln,Ue]of Object.entries(Ae)){const Oe=JSON.stringify([ln,Ue,"IFCTEXT"]);Q.add(Oe),Ut.push(c.createString(Oe))}J.push(i.createAttribute(c,i.createDataVector(c,Ut)))}{const bt=JSON.stringify(["Name",n,"IFCLABEL"]);Q.add(bt);const Ut=i.createDataVector(c,[c.createString(bt)]);J.push(i.createAttribute(c,Ut))}const E=a.createAttributesVector(c,J),kt=a.createUniqueAttributesVector(c,[...Q].map(bt=>c.createString(bt))),lt=this.changes.map(()=>c.createString(br));lt.push(c.createString(Tr));const At=a.createCategoriesVector(c,lt),Mt=[],Lt=[];this.changes.forEach((bt,Ut)=>{bt.item&&(Mt.push(c.createString(bt.item)),Lt.push(O[Ut]))});const Ot=a.createGuidsVector(c,Mt),tt=a.createGuidsItemsVector(c,Lt),vt=a.createLocalIdsVector(c,[...O,B]),Ht=this.changes.map((bt,Ut)=>l.createSpatialStructure(c,O[Ut],c.createString(br),0)),le=l.createSpatialStructure(c,B,c.createString(Tr),l.createChildrenVector(c,Ht)),ee=c.createString(n);a.startModel(c),a.addMeshes(c,Ee),a.addMetadata(c,te),a.addAttributes(c,E),a.addUniqueAttributes(c,kt),a.addLocalIds(c,vt),a.addCategories(c,At),a.addGuidsItems(c,tt),a.addGuids(c,Ot),a.addGuid(c,ee),a.addSpatialStructure(c,le),a.addMaxLocalId(c,b);const It=a.endModel(c);return a.finishModelBuffer(c,It),c.asUint8Array()}}async function Go(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${s instanceof Error?s.message:String(s)})`)}}function Er(s){return Number.isFinite(s)?String(s):"0"}async function Ho(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function Rn(s){const[t,e]=await Jo(),n=e.Model.getRootAsModel(new t.ByteBuffer(await Wo(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<n.guidsLength();a++){const l=n.guidsItems(a),d=n.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<n.attributesLength();a++){const l=n.localIds(a);if(l===null)continue;const d={},c=n.attributes(a);for(let y=0;y<((c==null?void 0:c.dataLength())??0);y++){const O=c.data(y);if(O)try{const[b,B]=JSON.parse(O);d[b]=B}catch{}}o.push({localId:l,guid:i.get(l)??null,category:n.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function Jo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){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). (${s instanceof Error?s.message:String(s)})`)}}async function Wo(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ei="Element",ni="Carried",Ne=1/.3048;function si(s){const t=[];for(const e of s)for(const n of[ei,ni]){const r=e.attrs[n];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"||t.push({id:a.id,kind:a.kind,params:a.params??{},item:e})}}catch{}}return t}function Pt(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function zo(s){const t=new Map;for(const[e,n]of xs(s))t.set(e,n.name);return t}function xs(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,r=e.params.at;typeof n=="string"&&typeof r=="number"&&t.set(e.id,{name:n,at:r})}return t}function ri(s){const t=new Map;for(const e of s){if(!e.kind.endsWith("Style"))continue;const n=e.params.name;typeof n=="string"&&t.set(n,e)}return t}function Rs(s,t){const e=new Map;for(const[n,r]of s.made)e.set(n,r.id),r.print&&(t==null||t.set(n,r.print));return e}function ii(s){const t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,e=JSON.stringify(t(s));let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function ks(s,t){var o,a;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const n=((a=(o=/\.([^.]+)$/.exec(t.name))==null?void 0:o[1])==null?void 0:a.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const l=s.client.recipes.importerFor(n);if(!l)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=oi(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),i=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await l(e,t.name)}return{picked:t,contents:await Rn(e),site:r,shapes:i}}function oi(s){var j;const t=new TextDecoder("latin1").decode(s),e=st=>new RegExp(`^${st}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=st=>[...st.matchAll(/#\d+|\$/g)].map(Z=>Z[0]),r=st=>[...st.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(Z=>Number(Z[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const o=(j=i[2].split(",")[5])==null?void 0:j.trim();if(!(o!=null&&o.startsWith("#")))return null;const a=e(o);if((a==null?void 0:a[1])!=="IFCLOCALPLACEMENT")return null;const[l,d]=n(a[2]);if(l!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[y,,O]=n(c[2]),b=y&&y!=="$"?e(y):null;if(!b)return null;const[B=0,H=0,G=0]=r(b[2]);let F=0;const D=O&&O!=="$"?e(O):null;if(D){const[st=1,Z=0]=r(D[2]);F=Math.atan2(Z,st)*180/Math.PI}const u=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),L={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},I=u?u[2]?L[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:B*I,north:H*I,elevation:G*I,angleDeg:F}}const Ns="thatopen/recipe@1",Ir="__project_data",Sr="recipes",Yo=s=>`${s}.recipe.json`,ai={OperationBuilder:xn,OP_SCHEMA:$s,readFrag:Rn,readPickedFrag:ks,recordsOf:si,innerJson:Pt,levelsOf:xs,levelNames:zo,stylesOf:ri,printOf:ii,siteLocationOf:oi,whatItMadeBefore:Rs,ELEMENT_FIELD:ei,CARRIED_FIELD:ni,FEET_PER_METRE:Ne},ci=/^[a-z0-9][a-z0-9-]{1,62}$/;async function li(s,t,e){const n=d=>[...d].sort((c,y)=>String(c._id).localeCompare(String(y._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Ir&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Ir,void 0,t)}const o=String(i._id),a=await s.listFolders({parentFolderId:o,projectId:t,archived:!1});let l=n(a.filter(d=>d.name===Sr&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder(Sr,o,t)}return String(l._id)}const Ko=s=>String(s._id??s.id??""),Xo=s=>String(s.tag??s.versionTag??""),os=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function He(s,t){const e=await li(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const o=String(i.name??"");o.endsWith(".recipe.json")&&r.set(o.slice(0,-12),{id:Ko(i)})}return r}async function pn(s,t,e){var i;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),r=JSON.parse(await n.text());if((r==null?void 0:r.schema)!==Ns||!((i=r.manifest)!=null&&i.name)||typeof r.code!="string")throw new Error(`This is not a recipe this library can read (${String(r==null?void 0:r.schema)}).`);return r}async function Je(s,t){return(await s.listVersions(t)).map(n=>({tag:Xo(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>os(n.tag)-os(r.tag))}var nn;class hi{constructor(t,e){z(this,nn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await He(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await Je(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await pn(this.client,r,a);return{manifest:l.manifest,origin:"project",version:a,author:l.author,savedAt:l.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await He(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await Je(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await pn(this.client,n.id,i);return{version:i,author:a.author,note:a.note,savedAt:a.savedAt??o}}catch{return{version:i,savedAt:o}}}))}async source(t,e,n){var o;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await Je(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await pn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!ci.test((r==null?void 0:r.name)??""))throw new Error('A recipe name is lower case letters, digits and dashes, 2 to 63 of them: "walls-from-ifc".');if(this.builtinNames().has(r.name))throw new Error(`"${r.name}" is a built-in recipe. Give yours a name of its own.`);if(!r.to||!r.description||!Array.isArray(r.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await as(r,i);const o={schema:Ns,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),l=(await He(this.client,t)).get(r.name);if(l){const c=await Je(this.client,l.id),y=`v${Math.max(0,...c.map(O=>os(O.tag)))+1}`;return await this.client.createVersion(l.id,a,y),y}const d=await li(this.client,t,!0);return await this.client.createFile({file:a,name:Yo(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await Je(this.client,r.id)).pop())==null?void 0:l.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const o=`${r.id}@${i}`;let a=m(this,nn).get(o);if(!a){const d=await pn(this.client,r.id,i);a=await as(d.manifest,d.code),m(this,nn).set(o,a)}return{recipe:a,version:i}}}nn=new WeakMap;async function as(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${Qo(t)}`)}catch(i){throw new Error(`The recipe's code does not load: ${i instanceof Error?i.message:String(i)}`)}const n=e.run??((r=e.default)==null?void 0:r.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:i=>n({...i,kit:ai})}}function Qo(s){const t=new TextEncoder().encode(s);let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}async function Zo(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await Rn(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const o={};for(const[a,l]of Object.entries(i.attrs))a.startsWith("flow:")||(o[a]=l);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:o}});return{envelope:n??{},changes:r}}class Ms extends Error{constructor(t){super(t),this.name="UpToDate"}}var oe,sn,rn;class di{constructor(t){z(this,oe,new Map);z(this,sn,new Map);z(this,rn,new Map);xt(this,"project");this.client=t,this.project=new hi(t,()=>new Set(m(this,oe).keys()))}provideImporter(t,e){m(this,sn).set(t.toLowerCase(),e)}provideShapes(t,e){m(this,rn).set(t.toLowerCase(),e)}shapesFor(t){return m(this,rn).get(t.toLowerCase())}importerFor(t){return m(this,sn).get(t.toLowerCase())}register(t){if(m(this,oe).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);m(this,oe).set(t.name,t)}list(t){return[...m(this,oe).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return m(this,oe).get(t)}async catalog(t,e){const n=this.list(e).map(i=>({manifest:i,origin:"builtin"}));let r=[];try{r=(await this.project.list(t)).filter(i=>!(e!=null&&e.to)||i.manifest.to===e.to)}catch{}return[...n,...r.sort((i,o)=>i.manifest.name.localeCompare(o.manifest.name))]}async resolve(t,e,n){const r=m(this,oe).get(t);return r?{recipe:r,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),r=n.source;if((r==null?void 0:r.kind)!=="project-file")return[];const i=(r.extensions??[]).map(d=>d.toLowerCase()),a=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),l=await fi(this.client,a.map(d=>d.descriptor.native.fileId));return a.map(d=>{const c=d.descriptor.native;return{label:d.descriptor.name,fileId:c.fileId,name:`${d.descriptor.name}.${c.format}`,folderId:d.folderId,version:l.get(c.fileId)??"v1"}}).sort((d,c)=>d.label.localeCompare(c.label))}async run(t,e){const{recipe:n}=await this.resolve(t,e.projectId,e.recipeVersion);if(n.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${n.to}, but the target document belongs to ${e.target.source}.`);return await n.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??As(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}oe=new WeakMap,sn=new WeakMap,rn=new WeakMap;async function fi(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var o;return Number(((o=/(\d+)/.exec(String(i??"")))==null?void 0:o[1])??-1)},r=i=>{const a=i.slice().sort((l,d)=>{const c=l!=null&&l.createdAt?new Date(String(l.createdAt)).getTime():NaN,y=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(y)&&c!==y?y-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((l==null?void 0:l.tag)??(l==null?void 0:l.versionTag))})[0];return a?String(a.tag??a.versionTag??"v1"):"v1"};return await Promise.all(t.map(async i=>{try{e.set(i,r(await s.listVersions(i)))}catch{e.set(i,"v1")}})),e}const cs=100;function ta(s){try{const t=JSON.parse(s);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function ea(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class kn extends Error{constructor(e,n,r,i){const o=ta(r);super(o.message??`${n||"Request failed"} (${e})`);xt(this,"status");xt(this,"code");xt(this,"details");xt(this,"body");xt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??ea(o.details)}}const Jt="item/folder",U="item",fe="processor",na="npm-registry",se="hidden",Un="FILE",qn="TOOL",Vn="APP",sa=500,_r=3e4,ra=.25,ia=s=>new Promise(t=>setTimeout(t,s));function oa(s){var r,i;const t=(i=(r=s.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,(n-Date.now())/1e3)}function aa(s){return s instanceof kn?s.status===429||s.status>=500:!0}function ca(s,t){const e=Math.min(sa*2**t,_r),n=e*ra*Math.random(),r=s instanceof kn&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,_r)+n:e+n}var v,ls,C,ge,on,Ye,En,In,hs,ds,ui;const Ps=class Ps{constructor(t,e,n){z(this,v);xt(this,"apiUrl");xt(this,"accessToken");xt(this,"wsUrl");xt(this,"retries");xt(this,"useBearer");xt(this,"builtInGlobals",null);xt(this,"localServerUrl",null);xt(this,"context");z(this,on);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=n||{};let a=e;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=t,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Ps(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,n){return p(this,v,C).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await p(this,v,C).call(this,"GET",`${Jt}/${e}/items`,{query:{itemType:Un,archived:n}}):await p(this,v,C).call(this,"GET",`${U}`,{query:{itemType:Un,archived:n,...r&&{projectId:r}}})}async getFile(t,e){return await p(this,v,ds).call(this,t,e)}async createFile(t){return await p(this,v,In).call(this,t,Un)}async updateFile(t,e){return await p(this,v,hs).call(this,t,e)}async archiveFile(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}`)}async recoverFile(t){return await p(this,v,C).call(this,"PUT",`${U}/${t}/recover`)}async downloadFile(t,e){return await p(this,v,En).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await p(this,v,C).call(this,"GET",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await p(this,v,C).call(this,"PUT",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await p(this,v,C).call(this,"DELETE",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await p(this,v,Ye).call(this,t,async r=>(await p(this,v,C).call(this,"POST",`${U}/batch/version-metadata`,{body:JSON.stringify({entries:r,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:r}=t||{};return await p(this,v,C).call(this,"GET",Jt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await p(this,v,C).call(this,"GET",`${Jt}/${t}`)}async getFoldersBatch(t){return await p(this,v,Ye).call(this,t,async e=>(await p(this,v,C).call(this,"POST",`${U}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await p(this,v,C).call(this,"POST",Jt,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await p(this,v,C).call(this,"PUT",`${Jt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await p(this,v,C).call(this,"DELETE",`${Jt}/${t}`)}async recoverFolder(t){return await p(this,v,C).call(this,"PUT",`${Jt}/${t}/recover`)}async downloadFolder(t){return await p(this,v,ge).call(this,`${Jt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,v,C).call(this,"GET",`${Jt}/${e}/items`,{query:{itemType:qn,...n&&{ShowVersions:n}}}):await p(this,v,C).call(this,"GET",`${U}`,{query:{itemType:qn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await p(this,v,ds).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await p(this,v,In).call(this,t,qn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await p(this,v,hs).call(this,t,e,n)}async downloadComponent(t,e){return await p(this,v,En).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,v,ge).call(this,`${U}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}`)}async recoverComponent(t){return await p(this,v,C).call(this,"PUT",`${U}/${t}/recover`)}async getBuiltInComponent(t){return await(await p(this,v,ge).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const r=await this.getBuiltInComponent(t.uuid),i=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(y=>i[y]),d=new Function(...o,`${r}
|
|
2
|
-
return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){var o,a;const n=t.OBC,r=t.BUI;if(!(n!=null&&n.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 n.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(t,e){var n,r;(r=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||r.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,v,C).call(this,"GET",`${Jt}/${e}/items`,{query:{itemType:Vn,...n&&{ShowVersions:n}}}):await p(this,v,C).call(this,"GET",`${U}`,{query:{itemType:Vn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await p(this,v,In).call(this,t,Vn,e)}async downloadApp(t,e){return await p(this,v,En).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,v,ge).call(this,`${U}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}`)}async getNpmCredentials(){return await p(this,v,C).call(this,"GET",`${na}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${fe}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});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 p(this,v,C).call(this,"POST",`${fe}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${fe}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,v,C).call(this,"POST",`${fe}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${fe}/${t}/progress${n}`,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 p(this,v,C).call(this,"GET",`${fe}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${fe}/progress/${t}`,n=await fetch(e);if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,v,C).call(this,"GET",`${fe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await Xe(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new Cs(this,t)}history(t){return new Ss(this,t)}get recipes(){return m(this,on)??rt(this,on,new di(this)),m(this,on)}async createHiddenFile(t,e,n){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,v,C).call(this,"POST",`${U}/${se}`,{body:r})}async createHiddenFilesBatch(t,e,n){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,v,C).call(this,"POST",`${U}/${se}/batch`,{body:r})}async deleteHiddenFile(t){return await p(this,v,C).call(this,"DELETE",`${U}/${se}/${t}`)}async getHiddenFile(t){return await p(this,v,C).call(this,"GET",`${U}/${se}/${t}`)}async downloadHiddenFile(t){return await p(this,v,ge).call(this,`${U}/${se}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await p(this,v,C).call(this,"GET",`${U}/${se}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getFileSignedUrl(t,e){const n={...(e==null?void 0:e.versionTag)&&{versionTag:e.versionTag},...(e==null?void 0:e.expiresIn)!=null&&{expiresIn:e.expiresIn}};return await p(this,v,C).call(this,"GET",`${U}/${encodeURIComponent(t)}/signed-url`,{...Object.keys(n).length>0&&{query:n}})}async getHiddenFileSignedUrlsBatch(t,e){return await p(this,v,Ye).call(this,t,async n=>(await p(this,v,C).call(this,"POST",`${U}/${se}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await p(this,v,C).call(this,"GET",`${U}/${t}/${se}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}/${se}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await p(this,v,C).call(this,"PUT",`${U}/${t}/icon`,{body:n})}async getItemIcon(t){return await p(this,v,ge).call(this,`${U}/${t}/icon`)}async removeItemIcon(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}/icon`)}async updateItem(t,e){return await p(this,v,C).call(this,"PUT",`${U}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",n),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await p(this,v,C).call(this,"POST",`${U}/${t}/version`,{body:o})}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let n=0;for(const r of e){const i=/^v(\d{1,6})$/.exec(String(r.tag??r.versionTag??""));i&&(n=Math.max(n,Number(i[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await p(this,v,C).call(this,"GET",`${U}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await p(this,v,Ye).call(this,t,async r=>(await p(this,v,C).call(this,"POST",`${U}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await p(this,v,C).call(this,"PUT",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await p(this,v,C).call(this,"PUT",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await p(this,v,C).call(this,"DELETE",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};v=new WeakSet,ls=function(t){return`${this.apiUrl}/${t}`},C=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=p(this,v,ls).call(this,e),y=p(this,v,ui).call(this,i),O=await this.resolveAccessToken(),b={...y,...this.useBearer?{}:{accessToken:O}};try{const B=await fetch(c+"?"+new URLSearchParams(b).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${O}`}},...r&&{body:r}});if(!B.ok){const H=await B.text().then(G=>G).catch(()=>"");throw new kn(B.status,B.statusText,H,oa(B))}return l==="blob"?await B.blob():B.json().then(H=>H).catch(()=>{})}catch(B){const H=a??this.retries;if(H>0&&aa(B)){const G=d??0;return await ia(ca(B,G)),await p(this,v,C).call(this,t,e,{...n,retries:H-1,retryAttempt:G+1})}throw B}},ge=async function(t,e){const{query:n}=e||{},r=p(this,v,ls).call(this,t),i=await this.resolveAccessToken(),o={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},on=new WeakMap,Ye=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=cs)n.push(t.slice(i,i+cs));return(await Promise.all(n.map(e))).flat()},En=async function(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,v,ge).call(this,`${U}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})},In=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=t,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),a&&c.append("projectId",a),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await p(this,v,C).call(this,"POST",U,{body:c})},hs=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const y=new FormData;y.append("file",a),i&&y.append("versionTag",i),n&&y.append("extraProps",JSON.stringify(n)),l&&y.append("metadata",JSON.stringify(l)),c=await p(this,v,C).call(this,"POST",`${U}/${t}/version`,{body:y})}if(r||o){const y={...r&&{name:r},...o&&{folderId:o}},O=JSON.stringify(y);d=await p(this,v,C).call(this,"PUT",`${U}/${t}`,{body:O,contentType:"application/json"})}return{item:d,version:c}},ds=async function(t,e){const{showVersions:n=!1}=e||{};return await p(this,v,C).call(this,"GET",`${U}/${t}`,{query:{showVersions:n}})},ui=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let An=Ps;function pi(){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:s=>window.parent.postMessage(s,"*"),listen:s=>{const t=e=>{e.source===window.parent&&s(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const fs="channel:",la=1e4;function Sn(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ae,Bt,Dt,Me,Fe,Le,Ft,us,ps,ke;class Fs{constructor(t,e){z(this,Ft);z(this,ae,!1);z(this,Bt,[]);z(this,Dt,[]);z(this,Me,new Set);z(this,Fe,new Set);z(this,Le,new Set);this.transport=t,this.controls=e}get joined(){return m(this,ae)}get peers(){return m(this,Bt)}join(){return m(this,ae)?Promise.resolve():p(this,Ft,us).call(this,"joined",this.controls.join)}leave(){return!m(this,ae)&&!m(this,Dt).some(t=>t.want==="joined")?Promise.resolve():p(this,Ft,us).call(this,"left",this.controls.leave)}onChange(t){return m(this,Me).add(t),()=>void m(this,Me).delete(t)}onPeerJoined(t){return m(this,Fe).add(t),()=>void m(this,Fe).delete(t)}onPeerLeft(t){return m(this,Le).add(t),()=>void m(this,Le).delete(t)}applyJoined(){rt(this,ae,!0),p(this,Ft,ps).call(this,"joined"),p(this,Ft,ke).call(this)}applyLeft(){rt(this,ae,!1),rt(this,Bt,[]),p(this,Ft,ps).call(this,"left"),p(this,Ft,ke).call(this)}applyPeers(t){rt(this,Bt,t),p(this,Ft,ke).call(this)}applyPeerJoined(t){!m(this,ae)||m(this,Bt).some(e=>e.from===t.from)||(rt(this,Bt,[...m(this,Bt),t]),m(this,Fe).forEach(e=>Sn(()=>e(t))),p(this,Ft,ke).call(this))}applyPeerLeft(t){const e=m(this,Bt).find(n=>n.from===t);e&&(rt(this,Bt,m(this,Bt).filter(n=>n.from!==t)),m(this,Le).forEach(n=>Sn(()=>n(e))),p(this,Ft,ke).call(this))}failPending(t){const e=m(this,Dt);return rt(this,Dt,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}ae=new WeakMap,Bt=new WeakMap,Dt=new WeakMap,Me=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Ft=new WeakSet,us=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{rt(this,Dt,m(this,Dt).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},la)};m(this,Dt).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ps=function(t){const e=m(this,Dt).filter(n=>n.want===t);rt(this,Dt,m(this,Dt).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},ke=function(){m(this,Me).forEach(t=>Sn(t))};var Pe;class mi extends Fs{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});z(this,Pe,new Map)}on(e,n){const r=m(this,Pe).get(e)??new Set;return r.add(n),m(this,Pe).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(fs))throw new Error(`Message types starting with '${fs}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=m(this,Pe).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=yi(e);return n.forEach(i=>Sn(()=>i(e.payload,r))),{handled:!0}}}Pe=new WeakMap;var we;class gi extends Fs{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});z(this,we,new Map);this.kind=n}on(e,n){if(m(this,we).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return m(this,we).set(e,n),()=>void m(this,we).delete(e)}accepts(e,n){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===n}get hasHandlers(){return m(this,we).size>0}async handle(e){const n=m(this,we).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,yi(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}we=new WeakMap;function yi(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function ha(s){const t=s;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var _e,an,ce,ve,be,_t,ms,_n,vi,bi,Ti,gs;class wi{constructor(t){z(this,_t);z(this,_e);z(this,an);z(this,ce);z(this,ve,new Map);z(this,be,new Set);rt(this,_e,t),rt(this,an,t.listen(e=>void p(this,_t,vi).call(this,e)))}collab(){return m(this,ce)??rt(this,ce,new mi(m(this,_e))),m(this,ce)}external(t){const e=t??"";let n=m(this,ve).get(e);return n||(n=new gi(m(this,_e),t),m(this,ve).set(e,n)),n}dispose(){m(this,an).call(this)}}_e=new WeakMap,an=new WeakMap,ce=new WeakMap,ve=new WeakMap,be=new WeakMap,_t=new WeakSet,ms=function(){return[...m(this,ce)?[m(this,ce)]:[],...m(this,ve).values()]},_n=function(t,e){if(t==="collab")return m(this,ce);if(t==="external")return m(this,ve).get(typeof e=="string"?e:"")},vi=async function(t){const e=ha(t);if(e){if(e.type.startsWith(fs)){p(this,_t,bi).call(this,e);return}await p(this,_t,Ti).call(this,e)}},bi=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=p(this,_t,_n).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=p(this,_t,_n).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=p(this,_t,_n).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[m(this,ce)]:[...m(this,ve).values()].filter(a=>a.accepts("external",e.kind));for(const a of o)t.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:e.from,kind:e.kind}):a==null||a.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));p(this,_t,ms).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ti=async function(t){const e=p(this,_t,ms).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const o=await i.handle(t);o.handled&&(n=!0,t.requestId&&p(this,_t,gs).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&p(this,_t,gs).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},gs=function(t,e){m(this,be).has(t)||(m(this,be).add(t),m(this,be).size>500&&m(this,be).delete(m(this,be).values().next().value),m(this,_e).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const Ie="project",Ce="notifications";var Be,cn;const Bs=class Bs extends An{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});z(this,Be);z(this,cn);typeof e=="function"&&rt(this,Be,e)}async resolveAccessToken(){return m(this,Be)?await m(this,Be).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Bs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return m(this,cn)??rt(this,cn,new wi(pi())),m(this,cn)}async listProjects(){return await this.request("GET",Ie)}async getProject(e){return await this.request("GET",`${Ie}/${e}`)}async getProjectData(e){return await this.request("GET",`${Ie}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${Ie}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${Ie}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Ce,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${Ce}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Ce}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Ce}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Ce}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Ce}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${Ie}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${Ie}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=Xe(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};Be=new WeakMap,cn=new WeakMap;let ys=Bs;const $e=1/.3048,da={IFCDOOR:"OST_Doors",IFCWINDOW:"OST_Windows",IFCFURNITURE:"OST_Furniture",IFCFURNISHINGELEMENT:"OST_Furniture",IFCSYSTEMFURNITUREELEMENT:"OST_FurnitureSystems",IFCLIGHTFIXTURE:"OST_LightingFixtures",IFCSANITARYTERMINAL:"OST_PlumbingFixtures",IFCFLOWTERMINAL:"OST_PlumbingFixtures",IFCCOLUMN:"OST_Columns",IFCFOOTING:"OST_StructuralFoundation",IFCGEOGRAPHICELEMENT:"OST_Site",IFCELECTRICAPPLIANCE:"OST_ElectricalEquipment",IFCELECTRICDISTRIBUTIONBOARD:"OST_ElectricalEquipment",IFCUNITARYEQUIPMENT:"OST_MechanicalEquipment"},fa="OST_GenericModel",ua=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),ye=(s,t)=>Math.round(s/t)*t,pa=s=>({x:[s[0],s[1],s[2]],y:[s[4],s[5],s[6]],z:[s[8],s[9],s[10]],t:[s[12],s[13],s[14]]}),On=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Gn=s=>Math.sqrt(On(s,s)),ws=(s,t)=>[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]];function ma(s,t,e){const n=new Set,r=new Map;for(const l of t){const d=l.split(":")[1];d&&(n.add(d),r.has(d)||r.set(d,l))}const i=new Map,o=new Map,a=[];for(const l of s.elements.values()){if(n.has(l.gid)||ua.has(l.ifcClass.toUpperCase())||l.parent&&n.has(l.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(l.ifcClass)||l.pieces.length===0)continue;const d=da[l.ifcClass.toUpperCase()]??fa,c=pa(l.pieces[0].matrix),y=Gn(c.x),O=Gn(c.y),b=Gn(c.z),B=c.z.map(Q=>Q/(b||1)),G=Math.abs(B[2]-1)<1e-6&&On(ws(c.x,c.y),c.z)>0&&Math.abs(y-O)<1e-6&&Math.abs(y-b)<1e-6?Math.atan2(c.x[1],c.x[0]):0,F=Math.cos(-G),D=Math.sin(-G),u=[c.t[0],c.t[1],c.t[2]],L=/COLUMN/i.test(d),I=Q=>{const J=Q[0]-u[0],E=Q[1]-u[1];return[F*J-D*E,D*J+F*E,Q[2]-u[2]]},j=[],st=[d];for(const Q of l.pieces){const J=s.geometries.get(Q.geometry);if(!J)continue;const E=Q.matrix,kt=[];for(let tt=0;tt<J.verts.length;tt+=3){const vt=J.verts[tt],Ht=J.verts[tt+1],le=J.verts[tt+2],ee=[E[0]*vt+E[4]*Ht+E[8]*le+E[12],E[1]*vt+E[5]*Ht+E[9]*le+E[13],E[2]*vt+E[6]*Ht+E[10]*le+E[14]],It=I(ee);kt.push(ye(It[0]*$e,1e-5),ye(It[1]*$e,1e-5),ye(It[2]*$e,1e-5))}const lt=On(ws([E[0],E[1],E[2]],[E[4],E[5],E[6]]),[E[8],E[9],E[10]])<0,At=[];for(let tt=0;tt+2<J.tris.length;tt+=3)lt?At.push(J.tris[tt],J.tris[tt+2],J.tris[tt+1]):At.push(J.tris[tt],J.tris[tt+1],J.tris[tt+2]);At.length&&j.push({v:kt,t:At});const Mt=I([E[12],E[13],E[14]]),Lt=[F*E[0]-D*E[1],D*E[0]+F*E[1],E[2]],Ot=[F*E[4]-D*E[5],D*E[4]+F*E[5],E[6]];st.push(`${Q.geometry}@${[...Mt,...Lt,...Ot].map(tt=>ye(tt,1e-4).toFixed(4)).join(",")}`)}if(j.length===0)continue;const Z=!l.host&&j.length===1?ya(j[0]):null;if(Z){const Q=Z.loops.map(Ot=>Ot.map(([tt,vt])=>`${Math.round(tt*304.8)},${Math.round(vt*304.8)}`).join(";")).join("|"),J=`prism|${d}|${Z.axis}|${Q}`;let E=i.get(J);if(!E){const Ot=Ar(l.typeName??l.objectType??l.name??l.ifcClass),tt=(o.get(Ot)??0)+1;o.set(Ot,tt);const vt=tt===1?Ot:`${Ot} (${tt})`;E={family:vt,type:vt,first:!0,key:Or(J)},i.set(J,E)}const kt={ShapeCategory:d,Family:E.family,Type:E.type,ShapeKey:E.key,PrismLength:String(ye(Z.length,1e-5)),...L?{ColumnFree:"1"}:{}};E.first&&(kt.Prism=JSON.stringify({axis:Z.axis,loops:Z.loops}),E.first=!1);const lt=[0,0,0];lt[Z.axis]=Z.from/$e;const At=Math.cos(G),Mt=Math.sin(G),Lt=[u[0]+At*lt[0]-Mt*lt[1],u[1]+Mt*lt[0]+At*lt[1],u[2]+lt[2]];a.push({key:`${e}:${l.gid}:shape`,attrs:kt,at:Lt,rotationDeg:G*180/Math.PI});continue}const mt=`${d}|${j.map(Q=>`${Q.v.map(J=>Math.round(J*304.8/2)).join(",")}/${Q.t.join(",")}`).join("|")}`,Rt=st.join("|");let Tt=i.get(Rt)??i.get(mt);if(Tt&&(i.set(Rt,Tt),i.set(mt,Tt)),!Tt){const Q=Ar(l.typeName??l.objectType??l.name??l.ifcClass),J=(o.get(Q)??0)+1;o.set(Q,J);const E=J===1?Q:`${Q} (${J})`;Tt={family:E,type:E,first:!0,key:Or(mt)},i.set(mt,Tt),i.set(Rt,Tt)}const Zt={ShapeCategory:d,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,...L?{ColumnFree:"1"}:{}};Tt.first&&(Zt.Shape=JSON.stringify({pieces:j}),Tt.first=!1);const Ee=l.host?r.get(l.host):void 0,te=l.opening?s.elements.get(l.opening):void 0;if(Ee&&te){const Q=[1/0,1/0,1/0],J=[-1/0,-1/0,-1/0];for(const E of te.pieces){const kt=s.geometries.get(E.geometry);if(!kt)continue;const lt=E.matrix;for(let At=0;At<kt.verts.length;At+=3){const Mt=kt.verts[At],Lt=kt.verts[At+1],Ot=kt.verts[At+2],tt=I([lt[0]*Mt+lt[4]*Lt+lt[8]*Ot+lt[12],lt[1]*Mt+lt[5]*Lt+lt[9]*Ot+lt[13],lt[2]*Mt+lt[6]*Lt+lt[10]*Ot+lt[14]]);for(let vt=0;vt<3;vt++)Q[vt]=Math.min(Q[vt],tt[vt]*$e),J[vt]=Math.max(J[vt],tt[vt]*$e)}}Number.isFinite(Q[0])&&(Zt.Opening=[...Q,...J].map(E=>ye(E,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Zt,at:[u[0],u[1],u[2]],rotationDeg:G*180/Math.PI,...Ee?{host:Ee}:{}})}return a}function Ar(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Or(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function ga(s,t,e){const n=new Map;for(const i of t){const[,o,a]=i.split(":");o&&/^run/.test(a??"")&&!n.has(o)&&n.set(o,i)}const r=[];for(const i of s.elements.values()){if(i.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!i.host)continue;const o=n.get(i.host);if(!o)continue;const a=De(s,i.gid);if(a.length<4)continue;const l=va(De(s,i.host));if(!l)continue;const d=a.map(b=>(b[0]-l.a[0])*l.u[0]+(b[1]-l.a[1])*l.u[1]),c=a.map(b=>-(b[0]-l.a[0])*l.u[1]+(b[1]-l.a[1])*l.u[0]),y=b=>Math.max(...b)-Math.min(...b),O=y(d)*y(c)*y(a.map(b=>b[2]));!(O>0)||Math.abs(ba(s,i.gid))<.75*O||r.push({key:`${e}:${i.gid}:opening`,host:o,box:a.flat()})}return r}function ya(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,o=-1/0;for(let a=0;a<e;a++){const l=s.v[a*3+r];i=Math.min(i,l),o=Math.max(o,l)}return o-i});for(const r of[0,1,2].sort((i,o)=>n[o]-n[i])){let i=1/0,o=-1/0;for(let u=0;u<e;u++){const L=s.v[u*3+r];i=Math.min(i,L),o=Math.max(o,L)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const L=s.v[u*3+r];Math.abs(L-i)>.001&&Math.abs(L-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,y=[],O=u=>{const L=[s.v[u*3+l],s.v[u*3+d]],I=`${Math.round(L[0]*3048)},${Math.round(L[1]*3048)}`;return c.has(I)||(c.set(I,y.length),y.push(L)),c.get(I)},b=new Map,B=[];for(let u=0;u+2<s.t.length;u+=3){const L=[s.t[u],s.t[u+1],s.t[u+2]];if(!L.every(j=>Math.abs(s.v[j*3+r]-i)<=.001))continue;const I=L.map(O);if(!(I[0]===I[1]||I[1]===I[2]||I[0]===I[2])){B.push(I);for(let j=0;j<3;j++){const st=I[j],Z=I[(j+1)%3],mt=st<Z?`${st},${Z}`:`${Z},${st}`;b.set(mt,(b.get(mt)??0)+1)}}}if(B.length===0)continue;const H=new Map;for(const u of B)for(let L=0;L<3;L++){const I=u[L],j=u[(L+1)%3];b.get(I<j?`${I},${j}`:`${j},${I}`)===1&&H.set(I,[...H.get(I)??[],j])}if([...H.values()].some(u=>u.length!==1))continue;const G=[],F=new Set(H.keys());for(;F.size;){const u=F.values().next().value,L=[];let I=u,j=0;do L.push(y[I]),F.delete(I),I=H.get(I)[0];while(I!==u&&j++<1e5&&H.has(I));if(I!==u||L.length<3){G.length=0;break}const st=L.filter((Z,mt)=>{const Rt=L[(mt-1+L.length)%L.length],Tt=L[(mt+1)%L.length];return Math.abs((Z[0]-Rt[0])*(Tt[1]-Rt[1])-(Z[1]-Rt[1])*(Tt[0]-Rt[0]))>1e-7});G.push(st.map(([Z,mt])=>[ye(Z,1e-5),ye(mt,1e-5)]))}if(G.length===0||G.some(u=>u.length<3))continue;let D=0;for(let u=0;u<e;u++)Math.abs(s.v[u*3+r]-o)<=.001&&D++;if(!(D<3))return{axis:r,from:i,length:o-i,loops:G}}return null}function wa(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let r=1/0,i=-1/0;const o=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const y=d.matrix,O=b=>{const B=c.verts[b*3],H=c.verts[b*3+1],G=c.verts[b*3+2];return[y[0]*B+y[4]*H+y[8]*G+y[12],y[1]*B+y[5]*H+y[9]*G+y[13],y[2]*B+y[6]*H+y[10]*G+y[14]]};for(let b=0;b+2<c.tris.length;b+=3){const B=[O(c.tris[b]),O(c.tris[b+1]),O(c.tris[b+2])];for(const H of B)r=Math.min(r,H[2]),i=Math.max(i,H[2]);o.push(B)}}if(!Number.isFinite(r)||i-r<.1)continue;let a=null,l=0;for(const d of o){if(!d.every(y=>Math.abs(y[2]-r)<.001))continue;const c=Math.abs((d[1][0]-d[0][0])*(d[2][1]-d[0][1])-(d[2][0]-d[0][0])*(d[1][1]-d[0][1]))/2;c>l&&(l=c,a=d)}a&&e.push({key:`${t}:${n.gid}:room`,at:[(a[0][0]+a[1][0]+a[2][0])/3,(a[0][1]+a[1][1]+a[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function va(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const r of s){const i=Math.hypot(r[0]-s[0][0],r[1]-s[0][1]);i>n&&(n=i,e=r)}n=0;for(const r of s){const i=Math.hypot(r[0]-e[0],r[1]-e[1]);i>n&&(n=i,t=r)}if(!(n<.1))return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function ba(s,t){const e=s.elements.get(t);let n=0;if(!e)return n;for(const r of e.pieces){const i=s.geometries.get(r.geometry);if(!i)continue;const o=r.matrix,a=l=>{const d=i.verts[l*3],c=i.verts[l*3+1],y=i.verts[l*3+2];return[o[0]*d+o[4]*c+o[8]*y+o[12],o[1]*d+o[5]*c+o[9]*y+o[13],o[2]*d+o[6]*c+o[10]*y+o[14]]};for(let l=0;l+2<i.tris.length;l+=3)n+=On(a(i.tris[l]),ws(a(i.tris[l+1]),a(i.tris[l+2])))/6}return n}function De(s,t){const e=s.elements.get(t),n=[];if(!e)return n;for(const r of e.pieces){const i=s.geometries.get(r.geometry);if(!i)continue;const o=r.matrix;for(let a=0;a<i.verts.length;a+=3){const l=i.verts[a],d=i.verts[a+1],c=i.verts[a+2];n.push([o[0]*l+o[4]*d+o[8]*c+o[12],o[1]*l+o[5]*d+o[9]*c+o[13],o[2]*l+o[6]*d+o[10]*c+o[14]])}}return n}function Ta(s,t,e){const n=De(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],o=0;for(const F of n){const D=Math.hypot(F[0]-n[0][0],F[1]-n[0][1]);D>o&&(o=D,i=F)}o=0;for(const F of n){const D=Math.hypot(F[0]-i[0],F[1]-i[1]);D>o&&(o=D,r=F)}if(o<.3)return;const a=(i[0]-r[0])/o,l=(i[1]-r[1])/o,d=F=>(F[0]-r[0])*a+(F[1]-r[1])*l,c=Math.max(...n.map(F=>F[2])),y=F=>Math.max(...n.filter(D=>Math.abs(d(D)-F)<.05).map(D=>D[2]),-1/0),O=y(0),b=y(o);if(Math.abs(O-b)<.05&&c-Math.max(O,b)<.05)return;const B=(r[0]+i[0])/2,H=(r[1]+i[1])/2;let G;for(const F of e){const D=De(s,F.gid);if(D.length===0)continue;const u=D.map(st=>st[0]),L=D.map(st=>st[1]),I=D.map(st=>st[2]);if(B<Math.min(...u)-.2||B>Math.max(...u)+.2||H<Math.min(...L)-.2||H>Math.max(...L)+.2)continue;const j=Math.min(...I)-c;j>1.5||Math.max(...I)<c-.05||(!G||Math.abs(j)<Math.abs(G.gap))&&(G={id:F.id,gap:j})}return G==null?void 0:G.id}const ue={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Ke(s){const t=s.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const r=t.slice(e+1,n).trim();return r?{family:t.slice(0,e).trim(),type:r}:null}function Cr(s){const t=Ke(s),e=s.item.attrs.PredefinedType;return t?/escalera|stair|landing|descansillo/i.test(t.family)||e==="LANDING"||/plataforma|^pad\b|building pad/i.test(t.family)?"other":/cubierta|roof/i.test(t.family)||e==="ROOF"?"roof":/cimentaci|foundation/i.test(t.family)||e==="BASESLAB"?"foundation":"floor":"floor"}const $r=180/Math.PI;function xr(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const pt=s=>String(s);function Ei(s){return async t=>{var js,Us,qs,Vs,Gs,Hs,Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or;const{picked:e,contents:n,site:r,shapes:i}=await ks(t,t.input),o=si(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Ne,r.north*Ne,r.elevation*Ne,r.angleDeg].map(h=>h.toFixed(6)).join(","):void 0;if(o.length===0)throw new Error(s==="ifc"?`Nothing in "${e.name}" could be read as a building element (walls, floors, levels...).`:`"${e.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:d,trustStyleNames:c,includeInstances:y}=t.settings,O=t.settings.createLevels!==!1;if(y&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const b=xs(o),B=ri(o),H=`recipe:${s}-to-revit`,G=new Map,F=Rs(t,G);t.progress("Writing the changes for Revit");const D=new xn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:H}),u=Ne,L=new Map;{const h=new Map;for(const f of o){const g=f.item.guid;if(!g)continue;const w=`${g}:${f.kind}`,A=h.get(w)??0;h.set(w,A+1),L.set(f.id,`${e.fileId}:${w}${A?`:${A}`:""}`)}}const I=h=>L.get(h)??`${e.fileId}:${h}`,j=new Set;let st=0,Z=0;const mt=(h,f,g)=>{j.add(h);const w=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,A=ii({attrs:w,placement:g??{}}),T=F.get(h);if(T){const _=G.get(h);return!_||_===A?(st++,!1):(D.remove(T),D.add({...w,"flow:print":A},{...g,source:h}),Z++,!1)}return D.add({...w,"flow:print":A},{...g,source:h}),!0},Rt=h=>{const f=typeof h=="string"?B.get(h):void 0,g=f==null?void 0:f.params.thickness;return typeof g=="number"&&g>0?g*u:void 0},Tt=h=>{var N,it;const f=Pt(h,"extrusion"),g=b.get(String((f==null?void 0:f.level)??h.params.level??"")),w=f==null?void 0:f.slopes,A=((it=(N=f==null?void 0:f.profile)==null?void 0:N.outline)==null?void 0:it.curves)??[],T=Array.isArray(w)?w.map(q=>typeof q=="number"):[],_=T.indexOf(!0);if(h.params.of!=="roof"||!g||A.length!==4||T.filter(Boolean).length!==2||_<0||_>1||!T[_+2])return null;const[S,R]=[A[_],A[_+2]],nt=S.from,ht=S.to,W=Math.hypot(ht[0]-nt[0],ht[1]-nt[1]),St=[(ht[0]-nt[0])/W,(ht[1]-nt[1])/W];let M=[-St[1],St[0]];const at=(R.from[0]-nt[0])*M[0]+(R.from[1]-nt[1])*M[1];at<0&&(M=[-M[0],-M[1]]);const gt=Math.abs(at),[k,K]=[w[_],w[_+2]],ct=g.at+(typeof h.params.base=="number"?h.params.base:0),Ct=(f==null?void 0:f.eaves)??[],[et,yt]=[ct+(Number(Ct[_])||0),ct+(Number(Ct[_+2])||0)],ft=(yt-et+K*gt)/(k+K);return{A:nt,u:St,n:M,L:W,W:gt,si:k,sj:K,ridge:ft,top:ct,ti:et,tj:yt,zAt:(q,x)=>{const P=(q-nt[0])*M[0]+(x-nt[1])*M[1];return Math.min(et+k*P,yt+K*(gt-P))}}},Zt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),Ee=[...Zt.values()].filter(h=>h.item.guid).map(h=>({id:h.id,gid:h.item.guid}));let te=0;if(O)for(const[h,f]of b)mt(I(h),{CategoryId:ue.levels,Name:f.name,Elevation:pt(f.at*u)})&&te++;let Q=0,J=0;const E=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Pt(h,"run"),g=((Us=(js=f==null?void 0:f.run)==null?void 0:js.line)==null?void 0:Us.curves)??[],w=h.params.lookRef,A=b.get(String((f==null?void 0:f.level)??h.params.level??""));if(typeof w!="string"||typeof(f==null?void 0:f.height)!="number"||!A){J++;continue}const T=(Rt(w)??0)/u,_=g.filter(S=>S.kind==="segment"&&S.from&&S.to);J+=g.length-_.length,_.forEach((S,R)=>E.push({record:h,i:R,width:T,from:[...S.from],to:[...S.to],joinStart:R===0&&String(h.params.meetsAtStart)==="true",joinEnd:R===_.length-1&&String(h.params.meetsAtEnd)==="true"}))}const kt=(h,f)=>{const g=[h.to[0]-h.from[0],h.to[1]-h.from[1]],w=[f.to[0]-f.from[0],f.to[1]-f.from[1]],A=g[0]*w[1]-g[1]*w[0];if(Math.abs(A)<1e-9*Math.hypot(...g)*Math.hypot(...w)*1e3)return null;const T=((f.from[0]-h.from[0])*w[1]-(f.from[1]-h.from[1])*w[0])/A;return[h.from[0]+T*g[0],h.from[1]+T*g[1]]},lt=(h,f)=>{const g=f.to[0]-f.from[0],w=f.to[1]-f.from[1],A=g*g+w*w||1,T=Math.max(0,Math.min(1,((h[0]-f.from[0])*g+(h[1]-f.from[1])*w)/A));return Math.hypot(h[0]-(f.from[0]+T*g),h[1]-(f.from[1]+T*w))},At=(h,f)=>{const g=Pt(h.record,"run"),w=Pt(f.record,"run"),A=[g.base,g.base+g.height],T=[w.base,w.base+w.height],_=b.get(String((g==null?void 0:g.level)??h.record.params.level)).at,S=b.get(String((w==null?void 0:w.level)??f.record.params.level)).at;return Math.min(_+A[1],S+T[1])>Math.max(_+A[0],S+T[0])},Mt=1,Lt=new Map;for(const h of E){const f=[["from",h.joinStart],["to",h.joinEnd]],g={from:h.from,to:h.to};for(const[w,A]of f){if(!A)continue;const T=h[w];let _=null,S=1/0;for(const ht of E){if(ht===h||!At(h,ht))continue;const W=lt(T,ht);W<S&&(S=W,_=ht)}if(!_||S>Mt)continue;const R=kt(h,_);if(!R)continue;const nt=Math.min(Mt,2*Math.max(h.width,_.width)+.02);Math.hypot(R[0]-T[0],R[1]-T[1])>nt||lt(R,_)>_.width+.01||(g[w]=R)}Lt.set(h,g)}for(const h of E){const{record:f}=h,g=Pt(f,"run"),w=typeof g.base=="number"?g.base:0,A=g.height,T=b.get(String(g.level??f.params.level??"")),_=f.params.lookRef;let{from:S,to:R}=Lt.get(h);const nt=new Set;if(i&&f.item.guid&&E.filter(N=>N.record===f).length===1?i.elements.get(f.item.guid):void 0){const N=De(i,f.item.guid),it=Math.hypot(R[0]-S[0],R[1]-S[1]);if(N.length>=4&&it>.05){const q=[(R[0]-S[0])/it,(R[1]-S[1])/it],x=N.map(wt=>(wt[0]-S[0])*q[0]+(wt[1]-S[1])*q[1]),P=Math.min(...x),ot=Math.max(...x),dt=N.map(wt=>-(wt[0]-S[0])*q[1]+(wt[1]-S[1])*q[0]),$t=Math.max(...dt)-Math.min(...dt),X=wt=>{const qt=dt.filter((he,de)=>Math.abs(x[de]-wt)<.002);return qt.length>=2&&Math.max(...qt)-Math.min(...qt)>.9*$t},V=S;X(P)&&(S=[V[0]+q[0]*P,V[1]+q[1]*P],nt.add("start")),X(ot)&&(R=[V[0]+q[0]*ot,V[1]+q[1]*ot],nt.add("end"))}}const W=(T.at+w)*u,St=`${pt(S[0]*u)},${pt(S[1]*u)},${pt(W)};${pt(R[0]*u)},${pt(R[1]*u)},${pt(W)}`,M={CategoryId:ue.walls,Type:((qs=Ke(f))==null?void 0:qs.type)??_,LocationLine:St,Level:T.name,BaseOffset:pt(w*u),Height:pt(A*u)},at=[S!==h.from||h.joinStart?"start":"",R!==h.to||h.joinEnd?"end":""].filter(N=>!!N&&!nt.has(N));at.length&&(M.JoinEnds=at.join(","));const gt=at.filter(N=>f.params[N==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");gt.length&&(M.Mitre=gt.join(","));const k=b.get(String(f.params.topLevel??""));k&&(M.TopLevel=k.name,M.TopOffset=pt((T.at+w+A-k.at)*u));const K=g.profile;if(Array.isArray(K)&&K.length>=3&&h.i===0&&!E.some(N=>N!==h&&N.record===f)){const N=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),it=[(h.to[0]-h.from[0])/N,(h.to[1]-h.from[1])/N],q=[],x=-((S[0]-h.from[0])*it[0]+(S[1]-h.from[1])*it[1]),P=(R[0]-h.to[0])*it[0]+(R[1]-h.to[1])*it[1];K.forEach(([ot,dt],$t)=>{const X=Math.abs(ot)<1e-6,V=Math.abs(ot-N)<1e-6;let wt=ot,qt=dt;if(X||V){wt=X?-x:N+P;const de=[K[($t-1+K.length)%K.length],K[($t+1)%K.length]].find(([Ve])=>Math.abs(Ve-ot)>1e-6);de&&(qt=dt+(de[1]-dt)/(de[0]-ot)*(wt-ot))}const he=[h.from[0]+wt*it[0],h.from[1]+wt*it[1]];q.push(he[0]*u,he[1]*u,(T.at+w+qt)*u)}),M.Profile=JSON.stringify([q]),delete M.TopLevel,delete M.TopOffset}const ct=f.params.topAttachedTo,Ct=f.params.topAttachedAt==="top"||g.topAttachedAt==="top",et=typeof ct=="string"&&Ct&&!M.Profile&&Zt.has(ct)?Tt(Zt.get(ct)):null;if(et){const N=Math.hypot(R[0]-S[0],R[1]-S[1]),it=X=>[S[0]+(R[0]-S[0])*X/N,S[1]+(R[1]-S[1])*X/N],q=(S[0]-et.A[0])*et.n[0]+(S[1]-et.A[1])*et.n[1],x=(R[0]-et.A[0])*et.n[0]+(R[1]-et.A[1])*et.n[1],P=[0,N];(q-et.ridge)*(x-et.ridge)<0&&P.splice(1,0,(et.ridge-q)/(x-q)*N);const ot=T.at+w,dt=[],$t=(X,V)=>{const wt=it(X);dt.push(wt[0]*u,wt[1]*u,V*u)};$t(0,ot),$t(N,ot);for(const X of[...P].reverse()){const V=it(X);$t(X,et.zAt(V[0],V[1]))}M.Profile=JSON.stringify([dt]),delete M.TopLevel,delete M.TopOffset}const yt=typeof ct=="string"?ct:i&&f.item.guid?Ta(i,f.item.guid,Ee):void 0;yt&&!M.Profile&&(M.AttachTop=I(yt));const ft=Rt(_);ft&&(M["Type.Width"]=pt(ft));const ut=f.item.guid?i==null?void 0:i.elements.get(f.item.guid):void 0;ut!=null&&ut.layers&&ut.layers.length>1&&(M["Type.Layers"]=JSON.stringify([...ut.layers].reverse().map(N=>[+pt(N.thickness*u),N.material??"",N.function??""])),ut.layersFlipped&&(M.FlipLayers="1")),mt(`${I(f.id)}#${h.i}`,M)&&Q++}const Ot=(h,f,g)=>{if(!(f>0)||f>=h)return[];const w=h-Math.floor(h/f+1e-9)*f,A=g==="beginning"?0:g==="end"?w:g==="centreLine"?h/2%f:w/2,T=[];for(let _=A;_<=h+1e-4;_+=f)_>1e-4&&_<h-1e-4&&T.push(_);return T};let tt=0,vt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;vt++;const f=Pt(h,"run"),g=(Hs=(Gs=(Vs=f==null?void 0:f.run)==null?void 0:Vs.line)==null?void 0:Gs.curves)==null?void 0:Hs[0],w=b.get(String((f==null?void 0:f.level)??h.params.level??"")),A=h.params.lookRef,T=typeof A=="string"?(Js=B.get(A))==null?void 0:Js.params:void 0;if(!(g!=null&&g.from)||!g.to||typeof(f==null?void 0:f.height)!="number"||!w||!T)continue;const _=ft=>typeof ft=="number"?ft:Number(ft)||0,S=_(T.uprightWidth)/2,R=_(T.horizontalWidth)/2,nt=Math.hypot(g.to[0]-g.from[0],g.to[1]-g.from[1]),ht=[(g.to[0]-g.from[0])/nt,(g.to[1]-g.from[1])/nt],W=[g.from[0]-ht[0]*S,g.from[1]-ht[1]*S],St=[g.to[0]+ht[0]*S,g.to[1]+ht[1]*S],M=(typeof f.base=="number"?f.base:0)-R,at=f.height+2*R,gt=(w.at+M)*u,k=((Ws=f.lines)==null?void 0:Ws.along)??Ot(nt,_(T.alongSpacing),T.alongJustify),K=((zs=f.lines)==null?void 0:zs.up)??Ot(f.height,_(T.upSpacing),T.upJustify),ct=(f.omitted??[]).flatMap(ft=>{const ut=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(ft);if(!ut)return[];const N=ut[1]==="horizontal",it=Number(ut[2])/1e3+(N?R:S),q=Number(ut[3])/1e3+(N?S:R);return[{horizontal:N,at:it*u,from:q*u}]}),Ct=(f.omitted??[]).flatMap(ft=>{const ut=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(ft);return ut?[{along:(Number(ut[1])/1e3+S)*u,up:(Number(ut[2])/1e3+R)*u}]:[]}),et={CategoryId:ue.walls,Type:((Ys=Ke(h))==null?void 0:Ys.type)??String(A),LocationLine:`${pt(W[0]*u)},${pt(W[1]*u)},${pt(gt)};${pt(St[0]*u)},${pt(St[1]*u)},${pt(gt)}`,Level:w.name,BaseOffset:pt(M*u),Height:pt(at*u),Curtain:JSON.stringify({along:k.map(ft=>(ft+S)*u),up:K.map(ft=>(ft+R)*u),omit:ct,empty:Ct,mullion:{width:_(T.uprightWidth)*u,depth:_(T.depth)*u},panel:{thickness:_(T.panelDepth)*u,offset:-_(T.panelOffset)*u}})},yt=f.profile;if(Array.isArray(yt)&&yt.length>=3){const ut=yt.reduce((x,P,ot)=>{const dt=yt[(ot+1)%yt.length];return x+P[0]*dt[1]-dt[0]*P[1]},0)>0?1:-1,N=yt.length,it=yt.map((x,P)=>{const ot=yt[(P-1+N)%N],dt=yt[(P+1)%N],$t=(he,de)=>{const Ve=de[0]-he[0],Mn=de[1]-he[1],ar=Math.hypot(Ve,Mn)||1,cr=ut*Mn/ar,lr=-ut*Ve/ar,hr=Math.abs(cr)>Math.abs(lr)?S:R;return{p:[he[0]+cr*hr,he[1]+lr*hr],d:[Ve,Mn]}},X=$t(ot,x),V=$t(x,dt),wt=X.d[0]*V.d[1]-X.d[1]*V.d[0];if(Math.abs(wt)<1e-12)return[V.p[0],V.p[1]];const qt=((V.p[0]-X.p[0])*V.d[1]-(V.p[1]-X.p[1])*V.d[0])/wt;return[X.p[0]+qt*X.d[0],X.p[1]+qt*X.d[1]]}),q=[];for(const[x,P]of it)q.push((g.from[0]+ht[0]*x)*u,(g.from[1]+ht[1]*x)*u,(w.at+M+R+P)*u);et.Profile=JSON.stringify([q])}mt(I(h.id),et)&&tt++}let Ht=0,le=0;for(const h of o){if(h.kind!=="stair"||h.params.of!=="stair")continue;le++;const f=Pt(h,"stair"),g=h.params.lookRef,w=typeof g=="string"?(Ks=B.get(g))==null?void 0:Ks.params:void 0,A=b.get(String((f==null?void 0:f.level)??h.params.level??""));if(!(f!=null&&f.start)||!f.end||!(Number(f.rise)>0)||!A||!w)continue;const T=k=>typeof k=="number"?k:Number(k)||0,_=Number(f.rise),S=Math.max(1,Math.ceil(_/T(w.maxRiser)-1e-6)),R=T(w.tread),nt=k=>[k[0]*u,k[1]*u],ht={family:String(g).split(":")[0],base:(A.at+T(h.params.base))*u,height:_*u,risers:S,tread:R*u,width:T(w.width)*u,sizes:{maxRiser:Math.ceil(_/S*1e3-1e-6)/1e3*u,minTread:R*u,waist:T(w.waist)*u,treadThickness:T(w.treadThickness)*u,riserThickness:T(w.riserThickness)*u,notchExtension:T(w.notchExtension)*u,notchThickness:T(w.notchThickness)*u}},W=f.sketch;if(W!=null&&W.boundary&&W.boundary.length>=4&&W.risers&&W.risers.length>=2){const k=W.boundary,K=W.risers[W.risers.length-1],ct=x=>[(x[0][0]+x[1][0])/2,(x[0][1]+x[1][1])/2],Ct=ct(K);let et=1,yt=1/0;for(let x=1;x<k.length;x++){const P=ct([k[x],k[(x+1)%k.length]]),ot=Math.abs(Math.hypot(P[0]-Ct[0],P[1]-Ct[1])-R);ot<yt&&(yt=ot,et=x)}const ft=(x,P)=>{const ot=[];for(let dt=x;dt!==P;dt=(dt+1)%k.length)ot.push([nt(k[dt]),nt(k[(dt+1)%k.length])]);return ot},ut=[...ft(1,et),...ft((et+1)%k.length,0)],N=W.risers.map(([x,P])=>[nt(x),nt(P)]);nt(k[et]),nt(k[(et+1)%k.length]);const it=N.map(([x,P])=>[(x[0]+P[0])/2,(x[1]+P[1])/2]);ht.sketch={boundary:ut,risers:N,path:it};let q=1/0;for(let x=0;x+1<W.risers.length;x++){const[P,ot]=W.risers[x],[dt,$t]=W.risers[x+1],X=[ot[0]-P[0],ot[1]-P[1]],V=[$t[0]-dt[0],$t[1]-dt[1]],wt=Math.hypot(X[0],X[1]),qt=Math.hypot(V[0],V[1]);Math.abs((X[0]*V[1]-X[1]*V[0])/(wt*qt))>.001||(q=Math.min(q,Math.abs(((dt[0]-P[0])*X[1]-(dt[1]-P[1])*X[0])/wt)))}Number.isFinite(q)&&(ht.tread=q*u,ht.sizes.minTread=q*u)}else ht.path=[nt([f.start[0],f.start[1]]),nt([f.end[0],f.end[1]])];const St=String(h.item.attrs.Name??""),M=St.replace(/ Run \d+$/,""),at=[];for(const k of o){if(k.kind!=="extrusion"||M===St||!new RegExp(`^${M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(k.item.attrs.Name??"")))continue;const K=Pt(k,"extrusion"),ct=K==null?void 0:K.on,Ct=(((Qs=(Xs=K==null?void 0:K.profile)==null?void 0:Xs.outline)==null?void 0:Qs.curves)??[]).flatMap(V=>V.from?[V.from]:[]),et=Rt(k.params.lookRef),yt=b.get(String((K==null?void 0:K.level)??k.params.level??""));if(!(ct!=null&&ct.origin)||!ct.u||!ct.v||Math.abs(ct.v[2]??0)<.99||!Ct.length||!et||!yt)continue;const[ft,ut]=[Math.min(...Ct.map(V=>V[0])),Math.max(...Ct.map(V=>V[0]))],[N,it]=[Math.min(...Ct.map(V=>V[1])),Math.max(...Ct.map(V=>V[1]))],q=ct.origin,x=ct.u;let P=[x[1],-x[0]];const ot=[(f.start[0]+f.end[0])/2,(f.start[1]+f.end[1])/2];(ot[0]-q[0])*P[0]+(ot[1]-q[1])*P[1]<0&&(P=[-P[0],-P[1]]);const $t=et/u,X=(V,wt)=>[(q[0]+x[0]*V+P[0]*wt)*u,(q[1]+x[1]*V+P[1]*wt)*u];at.push({outline:[X(ft,0),X(ut,0),X(ut,$t),X(ft,$t)],top:(yt.at+T(k.params.base)+q[2]+it)*u,thickness:(it-N)*u})}at.length&&(ht.landings=at);const gt={CategoryId:ue.stairs,Type:((Zs=Ke(h))==null?void 0:Zs.type)??String(g),Level:A.name,Stairs:JSON.stringify(ht)};mt(I(h.id),gt)&&Ht++}const ee={floor:0,foundation:0,roof:0,ceiling:0},It={floor:0,foundation:0,roof:0,ceiling:0};for(const h of o){const f=h.params.of;if(h.kind!=="extrusion"||f!=="slab"&&f!=="roof"&&f!=="covering")continue;const g=f==="covering"?"ceiling":f==="roof"?"roof":Cr(h);if(g==="other")continue;ee[g]++;const w=Pt(h,"extrusion"),A=typeof h.params.base=="number"?h.params.base:0,T=b.get(String((w==null?void 0:w.level)??h.params.level??"")),_=h.params.lookRef,S=M=>{if(!(M!=null&&M.length))return null;const at=[];for(const gt of M){if(gt.kind!=="segment"||!gt.from)return null;at.push(gt.from[0]*u,gt.from[1]*u,A*u)}return at.length>=9?at:null},R=S((er=(tr=w==null?void 0:w.profile)==null?void 0:tr.outline)==null?void 0:er.curves);if(typeof _!="string"||!T||!R)continue;const nt=[R],ht=g==="roof"?Tt(h):null;for(const M of((nr=w==null?void 0:w.profile)==null?void 0:nr.holes)??[]){const at=S(M==null?void 0:M.curves);if(at&&ht)for(let gt=0;gt+2<at.length;gt+=3)at[gt+2]=ht.zAt(at[gt]/u,at[gt+1]/u)*u;at&&nt.push(at)}const W={CategoryId:g==="roof"?ue.roofs:g==="ceiling"?ue.ceilings:g==="foundation"?ue.structuralFoundations:ue.floors,Type:((sr=Ke(h))==null?void 0:sr.type)??_,Profile:JSON.stringify(nt),Level:T.name},St=Rt(_);if(St&&(W["Type.Width"]=pt(St)),g==="roof"||g==="ceiling"){W.BaseOffset=pt(A*u);const M=Number(h.params.drop??((rr=w==null?void 0:w.said)==null?void 0:rr.drop));if(g==="ceiling"&&Number.isFinite(M)&&St){const k=[...b.values()].filter(K=>K.at>T.at+1e-6).sort((K,ct)=>K.at-ct.at)[0];k&&(W.BaseOffset=pt((k.at-M-St/u-T.at)*u))}const at=w==null?void 0:w.slopes;g==="roof"&&Array.isArray(at)&&at.some(k=>typeof k=="number")&&(W.Slopes=JSON.stringify(at.map(k=>typeof k=="number"?k:null)));const gt=g==="roof"?Tt(h):null;if(gt){const{A:k,n:K,u:ct,W:Ct,ridge:et,si:yt,ti:ft,tj:ut,L:N}=gt,it=(q,x)=>[(k[0]+K[0]*q)*u,(k[1]+K[1]*q)*u,x*u];W.Extrusion=JSON.stringify({profile:[it(0,ft),it(et,ft+yt*et),it(Ct,ut)],along:[ct[0],ct[1]],length:N*u}),delete W.Slopes}}else St&&(W.HeightOffset=pt(A*u+St));mt(I(h.id),W)&&It[g]++}let bt=0,Ut=0;for(const h of o){if(h.kind!=="member"||h.params.of!=="column")continue;Ut++;const f=Pt(h,"member"),g=f==null?void 0:f.start;if(!g||g.length!==3)continue;const w=c?xr(h.params.lookRef):null;if(c&&!w||!w&&!d)continue;const A=w??{family:d.family,type:d.type},T=b.get(String((f==null?void 0:f.level)??""));mt(I(h.id),{...d&&!w?{CategoryId:d.categoryId}:{},Family:A.family,Type:A.type,...T?{Level:T.name}:{}},{position:[g[0]*u,g[1]*u,g[2]*u],rotationDeg:(Number((f==null?void 0:f.roll)??0)||0)*$r})&&bt++}let Ae=0,ln=0,Ue=0;for(const h of o){if(h.kind!=="familyInstance")continue;if(h.params.host){Ue++;continue}if(ln++,!y)continue;const f=Pt(h,"instance"),g=(ir=f==null?void 0:f.placement)==null?void 0:ir.at;if(!g||g.length!==3)continue;const w=xr(h.params.type);if(!w)continue;const A=(or=f==null?void 0:f.placement)==null?void 0:or.right,T=A?Math.atan2(A[1],A[0])*$r:0;mt(I(h.id),{Family:w.family,Type:w.type},{position:[g[0]*u,g[1]*u,g[2]*u],rotationDeg:T})&&Ae++}const Oe=(()=>{if(!i)return 0;const h=[];for(const g of E){const w=g.record.item.guid;if(!w||!i.elements.has(w))continue;const A=Pt(g.record,"run"),T=b.get(String((A==null?void 0:A.level)??g.record.params.level??""));if(!A||!T)continue;const _=De(i,w);if(!_.length)continue;let S=1/0;for(const R of _)S=Math.min(S,R[2]);h.push(S-(T.at+(typeof A.base=="number"?A.base:0)))}h.sort((g,w)=>g-w);const f=h.length?h[Math.floor(h.length/2)]:0;return Math.abs(f)>.5?f:0})(),Ds=i?ma(i,j,e.fileId):[];let hn=0;for(const h of Ds)mt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-Oe)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&hn++;if(i)for(const h of ga(i,j,e.fileId))mt(h.key,{WallOpening:h.box.map((f,g)=>pt((g%3===2?f-Oe:f)*u)).join(",")},{host:h.host});if(i)for(const h of wa(i,e.fileId))mt(h.key,{Room:"1",Name:h.name,Number:h.number,Height:pt(h.height*u)},{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-Oe)*u]});let Nn=0;const Ci=new Set(["slab","roof","covering"]);for(const h of o){const f=h.params.of;(h.kind==="footing"||h.kind==="ramp"||h.kind==="stair"&&f!=="stair"||h.kind==="extrusion"&&!Ci.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Cr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&Nn++}let qe=0;for(const[h,f]of F)!h.startsWith(`${e.fileId}:`)||j.has(h)||(D.remove(f),qe++);if(D.length===0)throw new Ms(`Up to date: "${e.name}" holds ${st} element(s) this recipe already made, ${Ue+Nn} waiting on the applier, and nothing is left to remove.`);const $i=[te?`${te} level(s)`:"",Q?`${Q} wall(s)`:"",tt?`${tt} curtain wall(s)`:"",It.floor?`${It.floor} floor(s)`:"",It.foundation?`${It.foundation} foundation slab(s)`:"",It.roof?`${It.roof} roof(s)`:"",It.ceiling?`${It.ceiling} ceiling(s)`:"",Ht?`${Ht} stair(s)`:"",bt?`${bt} column(s)`:"",Ae?`${Ae} instance(s)`:"",hn?`${hn} family instance(s)`:"",Z?`${Z} changed`:"",qe?`${qe} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${$i.join(", ")}`,verb:D.summary,targets:D.length,payload:new Blob([await D.build(t.opId)]),ruleTallies:[{read:b.size,written:te},{read:E.length+J,written:Q},{read:vt,written:tt},{read:ee.floor+ee.foundation,written:It.floor+It.foundation},{read:ee.roof,written:It.roof},{read:ee.ceiling,written:It.ceiling},{read:le,written:Ht},{read:Ut,written:bt},{read:ln,written:Ae},{read:Ds.length,written:hn},{read:qe,written:qe},{read:Ue+Nn,written:0}]}}}const Ea={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 bring free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},Ia=[{reads:"Levels (datums)",writes:"The same level in Revit, ensured by name"},{reads:"Wall runs, one per straight segment",writes:"A native wall: line, type (made from its width when missing), level, height, joins; its edited profile or its top on a roof"},{reads:"Curtain wall runs",writes:"Revit's curtain wall: its grid lines, mullions and panels"},{reads:"Slabs: floors and foundation slabs",writes:"A native floor or foundation slab from the profile, holes included"},{reads:"Roofs",writes:"A footprint roof with its sloping edges, or a roof by extrusion for a gable"},{reads:"Ceilings (coverings)",writes:"A native ceiling from the profile, hung at its drop"},{reads:"Stairs",writes:"A native stair: a straight or sketched run, with its landings"},{reads:"Column records (members)",writes:"A Revit column at each, on its level"},{reads:"Free-standing family instances",writes:"When turned on: a new instance of the same-named type, placed and turned"},{reads:"Everything else with a body: doors, windows, furniture, fixtures, proxies, columns, railings",writes:"A family made from the file's own shape, one per shape, placed where the file has it (doors and windows in their wall)"},{reads:"Things this recipe made whose record is gone",writes:"That element removed"},{reads:"Hosted doors/windows, footings, ramps, other bodies",writes:"Nothing yet - read and counted"}],Ii=`
|
|
1
|
+
"use strict";var $i=Object.create;var Ln=Object.defineProperty;var Ri=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Mi=Object.prototype.hasOwnProperty;var dr=s=>{throw TypeError(s)};var Fi=(s,t,e)=>t in s?Ln(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Li=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ki(t))!Mi.call(s,r)&&r!==e&&Ln(s,r,{get:()=>t[r],enumerable:!(n=Ri(t,r))||n.enumerable});return s};var fn=(s,t,e)=>(e=s!=null?$i(Ni(s)):{},Li(t||!s||!s.__esModule?Ln(e,"default",{value:s,enumerable:!0}):e,s));var Rt=(s,t,e)=>Fi(s,typeof t!="symbol"?t+"":t,e),Pn=(s,t,e)=>t.has(s)||dr("Cannot "+e);var g=(s,t,e)=>(Pn(s,t,"read from private field"),e?e.call(s):t.get(s)),K=(s,t,e)=>t.has(s)?dr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),it=(s,t,e,n)=>(Pn(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),m=(s,t,e)=>(Pn(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=Object.create(null);ne.open="0";ne.close="1";ne.ping="2";ne.pong="3";ne.message="4";ne.upgrade="5";ne.noop="6";const gn=Object.create(null);Object.keys(ne).forEach(s=>{gn[ne[s]]=s});const Jn={type:"error",data:"parser error"},Rr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",kr=typeof ArrayBuffer=="function",Nr=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,vs=({type:s,data:t},e,n)=>Rr&&t instanceof Blob?e?n(t):fr(t,n):kr&&(t instanceof ArrayBuffer||Nr(t))?e?n(t):fr(new Blob([t]),n):n(ne[s]+(t||"")),fr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function ur(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Bn;function Pi(s,t){if(Rr&&s.data instanceof Blob)return s.data.arrayBuffer().then(ur).then(t);if(kr&&(s.data instanceof ArrayBuffer||Nr(s.data)))return t(ur(s.data));vs(s,!1,e=>{Bn||(Bn=new TextEncoder),t(Bn.encode(e))})}const pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",We=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<pr.length;s++)We[pr.charCodeAt(s)]=s;const Bi=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,a,l;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(n=0;n<e;n+=4)i=We[s.charCodeAt(n)],o=We[s.charCodeAt(n+1)],a=We[s.charCodeAt(n+2)],l=We[s.charCodeAt(n+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Di=typeof ArrayBuffer=="function",bs=(s,t)=>{if(typeof s!="string")return{type:"message",data:Mr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:ji(s.substring(1),t)}:gn[e]?s.length>1?{type:gn[e],data:s.substring(1)}:{type:gn[e]}:Jn},ji=(s,t)=>{if(Di){const e=Bi(s);return Mr(e,t)}else return{base64:!0,data:s}},Mr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Fr="",Ui=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{vs(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Fr))})})},qi=(s,t)=>{const e=s.split(Fr),n=[];for(let r=0;r<e.length;r++){const i=bs(e[r],t);if(n.push(i),i.type==="error")break}return n};function Vi(){return new TransformStream({transform(s,t){Pi(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Dn;function un(s){return s.reduce((t,e)=>t+e.length,0)}function pn(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function Gi(s,t){Dn||(Dn=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(e.push(o);;){if(n===0){if(un(e)<1)break;const l=pn(e,1);i=(l[0]&128)===128,r=l[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(un(e)<2)break;const l=pn(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(un(e)<8)break;const l=pn(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Jn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(un(e)<r)break;const l=pn(e,r);a.enqueue(bs(i?l:Dn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Jn);break}}}})}const Lr=4;function _t(s){if(s)return Hi(s)}function Hi(s){for(var t in _t.prototype)s[t]=_t.prototype[t];return s}_t.prototype.on=_t.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};_t.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};_t.prototype.off=_t.prototype.removeListener=_t.prototype.removeAllListeners=_t.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};_t.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};_t.prototype.emitReserved=_t.prototype.emit;_t.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};_t.prototype.hasListeners=function(s){return!!this.listeners(s).length};const xn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ji="arraybuffer";function Pr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Wi=qt.setTimeout,zi=qt.clearTimeout;function $n(s,t){t.useNativeTimers?(s.setTimeoutFn=Wi.bind(qt),s.clearTimeoutFn=zi.bind(qt)):(s.setTimeoutFn=qt.setTimeout.bind(qt),s.clearTimeoutFn=qt.clearTimeout.bind(qt))}const Yi=1.33;function Ki(s){return typeof s=="string"?Xi(s):Math.ceil((s.byteLength||s.size)*Yi)}function Xi(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function Br(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Qi(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function Zi(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class to extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Ts extends _t{constructor(t){super(),this.writable=!1,$n(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new to(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=bs(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_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(t){const e=Qi(t);return e.length?"?"+e:""}}class eo extends Ts{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};qi(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Ui(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Br()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Dr=!1;try{Dr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const no=Dr;function so(){}class ro extends eo{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class ee extends _t{constructor(t,e,n){super(),this.createRequest=t,$n(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const e=Pr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ee.requestsCount++,ee.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=so,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ee.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}ee.requestsCount=0;ee.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",mr);else if(typeof addEventListener=="function"){const s="onpagehide"in qt?"pagehide":"unload";addEventListener(s,mr,!1)}}function mr(){for(let s in ee.requests)ee.requests.hasOwnProperty(s)&&ee.requests[s].abort()}const io=function(){const s=jr({xdomain:!1});return s&&s.responseType!==null}();class oo extends ro{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=io&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ee(jr,this.uri(),t)}}function jr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||no))return new XMLHttpRequest}catch{}if(!t)try{return new qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ur=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ao extends Ts{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Ur?{}:Pr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}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=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;vs(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&xn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Br()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const jn=qt.WebSocket||qt.MozWebSocket;class co extends ao{createSocket(t,e,n){return Ur?new jn(t,e,n):e?new jn(t,e):new jn(t)}doWrite(t,e){this.ws.send(e)}}class lo extends Ts{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=Gi(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=Vi();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.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(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&xn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const ho={websocket:co,webtransport:lo,polling:oo},fo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,uo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Wn(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=fo.exec(s||""),i={},o=14;for(;o--;)i[uo[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,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=po(i,i.path),i.queryKey=mo(i,i.query),i}function po(s,t){const e=/\/{2,9}/g,n=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function mo(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const zn=typeof addEventListener=="function"&&typeof removeEventListener=="function",yn=[];zn&&addEventListener("offline",()=>{yn.forEach(s=>s())},!1);class Se extends _t{constructor(t,e){if(super(),this.binaryType=Ji,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const n=Wn(t);e.hostname=n.host,e.secure=n.protocol==="https"||n.protocol==="wss",e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Wn(e.host).host);$n(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),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},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Zi(this.opts.query)),zn&&(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"})},yn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Lr,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Se.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Se.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+=Ki(r)),n>0&&e>this._maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,xn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Se.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){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(),zn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=yn.indexOf(this._offlineEventListener);n!==-1&&yn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Se.protocol=Lr;class go extends Se{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;Se.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Se.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=e.name,this.emitReserved("upgradeError",w)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const o=p=>{const w=new Error("probe error: "+p);w.transport=e.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function d(p){e&&p.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};e.once("open",r),e.once("error",o),e.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let yo=class extends go{constructor(t,e={}){const n=typeof t=="object",r=n?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>ho[i]).filter(i=>!!i)),super(n?r:t,r)}};function wo(s,t="",e){let n=s;e=e||typeof location<"u"&&location,s==null&&(s=e.protocol+"//"+e.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=e.protocol+s:s=e.host+s),/^(https?|wss?):\/\//.test(s)||(typeof e<"u"?s=e.protocol+"//"+s:s="https://"+s),n=Wn(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}const vo=typeof ArrayBuffer=="function",bo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,qr=Object.prototype.toString,To=typeof Blob=="function"||typeof Blob<"u"&&qr.call(Blob)==="[object BlobConstructor]",Eo=typeof File=="function"||typeof File<"u"&&qr.call(File)==="[object FileConstructor]";function Es(s){return vo&&(s instanceof ArrayBuffer||bo(s))||To&&s instanceof Blob||Eo&&s instanceof File}function wn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(wn(s[e]))return!0;return!1}if(Es(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return wn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&wn(s[e]))return!0;return!1}function Io(s){const t=[],e=s.data,n=s;return n.data=Yn(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Yn(s,t){if(!s)return s;if(Es(s)){const e={_placeholder:!0,num:t.length};return t.push(s),e}else if(Array.isArray(s)){const e=new Array(s.length);for(let n=0;n<s.length;n++)e[n]=Yn(s[n],t);return e}else if(typeof s=="object"&&!(s instanceof Date)){const e={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(e[n]=Yn(s[n],t));return e}return s}function So(s,t){return s.data=Kn(s.data,t),delete s.attachments,s}function Kn(s,t){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<t.length)return t[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=Kn(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Kn(s[e],t));return s}const _o=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var X;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(X||(X={}));class Ao{constructor(t){this.replacer=t}encode(t){return(t.type===X.EVENT||t.type===X.ACK)&&wn(t)?this.encodeAsBinary({type:t.type===X.EVENT?X.BINARY_EVENT:X.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===X.BINARY_EVENT||t.type===X.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Io(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class Is extends _t{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===X.BINARY_EVENT;n||e.type===X.BINARY_ACK?(e.type=n?X.EVENT:X.ACK,this.reconstructor=new Oo(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Es(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(X[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===X.BINARY_EVENT||n.type===X.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Co(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(Is.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case X.CONNECT:return gr(e);case X.DISCONNECT:return e===void 0;case X.CONNECT_ERROR:return typeof e=="string"||gr(e);case X.EVENT:case X.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&_o.indexOf(e[0])===-1);case X.ACK:case X.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Oo{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=So(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Co=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function gr(s){return Object.prototype.toString.call(s)==="[object Object]"}const xo=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Is,Encoder:Ao,get PacketType(){return X}},Symbol.toStringTag,{value:"Module"}));function zt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const $o=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Vr extends _t{constructor(t,e,n){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=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[zt(t,"open",this.onopen.bind(this)),zt(t,"packet",this.onpacket.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if($o.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:X.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,p=e.pop();this._registerAckCallback(c,p),o.id=c}const a=(r=(n=this.io.engine)===null||n===void 0?void 0:n.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(t,e){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);e.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),e.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(o,a)=>o?r(o):n(a);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:X.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case X.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 X.EVENT:case X.BINARY_EVENT:this.onevent(t);break;case X.ACK:case X.BINARY_ACK:this.onack(t);break;case X.DISCONNECT:this.ondisconnect();break;case X.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:X.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:X.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function je(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}je.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*s);s=Math.floor(t*10)&1?s+e:s-e}return Math.min(s,this.max)|0};je.prototype.reset=function(){this.attempts=0};je.prototype.setMin=function(s){this.ms=s};je.prototype.setMax=function(s){this.max=s};je.prototype.setJitter=function(s){this.jitter=s};class Xn extends _t{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,$n(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((n=e.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new je({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||xo;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new yo(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=zt(e,"open",function(){n.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=zt(e,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(zt(t,"ping",this.onping.bind(this)),zt(t,"data",this.ondata.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this)),zt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){xn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Vr(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Ge={};function Xe(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=wo(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=Ge[r]&&i in Ge[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new Xn(n,t):(Ge[r]||(Ge[r]=new Xn(n,t)),l=Ge[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(Xe,{Manager:Xn,Socket:Vr,io:Xe,connect:Xe});class Qn extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const yr="bimterop",Zn="revitflow_history.json",Gr="revitflow_model.frag",Hr="revitflow_",Ro="bimterop-locks-anchor";function ko(s,t){return s.filter(e=>String(e.parentId??"")===t)}function No(s){const t=s==null?void 0:s.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Zt(s){return String(s._id??s.id??"")}var Wt,Ae,oe,en,nn,ts;class Ss{constructor(t,e){K(this,nn);K(this,Wt);K(this,Ae,new Map);K(this,oe);K(this,en,0);this.client=t,this.projectId=e}async docs(){const t=await m(this,nn,ts).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const r of e){if(r.archived)continue;const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:Zt(r)})).map(p=>String(p.name??"")),d=l.find(p=>p===Gr)??l.find(p=>p.endsWith(".frag")&&!p.startsWith(Hr)),c=l.includes(Zn)||!!d;n.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:Zt(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=g(this,Ae).get(n);return r||(r=new es(this.client,this,t,e),g(this,Ae).set(n,r)),r}document(t){const e=`platform-${t}`;let n=g(this,Ae).get(e);return n||(n=new es(this.client,this,"platform",t,t),g(this,Ae).set(e,n)),n}async childFolders(t,e=!1){return(e||!g(this,oe)||Date.now()-g(this,en)>3e4)&&(it(this,en,Date.now()),it(this,oe,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>ko(n,t))),g(this,oe).catch(()=>{it(this,oe,void 0)})),g(this,oe)}forgetFolders(){it(this,oe,void 0)}async rootFolderId(t=!1){if(g(this,Wt))return g(this,Wt);const e=await m(this,nn,ts).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(yr,void 0,this.projectId);return it(this,Wt,Zt(n)),g(this,Wt)}}Wt=new WeakMap,Ae=new WeakMap,oe=new WeakMap,en=new WeakMap,nn=new WeakSet,ts=async function(){if(g(this,Wt))return g(this,Wt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===yr&&!n.parentId);return e&&it(this,Wt,Zt(e)),g(this,Wt)};var Xt,N,ie,Re,ye,Qt,sn,ns,vn,we,Jr,bn,Wr,zr,Yr;class es{constructor(t,e,n,r,i){K(this,N);K(this,Xt);K(this,Qt);K(this,sn,0);this.client=t,this.project=e,this.source=n,this.docId=r,it(this,Xt,i)}async timeline(){const t=await m(this,N,bn).call(this);return _s((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await m(this,N,we).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async modelParts(t){const e=await this.timeline();if(e.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const n=t==null?void 0:t.at,r=n?e.findIndex(c=>c.guid===n):e.length-1;if(r<0)throw new Error(`No version ${n} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(e[c].full){i=c;break}const o=await m(this,N,we).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=e[i],l=e.slice(r+1).some(c=>c.full),d=e.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(p=>p.type==="delete").map(p=>p.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!l,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:e[r].guid}}async folderId(){return await m(this,N,ye).call(this,!1)}async descriptor(){return await g(this,N,ie).descriptor(await m(this,N,ye).call(this,!1))}async view(t){const e=await m(this,N,ye).call(this,!1),n=await g(this,N,ie).descriptor(e);if(n){for(const i of t){const o=n.views.find(a=>a.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await m(this,N,we).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await m(this,N,ye).call(this,!0);if(await g(this,N,ie).descriptor(e)){await g(this,N,ie).addView(e,t);return}const r=await m(this,N,we).call(this);await g(this,N,ie).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??g(this,N,Re),views:[t]})}async ensureDescriptor(){const t=await m(this,N,ye).call(this,!1),e=await g(this,N,ie).descriptor(t);if(e)return e;const n=await m(this,N,we).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await g(this,N,ie).setDescriptor(t,r),await g(this,N,ie).descriptor(t)}async ownership(){const t=await m(this,N,vn).call(this,Ro);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async o=>{try{const a=Zt(o),l=await this.client.downloadHiddenFile(a),d=JSON.parse(await l.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(c=>typeof c=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of n)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(t){var a;const e=await m(this,N,ye).call(this,!0);let n=await m(this,N,bn).call(this)??{model:this.docId,commits:[]};const r=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Qn(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:As(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...t.kind?{kind:t.kind}:{},...t.file?{file:t.file}:{},...t.origin?{origin:t.origin}:{},...(a=t.origins)!=null&&a.length?{origins:t.origins}:{},changes:t.changes,counts:Mo(t.changes)};if(t.model&&(await m(this,N,Yr).call(this,e,t.model),i.full=!0),t.delta){const l=await m(this,N,we).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const d=await this.client.createHiddenFile(t.delta,l.id);i.deltaId=No(d)}const o=await m(this,N,bn).call(this);if(o){n=o;const l=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new Qn(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await m(this,N,Wr).call(this,e,Zn,n),i}}Xt=new WeakMap,N=new WeakSet,ie=function(){return new Cs(this.client,this.project.projectId)},Re=function(){return`${this.source}-${this.docId}`},ye=async function(t){if(g(this,Xt))return g(this,Xt);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=o=>o.find(a=>String(a.name??"")===g(this,N,Re)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return it(this,Xt,Zt(r)),g(this,Xt);if(!t)throw new Error(`Document ${g(this,N,Re)} does not exist in this project.`);const i=await this.client.createFolder(g(this,N,Re),e,this.project.projectId);return this.project.forgetFolders(),it(this,Xt,Zt(i)),g(this,Xt)},Qt=new WeakMap,sn=new WeakMap,ns=async function(){return(!g(this,Qt)||Date.now()-g(this,sn)>5e3)&&(it(this,sn,Date.now()),it(this,Qt,(async()=>{const t=await m(this,N,ye).call(this,!1);return(await this.client.listFiles({folderId:t})).map(n=>({id:Zt(n),name:String(n.name??"")}))})()),g(this,Qt).catch(()=>{it(this,Qt,void 0)})),g(this,Qt)},vn=async function(t){try{return(await m(this,N,ns).call(this)).find(e=>e.name===t)}catch{return}},we=async function(){try{const t=await m(this,N,ns).call(this);return t.find(e=>e.name===Gr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Hr))}catch{return}},Jr=async function(t){const e=await m(this,N,vn).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},bn=function(){return m(this,N,Jr).call(this,Zn)},Wr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await m(this,N,vn).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await m(this,N,zr).call(this,t,e,n)},zr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:e}},Yr=async function(t,e){const n=await m(this,N,we).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${g(this,N,Re)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:r}};function Mo(s){const t={added:0,modified:0,removed:0};for(const e of s)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function _s(s){var l;if(s.length<=1)return s.forEach((d,c)=>d.ordinal=c),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const c=(l=d.parents)==null?void 0:l[0];if(c&&t.has(c)){const p=e.get(c)??[];p.push(d),e.set(c,p)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],o=[...n].reverse(),a=new Set;for(;o.length;){const d=o.pop();if(a.has(d.guid))continue;a.add(d.guid),i.push(d);const c=(e.get(d.guid)??[]).sort(r);for(let p=c.length-1;p>=0;p--)o.push(c[p])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function wr(s){const t=_s(s);return t[t.length-1]}function As(){const s=globalThis.crypto;return s!=null&&s.randomUUID?s.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}const Os={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawings",icon:"tabler:layout-board"},reality:{label:"Reality capture",icon:"tabler:3d-cube-sphere"},coordination:{label:"Coordination set",icon:"tabler:messages"},generic:{label:"Generic",icon:"tabler:file"}},Fo={rvt:"bim",rfa:"bim",ifc:"bim",frag:"bim",tostrm:"bim","3dm":"bim",nwd:"bim",dgn:"bim",dwg:"drawings",dxf:"drawings",las:"reality",laz:"reality",e57:"reality",ply:"reality",potree:"reality",splat:"reality",spz:"reality",ksplat:"reality",bcf:"coordination",bcfzip:"coordination"};function ss(s){var e;if(s.type&&s.type in Os)return s.type;const t=[(e=s.native)==null?void 0:e.format,...s.views.map(n=>n.format)];for(const n of t){const r=n?Fo[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const Ze="thatopen/document@1",Tn="document.json",Kr=["pdf","txt","md","json","csv","tsv","frag"];function se(s){return String(s._id??s.id??"")}var Nt,Xr,rs,Qr,Zr,En;class Cs{constructor(t,e){K(this,Nt);this.client=t,this.projectId=e}async list(t){const e=await m(this,Nt,Xr).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(ss(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=Un(r,n.fileExtension),o=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,n.folderId?String(n.folderId):void 0,this.projectId),l=se(a);await this.client.updateFile(t,{parentFolderId:l});const d=[],c=await m(this,Nt,Qr).call(this,n);if(c)try{const v=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:Un(String(v.name??""),v.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Kr.includes(i))&&d.push({fileId:t,format:i});const w={schema:Ze,name:o,native:{fileId:t,format:i},views:d};return w.type=(e==null?void 0:e.type)??ss(w),await this.setDescriptor(l,w),await this.recordUpload(l,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:l,descriptor:w}}async recordUpload(t,e,n){const r=new Ss(this.client,this.projectId).document(t),i=(await r.timeline()).length===0;await r.sync({author:n||"unknown",source:"platform",kind:"upload",message:i?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Un(e.name,void 0)},changes:[]})}async descriptor(t){const e=await m(this,Nt,En).call(this,t);return e?m(this,Nt,rs).call(this,e.id):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const r of e){const i=n.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.views=[...n.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,n)}async setType(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.type!==e&&await this.setDescriptor(t,{...n,type:e})}async setDescriptor(t,e){const n={...e,schema:Ze,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await m(this,Nt,En).call(this,t);if(i){await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:Tn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new ti(this.client,()=>m(this,Nt,En).call(this,t))}}Nt=new WeakSet,Xr=async function(){const e=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===Tn);return(await Promise.all(e.map(async r=>{const i=r,o=String(i.folderId??i.parentFolderId??"");if(!o)return null;const a=await m(this,Nt,rs).call(this,se(r));return a?{folderId:o,descriptor:a}:null}))).filter(r=>r!==null)},rs=async function(t){const n=await(await this.client.downloadFile(t)).text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Do(r)},Qr=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const a=n.find(l=>se(l)===se(t));e=(a==null?void 0:a.versions)??[]}const r=await m(this,Nt,Zr).call(this,t,e);if(r)return r;const i=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!i)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const o=n.find(a=>String(a.name??"").toLowerCase()===`${i}.frag`&&!a.archived&&se(a)!==se(t));return o?se(o):void 0},Zr=async function(t,e){const n=[...e].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")));for(const r of n)try{const i=await this.client.getFileVersionMetadata(se(t),r.tag),o=i==null?void 0:i.derivedFileId;if(typeof o=="string"&&o)return o}catch{}},En=async function(t){const n=(await this.client.listFiles({folderId:t})).find(r=>String(r.name??"")===Tn);return n?{id:se(n)}:void 0};const is="draft:",ke="TODRAFT1";var te,ze,os;class ti{constructor(t,e){K(this,te);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const n of await m(this,te,ze).call(this,t.id)){const r=e.get(n.userId);(!r||n.savedAt>r.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,r)=>+r.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const r=(await m(this,te,ze).call(this,e.id)).filter(l=>!(t!=null&&t.userId)||l.userId===t.userId).sort((l,d)=>+d.savedAt-+l.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await Bo(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(t,e){const n=await this.holder();if(!n)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Lo(e.userId),i=(await m(this,te,ze).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await Po(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await m(this,te,os).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:vr(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await m(this,te,ze).call(this,e.id)).filter(r=>r.userId===t.userId);await m(this,te,os).call(this,n.map(r=>r.hiddenId))}}te=new WeakSet,ze=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(is)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(is.length),savedAt:vr(r)}})},os=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Lo(s){const t=`${is}${s}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(t))throw new Error(`A draft cannot be tagged for user "${s}": ids must be letters, digits or :._- and short.`);return t}function vr(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function Po(s,t){const e=new TextEncoder().encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e.length,!0),new Blob([new TextEncoder().encode(ke),n,e,s])}async function Bo(s){const t=new Uint8Array(await s.slice(0,ke.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,ke.length))!==ke)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(ke.length,!0),n=ke.length+4,r=await s.slice(n,n+e).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:s.slice(n+e)}}function Un(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Do(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Ze||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(o=>!!o&&typeof o=="object"&&typeof o.fileId=="string"&&typeof o.format=="string"):[],n=t.native,r=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",i=typeof t.type=="string"&&t.type in Os?t.type:void 0;return{schema:Ze,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const jo="flow:",Uo="flow:op",qo="flow:source",Vo="flow:host",xs="revitflow/op@2",br="REVITFLOWCHANGE",Tr="REVITFLOWOPERATION";class Rn{constructor(t){Rt(this,"changes",[]);this.target=t}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(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,n={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,n)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:xs,opId:t,batchId:this.batchId??t,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},[n,r]=await Go();return Ho(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(jo)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Er).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Er(e.rotationDeg)),e.source&&(n[qo]=e.source),e.host&&(n[Vo]=e.host),n}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,n,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=e,c=new t.Builder(1024),p=this.changes.length,w=new Uint32Array(p);let v=1;for(let et=0;et<p;et++)w[et]=v++;const I=v++,_=et=>(et(c,0),c.endVector()),L=o.createShellsVector(c,[]),C=o.createCircleExtrusionsVector(c,[]),O=_(o.startSamplesVector),u=_(o.startRepresentationsVector),x=_(o.startMaterialsVector),T=_(o.startLocalTransformsVector),M=_(o.startGlobalTransformsVector),z=o.createMeshesItemsVector(c,[]),ut=o.createMaterialIdsVector(c,[]),wt=o.createRepresentationIdsVector(c,[]),Ot=o.createSampleIdsVector(c,[]),Vt=o.createLocalTransformIdsVector(c,[]),kt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,M),o.addShells(c,L),o.addRepresentations(c,u),o.addSamples(c,O),o.addLocalTransforms(c,T),o.addMaterials(c,x),o.addCircleExtrusions(c,C),o.addMeshesItems(c,z),o.addRepresentationIds(c,wt),o.addSampleIds(c,Ot),o.addMaterialIds(c,ut),o.addLocalTransformIds(c,Vt),o.addGlobalTransformIds(c,kt);const he=o.endMeshes(c),Yt=c.createString(r),It=new Set,Gt=[];for(const et of this.changes){const At=[],Ht={[Uo]:et.op,...et.attrs};for(const[de,Ue]of Object.entries(Ht)){const xe=JSON.stringify([de,Ue,"IFCTEXT"]);It.add(xe),At.push(c.createString(xe))}Gt.push(i.createAttribute(c,i.createDataVector(c,At)))}{const et=JSON.stringify(["Name",n,"IFCLABEL"]);It.add(et);const At=i.createDataVector(c,[c.createString(et)]);Gt.push(i.createAttribute(c,At))}const Mt=a.createAttributesVector(c,Gt),Ce=a.createUniqueAttributesVector(c,[...It].map(et=>c.createString(et))),q=this.changes.map(()=>c.createString(br));q.push(c.createString(Tr));const Z=a.createCategoriesVector(c,q),$=[],Tt=[];this.changes.forEach((et,At)=>{et.item&&($.push(c.createString(et.item)),Tt.push(w[At]))});const Et=a.createGuidsVector(c,$),pt=a.createGuidsItemsVector(c,Tt),Dt=a.createLocalIdsVector(c,[...w,I]),Ft=this.changes.map((et,At)=>l.createSpatialStructure(c,w[At],c.createString(br),0)),Pt=l.createSpatialStructure(c,I,c.createString(Tr),l.createChildrenVector(c,Ft)),st=c.createString(n);a.startModel(c),a.addMeshes(c,he),a.addMetadata(c,Yt),a.addAttributes(c,Mt),a.addUniqueAttributes(c,Ce),a.addLocalIds(c,Dt),a.addCategories(c,Z),a.addGuidsItems(c,pt),a.addGuids(c,Et),a.addGuid(c,st),a.addSpatialStructure(c,Pt),a.addMaxLocalId(c,v);const rt=a.endModel(c);return a.finishModelBuffer(c,rt),c.asUint8Array()}}async function Go(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${s instanceof Error?s.message:String(s)})`)}}function Er(s){return Number.isFinite(s)?String(s):"0"}async function Ho(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function kn(s){const[t,e]=await Jo(),n=e.Model.getRootAsModel(new t.ByteBuffer(await Wo(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<n.guidsLength();a++){const l=n.guidsItems(a),d=n.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<n.attributesLength();a++){const l=n.localIds(a);if(l===null)continue;const d={},c=n.attributes(a);for(let p=0;p<((c==null?void 0:c.dataLength())??0);p++){const w=c.data(p);if(w)try{const[v,I]=JSON.parse(w);d[v]=I}catch{}}o.push({localId:l,guid:i.get(l)??null,category:n.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function Jo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){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). (${s instanceof Error?s.message:String(s)})`)}}async function Wo(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ei="Element",ni="Carried",Me=1/.3048;function si(s){const t=[];for(const e of s)for(const n of[ei,ni]){const r=e.attrs[n];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"||t.push({id:a.id,kind:a.kind,params:a.params??{},item:e})}}catch{}}return t}function Bt(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function zo(s){const t=new Map;for(const[e,n]of $s(s))t.set(e,n.name);return t}function $s(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,r=e.params.at;typeof n=="string"&&typeof r=="number"&&t.set(e.id,{name:n,at:r})}return t}function ri(s){const t=new Map;for(const e of s){if(!e.kind.endsWith("Style"))continue;const n=e.params.name;typeof n=="string"&&t.set(n,e)}return t}function Rs(s,t){const e=new Map;for(const[n,r]of s.made)e.set(n,r.id),r.print&&(t==null||t.set(n,r.print));return e}function ii(s){const t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,e=JSON.stringify(t(s));let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function ks(s,t){var o,a;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const n=((a=(o=/\.([^.]+)$/.exec(t.name))==null?void 0:o[1])==null?void 0:a.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const l=s.client.recipes.importerFor(n);if(!l)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=oi(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),i=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await l(e,t.name)}return{picked:t,contents:await kn(e),site:r,shapes:i}}function oi(s){var M;const t=new TextDecoder("latin1").decode(s),e=z=>new RegExp(`^${z}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=z=>[...z.matchAll(/#\d+|\$/g)].map(ut=>ut[0]),r=z=>[...z.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(ut=>Number(ut[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const o=(M=i[2].split(",")[5])==null?void 0:M.trim();if(!(o!=null&&o.startsWith("#")))return null;const a=e(o);if((a==null?void 0:a[1])!=="IFCLOCALPLACEMENT")return null;const[l,d]=n(a[2]);if(l!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[p,,w]=n(c[2]),v=p&&p!=="$"?e(p):null;if(!v)return null;const[I=0,_=0,L=0]=r(v[2]);let C=0;const O=w&&w!=="$"?e(w):null;if(O){const[z=1,ut=0]=r(O[2]);C=Math.atan2(ut,z)*180/Math.PI}const u=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),x={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},T=u?u[2]?x[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:I*T,north:_*T,elevation:L*T,angleDeg:C}}const Ns="thatopen/recipe@1",Ir="__project_data",Sr="recipes",Yo=s=>`${s}.recipe.json`,ai={OperationBuilder:Rn,OP_SCHEMA:xs,readFrag:kn,readPickedFrag:ks,recordsOf:si,innerJson:Bt,levelsOf:$s,levelNames:zo,stylesOf:ri,printOf:ii,siteLocationOf:oi,whatItMadeBefore:Rs,ELEMENT_FIELD:ei,CARRIED_FIELD:ni,FEET_PER_METRE:Me},ci=/^[a-z0-9][a-z0-9-]{1,62}$/;async function li(s,t,e){const n=d=>[...d].sort((c,p)=>String(c._id).localeCompare(String(p._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Ir&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Ir,void 0,t)}const o=String(i._id),a=await s.listFolders({parentFolderId:o,projectId:t,archived:!1});let l=n(a.filter(d=>d.name===Sr&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder(Sr,o,t)}return String(l._id)}const Ko=s=>String(s._id??s.id??""),Xo=s=>String(s.tag??s.versionTag??""),as=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function He(s,t){const e=await li(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const o=String(i.name??"");o.endsWith(".recipe.json")&&r.set(o.slice(0,-12),{id:Ko(i)})}return r}async function mn(s,t,e){var i;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),r=JSON.parse(await n.text());if((r==null?void 0:r.schema)!==Ns||!((i=r.manifest)!=null&&i.name)||typeof r.code!="string")throw new Error(`This is not a recipe this library can read (${String(r==null?void 0:r.schema)}).`);return r}async function Je(s,t){return(await s.listVersions(t)).map(n=>({tag:Xo(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>as(n.tag)-as(r.tag))}var rn;class hi{constructor(t,e){K(this,rn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await He(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await Je(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await mn(this.client,r,a);return{manifest:l.manifest,origin:"project",version:a,author:l.author,savedAt:l.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await He(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await Je(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await mn(this.client,n.id,i);return{version:i,author:a.author,note:a.note,savedAt:a.savedAt??o}}catch{return{version:i,savedAt:o}}}))}async source(t,e,n){var o;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await Je(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await mn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!ci.test((r==null?void 0:r.name)??""))throw new Error('A recipe name is lower case letters, digits and dashes, 2 to 63 of them: "walls-from-ifc".');if(this.builtinNames().has(r.name))throw new Error(`"${r.name}" is a built-in recipe. Give yours a name of its own.`);if(!r.to||!r.description||!Array.isArray(r.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await cs(r,i);const o={schema:Ns,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),l=(await He(this.client,t)).get(r.name);if(l){const c=await Je(this.client,l.id),p=`v${Math.max(0,...c.map(w=>as(w.tag)))+1}`;return await this.client.createVersion(l.id,a,p),p}const d=await li(this.client,t,!0);return await this.client.createFile({file:a,name:Yo(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await Je(this.client,r.id)).pop())==null?void 0:l.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const o=`${r.id}@${i}`;let a=g(this,rn).get(o);if(!a){const d=await mn(this.client,r.id,i);a=await cs(d.manifest,d.code),g(this,rn).set(o,a)}return{recipe:a,version:i}}}rn=new WeakMap;async function cs(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${Qo(t)}`)}catch(i){throw new Error(`The recipe's code does not load: ${i instanceof Error?i.message:String(i)}`)}const n=e.run??((r=e.default)==null?void 0:r.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:i=>n({...i,kit:ai})}}function Qo(s){const t=new TextEncoder().encode(s);let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}async function Zo(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await kn(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const o={};for(const[a,l]of Object.entries(i.attrs))a.startsWith("flow:")||(o[a]=l);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:o}});return{envelope:n??{},changes:r}}class Ms extends Error{constructor(t){super(t),this.name="UpToDate"}}var ae,on,an;class di{constructor(t){K(this,ae,new Map);K(this,on,new Map);K(this,an,new Map);Rt(this,"project");this.client=t,this.project=new hi(t,()=>new Set(g(this,ae).keys()))}provideImporter(t,e){g(this,on).set(t.toLowerCase(),e)}provideShapes(t,e){g(this,an).set(t.toLowerCase(),e)}shapesFor(t){return g(this,an).get(t.toLowerCase())}importerFor(t){return g(this,on).get(t.toLowerCase())}register(t){if(g(this,ae).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);g(this,ae).set(t.name,t)}list(t){return[...g(this,ae).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return g(this,ae).get(t)}async catalog(t,e){const n=this.list(e).map(i=>({manifest:i,origin:"builtin"}));let r=[];try{r=(await this.project.list(t)).filter(i=>!(e!=null&&e.to)||i.manifest.to===e.to)}catch{}return[...n,...r.sort((i,o)=>i.manifest.name.localeCompare(o.manifest.name))]}async resolve(t,e,n){const r=g(this,ae).get(t);return r?{recipe:r,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),r=n.source;if((r==null?void 0:r.kind)!=="project-file")return[];const i=(r.extensions??[]).map(d=>d.toLowerCase()),a=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),l=await fi(this.client,a.map(d=>d.descriptor.native.fileId));return a.map(d=>{const c=d.descriptor.native;return{label:d.descriptor.name,fileId:c.fileId,name:`${d.descriptor.name}.${c.format}`,folderId:d.folderId,version:l.get(c.fileId)??"v1"}}).sort((d,c)=>d.label.localeCompare(c.label))}async run(t,e){const{recipe:n}=await this.resolve(t,e.projectId,e.recipeVersion);if(n.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${n.to}, but the target document belongs to ${e.target.source}.`);return await n.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??As(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}ae=new WeakMap,on=new WeakMap,an=new WeakMap;async function fi(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var o;return Number(((o=/(\d+)/.exec(String(i??"")))==null?void 0:o[1])??-1)},r=i=>{const a=i.slice().sort((l,d)=>{const c=l!=null&&l.createdAt?new Date(String(l.createdAt)).getTime():NaN,p=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(p)&&c!==p?p-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((l==null?void 0:l.tag)??(l==null?void 0:l.versionTag))})[0];return a?String(a.tag??a.versionTag??"v1"):"v1"};return await Promise.all(t.map(async i=>{try{e.set(i,r(await s.listVersions(i)))}catch{e.set(i,"v1")}})),e}const ls=100;function ta(s){try{const t=JSON.parse(s);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function ea(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Nn extends Error{constructor(e,n,r,i){const o=ta(r);super(o.message??`${n||"Request failed"} (${e})`);Rt(this,"status");Rt(this,"code");Rt(this,"details");Rt(this,"body");Rt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??ea(o.details)}}const Kt="item/folder",W="item",pe="processor",na="npm-registry",re="hidden",qn="FILE",Vn="TOOL",Gn="APP",sa=500,_r=3e4,ra=.25,ia=s=>new Promise(t=>setTimeout(t,s));function oa(s){var r,i;const t=(i=(r=s.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,(n-Date.now())/1e3)}function aa(s){return s instanceof Nn?s.status===429||s.status>=500:!0}function ca(s,t){const e=Math.min(sa*2**t,_r),n=e*ra*Math.random(),r=s instanceof Nn&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,_r)+n:e+n}var E,hs,F,ve,cn,Ye,In,Sn,ds,fs,ui;const Ps=class Ps{constructor(t,e,n){K(this,E);Rt(this,"apiUrl");Rt(this,"accessToken");Rt(this,"wsUrl");Rt(this,"retries");Rt(this,"useBearer");Rt(this,"builtInGlobals",null);Rt(this,"localServerUrl",null);Rt(this,"context");K(this,cn);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=n||{};let a=e;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=t,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Ps(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,n){return m(this,E,F).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await m(this,E,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:qn,archived:n}}):await m(this,E,F).call(this,"GET",`${W}`,{query:{itemType:qn,archived:n,...r&&{projectId:r}}})}async getFile(t,e){return await m(this,E,fs).call(this,t,e)}async createFile(t){return await m(this,E,Sn).call(this,t,qn)}async updateFile(t,e){return await m(this,E,ds).call(this,t,e)}async archiveFile(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}`)}async recoverFile(t){return await m(this,E,F).call(this,"PUT",`${W}/${t}/recover`)}async downloadFile(t,e){return await m(this,E,In).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await m(this,E,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await m(this,E,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await m(this,E,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await m(this,E,Ye).call(this,t,async r=>(await m(this,E,F).call(this,"POST",`${W}/batch/version-metadata`,{body:JSON.stringify({entries:r,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:r}=t||{};return await m(this,E,F).call(this,"GET",Kt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await m(this,E,F).call(this,"GET",`${Kt}/${t}`)}async getFoldersBatch(t){return await m(this,E,Ye).call(this,t,async e=>(await m(this,E,F).call(this,"POST",`${W}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await m(this,E,F).call(this,"POST",Kt,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await m(this,E,F).call(this,"PUT",`${Kt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await m(this,E,F).call(this,"DELETE",`${Kt}/${t}`)}async recoverFolder(t){return await m(this,E,F).call(this,"PUT",`${Kt}/${t}/recover`)}async downloadFolder(t){return await m(this,E,ve).call(this,`${Kt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await m(this,E,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Vn,...n&&{ShowVersions:n}}}):await m(this,E,F).call(this,"GET",`${W}`,{query:{itemType:Vn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await m(this,E,fs).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await m(this,E,Sn).call(this,t,Vn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await m(this,E,ds).call(this,t,e,n)}async downloadComponent(t,e){return await m(this,E,In).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await m(this,E,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}`)}async recoverComponent(t){return await m(this,E,F).call(this,"PUT",`${W}/${t}/recover`)}async getBuiltInComponent(t){return await(await m(this,E,ve).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const r=await this.getBuiltInComponent(t.uuid),i=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(p=>i[p]),d=new Function(...o,`${r}
|
|
2
|
+
return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){var o,a;const n=t.OBC,r=t.BUI;if(!(n!=null&&n.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 n.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(t,e){var n,r;(r=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||r.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await m(this,E,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Gn,...n&&{ShowVersions:n}}}):await m(this,E,F).call(this,"GET",`${W}`,{query:{itemType:Gn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await m(this,E,Sn).call(this,t,Gn,e)}async downloadApp(t,e){return await m(this,E,In).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await m(this,E,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}`)}async getNpmCredentials(){return await m(this,E,F).call(this,"GET",`${na}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${pe}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});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 m(this,E,F).call(this,"POST",`${pe}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await m(this,E,F).call(this,"POST",`${pe}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${pe}/${t}/progress${n}`,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 m(this,E,F).call(this,"GET",`${pe}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}`,n=await fetch(e);if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await m(this,E,F).call(this,"GET",`${pe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await Xe(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new Cs(this,t)}history(t){return new Ss(this,t)}get recipes(){return g(this,cn)??it(this,cn,new di(this)),g(this,cn)}async createHiddenFile(t,e,n){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),n!=null&&r.append("tag",n),await m(this,E,F).call(this,"POST",`${W}/${re}`,{body:r})}async createHiddenFilesBatch(t,e,n){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),n!=null&&r.append("tag",n),await m(this,E,F).call(this,"POST",`${W}/${re}/batch`,{body:r})}async deleteHiddenFile(t){return await m(this,E,F).call(this,"DELETE",`${W}/${re}/${t}`)}async getHiddenFile(t){return await m(this,E,F).call(this,"GET",`${W}/${re}/${t}`)}async downloadHiddenFile(t){return await m(this,E,ve).call(this,`${W}/${re}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await m(this,E,F).call(this,"GET",`${W}/${re}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await m(this,E,Ye).call(this,t,async n=>(await m(this,E,F).call(this,"POST",`${W}/${re}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await m(this,E,F).call(this,"GET",`${W}/${t}/${re}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}/${re}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await m(this,E,F).call(this,"PUT",`${W}/${t}/icon`,{body:n})}async getItemIcon(t){return await m(this,E,ve).call(this,`${W}/${t}/icon`)}async removeItemIcon(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}/icon`)}async updateItem(t,e){return await m(this,E,F).call(this,"PUT",`${W}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",n),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await m(this,E,F).call(this,"POST",`${W}/${t}/version`,{body:o})}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let n=0;for(const r of e){const i=/^v(\d{1,6})$/.exec(String(r.tag??r.versionTag??""));i&&(n=Math.max(n,Number(i[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await m(this,E,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await m(this,E,Ye).call(this,t,async r=>(await m(this,E,F).call(this,"POST",`${W}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await m(this,E,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await m(this,E,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await m(this,E,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};E=new WeakSet,hs=function(t){return`${this.apiUrl}/${t}`},F=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=m(this,E,hs).call(this,e),p=m(this,E,ui).call(this,i),w=await this.resolveAccessToken(),v={...p,...this.useBearer?{}:{accessToken:w}};try{const I=await fetch(c+"?"+new URLSearchParams(v).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${w}`}},...r&&{body:r}});if(!I.ok){const _=await I.text().then(L=>L).catch(()=>"");throw new Nn(I.status,I.statusText,_,oa(I))}return l==="blob"?await I.blob():I.json().then(_=>_).catch(()=>{})}catch(I){const _=a??this.retries;if(_>0&&aa(I)){const L=d??0;return await ia(ca(I,L)),await m(this,E,F).call(this,t,e,{...n,retries:_-1,retryAttempt:L+1})}throw I}},ve=async function(t,e){const{query:n}=e||{},r=m(this,E,hs).call(this,t),i=await this.resolveAccessToken(),o={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},cn=new WeakMap,Ye=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=ls)n.push(t.slice(i,i+ls));return(await Promise.all(n.map(e))).flat()},In=async function(t,e){const{versionTag:n,withDraft:r}=e||{};return await m(this,E,ve).call(this,`${W}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})},Sn=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=t,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),a&&c.append("projectId",a),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await m(this,E,F).call(this,"POST",W,{body:c})},ds=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const p=new FormData;p.append("file",a),i&&p.append("versionTag",i),n&&p.append("extraProps",JSON.stringify(n)),l&&p.append("metadata",JSON.stringify(l)),c=await m(this,E,F).call(this,"POST",`${W}/${t}/version`,{body:p})}if(r||o){const p={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(p);d=await m(this,E,F).call(this,"PUT",`${W}/${t}`,{body:w,contentType:"application/json"})}return{item:d,version:c}},fs=async function(t,e){const{showVersions:n=!1}=e||{};return await m(this,E,F).call(this,"GET",`${W}/${t}`,{query:{showVersions:n}})},ui=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let Cn=Ps;function pi(){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:s=>window.parent.postMessage(s,"*"),listen:s=>{const t=e=>{e.source===window.parent&&s(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const us="channel:",la=1e4;function _n(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ce,jt,Ut,Fe,Le,Pe,Lt,ps,ms,Ne;class Fs{constructor(t,e){K(this,Lt);K(this,ce,!1);K(this,jt,[]);K(this,Ut,[]);K(this,Fe,new Set);K(this,Le,new Set);K(this,Pe,new Set);this.transport=t,this.controls=e}get joined(){return g(this,ce)}get peers(){return g(this,jt)}join(){return g(this,ce)?Promise.resolve():m(this,Lt,ps).call(this,"joined",this.controls.join)}leave(){return!g(this,ce)&&!g(this,Ut).some(t=>t.want==="joined")?Promise.resolve():m(this,Lt,ps).call(this,"left",this.controls.leave)}onChange(t){return g(this,Fe).add(t),()=>void g(this,Fe).delete(t)}onPeerJoined(t){return g(this,Le).add(t),()=>void g(this,Le).delete(t)}onPeerLeft(t){return g(this,Pe).add(t),()=>void g(this,Pe).delete(t)}applyJoined(){it(this,ce,!0),m(this,Lt,ms).call(this,"joined"),m(this,Lt,Ne).call(this)}applyLeft(){it(this,ce,!1),it(this,jt,[]),m(this,Lt,ms).call(this,"left"),m(this,Lt,Ne).call(this)}applyPeers(t){it(this,jt,t),m(this,Lt,Ne).call(this)}applyPeerJoined(t){!g(this,ce)||g(this,jt).some(e=>e.from===t.from)||(it(this,jt,[...g(this,jt),t]),g(this,Le).forEach(e=>_n(()=>e(t))),m(this,Lt,Ne).call(this))}applyPeerLeft(t){const e=g(this,jt).find(n=>n.from===t);e&&(it(this,jt,g(this,jt).filter(n=>n.from!==t)),g(this,Pe).forEach(n=>_n(()=>n(e))),m(this,Lt,Ne).call(this))}failPending(t){const e=g(this,Ut);return it(this,Ut,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}ce=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Pe=new WeakMap,Lt=new WeakSet,ps=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{it(this,Ut,g(this,Ut).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},la)};g(this,Ut).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ms=function(t){const e=g(this,Ut).filter(n=>n.want===t);it(this,Ut,g(this,Ut).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},Ne=function(){g(this,Fe).forEach(t=>_n(t))};var Be;class mi extends Fs{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});K(this,Be,new Map)}on(e,n){const r=g(this,Be).get(e)??new Set;return r.add(n),g(this,Be).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(us))throw new Error(`Message types starting with '${us}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=g(this,Be).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=yi(e);return n.forEach(i=>_n(()=>i(e.payload,r))),{handled:!0}}}Be=new WeakMap;var Te;class gi extends Fs{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});K(this,Te,new Map);this.kind=n}on(e,n){if(g(this,Te).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return g(this,Te).set(e,n),()=>void g(this,Te).delete(e)}accepts(e,n){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===n}get hasHandlers(){return g(this,Te).size>0}async handle(e){const n=g(this,Te).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,yi(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}Te=new WeakMap;function yi(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function ha(s){const t=s;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var Oe,ln,le,Ee,Ie,Ct,gs,An,vi,bi,Ti,ys;class wi{constructor(t){K(this,Ct);K(this,Oe);K(this,ln);K(this,le);K(this,Ee,new Map);K(this,Ie,new Set);it(this,Oe,t),it(this,ln,t.listen(e=>void m(this,Ct,vi).call(this,e)))}collab(){return g(this,le)??it(this,le,new mi(g(this,Oe))),g(this,le)}external(t){const e=t??"";let n=g(this,Ee).get(e);return n||(n=new gi(g(this,Oe),t),g(this,Ee).set(e,n)),n}dispose(){g(this,ln).call(this)}}Oe=new WeakMap,ln=new WeakMap,le=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,Ct=new WeakSet,gs=function(){return[...g(this,le)?[g(this,le)]:[],...g(this,Ee).values()]},An=function(t,e){if(t==="collab")return g(this,le);if(t==="external")return g(this,Ee).get(typeof e=="string"?e:"")},vi=async function(t){const e=ha(t);if(e){if(e.type.startsWith(us)){m(this,Ct,bi).call(this,e);return}await m(this,Ct,Ti).call(this,e)}},bi=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=m(this,Ct,An).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=m(this,Ct,An).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=m(this,Ct,An).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[g(this,le)]:[...g(this,Ee).values()].filter(a=>a.accepts("external",e.kind));for(const a of o)t.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:e.from,kind:e.kind}):a==null||a.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));m(this,Ct,gs).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ti=async function(t){const e=m(this,Ct,gs).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const o=await i.handle(t);o.handled&&(n=!0,t.requestId&&m(this,Ct,ys).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&m(this,Ct,ys).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},ys=function(t,e){g(this,Ie).has(t)||(g(this,Ie).add(t),g(this,Ie).size>500&&g(this,Ie).delete(g(this,Ie).values().next().value),g(this,Oe).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const _e="project",$e="notifications";var De,hn;const Bs=class Bs extends Cn{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});K(this,De);K(this,hn);typeof e=="function"&&it(this,De,e)}async resolveAccessToken(){return g(this,De)?await g(this,De).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Bs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return g(this,hn)??it(this,hn,new wi(pi())),g(this,hn)}async listProjects(){return await this.request("GET",_e)}async getProject(e){return await this.request("GET",`${_e}/${e}`)}async getProjectData(e){return await this.request("GET",`${_e}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${_e}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${_e}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",$e,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${$e}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${$e}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${$e}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${$e}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${$e}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=Xe(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};De=new WeakMap,hn=new WeakMap;let ws=Bs;const me=1/.3048,da={IFCDOOR:"OST_Doors",IFCWINDOW:"OST_Windows",IFCFURNITURE:"OST_Furniture",IFCFURNISHINGELEMENT:"OST_Furniture",IFCSYSTEMFURNITUREELEMENT:"OST_FurnitureSystems",IFCLIGHTFIXTURE:"OST_LightingFixtures",IFCSANITARYTERMINAL:"OST_PlumbingFixtures",IFCFLOWTERMINAL:"OST_PlumbingFixtures",IFCCOLUMN:"OST_Columns",IFCFOOTING:"OST_StructuralFoundation",IFCGEOGRAPHICELEMENT:"OST_Site",IFCELECTRICAPPLIANCE:"OST_ElectricalEquipment",IFCELECTRICDISTRIBUTIONBOARD:"OST_ElectricalEquipment",IFCUNITARYEQUIPMENT:"OST_MechanicalEquipment"},fa="OST_GenericModel",ua=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),be=(s,t)=>Math.round(s/t)*t,pa=s=>({x:[s[0],s[1],s[2]],y:[s[4],s[5],s[6]],z:[s[8],s[9],s[10]],t:[s[12],s[13],s[14]]}),Qe=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Hn=s=>Math.sqrt(Qe(s,s)),On=(s,t)=>[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]];function ma(s,t,e){const n=new Set,r=new Map;for(const l of t){const d=l.split(":")[1];d&&(n.add(d),r.has(d)||r.set(d,l))}const i=new Map,o=new Map,a=[];for(const l of s.elements.values()){if(n.has(l.gid)||ua.has(l.ifcClass.toUpperCase())||l.parent&&n.has(l.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(l.ifcClass)||l.pieces.length===0)continue;const c=/^IFCCOLUMN$/i.test(l.ifcClass)&&/structural|estructural|结构柱|tragend|tragwerk/i.test(`${l.typeName??""} ${l.objectType??""} ${l.name??""}`)?"OST_StructuralColumns":da[l.ifcClass.toUpperCase()]??fa,p=pa(l.pieces[0].matrix),w=Hn(p.x),v=Hn(p.y),I=Hn(p.z),_=p.z.map(q=>q/(I||1)),L=Math.abs(_[2]-1)<1e-6&&Qe(On(p.x,p.y),p.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,C=Qe(On(p.x,p.y),p.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,O=[p.x,p.y,p.z].map(q=>q.map(Z=>Z/(w||1))),u=C&&!L&&O.some(q=>Math.abs(Math.abs(q[2])-1)<1e-6)?O.find(q=>Math.abs(q[2])<1e-6):void 0,x=L?Math.atan2(p.x[1],p.x[0]):u?Math.atan2(u[1],u[0]):0,T=Math.cos(-x),M=Math.sin(-x),z=[p.t[0],p.t[1],p.t[2]],ut=/COLUMN/i.test(c),wt=q=>{const Z=q[0]-z[0],$=q[1]-z[1];return[T*Z-M*$,M*Z+T*$,q[2]-z[2]]},Ot=[],Vt=[c];for(const q of l.pieces){const Z=s.geometries.get(q.geometry);if(!Z)continue;const $=q.matrix,Tt=[];for(let st=0;st<Z.verts.length;st+=3){const rt=Z.verts[st],et=Z.verts[st+1],At=Z.verts[st+2],Ht=[$[0]*rt+$[4]*et+$[8]*At+$[12],$[1]*rt+$[5]*et+$[9]*At+$[13],$[2]*rt+$[6]*et+$[10]*At+$[14]],de=wt(Ht);Tt.push(be(de[0]*me,1e-5),be(de[1]*me,1e-5),be(de[2]*me,1e-5))}const Et=Qe(On([$[0],$[1],$[2]],[$[4],$[5],$[6]]),[$[8],$[9],$[10]])<0,pt=[];for(let st=0;st+2<Z.tris.length;st+=3)Et?pt.push(Z.tris[st],Z.tris[st+2],Z.tris[st+1]):pt.push(Z.tris[st],Z.tris[st+1],Z.tris[st+2]);pt.length&&Ot.push({v:Tt,t:pt});const Dt=wt([$[12],$[13],$[14]]),Ft=[T*$[0]-M*$[1],M*$[0]+T*$[1],$[2]],Pt=[T*$[4]-M*$[5],M*$[4]+T*$[5],$[6]];Vt.push(`${q.geometry}@${[...Dt,...Ft,...Pt].map(st=>be(st,1e-4).toFixed(4)).join(",")}`)}if(Ot.length===0)continue;const kt=!l.host&&Ot.length===1?wa(Ot[0]):null;if(kt){const q=ya(kt),Z=q.key,$=`prism|${c}|${q.axis}|${Z}`;let Tt=i.get($);if(!Tt){const et=Ar(l.typeName??l.objectType??l.name??l.ifcClass),At=(o.get(et)??0)+1;o.set(et,At);const Ht=At===1?et:`${et} (${At})`;Tt={family:Ht,type:Ht,first:!0,key:Or($)},i.set($,Tt)}const Et={ShapeCategory:c,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,PrismLength:String(be(kt.length,1e-5)),...ut?{ColumnFree:"1"}:{}};Tt.first&&(Et.Prism=JSON.stringify({axis:q.axis,loops:q.loops}),Tt.first=!1);const pt=[0,0,0];pt[kt.axis]=(q.flipped?kt.from+kt.length:kt.from)/me;const Dt=(kt.axis+1)%3,Ft=(kt.axis+2)%3;pt[Dt]+=q.centre[0]/me,pt[Ft]+=q.centre[1]/me;const Pt=Math.cos(x),st=Math.sin(x),rt=[z[0]+Pt*pt[0]-st*pt[1],z[1]+st*pt[0]+Pt*pt[1],z[2]+pt[2]];a.push({key:`${e}:${l.gid}:shape`,attrs:Et,at:rt,rotationDeg:(x+q.turn)*180/Math.PI});continue}const he=`${c}|${Ot.map(q=>`${q.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${q.t.join(",")}`).join("|")}`,Yt=Vt.join("|");let It=i.get(Yt)??i.get(he);if(It&&(i.set(Yt,It),i.set(he,It)),!It){const q=Ar(l.typeName??l.objectType??l.name??l.ifcClass),Z=(o.get(q)??0)+1;o.set(q,Z);const $=Z===1?q:`${q} (${Z})`;It={family:$,type:$,first:!0,key:Or(he)},i.set(he,It),i.set(Yt,It)}const Gt={ShapeCategory:c,Family:It.family,Type:It.type,ShapeKey:It.key,...ut?{ColumnFree:"1"}:{}};It.first&&(Gt.Shape=JSON.stringify({pieces:Ot}),It.first=!1);const Mt=l.host?r.get(l.host):void 0,Ce=l.opening?s.elements.get(l.opening):void 0;if(Mt&&Ce){const q=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const $ of Ce.pieces){const Tt=s.geometries.get($.geometry);if(!Tt)continue;const Et=$.matrix;for(let pt=0;pt<Tt.verts.length;pt+=3){const Dt=Tt.verts[pt],Ft=Tt.verts[pt+1],Pt=Tt.verts[pt+2],st=wt([Et[0]*Dt+Et[4]*Ft+Et[8]*Pt+Et[12],Et[1]*Dt+Et[5]*Ft+Et[9]*Pt+Et[13],Et[2]*Dt+Et[6]*Ft+Et[10]*Pt+Et[14]]);for(let rt=0;rt<3;rt++)q[rt]=Math.min(q[rt],st[rt]*me),Z[rt]=Math.max(Z[rt],st[rt]*me)}}Number.isFinite(q[0])&&(Gt.Opening=[...q,...Z].map($=>be($,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Gt,at:[z[0],z[1],z[2]],rotationDeg:x*180/Math.PI,...Mt?{host:Mt}:{}})}return a}function Ar(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Or(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function ga(s,t,e){const n=new Map;for(const i of t){const[,o,a]=i.split(":");o&&/^run/.test(a??"")&&!n.has(o)&&n.set(o,i)}const r=[];for(const i of s.elements.values()){if(i.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!i.host)continue;const o=n.get(i.host);if(o)for(const a of Ta(s,i.gid)){const l=a.pts;if(l.length<4)continue;const d=ba(tn(s,i.host));if(!d)continue;const c=l.map(I=>(I[0]-d.a[0])*d.u[0]+(I[1]-d.a[1])*d.u[1]),p=l.map(I=>-(I[0]-d.a[0])*d.u[1]+(I[1]-d.a[1])*d.u[0]),w=I=>Math.max(...I)-Math.min(...I),v=w(c)*w(p)*w(l.map(I=>I[2]));!(v>0)||Math.abs(a.volume)<.75*v||r.push({key:`${e}:${i.gid}:opening${a.index===0&&a.of===1?"":`#${a.index}`}`,host:o,box:l.flat()})}}return r}function ya(s){const t=s.loops.flat(),e=[t.reduce((w,v)=>w+v[0],0)/t.length,t.reduce((w,v)=>w+v[1],0)/t.length],n=s.loops.map(w=>{const v=w.map(([O,u])=>[O-e[0],u-e[1]]),I=v.map(([O,u])=>Math.hypot(O,u)),_=I.reduce((O,u)=>O+u,0)/I.length;if(v.length<8||_<=0||I.some(O=>Math.abs(O-_)>.02*_))return v;const C=v.reduce((O,u,x)=>{const T=v[(x+1)%v.length];return O+u[0]*T[1]-T[0]*u[1]},0)>=0?1:-1;return v.map((O,u)=>[_*Math.cos(C*2*Math.PI*u/v.length),_*Math.sin(C*2*Math.PI*u/v.length)])}),r=w=>w.map(I=>{const _=I.map(([C,O])=>`${Math.round(C*304.8)},${Math.round(O*304.8)}`);let L=0;for(let C=1;C<_.length;C++)_[C]<_[L]&&(L=C);return[..._.slice(L),..._.slice(0,L)].join(";")}).sort().join("|"),i=(w,v)=>{const I=Math.cos(-v),_=Math.sin(-v);return w.map(L=>L.map(([C,O])=>[I*C-_*O,_*C+I*O]))},o=[];let a=s.axis,l=0,d=n;if(a===1&&(a=0,l=Math.PI/2,d=n.map(w=>w.map(([v,I])=>[-I,v]))),a===2){let w=0,v=0,I=0;const _=n.flat();for(const[T,M]of _)w+=T*T,v+=M*M,I+=T*M;const L=new Set,C=.5*Math.atan2(2*I,w-v);for(let T=0;T<4;T++)L.add(C+T*Math.PI/2);const O=_.map(([T,M])=>Math.hypot(T,M)),u=Math.max(...O),x=_.filter((T,M)=>O[M]>u-.003);if(Math.abs(w-v)<.001*(w+v)||x.length>4)for(const[T,M]of x.slice(0,64))L.add(Math.atan2(M,T));for(const T of L)o.push({loops:i(n,T),turn:T,flipped:!1})}else o.push({loops:d,turn:0,flipped:!1}),o.push({loops:d.map(w=>w.map(([v,I])=>[-v,I]).reverse()),turn:Math.PI,flipped:!0});let c=o[0],p=r(c.loops);for(const w of o.slice(1)){const v=r(w.loops);v<p&&(c=w,p=v)}return{axis:a,loops:c.loops,key:p,centre:e,turn:l+c.turn,flipped:c.flipped}}function wa(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,o=-1/0;for(let a=0;a<e;a++){const l=s.v[a*3+r];i=Math.min(i,l),o=Math.max(o,l)}return o-i});for(const r of[0,1,2].sort((i,o)=>n[o]-n[i])){let i=1/0,o=-1/0;for(let u=0;u<e;u++){const x=s.v[u*3+r];i=Math.min(i,x),o=Math.max(o,x)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const x=s.v[u*3+r];Math.abs(x-i)>.001&&Math.abs(x-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,p=[],w=u=>{const x=[s.v[u*3+l],s.v[u*3+d]],T=`${Math.round(x[0]*3048)},${Math.round(x[1]*3048)}`;return c.has(T)||(c.set(T,p.length),p.push(x)),c.get(T)},v=new Map,I=[];for(let u=0;u+2<s.t.length;u+=3){const x=[s.t[u],s.t[u+1],s.t[u+2]];if(!x.every(M=>Math.abs(s.v[M*3+r]-i)<=.001))continue;const T=x.map(w);if(!(T[0]===T[1]||T[1]===T[2]||T[0]===T[2])){I.push(T);for(let M=0;M<3;M++){const z=T[M],ut=T[(M+1)%3],wt=z<ut?`${z},${ut}`:`${ut},${z}`;v.set(wt,(v.get(wt)??0)+1)}}}if(I.length===0)continue;const _=new Map;for(const u of I)for(let x=0;x<3;x++){const T=u[x],M=u[(x+1)%3];v.get(T<M?`${T},${M}`:`${M},${T}`)===1&&_.set(T,[..._.get(T)??[],M])}if([..._.values()].some(u=>u.length!==1))continue;const L=[],C=new Set(_.keys());for(;C.size;){const u=C.values().next().value,x=[];let T=u,M=0;do x.push(p[T]),C.delete(T),T=_.get(T)[0];while(T!==u&&M++<1e5&&_.has(T));if(T!==u||x.length<3){L.length=0;break}const z=x.filter((ut,wt)=>{const Ot=x[(wt-1+x.length)%x.length],Vt=x[(wt+1)%x.length];return Math.abs((ut[0]-Ot[0])*(Vt[1]-Ot[1])-(ut[1]-Ot[1])*(Vt[0]-Ot[0]))>1e-7});L.push(z.map(([ut,wt])=>[be(ut,1e-5),be(wt,1e-5)]))}if(L.length===0||L.some(u=>u.length<3))continue;let O=0;for(let u=0;u<e;u++)Math.abs(s.v[u*3+r]-o)<=.001&&O++;if(!(O<3))return{axis:r,from:i,length:o-i,loops:L}}return null}function va(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let r=1/0,i=-1/0;const o=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const p=d.matrix,w=v=>{const I=c.verts[v*3],_=c.verts[v*3+1],L=c.verts[v*3+2];return[p[0]*I+p[4]*_+p[8]*L+p[12],p[1]*I+p[5]*_+p[9]*L+p[13],p[2]*I+p[6]*_+p[10]*L+p[14]]};for(let v=0;v+2<c.tris.length;v+=3){const I=[w(c.tris[v]),w(c.tris[v+1]),w(c.tris[v+2])];for(const _ of I)r=Math.min(r,_[2]),i=Math.max(i,_[2]);o.push(I)}}if(!Number.isFinite(r)||i-r<.1)continue;let a=null,l=0;for(const d of o){if(!d.every(p=>Math.abs(p[2]-r)<.001))continue;const c=Math.abs((d[1][0]-d[0][0])*(d[2][1]-d[0][1])-(d[2][0]-d[0][0])*(d[1][1]-d[0][1]))/2;c>l&&(l=c,a=d)}a&&e.push({key:`${t}:${n.gid}:room`,at:[(a[0][0]+a[1][0]+a[2][0])/3,(a[0][1]+a[1][1]+a[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function ba(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const r of s){const i=Math.hypot(r[0]-s[0][0],r[1]-s[0][1]);i>n&&(n=i,e=r)}n=0;for(const r of s){const i=Math.hypot(r[0]-e[0],r[1]-e[1]);i>n&&(n=i,t=r)}if(!(n<.1))return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function Ta(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],r=[],i=new Map;for(const c of e.pieces){const p=s.geometries.get(c.geometry);if(!p)continue;const w=c.matrix,v=[];for(let I=0;I<p.verts.length;I+=3){const _=p.verts[I],L=p.verts[I+1],C=p.verts[I+2],O=[w[0]*_+w[4]*L+w[8]*C+w[12],w[1]*_+w[5]*L+w[9]*C+w[13],w[2]*_+w[6]*L+w[10]*C+w[14]],u=O.map(T=>Math.round(T*1e4)).join(",");let x=i.get(u);x===void 0&&(x=n.length,i.set(u,x),n.push(O)),v.push(x)}for(let I=0;I+2<p.tris.length;I+=3)r.push(v[p.tris[I]],v[p.tris[I+1]],v[p.tris[I+2]])}const o=n.map((c,p)=>p),a=c=>{for(;o[c]!==c;)o[c]=o[o[c]],c=o[c];return c};for(let c=0;c<r.length;c+=3){const p=a(r[c]);o[a(r[c+1])]=p,o[a(r[c+2])]=p}const l=new Map;for(let c=0;c<r.length;c+=3){const p=a(r[c]);let w=l.get(p);w||(w={pts:new Set,volume:0},l.set(p,w));const[v,I,_]=[n[r[c]],n[r[c+1]],n[r[c+2]]];w.volume+=Qe(v,On(I,_))/6,w.pts.add(r[c]),w.pts.add(r[c+1]),w.pts.add(r[c+2])}const d=[...l.values()];return d.map((c,p)=>({pts:[...c.pts].map(w=>n[w]),volume:c.volume,index:p,of:d.length}))}function tn(s,t,e){const n=s.elements.get(t),r=[];if(!n)return r;for(const i of n.pieces){const o=s.geometries.get(i.geometry);if(!o)continue;const a=i.matrix;for(let l=0;l<o.verts.length;l+=3){const d=o.verts[l],c=o.verts[l+1],p=o.verts[l+2];r.push([a[0]*d+a[4]*c+a[8]*p+a[12],a[1]*d+a[5]*c+a[9]*p+a[13],a[2]*d+a[6]*c+a[10]*p+a[14]])}}return r}function Ea(s,t,e){const n=tn(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],o=0;for(const C of n){const O=Math.hypot(C[0]-n[0][0],C[1]-n[0][1]);O>o&&(o=O,i=C)}o=0;for(const C of n){const O=Math.hypot(C[0]-i[0],C[1]-i[1]);O>o&&(o=O,r=C)}if(o<.3)return;const a=(i[0]-r[0])/o,l=(i[1]-r[1])/o,d=C=>(C[0]-r[0])*a+(C[1]-r[1])*l,c=Math.max(...n.map(C=>C[2])),p=C=>Math.max(...n.filter(O=>Math.abs(d(O)-C)<.05).map(O=>O[2]),-1/0),w=p(0),v=p(o);if(Math.abs(w-v)<.05&&c-Math.max(w,v)<.05)return;const I=(r[0]+i[0])/2,_=(r[1]+i[1])/2;let L;for(const C of e){const O=tn(s,C.gid);if(O.length===0)continue;const u=O.map(z=>z[0]),x=O.map(z=>z[1]),T=O.map(z=>z[2]);if(I<Math.min(...u)-.2||I>Math.max(...u)+.2||_<Math.min(...x)-.2||_>Math.max(...x)+.2)continue;const M=Math.min(...T)-c;M>1.5||Math.max(...T)<c-.05||(!L||Math.abs(M)<Math.abs(L.gap))&&(L={id:C.id,gap:M})}return L==null?void 0:L.id}const ge={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Ke(s){const t=s.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const r=t.slice(e+1,n).trim();return r?{family:t.slice(0,e).trim(),type:r}:null}function Cr(s){const t=Ke(s),e=s.item.attrs.PredefinedType;return t?/escalera|stair|landing|descansillo/i.test(t.family)||e==="LANDING"||/plataforma|^pad\b|building pad/i.test(t.family)?"other":/cubierta|roof/i.test(t.family)||e==="ROOF"?"roof":/cimentaci|foundation/i.test(t.family)||e==="BASESLAB"?"foundation":"floor":"floor"}const xr=180/Math.PI;function $r(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const ft=s=>String(s);function Ei(s){return async t=>{var js,Us,qs,Vs,Gs,Hs,Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or;const{picked:e,contents:n,site:r,shapes:i}=await ks(t,t.input),o=si(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Me,r.north*Me,r.elevation*Me,r.angleDeg].map(h=>h.toFixed(6)).join(","):void 0;if(o.length===0)throw new Error(s==="ifc"?`Nothing in "${e.name}" could be read as a building element (walls, floors, levels...).`:`"${e.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:d,trustStyleNames:c,includeInstances:p}=t.settings,w=t.settings.createLevels!==!1;if(p&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const v=$s(o),I=ri(o),_=`recipe:${s}-to-revit`,L=new Map,C=Rs(t,L);t.progress("Writing the changes for Revit");const O=new Rn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:_}),u=Me,x=new Map;{const h=new Map;for(const f of o){const y=f.item.guid;if(!y)continue;const b=`${y}:${f.kind}`,R=h.get(b)??0;h.set(b,R+1),x.set(f.id,`${e.fileId}:${b}${R?`:${R}`:""}`)}}const T=h=>x.get(h)??`${e.fileId}:${h}`,M=new Set;let z=0,ut=0;const wt=(h,f,y)=>{M.add(h);const b=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,R=ii({attrs:b,placement:y??{}}),S=C.get(h);if(S){const k=L.get(h);return!k||k===R?(z++,!1):(O.remove(S),O.add({...b,"flow:print":R},{...y,source:h}),ut++,!1)}return O.add({...b,"flow:print":R},{...y,source:h}),!0},Ot=h=>{const f=typeof h=="string"?I.get(h):void 0,y=f==null?void 0:f.params.thickness;return typeof y=="number"&&y>0?y*u:void 0},Vt=h=>{var j,at;const f=Bt(h,"extrusion"),y=v.get(String((f==null?void 0:f.level)??h.params.level??"")),b=f==null?void 0:f.slopes,R=((at=(j=f==null?void 0:f.profile)==null?void 0:j.outline)==null?void 0:at.curves)??[],S=Array.isArray(b)?b.map(H=>typeof H=="number"):[],k=S.indexOf(!0);if(h.params.of!=="roof"||!y||R.length!==4||S.filter(Boolean).length!==2||k<0||k>1||!S[k+2])return null;const[A,D]=[R[k],R[k+2]],nt=A.from,ht=A.to,Y=Math.hypot(ht[0]-nt[0],ht[1]-nt[1]),St=[(ht[0]-nt[0])/Y,(ht[1]-nt[1])/Y];let U=[-St[1],St[0]];const ot=(D.from[0]-nt[0])*U[0]+(D.from[1]-nt[1])*U[1];ot<0&&(U=[-U[0],-U[1]]);const yt=Math.abs(ot),[P,G]=[b[k],b[k+2]],lt=y.at+(typeof h.params.base=="number"?h.params.base:0),xt=(f==null?void 0:f.eaves)??[],[tt,vt]=[lt+(Number(xt[k])||0),lt+(Number(xt[k+2])||0)],mt=(vt-tt+G*yt)/(P+G);return{A:nt,u:St,n:U,L:Y,W:yt,si:P,sj:G,ridge:mt,top:lt,ti:tt,tj:vt,zAt:(H,B)=>{const V=(H-nt[0])*U[0]+(B-nt[1])*U[1];return Math.min(tt+P*V,vt+G*(yt-V))}}},kt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),he=[...kt.values()].filter(h=>h.item.guid).map(h=>({id:h.id,gid:h.item.guid}));let Yt=0;if(w)for(const[h,f]of v)wt(T(h),{CategoryId:ge.levels,Name:f.name,Elevation:ft(f.at*u)})&&Yt++;let It=0,Gt=0;const Mt=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Bt(h,"run"),y=((Us=(js=f==null?void 0:f.run)==null?void 0:js.line)==null?void 0:Us.curves)??[],b=h.params.lookRef,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(typeof b!="string"||typeof(f==null?void 0:f.height)!="number"||!R){Gt++;continue}const S=(Ot(b)??0)/u,k=y.filter(A=>A.kind==="segment"&&A.from&&A.to);Gt+=y.length-k.length,k.forEach((A,D)=>Mt.push({record:h,i:D,width:S,from:[...A.from],to:[...A.to],joinStart:D===0&&String(h.params.meetsAtStart)==="true",joinEnd:D===k.length-1&&String(h.params.meetsAtEnd)==="true"}))}const Ce=(h,f)=>{const y=[h.to[0]-h.from[0],h.to[1]-h.from[1]],b=[f.to[0]-f.from[0],f.to[1]-f.from[1]],R=y[0]*b[1]-y[1]*b[0];if(Math.abs(R)<1e-9*Math.hypot(...y)*Math.hypot(...b)*1e3)return null;const S=((f.from[0]-h.from[0])*b[1]-(f.from[1]-h.from[1])*b[0])/R;return[h.from[0]+S*y[0],h.from[1]+S*y[1]]},q=(h,f)=>{const y=f.to[0]-f.from[0],b=f.to[1]-f.from[1],R=y*y+b*b||1,S=Math.max(0,Math.min(1,((h[0]-f.from[0])*y+(h[1]-f.from[1])*b)/R));return Math.hypot(h[0]-(f.from[0]+S*y),h[1]-(f.from[1]+S*b))},Z=(h,f)=>{const y=Bt(h.record,"run"),b=Bt(f.record,"run"),R=[y.base,y.base+y.height],S=[b.base,b.base+b.height],k=v.get(String((y==null?void 0:y.level)??h.record.params.level)).at,A=v.get(String((b==null?void 0:b.level)??f.record.params.level)).at;return Math.min(k+R[1],A+S[1])>Math.max(k+R[0],A+S[0])},$=1,Tt=new Map;for(const h of Mt){const f=[["from",h.joinStart],["to",h.joinEnd]],y={from:h.from,to:h.to};for(const[b,R]of f){if(!R)continue;const S=h[b];let k=null,A=1/0;for(const ht of Mt){if(ht===h||!Z(h,ht))continue;const Y=q(S,ht);Y<A&&(A=Y,k=ht)}if(!k||A>$)continue;const D=Ce(h,k);if(!D)continue;const nt=Math.min($,2*Math.max(h.width,k.width)+.02);Math.hypot(D[0]-S[0],D[1]-S[1])>nt||q(D,k)>k.width+.01||(y[b]=D)}Tt.set(h,y)}for(const h of Mt){const{record:f}=h,y=Bt(f,"run"),b=typeof y.base=="number"?y.base:0,R=y.height,S=v.get(String(y.level??f.params.level??"")),k=f.params.lookRef;let{from:A,to:D}=Tt.get(h);const nt=new Set;if(i&&f.item.guid&&Mt.filter(j=>j.record===f).length===1?i.elements.get(f.item.guid):void 0){const j=tn(i,f.item.guid),at=Math.hypot(D[0]-A[0],D[1]-A[1]);if(j.length>=4&&at>.05){const H=[(D[0]-A[0])/at,(D[1]-A[1])/at],B=j.map(bt=>(bt[0]-A[0])*H[0]+(bt[1]-A[1])*H[1]),V=Math.min(...B),ct=Math.max(...B),dt=j.map(bt=>-(bt[0]-A[0])*H[1]+(bt[1]-A[1])*H[0]),$t=Math.max(...dt)-Math.min(...dt),Q=bt=>{const Jt=dt.filter((fe,ue)=>Math.abs(B[ue]-bt)<.002);return Jt.length>=2&&Math.max(...Jt)-Math.min(...Jt)>.9*$t},J=A;Q(V)&&(A=[J[0]+H[0]*V,J[1]+H[1]*V],nt.add("start")),Q(ct)&&(D=[J[0]+H[0]*ct,J[1]+H[1]*ct],nt.add("end"))}}const Y=(S.at+b)*u,St=`${ft(A[0]*u)},${ft(A[1]*u)},${ft(Y)};${ft(D[0]*u)},${ft(D[1]*u)},${ft(Y)}`,U={CategoryId:ge.walls,Type:((qs=Ke(f))==null?void 0:qs.type)??k,LocationLine:St,Level:S.name,BaseOffset:ft(b*u),Height:ft(R*u)},ot=[A!==h.from||h.joinStart?"start":"",D!==h.to||h.joinEnd?"end":""].filter(j=>!!j&&!nt.has(j));ot.length&&(U.JoinEnds=ot.join(","));const yt=ot.filter(j=>f.params[j==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");yt.length&&(U.Mitre=yt.join(","));const P=v.get(String(f.params.topLevel??""));P&&(U.TopLevel=P.name,U.TopOffset=ft((S.at+b+R-P.at)*u));const G=y.profile;if(Array.isArray(G)&&G.length>=3&&h.i===0&&!Mt.some(j=>j!==h&&j.record===f)){const j=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),at=[(h.to[0]-h.from[0])/j,(h.to[1]-h.from[1])/j],H=[],B=-((A[0]-h.from[0])*at[0]+(A[1]-h.from[1])*at[1]),V=(D[0]-h.to[0])*at[0]+(D[1]-h.to[1])*at[1];G.forEach(([ct,dt],$t)=>{const Q=Math.abs(ct)<1e-6,J=Math.abs(ct-j)<1e-6;let bt=ct,Jt=dt;if(Q||J){bt=Q?-B:j+V;const ue=[G[($t-1+G.length)%G.length],G[($t+1)%G.length]].find(([Ve])=>Math.abs(Ve-ct)>1e-6);ue&&(Jt=dt+(ue[1]-dt)/(ue[0]-ct)*(bt-ct))}const fe=[h.from[0]+bt*at[0],h.from[1]+bt*at[1]];H.push(fe[0]*u,fe[1]*u,(S.at+b+Jt)*u)}),U.Profile=JSON.stringify([H]),delete U.TopLevel,delete U.TopOffset}const lt=f.params.topAttachedTo,xt=f.params.topAttachedAt==="top"||y.topAttachedAt==="top",tt=typeof lt=="string"&&xt&&!U.Profile&&kt.has(lt)?Vt(kt.get(lt)):null;if(tt){const j=Math.hypot(D[0]-A[0],D[1]-A[1]),at=Q=>[A[0]+(D[0]-A[0])*Q/j,A[1]+(D[1]-A[1])*Q/j],H=(A[0]-tt.A[0])*tt.n[0]+(A[1]-tt.A[1])*tt.n[1],B=(D[0]-tt.A[0])*tt.n[0]+(D[1]-tt.A[1])*tt.n[1],V=[0,j];(H-tt.ridge)*(B-tt.ridge)<0&&V.splice(1,0,(tt.ridge-H)/(B-H)*j);const ct=S.at+b,dt=[],$t=(Q,J)=>{const bt=at(Q);dt.push(bt[0]*u,bt[1]*u,J*u)};$t(0,ct),$t(j,ct);for(const Q of[...V].reverse()){const J=at(Q);$t(Q,tt.zAt(J[0],J[1]))}U.Profile=JSON.stringify([dt]),delete U.TopLevel,delete U.TopOffset}const vt=typeof lt=="string"?lt:i&&f.item.guid?Ea(i,f.item.guid,he):void 0;vt&&!U.Profile&&(U.AttachTop=T(vt));const mt=Ot(k);mt&&(U["Type.Width"]=ft(mt));const gt=f.item.guid?i==null?void 0:i.elements.get(f.item.guid):void 0;gt!=null&>.layers&>.layers.length>1&&(U["Type.Layers"]=JSON.stringify([...gt.layers].reverse().map(j=>[+ft(j.thickness*u),j.material??"",j.function??""])),gt.layersFlipped&&(U.FlipLayers="1")),wt(`${T(f.id)}#${h.i}`,U)&&It++}const Et=(h,f,y)=>{if(!(f>0)||f>=h)return[];const b=h-Math.floor(h/f+1e-9)*f,R=y==="beginning"?0:y==="end"?b:y==="centreLine"?h/2%f:b/2,S=[];for(let k=R;k<=h+1e-4;k+=f)k>1e-4&&k<h-1e-4&&S.push(k);return S};let pt=0,Dt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;Dt++;const f=Bt(h,"run"),y=(Hs=(Gs=(Vs=f==null?void 0:f.run)==null?void 0:Vs.line)==null?void 0:Gs.curves)==null?void 0:Hs[0],b=v.get(String((f==null?void 0:f.level)??h.params.level??"")),R=h.params.lookRef,S=typeof R=="string"?(Js=I.get(R))==null?void 0:Js.params:void 0;if(!(y!=null&&y.from)||!y.to||typeof(f==null?void 0:f.height)!="number"||!b||!S)continue;const k=mt=>typeof mt=="number"?mt:Number(mt)||0,A=k(S.uprightWidth)/2,D=k(S.horizontalWidth)/2,nt=Math.hypot(y.to[0]-y.from[0],y.to[1]-y.from[1]),ht=[(y.to[0]-y.from[0])/nt,(y.to[1]-y.from[1])/nt],Y=[y.from[0]-ht[0]*A,y.from[1]-ht[1]*A],St=[y.to[0]+ht[0]*A,y.to[1]+ht[1]*A],U=(typeof f.base=="number"?f.base:0)-D,ot=f.height+2*D,yt=(b.at+U)*u,P=((Ws=f.lines)==null?void 0:Ws.along)??Et(nt,k(S.alongSpacing),S.alongJustify),G=((zs=f.lines)==null?void 0:zs.up)??Et(f.height,k(S.upSpacing),S.upJustify),lt=(f.omitted??[]).flatMap(mt=>{const gt=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(mt);if(!gt)return[];const j=gt[1]==="horizontal",at=Number(gt[2])/1e3+(j?D:A),H=Number(gt[3])/1e3+(j?A:D);return[{horizontal:j,at:at*u,from:H*u}]}),xt=(f.omitted??[]).flatMap(mt=>{const gt=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(mt);return gt?[{along:(Number(gt[1])/1e3+A)*u,up:(Number(gt[2])/1e3+D)*u}]:[]}),tt={CategoryId:ge.walls,Type:((Ys=Ke(h))==null?void 0:Ys.type)??String(R),LocationLine:`${ft(Y[0]*u)},${ft(Y[1]*u)},${ft(yt)};${ft(St[0]*u)},${ft(St[1]*u)},${ft(yt)}`,Level:b.name,BaseOffset:ft(U*u),Height:ft(ot*u),Curtain:JSON.stringify({along:P.map(mt=>(mt+A)*u),up:G.map(mt=>(mt+D)*u),omit:lt,empty:xt,mullion:{width:k(S.uprightWidth)*u,depth:k(S.depth)*u},panel:{thickness:k(S.panelDepth)*u,offset:-k(S.panelOffset)*u}})},vt=f.profile;if(Array.isArray(vt)&&vt.length>=3){const gt=vt.reduce((B,V,ct)=>{const dt=vt[(ct+1)%vt.length];return B+V[0]*dt[1]-dt[0]*V[1]},0)>0?1:-1,j=vt.length,at=vt.map((B,V)=>{const ct=vt[(V-1+j)%j],dt=vt[(V+1)%j],$t=(fe,ue)=>{const Ve=ue[0]-fe[0],Fn=ue[1]-fe[1],ar=Math.hypot(Ve,Fn)||1,cr=gt*Fn/ar,lr=-gt*Ve/ar,hr=Math.abs(cr)>Math.abs(lr)?A:D;return{p:[fe[0]+cr*hr,fe[1]+lr*hr],d:[Ve,Fn]}},Q=$t(ct,B),J=$t(B,dt),bt=Q.d[0]*J.d[1]-Q.d[1]*J.d[0];if(Math.abs(bt)<1e-12)return[J.p[0],J.p[1]];const Jt=((J.p[0]-Q.p[0])*J.d[1]-(J.p[1]-Q.p[1])*J.d[0])/bt;return[Q.p[0]+Jt*Q.d[0],Q.p[1]+Jt*Q.d[1]]}),H=[];for(const[B,V]of at)H.push((y.from[0]+ht[0]*B)*u,(y.from[1]+ht[1]*B)*u,(b.at+U+D+V)*u);tt.Profile=JSON.stringify([H])}wt(T(h.id),tt)&&pt++}let Ft=0,Pt=0;for(const h of o){if(h.kind!=="stair"||h.params.of!=="stair")continue;Pt++;const f=Bt(h,"stair"),y=h.params.lookRef,b=typeof y=="string"?(Ks=I.get(y))==null?void 0:Ks.params:void 0,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(!(f!=null&&f.start)||!f.end||!(Number(f.rise)>0)||!R||!b)continue;const S=P=>typeof P=="number"?P:Number(P)||0,k=Number(f.rise),A=Math.max(1,Math.ceil(k/S(b.maxRiser)-1e-6)),D=S(b.tread),nt=P=>[P[0]*u,P[1]*u],ht={family:String(y).split(":")[0],base:(R.at+S(h.params.base))*u,height:k*u,risers:A,tread:D*u,width:S(b.width)*u,sizes:{maxRiser:Math.ceil(k/A*1e3-1e-6)/1e3*u,minTread:D*u,waist:S(b.waist)*u,treadThickness:S(b.treadThickness)*u,riserThickness:S(b.riserThickness)*u,notchExtension:S(b.notchExtension)*u,notchThickness:S(b.notchThickness)*u}},Y=f.sketch;if(Y!=null&&Y.boundary&&Y.boundary.length>=4&&Y.risers&&Y.risers.length>=2){const P=Y.boundary,G=Y.risers[Y.risers.length-1],lt=B=>[(B[0][0]+B[1][0])/2,(B[0][1]+B[1][1])/2],xt=lt(G);let tt=1,vt=1/0;for(let B=1;B<P.length;B++){const V=lt([P[B],P[(B+1)%P.length]]),ct=Math.abs(Math.hypot(V[0]-xt[0],V[1]-xt[1])-D);ct<vt&&(vt=ct,tt=B)}const mt=(B,V)=>{const ct=[];for(let dt=B;dt!==V;dt=(dt+1)%P.length)ct.push([nt(P[dt]),nt(P[(dt+1)%P.length])]);return ct},gt=[...mt(1,tt),...mt((tt+1)%P.length,0)],j=Y.risers.map(([B,V])=>[nt(B),nt(V)]);nt(P[tt]),nt(P[(tt+1)%P.length]);const at=j.map(([B,V])=>[(B[0]+V[0])/2,(B[1]+V[1])/2]);ht.sketch={boundary:gt,risers:j,path:at};let H=1/0;for(let B=0;B+1<Y.risers.length;B++){const[V,ct]=Y.risers[B],[dt,$t]=Y.risers[B+1],Q=[ct[0]-V[0],ct[1]-V[1]],J=[$t[0]-dt[0],$t[1]-dt[1]],bt=Math.hypot(Q[0],Q[1]),Jt=Math.hypot(J[0],J[1]);Math.abs((Q[0]*J[1]-Q[1]*J[0])/(bt*Jt))>.001||(H=Math.min(H,Math.abs(((dt[0]-V[0])*Q[1]-(dt[1]-V[1])*Q[0])/bt)))}Number.isFinite(H)&&(ht.tread=H*u,ht.sizes.minTread=H*u)}else ht.path=[nt([f.start[0],f.start[1]]),nt([f.end[0],f.end[1]])];const St=String(h.item.attrs.Name??""),U=St.replace(/ Run \d+$/,""),ot=[];for(const P of o){if(P.kind!=="extrusion"||U===St||!new RegExp(`^${U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(P.item.attrs.Name??"")))continue;const G=Bt(P,"extrusion"),lt=G==null?void 0:G.on,xt=(((Qs=(Xs=G==null?void 0:G.profile)==null?void 0:Xs.outline)==null?void 0:Qs.curves)??[]).flatMap(J=>J.from?[J.from]:[]),tt=Ot(P.params.lookRef),vt=v.get(String((G==null?void 0:G.level)??P.params.level??""));if(!(lt!=null&<.origin)||!lt.u||!lt.v||Math.abs(lt.v[2]??0)<.99||!xt.length||!tt||!vt)continue;const[mt,gt]=[Math.min(...xt.map(J=>J[0])),Math.max(...xt.map(J=>J[0]))],[j,at]=[Math.min(...xt.map(J=>J[1])),Math.max(...xt.map(J=>J[1]))],H=lt.origin,B=lt.u;let V=[B[1],-B[0]];const ct=[(f.start[0]+f.end[0])/2,(f.start[1]+f.end[1])/2];(ct[0]-H[0])*V[0]+(ct[1]-H[1])*V[1]<0&&(V=[-V[0],-V[1]]);const $t=tt/u,Q=(J,bt)=>[(H[0]+B[0]*J+V[0]*bt)*u,(H[1]+B[1]*J+V[1]*bt)*u];ot.push({outline:[Q(mt,0),Q(gt,0),Q(gt,$t),Q(mt,$t)],top:(vt.at+S(P.params.base)+H[2]+at)*u,thickness:(at-j)*u})}ot.length&&(ht.landings=ot);const yt={CategoryId:ge.stairs,Type:((Zs=Ke(h))==null?void 0:Zs.type)??String(y),Level:R.name,Stairs:JSON.stringify(ht)};wt(T(h.id),yt)&&Ft++}const st={floor:0,foundation:0,roof:0,ceiling:0},rt={floor:0,foundation:0,roof:0,ceiling:0};for(const h of o){const f=h.params.of;if(h.kind!=="extrusion"||f!=="slab"&&f!=="roof"&&f!=="covering")continue;const y=f==="covering"?"ceiling":f==="roof"?"roof":Cr(h);if(y==="other")continue;st[y]++;const b=Bt(h,"extrusion"),R=typeof h.params.base=="number"?h.params.base:0,S=v.get(String((b==null?void 0:b.level)??h.params.level??"")),k=h.params.lookRef,A=U=>{if(!(U!=null&&U.length))return null;const ot=[];for(const yt of U){if(yt.kind!=="segment"||!yt.from)return null;ot.push(yt.from[0]*u,yt.from[1]*u,R*u)}return ot.length>=9?ot:null},D=A((er=(tr=b==null?void 0:b.profile)==null?void 0:tr.outline)==null?void 0:er.curves);if(typeof k!="string"||!S||!D)continue;const nt=[D],ht=y==="roof"?Vt(h):null;for(const U of((nr=b==null?void 0:b.profile)==null?void 0:nr.holes)??[]){const ot=A(U==null?void 0:U.curves);if(ot&&ht)for(let yt=0;yt+2<ot.length;yt+=3)ot[yt+2]=ht.zAt(ot[yt]/u,ot[yt+1]/u)*u;ot&&nt.push(ot)}const Y={CategoryId:y==="roof"?ge.roofs:y==="ceiling"?ge.ceilings:y==="foundation"?ge.structuralFoundations:ge.floors,Type:((sr=Ke(h))==null?void 0:sr.type)??k,Profile:JSON.stringify(nt),Level:S.name},St=Ot(k);if(St&&(Y["Type.Width"]=ft(St)),y==="roof"||y==="ceiling"){Y.BaseOffset=ft(R*u);const U=Number(h.params.drop??((rr=b==null?void 0:b.said)==null?void 0:rr.drop));if(y==="ceiling"&&Number.isFinite(U)&&St){const P=[...v.values()].filter(G=>G.at>S.at+1e-6).sort((G,lt)=>G.at-lt.at)[0];P&&(Y.BaseOffset=ft((P.at-U-St/u-S.at)*u))}const ot=b==null?void 0:b.slopes;if(y==="roof"&&Array.isArray(ot)&&ot.some(P=>typeof P=="number")){Y.Slopes=JSON.stringify(ot.map(G=>typeof G=="number"?G:null));const P=Math.max(...ot.filter(G=>typeof G=="number").map(G=>Math.abs(G)));St&&P>0&&(Y.BaseOffset=ft(R*u-St*Math.sqrt(1+P*P)))}const yt=y==="roof"?Vt(h):null;if(yt){const{A:P,n:G,u:lt,W:xt,ridge:tt,si:vt,ti:mt,tj:gt,L:j}=yt,at=(H,B)=>[(P[0]+G[0]*H)*u,(P[1]+G[1]*H)*u,B*u];Y.Extrusion=JSON.stringify({profile:[at(0,mt),at(tt,mt+vt*tt),at(xt,gt)],along:[lt[0],lt[1]],length:j*u}),delete Y.Slopes}}else St&&(Y.HeightOffset=ft(R*u+St));wt(T(h.id),Y)&&rt[y]++}let et=0,At=0;for(const h of o){if(h.kind!=="member"||h.params.of!=="column")continue;At++;const f=Bt(h,"member"),y=f==null?void 0:f.start;if(!y||y.length!==3)continue;const b=c?$r(h.params.lookRef):null;if(c&&!b||!b&&!d)continue;const R=b??{family:d.family,type:d.type},S=v.get(String((f==null?void 0:f.level)??""));wt(T(h.id),{...d&&!b?{CategoryId:d.categoryId}:{},Family:R.family,Type:R.type,...S?{Level:S.name}:{}},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:(Number((f==null?void 0:f.roll)??0)||0)*xr})&&et++}let Ht=0,de=0,Ue=0;for(const h of o){if(h.kind!=="familyInstance")continue;if(h.params.host){Ue++;continue}if(de++,!p)continue;const f=Bt(h,"instance"),y=(ir=f==null?void 0:f.placement)==null?void 0:ir.at;if(!y||y.length!==3)continue;const b=$r(h.params.type);if(!b)continue;const R=(or=f==null?void 0:f.placement)==null?void 0:or.right,S=R?Math.atan2(R[1],R[0])*xr:0;wt(T(h.id),{Family:b.family,Type:b.type},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:S})&&Ht++}const xe=(()=>{if(!i)return 0;const h=[];for(const y of Mt){const b=y.record.item.guid;if(!b||!i.elements.has(b))continue;const R=Bt(y.record,"run"),S=v.get(String((R==null?void 0:R.level)??y.record.params.level??""));if(!R||!S)continue;const k=tn(i,b);if(!k.length)continue;let A=1/0;for(const D of k)A=Math.min(A,D[2]);h.push(A-(S.at+(typeof R.base=="number"?R.base:0)))}h.sort((y,b)=>y-b);const f=h.length?h[Math.floor(h.length/2)]:0;return Math.abs(f)>.5?f:0})(),Ds=i?ma(i,M,e.fileId):[];let dn=0;for(const h of Ds)wt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-xe)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&dn++;if(i)for(const h of ga(i,M,e.fileId))wt(h.key,{WallOpening:h.box.map((f,y)=>ft((y%3===2?f-xe:f)*u)).join(",")},{host:h.host});if(i)for(const h of va(i,e.fileId))wt(h.key,{Room:"1",Name:h.name,Number:h.number,Height:ft(h.height*u)},{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-xe)*u]});let Mn=0;const Ci=new Set(["slab","roof","covering"]);for(const h of o){const f=h.params.of;(h.kind==="footing"||h.kind==="ramp"||h.kind==="stair"&&f!=="stair"||h.kind==="extrusion"&&!Ci.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Cr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&Mn++}let qe=0;for(const[h,f]of C)!h.startsWith(`${e.fileId}:`)||M.has(h)||(O.remove(f),qe++);if(O.length===0)throw new Ms(`Up to date: "${e.name}" holds ${z} element(s) this recipe already made, ${Ue+Mn} waiting on the applier, and nothing is left to remove.`);const xi=[Yt?`${Yt} level(s)`:"",It?`${It} wall(s)`:"",pt?`${pt} curtain wall(s)`:"",rt.floor?`${rt.floor} floor(s)`:"",rt.foundation?`${rt.foundation} foundation slab(s)`:"",rt.roof?`${rt.roof} roof(s)`:"",rt.ceiling?`${rt.ceiling} ceiling(s)`:"",Ft?`${Ft} stair(s)`:"",et?`${et} column(s)`:"",Ht?`${Ht} instance(s)`:"",dn?`${dn} family instance(s)`:"",ut?`${ut} changed`:"",qe?`${qe} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${xi.join(", ")}`,verb:O.summary,targets:O.length,payload:new Blob([await O.build(t.opId)]),ruleTallies:[{read:v.size,written:Yt},{read:Mt.length+Gt,written:It},{read:Dt,written:pt},{read:st.floor+st.foundation,written:rt.floor+rt.foundation},{read:st.roof,written:rt.roof},{read:st.ceiling,written:rt.ceiling},{read:Pt,written:Ft},{read:At,written:et},{read:de,written:Ht},{read:Ds.length,written:dn},{read:qe,written:qe},{read:Ue+Mn,written:0}]}}}const Ia={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 bring free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},Sa=[{reads:"Levels (datums)",writes:"The same level in Revit, ensured by name"},{reads:"Wall runs, one per straight segment",writes:"A native wall: line, type (made from its width when missing), level, height, joins; its edited profile or its top on a roof"},{reads:"Curtain wall runs",writes:"Revit's curtain wall: its grid lines, mullions and panels"},{reads:"Slabs: floors and foundation slabs",writes:"A native floor or foundation slab from the profile, holes included"},{reads:"Roofs",writes:"A footprint roof with its sloping edges, or a roof by extrusion for a gable"},{reads:"Ceilings (coverings)",writes:"A native ceiling from the profile, hung at its drop"},{reads:"Stairs",writes:"A native stair: a straight or sketched run, with its landings"},{reads:"Column records (members)",writes:"A Revit column at each, on its level"},{reads:"Free-standing family instances",writes:"When turned on: a new instance of the same-named type, placed and turned"},{reads:"Everything else with a body: doors, windows, furniture, fixtures, proxies, columns, railings",writes:"A family made from the file's own shape, one per shape, placed where the file has it (doors and windows in their wall)"},{reads:"Things this recipe made whose record is gone",writes:"That element removed"},{reads:"Hosted doors/windows, footings, ramps, other bodies",writes:"Nothing yet - read and counted"}],Ii=`
|
|
3
3
|
## How to use it
|
|
4
4
|
|
|
5
5
|
In Revit, with the That Open plugin: **That Open > Select recipe**, pick this
|
|
@@ -47,13 +47,13 @@ are read and counted, and their rule row says so.
|
|
|
47
47
|
Records are metres and radians, Z up; Revit gets feet and degrees. Types are
|
|
48
48
|
matched exactly by name; Revit refuses the whole apply when a loadable type is
|
|
49
49
|
missing (system types are created from their width instead).
|
|
50
|
-
`,Ls={name:"frag-to-revit",title:"Platform model to Revit",description:"Builds in Revit the platform records of a .frag: levels, walls, curtain walls, floors, roofs, ceilings, stairs, columns, instances.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:
|
|
50
|
+
`,Ls={name:"frag-to-revit",title:"Platform model to Revit",description:"Builds in Revit the platform records of a .frag: levels, walls, curtain walls, floors, roofs, ceilings, stairs, columns, instances.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:Ia,rules:Sa,doc:Ii,run:Ei("frag")},Si={...Ls,name:"ifc-to-revit",title:"IFC to Revit",description:"Builds an IFC of the project in Revit as native elements: levels, walls, floors, roofs, stairs, curtain walls, columns, instances.",inputs:["ifc-model"],source:{kind:"project-file",extensions:["ifc"]},doc:`
|
|
51
51
|
## Point it at the IFC
|
|
52
52
|
|
|
53
53
|
It reads the IFC file itself, the version uploaded last. Its first step
|
|
54
54
|
converts it into the platform's records - what each element is, not only its
|
|
55
55
|
shape - and Revit gets those. Nothing has to be prepared before.
|
|
56
|
-
`+Ii,run:Ei("ifc")},
|
|
56
|
+
`+Ii,run:Ei("ifc")},_a={millimeters:.001,millimetres:.001,mm:.001,centimeters:.01,centimetres:.01,cm:.01,meters:1,metres:1,m:1,inches:.0254,in:.0254,feet:.3048,ft:.3048},_i="rhino-to-revit",Aa=`recipe:${_i}`;function Oa(s){const t=(s.attrs.Position??"").split(",").map(e=>Number(e.trim()));return t.length!==3||t.some(e=>!Number.isFinite(e))?null:[t[0],t[1],t[2]]}const Ai={name:_i,title:"Rhino to Revit",description:"Places in Revit an instance of a chosen type at each placed object of a Rhino layer.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:{type:"object",properties:{layer:{type:"string",title:"Rhino layer","x-existing":{of:"layer",from:"source"}},instanceType:{type:"object",title:"Revit type","x-existing":{of:"family-type",from:"target"}}},required:["layer","instanceType"]},rules:[{reads:"Objects on the chosen layer with no instance yet",writes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",writes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",writes:"That instance removed"},{reads:"Everything on other layers",writes:"Nothing"}],doc:`
|
|
57
57
|
## What it does
|
|
58
58
|
|
|
59
59
|
It reads a model published from Rhino and places in Revit instances of one
|
|
@@ -80,5 +80,5 @@ it. What it made is remembered with the model's That Open data.
|
|
|
80
80
|
Where an object becomes an instance, Revit decides the level: the nearest one
|
|
81
81
|
at or below the point. For a level-based family the level wins over the
|
|
82
82
|
point's height.
|
|
83
|
-
`,async run(s){var
|
|
83
|
+
`,async run(s){var x;const{picked:t,contents:e}=await ks(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=(x=e.metadata)==null?void 0:x.data,o=i==null?void 0:i.units,a=typeof o=="string"?_a[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${t.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(`"${t.name}" declares its data as "${l}"; this recipe only converts Z up.`);const d=a*Me,c=Rs(s),p=new Rn({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:Aa});let w=0,v=0,I=0;const _=new Set,L=[];for(const T of e.items){if(!T.guid||Object.keys(T.attrs).length===0)continue;if((T.attrs.Layer??"")!==n){I++;continue}const M=Oa(T);if(!M)continue;_.add(T.guid);const z=[M[0]*d,M[1]*d,M[2]*d],ut=c.get(T.guid);ut?L.push({instance:ut,object:T.guid,position:z}):(p.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:z,source:T.guid}),w++)}for(const T of L)p.set(T.instance,{},{position:T.position,source:T.object}),v++;let C=0;for(const[T,M]of c)_.has(T)||(p.remove(M),C++);const O=w+v+C;if(O===0)throw new Ms(`Nothing to write: layer "${n}" of "${t.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[w?`${w} new`:"",v?`${v} moved`:"",C?`${C} gone`:""].filter(Boolean).join(", ")}`,verb:p.summary,targets:O,payload:new Blob([await p.build(s.opId)]),ruleTallies:[{read:w,written:w},{read:v,written:v},{read:C,written:C},{read:I,written:0}]}}},Oi=[Ai,Si,Ls];function Ca(s){for(const t of Oi)s.recipes.register(t)}const xa={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},$a={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Ra={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},ka={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Na={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Ma={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Fa={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},La={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Pa={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Ba={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=$a;exports.ChannelClient=wi;exports.ChannelRoom=Fs;exports.ClashesManager=Ra;exports.CollabRoom=mi;exports.DOCUMENT_FILE=Tn;exports.DOCUMENT_SCHEMA=Ze;exports.DOCUMENT_TYPES=Os;exports.DocumentDrafts=ti;exports.EngineServicesClient=Cn;exports.ExternalRoom=gi;exports.FileList=ka;exports.FlowDoc=es;exports.GISManager=Na;exports.GitHistoryManager=Ma;exports.HelloWorld=Fa;exports.METADATA_LIMITS=xa;exports.OP_SCHEMA=xs;exports.OperationBuilder=Rn;exports.PROJECT_RECIPE_SCHEMA=Ns;exports.PlatformClient=ws;exports.ProjectDocuments=Cs;exports.ProjectHistory=Ss;exports.ProjectManager=La;exports.ProjectRecipes=hi;exports.RECIPE_NAME=ci;exports.RecipeKit=ai;exports.Recipes=di;exports.RequestError=Nn;exports.SELF_VIEWING_FORMATS=Kr;exports.STORAGE_BATCH_MAX=ls;exports.StaleHistoryError=Qn;exports.TopicsManager=Pa;exports.UIManager=Ba;exports.UpToDate=Ms;exports.builtinRecipes=Oi;exports.compileRecipe=cs;exports.describeChanges=Zo;exports.documentTypeOf=ss;exports.fragToRevit=Ls;exports.ifcToRevit=Si;exports.latestVersions=fi;exports.mintGuid=As;exports.orderByGraph=_s;exports.readFrag=kn;exports.registerBuiltinRecipes=Ca;exports.rhinoToRevit=Ai;exports.windowTransport=pi;
|
|
84
84
|
//# sourceMappingURL=index.cjs.js.map
|