@thatopen/services 0.34.3 → 0.34.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Ya=Object.create;var gs=Object.defineProperty;var Ka=Object.getOwnPropertyDescriptor;var Xa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,Qa=Object.prototype.hasOwnProperty;var So=s=>{throw TypeError(s)};var tc=(s,t,e)=>t in s?gs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var ec=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xa(t))!Qa.call(s,i)&&i!==e&&gs(s,i,{get:()=>t[i],enumerable:!(n=Ka(t,i))||n.enumerable});return s};var Vn=(s,t,e)=>(e=s!=null?Ya(Za(s)):{},ec(t||!s||!s.__esModule?gs(e,"default",{value:s,enumerable:!0}):e,s));var he=(s,t,e)=>tc(s,typeof t!="symbol"?t+"":t,e),ys=(s,t,e)=>t.has(s)||So("Cannot "+e);var N=(s,t,e)=>(ys(s,t,"read from private field"),e?e.call(s):t.get(s)),qt=(s,t,e)=>t.has(s)?So("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),Xt=(s,t,e,n)=>(ys(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),I=(s,t,e)=>(ys(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=Object.create(null);_e.open="0";_e.close="1";_e.ping="2";_e.pong="3";_e.message="4";_e.upgrade="5";_e.noop="6";const Kn=Object.create(null);Object.keys(_e).forEach(s=>{Kn[_e[s]]=s});const xs={type:"error",data:"parser error"},Wo=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Yo=typeof ArrayBuffer=="function",Ko=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,ni=({type:s,data:t},e,n)=>Wo&&t instanceof Blob?e?n(t):xo(t,n):Yo&&(t instanceof ArrayBuffer||Ko(t))?e?n(t):xo(new Blob([t]),n):n(_e[s]+(t||"")),xo=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function _o(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let ws;function nc(s,t){if(Wo&&s.data instanceof Blob)return s.data.arrayBuffer().then(_o).then(t);if(Yo&&(s.data instanceof ArrayBuffer||Ko(s.data)))return t(_o(s.data));ni(s,!1,e=>{ws||(ws=new TextEncoder),t(ws.encode(e))})}const Ao="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Tn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Ao.length;s++)Tn[Ao.charCodeAt(s)]=s;const sc=s=>{let t=s.length*.75,e=s.length,n,i=0,r,a,l,p;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)r=Tn[s.charCodeAt(n)],a=Tn[s.charCodeAt(n+1)],l=Tn[s.charCodeAt(n+2)],p=Tn[s.charCodeAt(n+3)],c[i++]=r<<2|a>>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|p&63;return d},ic=typeof ArrayBuffer=="function",si=(s,t)=>{if(typeof s!="string")return{type:"message",data:Xo(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:rc(s.substring(1),t)}:Kn[e]?s.length>1?{type:Kn[e],data:s.substring(1)}:{type:Kn[e]}:xs},rc=(s,t)=>{if(ic){const e=sc(s);return Xo(e,t)}else return{base64:!0,data:s}},Xo=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Zo="",oc=(s,t)=>{const e=s.length,n=new Array(e);let i=0;s.forEach((r,a)=>{ni(r,!1,l=>{n[a]=l,++i===e&&t(n.join(Zo))})})},ac=(s,t)=>{const e=s.split(Zo),n=[];for(let i=0;i<e.length;i++){const r=si(e[i],t);if(n.push(r),r.type==="error")break}return n};function cc(){return new TransformStream({transform(s,t){nc(s,e=>{const n=e.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,n)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(e)})}})}let bs;function zn(s){return s.reduce((t,e)=>t+e.length,0)}function Wn(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)e[i]=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 lc(s,t){bs||(bs=new TextDecoder);const e=[];let n=0,i=-1,r=!1;return new TransformStream({transform(a,l){for(e.push(a);;){if(n===0){if(zn(e)<1)break;const p=Wn(e,1);r=(p[0]&128)===128,i=p[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(zn(e)<2)break;const p=Wn(e,2);i=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),n=3}else if(n===2){if(zn(e)<8)break;const p=Wn(e,8),d=new DataView(p.buffer,p.byteOffset,p.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){l.enqueue(xs);break}i=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(zn(e)<i)break;const p=Wn(e,i);l.enqueue(si(r?p:bs.decode(p),t)),n=0}if(i===0||i>s){l.enqueue(xs);break}}}})}const Qo=4;function oe(s){if(s)return hc(s)}function hc(s){for(var t in oe.prototype)s[t]=oe.prototype[t];return s}oe.prototype.on=oe.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};oe.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};oe.prototype.off=oe.prototype.removeListener=oe.prototype.removeAllListeners=oe.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,i=0;i<e.length;i++)if(n=e[i],n===t||n.fn===t){e.splice(i,1);break}return e.length===0&&delete this._callbacks["$"+s],this};oe.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,i=e.length;n<i;++n)e[n].apply(this,t)}return this};oe.prototype.emitReserved=oe.prototype.emit;oe.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};oe.prototype.hasListeners=function(s){return!!this.listeners(s).length};const ls=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),we=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),fc="arraybuffer";function ta(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const dc=we.setTimeout,uc=we.clearTimeout;function hs(s,t){t.useNativeTimers?(s.setTimeoutFn=dc.bind(we),s.clearTimeoutFn=uc.bind(we)):(s.setTimeoutFn=we.setTimeout.bind(we),s.clearTimeoutFn=we.clearTimeout.bind(we))}const pc=1.33;function mc(s){return typeof s=="string"?gc(s):Math.ceil((s.byteLength||s.size)*pc)}function gc(s){let t=0,e=0;for(let n=0,i=s.length;n<i;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 ea(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function yc(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function wc(s){let t={},e=s.split("&");for(let n=0,i=e.length;n<i;n++){let r=e[n].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}class bc extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class ii extends oe{constructor(t){super(),this.writable=!1,hs(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 bc(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=si(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=yc(t);return e.length?"?"+e:""}}class vc extends ii{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)};ac(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,oc(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]=ea()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let na=!1;try{na=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Ec=na;function Tc(){}class Mc extends vc{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",(i,r)=>{this.onError("xhr post error",i,r)})}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 xe extends oe{constructor(t,e,n){super(),this.createRequest=t,hs(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=ta(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 i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}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 i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.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(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=xe.requestsCount++,xe.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=Tc,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete xe.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()}}xe.requestsCount=0;xe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Co);else if(typeof addEventListener=="function"){const s="onpagehide"in we?"pagehide":"unload";addEventListener(s,Co,!1)}}function Co(){for(let s in xe.requests)xe.requests.hasOwnProperty(s)&&xe.requests[s].abort()}const $c=function(){const s=sa({xdomain:!1});return s&&s.responseType!==null}();class Ic extends Mc{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=$c&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xe(sa,this.uri(),t)}}function sa(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Ec))return new XMLHttpRequest}catch{}if(!t)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ia=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Sc extends ii{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=ia?{}:ta(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(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=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],i=e===t.length-1;ni(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}i&&ls(()=>{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]=ea()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const vs=we.WebSocket||we.MozWebSocket;class xc extends Sc{createSocket(t,e,n){return ia?new vs(t,e,n):e?new vs(t,e):new vs(t)}doWrite(t,e){this.ws.send(e)}}class _c extends ii{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=lc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=cc();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const r=()=>{n.read().then(({done:l,value:p})=>{l||(this.onPacket(p),r())}).catch(l=>{})};r();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;this._writer.write(n).then(()=>{i&&ls(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Ac={websocket:xc,webtransport:_c,polling:Ic},Cc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Rc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function _s(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 i=Cc.exec(s||""),r={},a=14;for(;a--;)r[Rc[a]]=i[a]||"";return e!=-1&&n!=-1&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Oc(r,r.path),r.queryKey=kc(r,r.query),r}function Oc(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 kc(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,r){i&&(e[i]=r)}),e}const As=typeof addEventListener=="function"&&typeof removeEventListener=="function",Xn=[];As&&addEventListener("offline",()=>{Xn.forEach(s=>s())},!1);class We extends oe{constructor(t,e){if(super(),this.binaryType=fc,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=_s(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=_s(e.host).host);hs(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 i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=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=wc(this.opts.query)),As&&(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"})},Xn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Qo,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&&We.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",We.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 i=this.writeBuffer[n].data;if(i&&(e+=mc(i)),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,ls(()=>{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,i){if(typeof e=="function"&&(i=e,e=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),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(We.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(),As&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Xn.indexOf(this._offlineEventListener);n!==-1&&Xn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}We.protocol=Qo;class Nc extends We{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;We.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",E=>{if(!n)if(E.type==="pong"&&E.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;We.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 b=new Error("probe error");b.transport=e.name,this.emitReserved("upgradeError",b)}}))};function r(){n||(n=!0,c(),e.close(),e=null)}const a=E=>{const b=new Error("probe error: "+E);b.transport=e.name,r(),this.emitReserved("upgradeError",b)};function l(){a("transport closed")}function p(){a("socket closed")}function d(E){e&&E.name!==e.name&&r()}const c=()=>{e.removeListener("open",i),e.removeListener("error",a),e.removeListener("close",l),this.off("close",p),this.off("upgrading",d)};e.once("open",i),e.once("error",a),e.once("close",l),this.once("close",p),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 Fc=class extends Nc{constructor(t,e={}){const n=typeof t=="object",i=n?{...t}:{...e};(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(r=>Ac[r]).filter(r=>!!r)),super(n?i:t,i)}};function Pc(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=_s(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 r=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port+t,n.href=n.protocol+"://"+r+(e&&e.port===n.port?"":":"+n.port),n}const Lc=typeof ArrayBuffer=="function",Bc=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,ra=Object.prototype.toString,jc=typeof Blob=="function"||typeof Blob<"u"&&ra.call(Blob)==="[object BlobConstructor]",Dc=typeof File=="function"||typeof File<"u"&&ra.call(File)==="[object FileConstructor]";function ri(s){return Lc&&(s instanceof ArrayBuffer||Bc(s))||jc&&s instanceof Blob||Dc&&s instanceof File}function Zn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(Zn(s[e]))return!0;return!1}if(ri(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Zn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&Zn(s[e]))return!0;return!1}function Uc(s){const t=[],e=s.data,n=s;return n.data=Cs(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Cs(s,t){if(!s)return s;if(ri(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]=Cs(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]=Cs(s[n],t));return e}return s}function Jc(s,t){return s.data=Rs(s.data,t),delete s.attachments,s}function Rs(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]=Rs(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Rs(s[e],t));return s}const qc=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Vt;(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"})(Vt||(Vt={}));class Gc{constructor(t){this.replacer=t}encode(t){return(t.type===Vt.EVENT||t.type===Vt.ACK)&&Zn(t)?this.encodeAsBinary({type:t.type===Vt.EVENT?Vt.BINARY_EVENT:Vt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===Vt.BINARY_EVENT||t.type===Vt.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=Uc(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}}class oi extends oe{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===Vt.BINARY_EVENT;n||e.type===Vt.BINARY_ACK?(e.type=n?Vt.EVENT:Vt.ACK,this.reconstructor=new Hc(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(ri(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(Vt[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Vt.BINARY_EVENT||n.type===Vt.BINARY_ACK){const r=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const a=t.substring(r,e);if(a!=Number(a)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const l=Number(a);if(!Vc(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=l}if(t.charAt(e+1)==="/"){const r=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(r,e)}else n.nsp="/";const i=t.charAt(e+1);if(i!==""&&Number(i)==i){const r=e+1;for(;++e;){const a=t.charAt(e);if(a==null||Number(a)!=a){--e;break}if(e===t.length)break}n.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(oi.isPayloadValid(n.type,r))n.data=r;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 Vt.CONNECT:return Ro(e);case Vt.DISCONNECT:return e===void 0;case Vt.CONNECT_ERROR:return typeof e=="string"||Ro(e);case Vt.EVENT:case Vt.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&qc.indexOf(e[0])===-1);case Vt.ACK:case Vt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Hc{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=Jc(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Vc=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Ro(s){return Object.prototype.toString.call(s)==="[object Object]"}const zc=Object.freeze(Object.defineProperty({__proto__:null,Decoder:oi,Encoder:Gc,get PacketType(){return Vt}},Symbol.toStringTag,{value:"Module"}));function Ee(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Wc=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class oa extends oe{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=[Ee(t,"open",this.onopen.bind(this)),Ee(t,"packet",this.onpacket.bind(this)),Ee(t,"error",this.onerror.bind(this)),Ee(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,i,r;if(Wc.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 a={type:Vt.EVENT,data:e};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,E=e.pop();this._registerAckCallback(c,E),a.id=c}const l=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,p=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!l||(p?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,e){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[t]=e;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);e.call(this,new Error("operation has timed out"))},i),a=(...l)=>{this.io.clearTimeoutFn(r),e.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...e){return new Promise((n,i)=>{const r=(a,l)=>a?i(a):n(l);r.withError=!0,e.push(r),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((i,...r)=>(this._queue[0],i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(i)):(this._queue.shift(),e&&e(null,...r)),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:Vt.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 Vt.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 Vt.EVENT:case Vt.BINARY_EVENT:this.onevent(t);break;case Vt.ACK:case Vt.BINARY_ACK:this.onack(t);break;case Vt.DISCONNECT:this.ondisconnect();break;case Vt.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(...i){n||(n=!0,e.packet({type:Vt.ACK,id:t,data:i}))}}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:Vt.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 fn(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}fn.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};fn.prototype.reset=function(){this.attempts=0};fn.prototype.setMin=function(s){this.ms=s};fn.prototype.setMax=function(s){this.max=s};fn.prototype.setJitter=function(s){this.jitter=s};class Os extends oe{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,hs(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 fn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||zc;this.encoder=new i.Encoder,this.decoder=new i.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 Fc(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=Ee(e,"open",function(){n.onopen(),t&&t()}),r=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=Ee(e,"error",r);if(this._timeout!==!1){const l=this._timeout,p=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),e.close()},l);this.opts.autoUnref&&p.unref(),this.subs.push(()=>{this.clearTimeoutFn(p)})}return this.subs.push(i),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ee(t,"ping",this.onping.bind(this)),Ee(t,"data",this.ondata.bind(this)),Ee(t,"error",this.onerror.bind(this)),Ee(t,"close",this.onclose.bind(this)),Ee(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){ls(()=>{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 oa(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(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):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 gn={};function _n(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Pc(s,t.path||"/socket.io"),n=e.source,i=e.id,r=e.path,a=gn[i]&&r in gn[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let p;return l?p=new Os(n,t):(gn[i]||(gn[i]=new Os(n,t)),p=gn[i]),e.query&&!t.query&&(t.query=e.queryKey),p.socket(e.path,t)}Object.assign(_n,{Manager:Os,Socket:oa,io:_n,connect:_n});class ks 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 Oo="bimterop",Ns="revitflow_history.json",aa="revitflow_model.frag",ca="revitflow_",Yc="bimterop-locks-anchor",yn=new Map;function Kc(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Xc(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 Ie(s){return String(s._id??s.id??"")}var ve,Ye,ke,Rn,On,Fs;class ai{constructor(t,e){qt(this,On);qt(this,ve);qt(this,Ye,new Map);qt(this,ke);qt(this,Rn,0);this.client=t,this.projectId=e}async docs(){const t=await I(this,On,Fs).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const i of e){if(i.archived)continue;const r=String(i.name??""),a=r.indexOf("-");if(a<=0)continue;const p=(await this.client.listFiles({folderId:Ie(i)})).map(E=>String(E.name??"")),d=p.find(E=>E===aa)??p.find(E=>E.endsWith(".frag")&&!E.startsWith(ca)),c=p.includes(Ns)||!!d;n.push({source:r.slice(0,a),docId:r.slice(a+1),folderId:Ie(i),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let i=N(this,Ye).get(n);return i||(i=new Ps(this.client,this,t,e),N(this,Ye).set(n,i)),i}document(t){const e=`platform-${t}`;let n=N(this,Ye).get(e);return n||(n=new Ps(this.client,this,"platform",t,t),N(this,Ye).set(e,n)),n}async childFolders(t,e=!1){return(e||!N(this,ke)||Date.now()-N(this,Rn)>3e4)&&(Xt(this,Rn,Date.now()),Xt(this,ke,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Kc(n,t))),N(this,ke).catch(()=>{Xt(this,ke,void 0)})),N(this,ke)}forgetFolders(){Xt(this,ke,void 0)}async rootFolderId(t=!1){if(N(this,ve))return N(this,ve);const e=await I(this,On,Fs).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Oo,void 0,this.projectId);return Xt(this,ve,Ie(n)),N(this,ve)}}ve=new WeakMap,Ye=new WeakMap,ke=new WeakMap,Rn=new WeakMap,On=new WeakSet,Fs=async function(){if(N(this,ve))return N(this,ve);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Oo&&!n.parentId);return e&&Xt(this,ve,Ie(e)),N(this,ve)};var Me,Et,Re,tn,Ue,$e,kn,Ls,Qn,Je,la,ha,ts,fa,da,ua;class Ps{constructor(t,e,n,i,r){qt(this,Et);qt(this,Me);qt(this,$e);qt(this,kn,0);this.client=t,this.project=e,this.source=n,this.docId=i,Xt(this,Me,r)}async timeline(){const t=await I(this,Et,ts).call(this);return ci((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 I(this,Et,Je).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const e=await this.client.downloadFile(t.id);if(!e.ok)throw new Error(`Reading the model answered ${e.status}`);return await e.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,i=n?e.findIndex(c=>c.guid===n):e.length-1;if(i<0)throw new Error(`No version ${n} in this document's timeline.`);let r=0;for(let c=i;c>=0;c--)if(e[c].full){r=c;break}const a=await I(this,Et,Je).call(this);if(!a)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const l=e[r],p=e.slice(i+1).some(c=>c.full),d=e.slice(r+1,i+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(E=>E.type==="delete").map(E=>E.uniqueId)}));return{baseline:{fileId:a.id,guid:l.guid,current:!p,...l.version!==void 0?{storageVersion:l.version}:{}},steps:d,at:e[i].guid}}async folderId(){return await I(this,Et,Ue).call(this,!1)}async descriptor(){return await N(this,Et,Re).descriptor(await I(this,Et,Ue).call(this,!1))}async view(t){const e=await I(this,Et,Ue).call(this,!1),n=await N(this,Et,Re).descriptor(e);if(n){for(const r of t){const a=n.views.find(l=>l.format===r);if(a)return a}return null}if(!t.includes("frag"))return null;const i=await I(this,Et,Je).call(this);return i?{fileId:i.id,format:"frag"}:null}async addView(t){const e=await I(this,Et,Ue).call(this,!0);if(await N(this,Et,Re).descriptor(e)){await N(this,Et,Re).addView(e,t);return}const i=await I(this,Et,Je).call(this);await N(this,Et,Re).setDescriptor(e,{name:(i==null?void 0:i.name.replace(/\.frag$/,""))??N(this,Et,tn),views:[t]})}async ensureDescriptor(){const t=await I(this,Et,Ue).call(this,!1),e=await N(this,Et,Re).descriptor(t);if(e)return e;const n=await I(this,Et,Je).call(this);if(!n)return null;const i={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await N(this,Et,Re).setDescriptor(t,i),await N(this,Et,Re).descriptor(t)}async ownership(){const t=await I(this,Et,Qn).call(this,Yc);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async a=>{try{const l=Ie(a),p=await this.client.downloadHiddenFile(l),d=JSON.parse(await p.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}})),i=new Set,r=new Map;for(const a of n)if(a)for(const l of a.keys){if(!l||i.has(l))continue;i.add(l);const p=r.get(a.owner)??[];p.push(l),r.set(a.owner,p)}return[...r.entries()].map(([a,l])=>({owner:a,elements:l}))}async sync(t){var l,p,d;const e=await I(this,Et,Ue).call(this,!0);let n=await I(this,Et,ts).call(this)??{model:this.docId,commits:[]};const i=ko(n.commits);if(t.expectedLatestGuid!==void 0&&(i==null?void 0:i.guid)!==t.expectedLatestGuid)throw new ks(t.expectedLatestGuid,i==null?void 0:i.guid);const r={guid:li(),...i?{parents:[i.guid]}:{},author:t.author,source:t.source,timestamp:t.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}:{},...(l=t.origins)!=null&&l.length?{origins:t.origins}:{},changes:t.changes,counts:Zc(t.changes)};if(t.model&&(await I(this,Et,ua).call(this,e,t.model),r.full=!0),t.delta){const c=((p=await I(this,Et,Je).call(this))==null?void 0:p.id)??((d=t.file)==null?void 0:d.fileId)??void 0;if(!c)throw new Error("A delta needs the model file to hang from: sync a full model first.");const E=await this.client.createHiddenFile(t.delta,c);r.deltaId=Xc(E)}const a=await I(this,Et,ts).call(this);if(a){n=a;const c=ko(n.commits);if(t.expectedLatestGuid!==void 0&&(c==null?void 0:c.guid)!==t.expectedLatestGuid)throw new ks(t.expectedLatestGuid,c==null?void 0:c.guid);c&&!r.parents&&(r.parents=[c.guid])}return n.commits.push(r),await I(this,Et,fa).call(this,e,Ns,n),r}}Me=new WeakMap,Et=new WeakSet,Re=function(){return new fi(this.client,this.project.projectId)},tn=function(){return`${this.source}-${this.docId}`},Ue=async function(t){if(N(this,Me))return N(this,Me);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=a=>a.find(l=>String(l.name??"")===N(this,Et,tn)),i=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(i)return Xt(this,Me,Ie(i)),N(this,Me);if(!t)throw new Error(`Document ${N(this,Et,tn)} does not exist in this project.`);const r=await this.client.createFolder(N(this,Et,tn),e,this.project.projectId);return this.project.forgetFolders(),Xt(this,Me,Ie(r)),N(this,Me)},$e=new WeakMap,kn=new WeakMap,Ls=async function(){return(!N(this,$e)||Date.now()-N(this,kn)>5e3)&&(Xt(this,kn,Date.now()),Xt(this,$e,(async()=>{const t=await I(this,Et,Ue).call(this,!1);return t?(await this.client.listFiles({folderId:t,versions:!0})).map(n=>({id:Ie(n),name:String(n.name??""),stamp:as(n)})):[]})()),N(this,$e).catch(()=>{Xt(this,$e,void 0)})),N(this,$e)},Qn=async function(t){try{return(await I(this,Et,Ls).call(this)).find(e=>e.name===t)}catch{return}},Je=async function(){try{const t=await I(this,Et,Ls).call(this);return t.find(e=>e.name===aa)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(ca))}catch{return}},la=async function(t){const e=await I(this,Et,Qn).call(this,t);if(!e)return;const n=e.stamp?yn.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const i=I(this,Et,ha).call(this,e,t);return e.stamp&&(yn.set(e.id,{stamp:e.stamp,value:i}),i.catch(()=>{var r;((r=yn.get(e.id))==null?void 0:r.value)===i&&yn.delete(e.id)})),structuredClone(await i)},ha=async function(t,e){const n=await this.client.downloadFile(t.id);if(!n.ok)throw new Error(`Reading ${e} answered ${n.status}`);const i=await n.text();if(i.trim())return JSON.parse(i)},ts=function(){return I(this,Et,la).call(this,Ns)},fa=async function(t,e,n){const i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,Et,Qn).call(this,e);return r?(yn.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)}),r):await I(this,Et,da).call(this,t,e,n)},da=async function(t,e,n){const i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await this.client.createFile({file:i,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Xt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:e}},ua=async function(t,e){const n=await I(this,Et,Je).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const i=`${N(this,Et,tn)}.frag`,r=await this.client.createFile({file:e,name:i,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Xt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:i}};function Zc(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 ci(s){var p;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=(p=d.parents)==null?void 0:p[0];if(c&&t.has(c)){const E=e.get(c)??[];E.push(d),e.set(c,E)}else n.push(d)}const i=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(i);const r=[],a=[...n].reverse(),l=new Set;for(;a.length;){const d=a.pop();if(l.has(d.guid))continue;l.add(d.guid),r.push(d);const c=(e.get(d.guid)??[]).sort(i);for(let E=c.length-1;E>=0;E--)a.push(c[E])}for(const d of s)l.has(d.guid)||r.push(d);return r.forEach((d,c)=>d.ordinal=c),r}function ko(s){const t=ci(s);return t[t.length-1]}function li(){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 hi={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawing set",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"}},Qc={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 Bs(s){var e;if(s.type&&s.type in hi)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 i=n?Qc[n.toLowerCase()]:void 0;if(i)return i}return"generic"}const Cn="thatopen/document@1",Mn="document.json",pa=["pdf","txt","md","json","csv","tsv","frag"];function be(s){return String(s._id??s.id??"")}const Ze=new Map;let No=!1;const as=s=>{const t=s,e=[...t.versions??[]].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0],n=(e==null?void 0:e.tag)??t.versionTag;return n==null?void 0:String(n)};var se,ma,ga,js,ya,wa,ba,va,$n;class fi{constructor(t,e){qt(this,se);this.client=t,this.projectId=e}async list(t){const e=await I(this,se,ma).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(i=>n.includes(Bs(i.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),i=String(n.name??""),r=Es(i,n.fileExtension),a=(e==null?void 0:e.name)??i.replace(/\.[^.]+$/,"")??i,l=new Set((await this.list().catch(()=>[])).map(k=>String(k.descriptor.name??"").toLowerCase())),p=n.folderId?String(n.folderId):void 0;let d=a,c="";for(let k=1;k<100;k++){if(d=k===1?a:`${a} (${k})`,l.has(d.toLowerCase()))continue;const W=await this.client.createFolder(d,p,this.projectId);if(c=be(W),!await I(this,se,$n).call(this,c))break}await this.client.updateFile(t,{parentFolderId:c});const E=[],b=await I(this,se,wa).call(this,n);if(b)try{const k=await this.client.getFile(b);await this.client.updateFile(b,{parentFolderId:c}),E.push({fileId:b,format:Es(String(k.name??""),k.fileExtension)})}catch{}((e==null?void 0:e.selfView)??pa.includes(r))&&E.push({fileId:t,format:r});const P={schema:Cn,name:d,native:{fileId:t,format:r},views:E};return P.type=(e==null?void 0:e.type)??Bs(P),await this.setDescriptor(c,P),await this.recordUpload(c,{fileId:t,name:i,format:r},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:c,descriptor:P}}async recordUpload(t,e,n){const i=new ai(this.client,this.projectId).document(t),r=(await i.timeline()).length===0;await i.sync({author:n||"unknown",source:"platform",kind:"upload",message:r?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Es(e.name,void 0)},changes:[]})}async descriptor(t){const e=await I(this,se,$n).call(this,t);return e?I(this,se,js).call(this,e.id,e.stamp):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const i of e){const r=n.views.find(a=>a.format===i);if(r)return r}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(i=>i.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:Cn,views:e.views??[]},i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,se,$n).call(this,t);if(r){Ze.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)});return}await this.client.createFile({file:i,name:Mn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new Ea(this.client,()=>I(this,se,$n).call(this,t))}}se=new WeakSet,ma=async function(){const t=await I(this,se,ga).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===Mn);return(await Promise.all(n.map(async r=>{const a=r,l=String(a.folderId??a.parentFolderId??"");if(!l)return null;const p=await I(this,se,js).call(this,be(r),as(r));return p?{folderId:l,descriptor:p}:null}))).filter(r=>r!==null)},ga=async function(){if(No)return null;let t;try{t=await this.client.listDocumentDescriptors(this.projectId)}catch(n){const i=n.status;if(i===404||i===400||i===405)return No=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const i=Po(n.descriptor);!i||!n.folderId||(n.fileId&&n.versionTag&&Ze.set(n.fileId,{stamp:n.versionTag,value:Promise.resolve(i)}),e.push({folderId:String(n.folderId),descriptor:i}))}return e},js=function(t,e){const n=e?Ze.get(t):void 0;if(n&&n.stamp===e)return n.value;const i=I(this,se,ya).call(this,t);return e&&(Ze.set(t,{stamp:e,value:i}),i.catch(()=>{var r;((r=Ze.get(t))==null?void 0:r.value)===i&&Ze.delete(t)})),i},ya=async function(t){const e=await this.client.downloadFile(t);if(!e.ok)throw new Error(`Reading a document's descriptor answered ${e.status}`);const n=await e.text();if(!n.trim())return null;let i;try{i=JSON.parse(n)}catch{return null}return Po(i)},wa=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const d=n.find(c=>be(c)===be(t));e=(d==null?void 0:d.versions)??[]}const i=await I(this,se,va).call(this,t,e);if(i)return i;const r=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!r)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const a=d=>String(d.folderId??d.parentFolderId??""),l=new Set(n.filter(d=>String(d.name??"")===Mn).map(a)),p=n.filter(d=>String(d.name??"").toLowerCase()===`${r}.frag`&&!d.archived&&be(d)!==be(t)&&!l.has(a(d)));for(const d of p){const c=await I(this,se,ba).call(this,d);if(c===void 0||c===be(t))return be(d)}},ba=async function(t){const n=[...t.versions??[]].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0];if(n)try{const i=await this.client.getFileVersionMetadata(be(t),n.tag);return typeof(i==null?void 0:i.sourceIfcId)=="string"&&i.sourceIfcId?i.sourceIfcId:void 0}catch{return}},va=async function(t,e){const n=[...e].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")));for(const i of n)try{const r=await this.client.getFileVersionMetadata(be(t),i.tag),a=r==null?void 0:r.derivedFileId;if(typeof a=="string"&&a)return a}catch{}},$n=async function(t){if(!t)return;const n=(await this.client.listFiles({folderId:t,versions:!0})).find(i=>String(i.name??"")===Mn);return n?{id:be(n),stamp:as(n)}:void 0};const Ds="draft:",en="TODRAFT1";var Se,In,Us;class Ea{constructor(t,e){qt(this,Se);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 I(this,Se,In).call(this,t.id)){const i=e.get(n.userId);(!i||n.savedAt>i.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,i)=>+i.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const i=(await I(this,Se,In).call(this,e.id)).filter(p=>!(t!=null&&t.userId)||p.userId===t.userId).sort((p,d)=>+d.savedAt-+p.savedAt)[0];if(!i)return null;const r=await this.client.downloadHiddenFile(i.hiddenId),{meta:a,blob:l}=await nl(await r.blob());return{userId:i.userId,savedAt:i.savedAt,meta:a,blob:l}}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 i=tl(e.userId),r=(await I(this,Se,In).call(this,n.id)).filter(p=>p.userId===e.userId),l=(await this.client.createHiddenFile(await el(t,e.meta??{}),n.id,i)).hiddenFileId;if(!l)throw new Error("The draft upload answered without a hiddenFileId.");return await I(this,Se,Us).call(this,r.map(p=>p.hiddenId)),{userId:e.userId,savedAt:Fo(l)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await I(this,Se,In).call(this,e.id)).filter(i=>i.userId===t.userId);await I(this,Se,Us).call(this,n.map(i=>i.hiddenId))}}Se=new WeakSet,In=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(Ds)).map(n=>{const i=String(n._id);return{hiddenId:i,userId:n.tag.slice(Ds.length),savedAt:Fo(i)}})},Us=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function tl(s){const t=`${Ds}${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 Fo(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function el(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(en),n,e,s])}async function nl(s){const t=new Uint8Array(await s.slice(0,en.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,en.length))!==en)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(en.length,!0),n=en.length+4,i=await s.slice(n,n+e).text();let r={};try{r=JSON.parse(i)}catch{}return{meta:r,blob:s.slice(n+e)}}function Es(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Po(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Cn||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(l=>!!l&&typeof l=="object"&&typeof l.fileId=="string"&&typeof l.format=="string"):[],n=t.native,i=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",r=typeof t.type=="string"&&t.type in hi?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:Cn,name:t.name,...r?{type:r}:{},...i?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const sl="flow:",il="flow:op",rl="flow:source",ol="flow:host",al="flow:print",di="revitflow/op@2",Lo="REVITFLOWCHANGE",Bo="REVITFLOWOPERATION";class fs{constructor(t){he(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:di,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,i]=await cl();return ll(this.flatbuffer(n,i,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[i,r]of Object.entries(t??{}))i.startsWith(sl)&&i!==al||(n[i]=String(r));return e.position&&(n.Position=e.position.map(jo).join(",")),e.rotationDeg!==void 0&&(n.Rotation=jo(e.rotationDeg)),e.source&&(n[rl]=e.source),e.host&&(n[ol]=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,i){const{Attribute:r,Meshes:a,Model:l,SpatialStructure:p,Transform:d}=e,c=new t.Builder(1024),E=this.changes.length,b=new Uint32Array(E);let $=1;for(let rt=0;rt<E;rt++)b[rt]=$++;const P=$++,k=rt=>(rt(c,0),c.endVector()),W=a.createShellsVector(c,[]),V=a.createCircleExtrusionsVector(c,[]),D=k(a.startSamplesVector),f=k(a.startRepresentationsVector),Tt=k(a.startMaterialsVector),nt=k(a.startLocalTransformsVector),wt=k(a.startGlobalTransformsVector),Pt=a.createMeshesItemsVector(c,[]),tt=a.createMaterialIdsVector(c,[]),ct=a.createRepresentationIdsVector(c,[]),ht=a.createSampleIdsVector(c,[]),kt=a.createLocalTransformIdsVector(c,[]),te=a.createGlobalTransformIdsVector(c,[]);a.startMeshes(c),a.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),a.addGlobalTransforms(c,wt),a.addShells(c,W),a.addRepresentations(c,f),a.addSamples(c,D),a.addLocalTransforms(c,nt),a.addMaterials(c,Tt),a.addCircleExtrusions(c,V),a.addMeshesItems(c,Pt),a.addRepresentationIds(c,ct),a.addSampleIds(c,ht),a.addMaterialIds(c,tt),a.addLocalTransformIds(c,kt),a.addGlobalTransformIds(c,te);const Wt=a.endMeshes(c),at=c.createString(i),st=new Set,pt=[];for(const rt of this.changes){const _t=[],ie={[il]:rt.op,...rt.attrs};for(const[Nt,le]of Object.entries(ie)){const me=JSON.stringify([Nt,le,"IFCTEXT"]);st.add(me),_t.push(c.createString(me))}pt.push(r.createAttribute(c,r.createDataVector(c,_t)))}{const rt=JSON.stringify(["Name",n,"IFCLABEL"]);st.add(rt);const _t=r.createDataVector(c,[c.createString(rt)]);pt.push(r.createAttribute(c,_t))}const Bt=l.createAttributesVector(c,pt),Gt=l.createUniqueAttributesVector(c,[...st].map(rt=>c.createString(rt))),jt=this.changes.map(()=>c.createString(Lo));jt.push(c.createString(Bo));const Kt=l.createCategoriesVector(c,jt),Yt=[],zt=[];this.changes.forEach((rt,_t)=>{rt.item&&(Yt.push(c.createString(rt.item)),zt.push(b[_t]))});const U=l.createGuidsVector(c,Yt),Z=l.createGuidsItemsVector(c,zt),B=l.createLocalIdsVector(c,[...b,P]),ut=this.changes.map((rt,_t)=>p.createSpatialStructure(c,b[_t],c.createString(Lo),0)),X=p.createSpatialStructure(c,P,c.createString(Bo),p.createChildrenVector(c,ut)),dt=c.createString(n);l.startModel(c),l.addMeshes(c,Wt),l.addMetadata(c,at),l.addAttributes(c,Bt),l.addUniqueAttributes(c,Gt),l.addLocalIds(c,B),l.addCategories(c,Kt),l.addGuidsItems(c,Z),l.addGuids(c,U),l.addGuid(c,dt),l.addSpatialStructure(c,X),l.addMaxLocalId(c,$);const Mt=l.endModel(c);return l.finishModelBuffer(c,Mt),c.asUint8Array()}}async function cl(){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 jo(s){return Number.isFinite(s)?String(s):"0"}async function ll(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function ds(s){const[t,e]=await hl(),n=e.Model.getRootAsModel(new t.ByteBuffer(await fl(s)));let i={};try{i=JSON.parse(n.metadata()??"{}")}catch{}const r=new Map;for(let l=0;l<n.guidsLength();l++){const p=n.guidsItems(l),d=n.guids(l);p!==null&&d&&r.set(p,d)}const a=[];for(let l=0;l<n.attributesLength();l++){const p=n.localIds(l);if(p===null)continue;const d={},c=n.attributes(l);for(let E=0;E<((c==null?void 0:c.dataLength())??0);E++){const b=c.data(E);if(b)try{const[$,P]=JSON.parse(b);d[$]=P}catch{}}a.push({localId:p,guid:r.get(p)??null,category:n.categories(l)??null,attrs:d})}return{metadata:i,items:a}}async function hl(){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 fl(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const Ta="Element",Ma="Carried",sn=1/.3048;function $a(s){const t=[];for(const e of s)for(const n of[Ta,Ma]){const i=e.attrs[n];if(i)try{const r=JSON.parse(i);for(const a of Array.isArray(r)?r:[r]){const l=a;typeof(l==null?void 0:l.id)!="string"||typeof(l==null?void 0:l.kind)!="string"||t.push({id:l.id,kind:l.kind,params:l.params??{},item:e})}}catch{}}return t}function de(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function dl(s){const t=new Map;for(const[e,n]of ui(s))t.set(e,n.name);return t}function ui(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,i=e.params.at;typeof n=="string"&&typeof i=="number"&&t.set(e.id,{name:n,at:i})}return t}function Ia(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 pi(s,t){const e=new Map;for(const[n,i]of s.made)e.set(n,i.id),i.print&&(t==null||t.set(n,i.print));return e}function es(s){const t=i=>Array.isArray(i)?i.map(t):i&&typeof i=="object"?Object.fromEntries(Object.keys(i).sort().map(r=>[r,t(i[r])])):i,e=JSON.stringify(t(s));let n=2166136261;for(let i=0;i<e.length;i++)n^=e.charCodeAt(i),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function mi(s,t){var a,l;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=((l=(a=/\.([^.]+)$/.exec(t.name))==null?void 0:a[1])==null?void 0:l.toLowerCase())??"frag";let i=null,r=null;if(n!=="frag"){const p=s.client.recipes.importerFor(n);if(!p)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(i=Sa(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),r=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await p(e,t.name)}return{picked:t,contents:await ds(e),site:i,shapes:r}}function Sa(s){var wt;const t=new TextDecoder("latin1").decode(s),e=Pt=>new RegExp(`^${Pt}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=Pt=>[...Pt.matchAll(/#\d+|\$/g)].map(tt=>tt[0]),i=Pt=>[...Pt.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(tt=>Number(tt[0])),r=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!r)return null;const a=(wt=r[2].split(",")[5])==null?void 0:wt.trim();if(!(a!=null&&a.startsWith("#")))return null;const l=e(a);if((l==null?void 0:l[1])!=="IFCLOCALPLACEMENT")return null;const[p,d]=n(l[2]);if(p!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[E,,b]=n(c[2]),$=E&&E!=="$"?e(E):null;if(!$)return null;const[P=0,k=0,W=0]=i($[2]);let V=0;const D=b&&b!=="$"?e(b):null;if(D){const[Pt=1,tt=0]=i(D[2]);V=Math.atan2(tt,Pt)*180/Math.PI}const f=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),Tt={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},nt=f?f[2]?Tt[f[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:P*nt,north:k*nt,elevation:W*nt,angleDeg:V}}const gi="thatopen/recipe@1",Do="__project_data",Uo="recipes",ul=s=>`${s}.recipe.json`,xa={OperationBuilder:fs,OP_SCHEMA:di,readFrag:ds,readPickedFrag:mi,recordsOf:$a,innerJson:de,levelsOf:ui,levelNames:dl,stylesOf:Ia,printOf:es,siteLocationOf:Sa,whatItMadeBefore:pi,ELEMENT_FIELD:Ta,CARRIED_FIELD:Ma,FEET_PER_METRE:sn},_a=/^[a-z0-9][a-z0-9-]{1,62}$/;async function Aa(s,t,e){const n=d=>[...d].sort((c,E)=>String(c._id).localeCompare(String(E._id)))[0],i=await s.listFolders({projectId:t,archived:!1});let r=n(i.filter(d=>d.name===Do&&!d.parentId));if(!r){if(!e)return null;r=await s.createFolder(Do,void 0,t)}const a=String(r._id),l=await s.listFolders({parentFolderId:a,projectId:t,archived:!1});let p=n(l.filter(d=>d.name===Uo&&String(d.parentId)===a));if(!p){if(!e)return null;p=await s.createFolder(Uo,a,t)}return String(p._id)}const pl=s=>String(s._id??s.id??""),ml=s=>String(s.tag??s.versionTag??""),Js=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function wn(s,t){const e=await Aa(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),i=new Map;for(const r of n){const a=String(r.name??"");a.endsWith(".recipe.json")&&i.set(a.slice(0,-12),{id:pl(r)})}return i}async function Yn(s,t,e){var r;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),i=JSON.parse(await n.text());if((i==null?void 0:i.schema)!==gi||!((r=i.manifest)!=null&&r.name)||typeof i.code!="string")throw new Error(`This is not a recipe this library can read (${String(i==null?void 0:i.schema)}).`);return i}async function bn(s,t){return(await s.listVersions(t)).map(n=>({tag:ml(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,i)=>Js(n.tag)-Js(i.tag))}var Nn;class Ca{constructor(t,e){qt(this,Nn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await wn(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:i}])=>{var r;try{const a=await bn(this.client,i),l=(r=a[a.length-1])==null?void 0:r.tag,p=await Yn(this.client,i,l);return{manifest:p.manifest,origin:"project",version:l,author:p.author,savedAt:p.savedAt}}catch{return null}}))).filter(i=>i!==null)}async versions(t,e){const n=(await wn(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const i=await bn(this.client,n.id);return await Promise.all(i.map(async({tag:r,createdAt:a})=>{try{const l=await Yn(this.client,n.id,r);return{version:r,author:l.author,note:l.note,savedAt:l.savedAt??a}}catch{return{version:r,savedAt:a}}}))}async source(t,e,n){var a;const i=(await wn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((a=(await bn(this.client,i.id)).pop())==null?void 0:a.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);return{...await Yn(this.client,i.id,r),version:r}}async save(t,e,n){const{manifest:i,code:r}=e;if(!_a.test((i==null?void 0:i.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(i.name))throw new Error(`"${i.name}" is a built-in recipe. Give yours a name of its own.`);if(!i.to||!i.description||!Array.isArray(i.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await qs(i,r);const a={schema:gi,manifest:i,code:r,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},l=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),p=(await wn(this.client,t)).get(i.name);if(p){const c=await bn(this.client,p.id),E=`v${Math.max(0,...c.map(b=>Js(b.tag)))+1}`;return await this.client.createVersion(p.id,l,E),E}const d=await Aa(this.client,t,!0);return await this.client.createFile({file:l,name:ul(i.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var p;const i=(await wn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((p=(await bn(this.client,i.id)).pop())==null?void 0:p.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);const a=`${i.id}@${r}`;let l=N(this,Nn).get(a);if(!l){const d=await Yn(this.client,i.id,r);l=await qs(d.manifest,d.code),N(this,Nn).set(a,l)}return{recipe:l,version:r}}}Nn=new WeakMap;async function qs(s,t){var i;let e;try{e=await import(`data:text/javascript;base64,${gl(t)}`)}catch(r){throw new Error(`The recipe's code does not load: ${r instanceof Error?r.message:String(r)}`)}const n=e.run??((i=e.default)==null?void 0:i.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:r=>n({...r,kit:xa})}}function gl(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 yl(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await ds(t),i=e.filter(r=>r.attrs["flow:op"]).map(r=>{const a={};for(const[l,p]of Object.entries(r.attrs))l.startsWith("flow:")||(a[l]=p);return{op:r.attrs["flow:op"],...r.guid?{target:r.guid}:{},...r.attrs["flow:source"]?{source:r.attrs["flow:source"]}:{},attrs:a}});return{envelope:n??{},changes:i}}class yi extends Error{constructor(t){super(t),this.name="UpToDate"}}var Ne,Fn,Pn;class Ra{constructor(t){qt(this,Ne,new Map);qt(this,Fn,new Map);qt(this,Pn,new Map);he(this,"project");this.client=t,this.project=new Ca(t,()=>new Set(N(this,Ne).keys()))}provideImporter(t,e){N(this,Fn).set(t.toLowerCase(),e)}provideShapes(t,e){N(this,Pn).set(t.toLowerCase(),e)}shapesFor(t){return N(this,Pn).get(t.toLowerCase())}importerFor(t){return N(this,Fn).get(t.toLowerCase())}register(t){if(N(this,Ne).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);N(this,Ne).set(t.name,t)}list(t){return[...N(this,Ne).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return N(this,Ne).get(t)}async catalog(t,e){const n=this.list(e).map(r=>({manifest:r,origin:"builtin"}));let i=[];try{i=(await this.project.list(t)).filter(r=>!(e!=null&&e.to)||r.manifest.to===e.to)}catch{}return[...n,...i.sort((r,a)=>r.manifest.name.localeCompare(a.manifest.name))]}async resolve(t,e,n){const i=N(this,Ne).get(t);return i?{recipe:i,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),i=n.source;if((i==null?void 0:i.kind)!=="project-file")return[];const r=(i.extensions??[]).map(d=>d.toLowerCase()),l=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(r.length===0||r.includes(d.descriptor.native.format.toLowerCase()))),p=await Oa(this.client,l.map(d=>d.descriptor.native.fileId));return l.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:p.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??li(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}Ne=new WeakMap,Fn=new WeakMap,Pn=new WeakMap;async function Oa(s,t){const e=new Map;if(t.length===0)return e;const n=r=>{var a;return Number(((a=/(\d+)/.exec(String(r??"")))==null?void 0:a[1])??-1)},i=r=>{const l=r.slice().sort((p,d)=>{const c=p!=null&&p.createdAt?new Date(String(p.createdAt)).getTime():NaN,E=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(E)&&c!==E?E-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((p==null?void 0:p.tag)??(p==null?void 0:p.versionTag))})[0];return l?String(l.tag??l.versionTag??"v1"):"v1"};return await Promise.all(t.map(async r=>{try{e.set(r,i(await s.listVersions(r)))}catch{e.set(r,"v1")}})),e}const Gs=100;function wl(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 bl(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class us extends Error{constructor(e,n,i,r){const a=wl(i);super(a.message??`${n||"Request failed"} (${e})`);he(this,"status");he(this,"code");he(this,"details");he(this,"body");he(this,"retryAfter");this.name="RequestError",this.status=e,this.code=a.code,this.details=a.details,this.body=i,this.retryAfter=r??bl(a.details)}}const Te="item/folder",Lt="item",je="processor",vl="npm-registry",Ae="hidden",Ts="FILE",Ms="TOOL",$s="APP",El=500,Jo=3e4,Tl=2e3,Ml=15e3,$l=s=>/^\/?project\/permissions\/check/.test(s),Il=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),vn=new Map,Sl=.25,xl=s=>new Promise(t=>setTimeout(t,s));function _l(s){var i,r;const t=(r=(i=s.headers)==null?void 0:i.get)==null?void 0:r.call(i,"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 Al(s){return s instanceof us?s.status===429||s.status>=500:!0}function Cl(s,t){const e=Math.min(El*2**t,Jo),n=e*Sl*Math.random(),i=s instanceof us&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return i!=null?Math.min(i,Jo)+n:e+n}var Y,ns,vt,Hs,qe,Ln,Sn,ss,is,Vs,zs,Ws;const vi=class vi{constructor(t,e,n){qt(this,Y);he(this,"apiUrl");he(this,"accessToken");he(this,"wsUrl");he(this,"retries");he(this,"useBearer");he(this,"builtInGlobals",null);he(this,"localServerUrl",null);he(this,"context");qt(this,Ln);const{retries:i=0,useBearer:r=!1,localServerUrl:a}=n||{};let l=e;if(l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.apiUrl=`${l}/api`,this.accessToken=t,this.wsUrl=l,this.retries=i,this.useBearer=r,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},a){let p=a;p.charAt(p.length-1)==="/"&&(p=p.slice(0,-1)),this.localServerUrl=p}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new vi(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 I(this,Y,vt).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:i,versions:r}=t||{};return e?await I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ts,archived:n,...r&&{showVersions:!0}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:Ts,archived:n,...i&&{projectId:i}}})}async listDocumentDescriptors(t){return await I(this,Y,vt).call(this,"GET",`${Lt}/documents`,{query:{projectId:t}})}async exportProjectDocuments(t,e){return(e==null?void 0:e.format)==="csv"?(await(await I(this,Y,vt).call(this,"GET",`${Lt}/export`,{query:{projectId:t,format:"csv"},responseType:"blob"})).text()).replace(/^/,""):await I(this,Y,vt).call(this,"GET",`${Lt}/export`,{query:{projectId:t}})}async getFile(t,e){return await I(this,Y,zs).call(this,t,e)}async createFile(t){return await I(this,Y,is).call(this,t,Ts)}async updateFile(t,e){return await I(this,Y,Vs).call(this,t,e)}async archiveFile(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}`)}async recoverFile(t){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}/recover`)}async downloadFile(t,e){return await I(this,Y,ss).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:i}=n||{};return await I(this,Y,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...i&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await I(this,Y,Sn).call(this,t,async i=>(await I(this,Y,vt).call(this,"POST",`${Lt}/batch/version-metadata`,{body:JSON.stringify({entries:i,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:i}=t||{};return await I(this,Y,vt).call(this,"GET",Te,{query:{parentFolderId:n,archived:e,...i&&{projectId:i}}})}async getFolder(t){return await I(this,Y,vt).call(this,"GET",`${Te}/${t}`)}async getFoldersBatch(t){return await I(this,Y,Sn).call(this,t,async e=>(await I(this,Y,vt).call(this,"POST",`${Lt}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await I(this,Y,vt).call(this,"POST",Te,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await I(this,Y,vt).call(this,"PUT",`${Te}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await I(this,Y,vt).call(this,"DELETE",`${Te}/${t}`)}async recoverFolder(t){return await I(this,Y,vt).call(this,"PUT",`${Te}/${t}/recover`)}async downloadFolder(t){return await I(this,Y,qe).call(this,`${Te}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:i}=t||{};return e?await I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ms,...n&&{ShowVersions:n}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:Ms,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async getComponent(t,e){return await I(this,Y,zs).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await I(this,Y,is).call(this,t,Ms,e)}async updateComponent(t,e){const{componentProps:n}=e;return await I(this,Y,Vs).call(this,t,e,n)}async downloadComponent(t,e){return await I(this,Y,ss).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,Y,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}})}async archiveComponent(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}`)}async recoverComponent(t){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}/recover`)}async getBuiltInComponent(t){return await(await I(this,Y,qe).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const i=await this.getBuiltInComponent(t.uuid),r=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},a=Object.keys(r),l=a.map(E=>r[E]),d=new Function(...a,`${i}
2
- return main;`)(...l),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 a,l;const n=t.OBC,i=t.BUI;if(!(n!=null&&n.Components))throw new Error("globals.OBC must include Components");if(!(i!=null&&i.Manager))throw new Error("globals.BUI must include Manager");const r=new n.Components;return i.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(r,...e),r.init(),(l=(a=this.context.appEventOrchestrator)==null?void 0:a.appLoaded)==null||l.call(a),{components:r}}throwError(t,e){var n,i;(i=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||i.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:i}=t||{};return e?await I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:$s,...n&&{ShowVersions:n}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:$s,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async createApp(t){const{appProps:e}=t;return await I(this,Y,is).call(this,t,$s,e)}async downloadApp(t,e){return await I(this,Y,ss).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,Y,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}})}async archiveApp(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}`)}async getNpmCredentials(){return await I(this,Y,vt).call(this,"GET",`${vl}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const i=`${this.localServerUrl}/api/${je}/${t}/execute`,r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const a=await r.text().catch(()=>"");throw new Error(`Local server request failed: ${r.status} - ${a}`)}return await r.json()}return await I(this,Y,vt).call(this,"POST",`${je}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${i}`)}return await n.json()}return await I(this,Y,vt).call(this,"POST",`${je}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",i=`${this.localServerUrl}/api/${je}/${t}/progress${n}`,r=await fetch(i);if(!r.ok){const a=await r.text().catch(()=>"");throw new Error(`Local server request failed: ${r.status} - ${a}`)}return await r.json()}return await I(this,Y,vt).call(this,"GET",`${je}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/progress/${t}`,n=await fetch(e);if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${i}`)}return await n.json()}return await I(this,Y,vt).call(this,"GET",`${je}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,i=await _n(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});i.on("connect",function(){i.emit("executionSubscription",JSON.stringify({executionId:t})),i.on("execution",r=>{e(r)})}),i.on("connect_error",function(r){console.log(r)})}documents(t){return new fi(this,t)}history(t){return new ai(this,t)}get recipes(){return N(this,Ln)??Xt(this,Ln,new Ra(this)),N(this,Ln)}async createHiddenFile(t,e,n){const i=new FormData;return i.append("file",t),i.append("parentItemId",e),n!=null&&i.append("tag",n),await I(this,Y,vt).call(this,"POST",`${Lt}/${Ae}`,{body:i})}async createHiddenFilesBatch(t,e,n){const i=new FormData;for(const r of t)i.append("files",r);return i.append("parentItemId",e),n!=null&&i.append("tag",n),await I(this,Y,vt).call(this,"POST",`${Lt}/${Ae}/batch`,{body:i})}async deleteHiddenFile(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${Ae}/${t}`)}async getHiddenFile(t){return await I(this,Y,vt).call(this,"GET",`${Lt}/${Ae}/${t}`)}async downloadHiddenFile(t){return await I(this,Y,qe).call(this,`${Lt}/${Ae}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await I(this,Y,vt).call(this,"GET",`${Lt}/${Ae}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await I(this,Y,Sn).call(this,t,async n=>(await I(this,Y,vt).call(this,"POST",`${Lt}/${Ae}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await I(this,Y,vt).call(this,"GET",`${Lt}/${t}/${Ae}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}/${Ae}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}/icon`,{body:n})}async getItemIcon(t){return await I(this,Y,qe).call(this,`${Lt}/${t}/icon`)}async removeItemIcon(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}/icon`)}async updateItem(t,e){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,i,r){const a=new FormData;a.append("file",e),a.append("versionTag",n),i&&a.append("extraProps",JSON.stringify(i));const l=await I(this,Y,vt).call(this,"POST",`${Lt}/${t}/version`,{body:a});return r&&await this.updateFileVersionMetadata(t,(l==null?void 0:l.tag)??n,r),l}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 i of e){const r=/^v(\d{1,6})$/.exec(String(i.tag??i.versionTag??""));r&&(n=Math.max(n,Number(r[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await I(this,Y,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await I(this,Y,Sn).call(this,t,async i=>(await I(this,Y,vt).call(this,"POST",`${Lt}/batch/versions`,{body:JSON.stringify({itemIds:i,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};Y=new WeakSet,ns=function(t){return`${this.apiUrl}/${t}`},vt=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const i=`${I(this,Y,ns).call(this,e)}?${new URLSearchParams(I(this,Y,Ws).call(this,n==null?void 0:n.query)).toString()}`,r=Date.now(),a=vn.get(i);if(a&&(a.pending||r-a.at<(Il(e)?Ml:Tl)))return a.answer.then(p=>p===void 0?p:structuredClone(p));const l={at:r,pending:!0,answer:I(this,Y,Hs).call(this,t,e,n)};return vn.set(i,l),l.answer.then(()=>{l.pending=!1,l.at=Date.now()},()=>{vn.get(i)===l&&vn.delete(i)}),l.answer.then(p=>p===void 0?p:structuredClone(p))}return t!=="GET"&&!$l(e)&&vn.clear(),I(this,Y,Hs).call(this,t,e,n)},Hs=async function(t,e,n){const{body:i,query:r,contentType:a,retries:l,responseType:p,retryAttempt:d}=n||{},c=I(this,Y,ns).call(this,e),E=I(this,Y,Ws).call(this,r),b=await this.resolveAccessToken(),$={...E,...this.useBearer?{}:{accessToken:b}};try{const P=await fetch(c+"?"+new URLSearchParams($).toString(),{method:t,headers:{Accept:"application/json",...a&&{"Content-Type":a},...this.useBearer&&{Authorization:`Bearer ${b}`}},...i&&{body:i}});if(!P.ok){const k=await P.text().then(W=>W).catch(()=>"");throw new us(P.status,P.statusText,k,_l(P))}return p==="blob"?await P.blob():P.json().then(k=>k).catch(()=>{})}catch(P){const k=l??this.retries;if(k>0&&Al(P)){const W=d??0;return await xl(Cl(P,W)),await I(this,Y,vt).call(this,t,e,{...n,retries:k-1,retryAttempt:W+1})}throw P}},qe=async function(t,e){const{query:n}=e||{},i=I(this,Y,ns).call(this,t),r=await this.resolveAccessToken(),a={...n,...this.useBearer?{}:{accessToken:r}};return await fetch(i+"?"+new URLSearchParams(a).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${r}`}}})},Ln=new WeakMap,Sn=async function(t,e){if(!t.length)return[];const n=[];for(let r=0;r<t.length;r+=Gs)n.push(t.slice(r,r+Gs));return(await Promise.all(n.map(e))).flat()},ss=async function(t,e){const{versionTag:n,withDraft:i}=e||{},r=await I(this,Y,qe).call(this,`${Lt}/${t}/download`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}});if(r.status===429||r.status>=500)throw new Error(`Downloading ${t} answered ${r.status}${r.status===429?" (rate limited)":""}`);return r},is=async function(t,e,n){const{name:i,versionTag:r,parentFolderId:a,projectId:l,file:p,metadata:d}=t,c=new FormData;return c.append("file",p),c.append("name",i),c.append("versionTag",r),c.append("itemType",e),a&&c.append("folderId",a),l&&c.append("projectId",l),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await I(this,Y,vt).call(this,"POST",Lt,{body:c})},Vs=async function(t,e,n){const{name:i,versionTag:r,parentFolderId:a,file:l,metadata:p}=e;let d,c;if(l){const E=new FormData;E.append("file",l),r&&E.append("versionTag",r),n&&E.append("extraProps",JSON.stringify(n)),c=await I(this,Y,vt).call(this,"POST",`${Lt}/${t}/version`,{body:E});const b=(c==null?void 0:c.tag)??r;p&&b&&await this.updateFileVersionMetadata(t,b,p)}if(i||a){const E={...i&&{name:i},...a&&{folderId:a}},b=JSON.stringify(E);d=await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}`,{body:b,contentType:"application/json"})}return{item:d,version:c}},zs=async function(t,e){const{showVersions:n=!1}=e||{};return await I(this,Y,vt).call(this,"GET",`${Lt}/${t}`,{query:{showVersions:n}})},Ws=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,i])=>(e[n]=i,e),{})};let cs=vi;function ka(){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 Ys="channel:",Rl=1e4;function rs(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var Fe,ge,ye,on,an,cn,ue,Ks,Xs,nn;class wi{constructor(t,e){qt(this,ue);qt(this,Fe,!1);qt(this,ge,[]);qt(this,ye,[]);qt(this,on,new Set);qt(this,an,new Set);qt(this,cn,new Set);this.transport=t,this.controls=e}get joined(){return N(this,Fe)}get peers(){return N(this,ge)}join(){return N(this,Fe)?Promise.resolve():I(this,ue,Ks).call(this,"joined",this.controls.join)}leave(){return!N(this,Fe)&&!N(this,ye).some(t=>t.want==="joined")?Promise.resolve():I(this,ue,Ks).call(this,"left",this.controls.leave)}onChange(t){return N(this,on).add(t),()=>void N(this,on).delete(t)}onPeerJoined(t){return N(this,an).add(t),()=>void N(this,an).delete(t)}onPeerLeft(t){return N(this,cn).add(t),()=>void N(this,cn).delete(t)}applyJoined(){Xt(this,Fe,!0),I(this,ue,Xs).call(this,"joined"),I(this,ue,nn).call(this)}applyLeft(){Xt(this,Fe,!1),Xt(this,ge,[]),I(this,ue,Xs).call(this,"left"),I(this,ue,nn).call(this)}applyPeers(t){Xt(this,ge,t),I(this,ue,nn).call(this)}applyPeerJoined(t){!N(this,Fe)||N(this,ge).some(e=>e.from===t.from)||(Xt(this,ge,[...N(this,ge),t]),N(this,an).forEach(e=>rs(()=>e(t))),I(this,ue,nn).call(this))}applyPeerLeft(t){const e=N(this,ge).find(n=>n.from===t);e&&(Xt(this,ge,N(this,ge).filter(n=>n.from!==t)),N(this,cn).forEach(n=>rs(()=>n(e))),I(this,ue,nn).call(this))}failPending(t){const e=N(this,ye);return Xt(this,ye,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}Fe=new WeakMap,ge=new WeakMap,ye=new WeakMap,on=new WeakMap,an=new WeakMap,cn=new WeakMap,ue=new WeakSet,Ks=function(t,e){return new Promise((n,i)=>{const r={want:t,resolve:n,reject:i,timer:setTimeout(()=>{Xt(this,ye,N(this,ye).filter(a=>a!==r)),i(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},Rl)};N(this,ye).push(r),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},Xs=function(t){const e=N(this,ye).filter(n=>n.want===t);Xt(this,ye,N(this,ye).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},nn=function(){N(this,on).forEach(t=>rs(t))};var ln;class Na extends wi{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});qt(this,ln,new Map)}on(e,n){const i=N(this,ln).get(e)??new Set;return i.add(n),N(this,ln).set(e,i),()=>void i.delete(n)}send(e,n){if(e.startsWith(Ys))throw new Error(`Message types starting with '${Ys}' 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=N(this,ln).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const i=Pa(e);return n.forEach(r=>rs(()=>r(e.payload,i))),{handled:!0}}}ln=new WeakMap;var Ge;class Fa extends wi{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});qt(this,Ge,new Map);this.kind=n}on(e,n){if(N(this,Ge).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return N(this,Ge).set(e,n),()=>void N(this,Ge).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 N(this,Ge).size>0}async handle(e){const n=N(this,Ge).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Pa(e))}}catch(i){return{handled:!0,error:i instanceof Error?i.message:String(i)}}}}Ge=new WeakMap;function Pa(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Ol(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 Ke,Bn,Pe,He,Ve,ce,Zs,os,Ba,ja,Da,Qs;class La{constructor(t){qt(this,ce);qt(this,Ke);qt(this,Bn);qt(this,Pe);qt(this,He,new Map);qt(this,Ve,new Set);Xt(this,Ke,t),Xt(this,Bn,t.listen(e=>void I(this,ce,Ba).call(this,e)))}collab(){return N(this,Pe)??Xt(this,Pe,new Na(N(this,Ke))),N(this,Pe)}external(t){const e=t??"";let n=N(this,He).get(e);return n||(n=new Fa(N(this,Ke),t),N(this,He).set(e,n)),n}dispose(){N(this,Bn).call(this)}}Ke=new WeakMap,Bn=new WeakMap,Pe=new WeakMap,He=new WeakMap,Ve=new WeakMap,ce=new WeakSet,Zs=function(){return[...N(this,Pe)?[N(this,Pe)]:[],...N(this,He).values()]},os=function(t,e){if(t==="collab")return N(this,Pe);if(t==="external")return N(this,He).get(typeof e=="string"?e:"")},Ba=async function(t){const e=Ol(t);if(e){if(e.type.startsWith(Ys)){I(this,ce,ja).call(this,e);return}await I(this,ce,Da).call(this,e)}},ja=function(t){var n,i,r;const e=t.payload??{};switch(t.type){case"channel:joined":(n=I(this,ce,os).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(i=I(this,ce,os).call(this,e.scope,e.kind))==null||i.applyLeft();break;case"channel:peers":(r=I(this,ce,os).call(this,e.scope,e.kind))==null||r.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const a=e.scope==="collab"?[N(this,Pe)]:[...N(this,He).values()].filter(l=>l.accepts("external",e.kind));for(const l of a)t.type==="channel:peer-joined"?l==null||l.applyPeerJoined({from:e.from,kind:e.kind}):l==null||l.applyPeerLeft(e.from);break}case"channel:error":{const a=new Error(String(t.payload));I(this,ce,Zs).call(this).map(p=>p.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Da=async function(t){const e=I(this,ce,Zs).call(this).filter(r=>r.accepts(t.scope,t.kind));let n=!1;for(const r of e){const a=await r.handle(t);a.handled&&(n=!0,t.requestId&&I(this,ce,Qs).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&I(this,ce,Qs).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Qs=function(t,e){N(this,Ve).has(t)||(N(this,Ve).add(t),N(this,Ve).size>500&&N(this,Ve).delete(N(this,Ve).values().next().value),N(this,Ke).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 ae="project",Qe="notifications",En="tokens",kl=6e4;var hn,jn,ze;const Ei=class Ei extends cs{constructor(e,n,i){super(typeof e=="string"?e:"",n,{...i,useBearer:!0});qt(this,hn);qt(this,jn);qt(this,ze,new Map);typeof e=="function"&&Xt(this,hn,e)}async resolveAccessToken(){return N(this,hn)?await N(this,hn).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},i=new Ei(n.accessToken,n.apiUrl,e);return i.context=n,i}get channel(){return N(this,jn)??Xt(this,jn,new La(ka())),N(this,jn)}async listProjects(){return await this.request("GET",ae)}async getProject(e){return await this.request("GET",`${ae}/${e}`)}async getProjectData(e){const n=N(this,ze).get(e);if(n&&Date.now()-n.at<kl)return await n.data;const i=this.request("GET",`${ae}/${e}/data`);return N(this,ze).set(e,{at:Date.now(),data:i}),i.catch(()=>{var r;((r=N(this,ze).get(e))==null?void 0:r.data)===i&&N(this,ze).delete(e)}),await i}async request(e,n,i){return e.toUpperCase()!=="GET"&&N(this,ze).clear(),await super.request(e,n,i)}async listMembers(e){return await this.request("GET",`${ae}/${e}/users`)}async addMember(e,n,i){return await this.request("POST",`${ae}/${e}/user`,{body:JSON.stringify({accountId:n,...i&&{projectRoleId:i}}),contentType:"application/json"})}async setMemberRole(e,n,i){return await this.request("PUT",`${ae}/${e}/user/${n}`,{body:JSON.stringify({projectRoleId:i}),contentType:"application/json"})}async removeMember(e,n){return await this.request("DELETE",`${ae}/${e}/user/${n}`)}async inviteMember(e,n,i){return await this.request("POST",`${ae}/${e}/invite`,{body:JSON.stringify({email:n,...i&&{projectRoleId:i}}),contentType:"application/json"})}async listInvitations(e){return await this.request("GET",`${ae}/${e}/invites`)}async cancelInvitation(e,n){return await this.request("DELETE",`${ae}/${e}/invite/${n}`)}async listRoles(e){return await this.request("GET",`${ae}/${e}/roles`)}async createRole(e,n){return await this.request("POST",`${ae}/${e}/role`,{body:JSON.stringify(n),contentType:"application/json"})}async updateRole(e,n){return await this.request("PUT",`${ae}/role/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async deleteRole(e){return await this.request("DELETE",`${ae}/role/${e}`)}async getPermissionMatrix(e){const[n,i]=await Promise.all([this.listRoles(e),this.listMembers(e)]);return n.map(r=>({role:r,permissions:r.permissions??[],members:i.filter(a=>{var l;return String((l=a.role)==null?void 0:l._id)===String(r._id)}).map(a=>a.user)}))}async listTokens(){return await this.request("GET",En)}async getTokenSecret(e){return await(await this.request("GET",`${En}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",En,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,n){return await this.request("PUT",`${En}/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${En}/${e}`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${ae}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${ae}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Qe,{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",`${Qe}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Qe}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Qe}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Qe}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Qe}/subscriptions/${e}`)}async subscribeToAutomation(e,n,i){return await this.request("POST",`${ae}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(i??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,i){return await this.request("PATCH",`${ae}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(i),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),i=_n(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return i.on("notification.created",r=>e({type:"created",id:r==null?void 0:r.id})),i.on("notification.read",r=>e({type:"read",id:r==null?void 0:r.id})),i.on("notifications.allRead",r=>e({type:"allRead",batch:r==null?void 0:r.batch})),()=>i.disconnect()}};hn=new WeakMap,jn=new WeakMap,ze=new WeakMap;let ti=Ei;const Ce=1/.3048,Nl={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"},Fl="OST_GenericModel",Pl=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Oe=(s,t)=>Math.round(s/t)*t,Ll=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]]}),An=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Is=s=>Math.sqrt(An(s,s)),rn=(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 Bl(s,t,e,n){var d,c,E;const i=new Set,r=new Map;for(const b of t){const[,$,P]=b.split(":");$&&(/^datum/.test(P??"")||(i.add($),r.has($)||r.set($,b)))}const a=new Map,l=new Map,p=[];for(const b of s.elements.values()){if(i.has(b.gid)||Pl.has(b.ifcClass.toUpperCase())||b.parent&&i.has(b.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(b.ifcClass)&&!(n!=null&&n.has(b.gid))||b.pieces.length===0)continue;const P=/^IFCCOLUMN$/i.test(b.ifcClass)&&(b.loadBearing||/structural|estructural|结构柱|tragend|tragwerk/i.test(`${b.typeName??""} ${b.objectType??""} ${b.name??""}`))?"OST_StructuralColumns":Nl[b.ifcClass.toUpperCase()]??Fl,k=Ll(b.pieces[0].matrix),W=Is(k.x),V=Is(k.y),D=Is(k.z),f=k.z.map(U=>U/(D||1)),Tt=Math.abs(f[2]-1)<1e-6&&An(rn(k.x,k.y),k.z)>0&&Math.abs(W-V)<1e-6&&Math.abs(W-D)<1e-6,nt=An(rn(k.x,k.y),k.z)>0&&Math.abs(W-V)<1e-6&&Math.abs(W-D)<1e-6,wt=[k.x,k.y,k.z].map(U=>U.map(Z=>Z/(W||1))),Pt=nt&&!Tt&&wt.some(U=>Math.abs(Math.abs(U[2])-1)<1e-6)?wt.find(U=>Math.abs(U[2])<1e-6):void 0,tt=Tt?Math.atan2(k.x[1],k.x[0]):Pt?Math.atan2(Pt[1],Pt[0]):0,ct=Math.cos(-tt),ht=Math.sin(-tt),kt=[k.t[0],k.t[1],k.t[2]],te=/COLUMN/i.test(P),Wt=U=>{const Z=U[0]-kt[0],B=U[1]-kt[1];return[ct*Z-ht*B,ht*Z+ct*B,U[2]-kt[2]]},at=[],st=[P];for(const U of b.pieces){const Z=s.geometries.get(U.geometry);if(!Z)continue;const B=U.matrix,ut=[];for(let Nt=0;Nt<Z.verts.length;Nt+=3){const le=Z.verts[Nt],me=Z.verts[Nt+1],Le=Z.verts[Nt+2],re=[B[0]*le+B[4]*me+B[8]*Le+B[12],B[1]*le+B[5]*me+B[9]*Le+B[13],B[2]*le+B[6]*me+B[10]*Le+B[14]],Xe=Wt(re);ut.push(Oe(Xe[0]*Ce,1e-5),Oe(Xe[1]*Ce,1e-5),Oe(Xe[2]*Ce,1e-5))}const X=An(rn([B[0],B[1],B[2]],[B[4],B[5],B[6]]),[B[8],B[9],B[10]])<0,dt=[];for(let Nt=0;Nt+2<Z.tris.length;Nt+=3)X?dt.push(Z.tris[Nt],Z.tris[Nt+2],Z.tris[Nt+1]):dt.push(Z.tris[Nt],Z.tris[Nt+1],Z.tris[Nt+2]);dt.length&&at.push({v:ut,t:dt});const Mt=Wt([B[12],B[13],B[14]]),rt=[ct*B[0]-ht*B[1],ht*B[0]+ct*B[1],B[2]],_t=[ct*B[4]-ht*B[5],ht*B[4]+ct*B[5],B[6]],ie=[ct*B[8]-ht*B[9],ht*B[8]+ct*B[9],B[10]];st.push(`${U.geometry}@${[...Mt,...rt,..._t,...ie].map(Nt=>Oe(Nt,1e-4).toFixed(4)).join(",")}`)}if(at.length===0)continue;const pt=!b.host&&at.length===1?Ul(at[0]):null;if(pt){const U=Dl(pt),Z=U.key,B=`prism|${P}|${U.axis}|${Z}`;let ut=a.get(B);if(!ut){const le=qo(b.typeName??b.objectType??b.name??b.ifcClass),me=(l.get(le.toLowerCase())??0)+1;l.set(le.toLowerCase(),me);const Le=me===1?le:`${le} (${me})`;ut={family:Le,type:Le,first:!0,key:Go(B)},a.set(B,ut)}const X={ShapeCategory:P,Family:ut.family,Type:ut.type,ShapeKey:ut.key,PrismLength:String(Oe(pt.length,1e-5)),...te?{ColumnFree:"1"}:{}};ut.first&&(X.Prism=JSON.stringify({axis:U.axis,loops:U.loops}),ut.first=!1);const dt=[0,0,0];dt[pt.axis]=(U.flipped?pt.from+pt.length:pt.from)/Ce;const Mt=(pt.axis+1)%3,rt=(pt.axis+2)%3;dt[Mt]+=U.centre[0]/Ce,dt[rt]+=U.centre[1]/Ce;const _t=Math.cos(tt),ie=Math.sin(tt),Nt=[kt[0]+_t*dt[0]-ie*dt[1],kt[1]+ie*dt[0]+_t*dt[1],kt[2]+dt[2]];p.push({key:`${e}:${b.gid}:shape`,attrs:X,at:Nt,rotationDeg:(tt+U.turn)*180/Math.PI});continue}const Bt=`${P}|${at.map(U=>`${U.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${U.t.join(",")}`).join("|")}`,Gt=st.join("|");let jt=a.get(Gt)??a.get(Bt);if(jt&&(a.set(Gt,jt),a.set(Bt,jt)),!jt){const U=qo(b.typeName??b.objectType??b.name??b.ifcClass),Z=(l.get(U.toLowerCase())??0)+1;l.set(U.toLowerCase(),Z);const B=Z===1?U:`${U} (${Z})`;jt={family:B,type:B,first:!0,key:Go(Bt)},a.set(Bt,jt),a.set(Gt,jt)}const Kt={ShapeCategory:P,Family:jt.family,Type:jt.type,ShapeKey:jt.key,...te?{ColumnFree:"1"}:{}};jt.first&&(Kt.Shape=JSON.stringify({pieces:at}),jt.first=!1);const Yt=b.host?r.get(b.host):void 0,zt=b.opening?s.elements.get(b.opening):void 0;if(Yt&&zt){const U=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const B of zt.pieces){const ut=s.geometries.get(B.geometry);if(!ut)continue;const X=B.matrix;for(let dt=0;dt<ut.verts.length;dt+=3){const Mt=ut.verts[dt],rt=ut.verts[dt+1],_t=ut.verts[dt+2],ie=Wt([X[0]*Mt+X[4]*rt+X[8]*_t+X[12],X[1]*Mt+X[5]*rt+X[9]*_t+X[13],X[2]*Mt+X[6]*rt+X[10]*_t+X[14]]);for(let Nt=0;Nt<3;Nt++)U[Nt]=Math.min(U[Nt],ie[Nt]*Ce),Z[Nt]=Math.max(Z[Nt],ie[Nt]*Ce)}}{const B=ei(s,zt.gid).flatMap(dt=>dt.pts).map(dt=>Wt(dt).map(Mt=>Mt*Ce)),ut=new Map;for(const dt of B){const Mt=Math.round(dt[1]*200);ut.set(Mt,[...ut.get(Mt)??[],dt])}let X=null;for(const dt of ut.values()){if(dt.length<4)continue;const Mt=[Math.min(...dt.map(rt=>rt[0])),Math.max(...dt.map(rt=>rt[0])),Math.min(...dt.map(rt=>rt[2])),Math.max(...dt.map(rt=>rt[2]))];Mt[1]-Mt[0]<.1||Mt[3]-Mt[2]<.1||(!X||(Mt[1]-Mt[0])*(Mt[3]-Mt[2])<(X[1]-X[0])*(X[3]-X[2])-1e-6)&&(X=Mt)}if(X&&ut.size>2&&(U[0]=X[0],Z[0]=X[1],U[2]=X[2],Z[2]=X[3]),X&&ut.size>2){const dt=[...ut.entries()].sort((rt,_t)=>rt[0]-_t[0]).map(([,rt])=>({y:rt[0][1],r:[Math.min(...rt.map(_t=>_t[0])),Math.max(...rt.map(_t=>_t[0])),Math.min(...rt.map(_t=>_t[2])),Math.max(...rt.map(_t=>_t[2]))]})),Mt=[];for(let rt=0;rt+1<dt.length;rt++){const _t=dt[rt].r,ie=dt[rt+1].r,Nt=[Math.max(_t[0],ie[0]),Math.min(_t[1],ie[1]),Math.max(_t[2],ie[2]),Math.min(_t[3],ie[3])];Nt[1]-Nt[0]<.1||Nt[3]-Nt[2]<.1||dt[rt+1].y-dt[rt].y<.01||(Nt[0]<X[0]-.016||Nt[1]>X[1]+.016||Nt[2]<X[2]-.016||Nt[3]>X[3]+.016)&&Mt.push([Nt[0],dt[rt].y,Nt[2],Nt[1],dt[rt+1].y,Nt[3]].map(le=>Oe(le,1e-5)))}Mt.length&&(Kt.OpeningSteps=JSON.stringify(Mt)),typeof process<"u"&&((d=process.env)!=null&&d.RECIPE_TRACE)&&console.error(`[opening-steps] ${b.gid}: ${dt.length} planes, narrowest ${JSON.stringify(X.map(rt=>+rt.toFixed(3)))}, steps ${JSON.stringify(Mt)}`)}}if(Number.isFinite(U[0])&&(Kt.Opening=[...U,...Z].map(B=>Oe(B,1e-5)).join(",")),typeof process<"u"&&((c=process.env)!=null&&c.RECIPE_CUT_LOST)&&b.host&&Number.isFinite(U[0])){const B=ei(s,zt.gid).flatMap(X=>X.pts),ut=Qt(s,b.host);if(B.length&&ut.length){const X=[0,1,2].map(_t=>Math.min(...B.map(ie=>ie[_t]))-.01),dt=[0,1,2].map(_t=>Math.max(...B.map(ie=>ie[_t]))+.01),Mt=Math.min(...ut.map(_t=>_t[2]))+.01,rt=ut.filter(_t=>_t[0]>X[0]&&_t[0]<dt[0]&&_t[1]>X[1]&&_t[1]<dt[1]&&_t[2]>Math.max(X[2],Mt)&&_t[2]<dt[2]).length;rt>=4&&(Kt.CutIfLost="1"),(E=process.env)!=null&&E.RECIPE_TRACE&&console.error(`[cut-if-lost] ${b.gid}: ${rt} of its wall's corners in its opening → ${rt>=4?"cut":"not"}`)}}}p.push({key:`${e}:${b.gid}:shape`,attrs:Kt,at:[kt[0],kt[1],kt[2]],rotationDeg:tt*180/Math.PI,...Yt?{host:Yt}:{}})}return p}function qo(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Go(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 jl(s,t,e){var r,a;const n=new Map;for(const l of t){const[,p,d]=l.split(":");p&&/^run/.test(d??"")&&!n.has(p)&&n.set(p,l)}const i=[];for(const l of s.elements.values()){if(l.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!l.host)continue;const p=n.get(l.host),d=typeof process<"u"&&((r=process.env)==null?void 0:r.RECIPE_TRACE);if(!p){d&&console.error(`[opening] ${l.gid}: its wall ${l.host} not written as a run`);continue}for(const c of ei(s,l.gid)){const E=c.pts;if(E.length<4)continue;const b=ql(Qt(s,l.host));if(!b)continue;const $=E.map(D=>(D[0]-b.a[0])*b.u[0]+(D[1]-b.a[1])*b.u[1]),P=E.map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]),k=D=>Math.max(...D)-Math.min(...D),W=k($)*k(P)*k(E.map(D=>D[2]));if(!(W>0)||Math.abs(c.volume)<.75*W){d&&console.error(`[opening] ${l.gid}: not a box (${c.volume.toFixed(3)} of ${W.toFixed(3)}: ${k($).toFixed(3)} along ${k(P).toFixed(3)} across ${k(E.map(D=>D[2])).toFixed(3)} up, axis ${JSON.stringify(b.u.map(D=>+D.toFixed(3)))})`);continue}const V=Qt(s,l.host).map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]);if(V.length&&(Math.min(...P)>Math.min(...V)+.005||Math.max(...P)<Math.max(...V)-.005)){d&&console.error(`[opening] ${l.gid}: not through its wall (across ${Math.min(...P).toFixed(3)}..${Math.max(...P).toFixed(3)}, its wall ${Math.min(...V).toFixed(3)}..${Math.max(...V).toFixed(3)})`);continue}d&&((a=process.env)==null?void 0:a.RECIPE_GID)===l.gid&&console.error(`[opening] ${l.gid} part ${c.index}/${c.of}: a box (${c.volume.toFixed(4)} of ${W.toFixed(4)}: ${k($).toFixed(3)} along ${k(P).toFixed(3)} across ${k(E.map(D=>D[2])).toFixed(3)} up, ${E.length} points)`),i.push({key:`${e}:${l.gid}:opening${c.index===0&&c.of===1?"":`#${c.index}`}`,host:p,box:E.flat()})}}return i}function Dl(s){const t=s.loops.flat(),e=[t.reduce((b,$)=>b+$[0],0)/t.length,t.reduce((b,$)=>b+$[1],0)/t.length],n=s.loops.map(b=>{const $=b.map(([f,Tt])=>[f-e[0],Tt-e[1]]),P=$.map(([f,Tt])=>Math.hypot(f,Tt)),k=P.reduce((f,Tt)=>f+Tt,0)/P.length;if($.length<8||k<=0||P.some(f=>Math.abs(f-k)>.02*k))return $;const W=2*Math.PI/$.length;for(let f=0;f<$.length;f++){const Tt=Math.atan2($[f][1],$[f][0]),nt=Math.atan2($[(f+1)%$.length][1],$[(f+1)%$.length][0]),wt=Math.abs(Math.atan2(Math.sin(nt-Tt),Math.cos(nt-Tt)));if(Math.abs(wt-W)>.1*W)return $}const D=$.reduce((f,Tt,nt)=>{const wt=$[(nt+1)%$.length];return f+Tt[0]*wt[1]-wt[0]*Tt[1]},0)>=0?1:-1;return $.map((f,Tt)=>[k*Math.cos(D*2*Math.PI*Tt/$.length),k*Math.sin(D*2*Math.PI*Tt/$.length)])}),i=b=>b.map(P=>{const k=P.map(([V,D])=>`${Math.round(V*304.8)},${Math.round(D*304.8)}`);let W=0;for(let V=1;V<k.length;V++)k[V]<k[W]&&(W=V);return[...k.slice(W),...k.slice(0,W)].join(";")}).sort().join("|"),r=(b,$)=>{const P=Math.cos(-$),k=Math.sin(-$);return b.map(W=>W.map(([V,D])=>[P*V-k*D,k*V+P*D]))},a=[];let l=s.axis,p=0,d=n;if(l===1&&(l=0,p=Math.PI/2,d=n.map(b=>b.map(([$,P])=>[-P,$]))),l===2){let b=0,$=0,P=0;const k=n.flat();for(const[nt,wt]of k)b+=nt*nt,$+=wt*wt,P+=nt*wt;const W=new Set,V=.5*Math.atan2(2*P,b-$);for(let nt=0;nt<4;nt++)W.add(V+nt*Math.PI/2);const D=k.map(([nt,wt])=>Math.hypot(nt,wt)),f=Math.max(...D),Tt=k.filter((nt,wt)=>D[wt]>f-.003);if(Math.abs(b-$)<.001*(b+$)||Tt.length>4)for(const[nt,wt]of Tt.slice(0,64))W.add(Math.atan2(wt,nt));for(const nt of W)a.push({loops:r(n,nt),turn:nt,flipped:!1})}else a.push({loops:d,turn:0,flipped:!1}),a.push({loops:d.map(b=>b.map(([$,P])=>[-$,P]).reverse()),turn:Math.PI,flipped:!0});let c=a[0],E=i(c.loops);for(const b of a.slice(1)){const $=i(b.loops);$<E&&(c=b,E=$)}return{axis:l,loops:c.loops,key:E,centre:e,turn:p+c.turn,flipped:c.flipped}}function Ul(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(i=>{let r=1/0,a=-1/0;for(let l=0;l<e;l++){const p=s.v[l*3+i];r=Math.min(r,p),a=Math.max(a,p)}return a-r});for(const i of[0,1,2].sort((r,a)=>n[a]-n[r])){let r=1/0,a=-1/0;for(let tt=0;tt<e;tt++){const ct=s.v[tt*3+i];r=Math.min(r,ct),a=Math.max(a,ct)}if(a-r<.01)continue;let l=!0;for(let tt=0;tt<e&&l;tt++){const ct=s.v[tt*3+i];Math.abs(ct-r)>.001&&Math.abs(ct-a)>.001&&(l=!1)}if(!l)continue;const p=(i+1)%3,d=(i+2)%3,c=new Map,E=[],b=tt=>{const ct=[s.v[tt*3+p],s.v[tt*3+d]],ht=`${Math.round(ct[0]*3048)},${Math.round(ct[1]*3048)}`;return c.has(ht)||(c.set(ht,E.length),E.push(ct)),c.get(ht)},$=[];for(let tt=0;tt+2<s.t.length;tt+=3){const ct=[s.t[tt],s.t[tt+1],s.t[tt+2]];if(!ct.every(kt=>Math.abs(s.v[kt*3+i]-r)<=.001))continue;const ht=ct.map(b);ht[0]===ht[1]||ht[1]===ht[2]||ht[0]===ht[2]||$.push(ht)}if($.length===0)continue;const P=(tt,ct)=>{const[ht,kt]=[E[tt],E[ct]],te=[kt[0]-ht[0],kt[1]-ht[1]],Wt=te[0]*te[0]+te[1]*te[1],at=[];if(E.length<=3e3)for(let st=0;st<E.length;st++){if(st===tt||st===ct)continue;const pt=((E[st][0]-ht[0])*te[0]+(E[st][1]-ht[1])*te[1])/Wt;if(pt<=1e-6||pt>=1-1e-6)continue;Math.abs((E[st][0]-ht[0])*te[1]-(E[st][1]-ht[1])*te[0])/Math.sqrt(Wt)<3e-4&&at.push({t:pt,id:st})}return[tt,...at.sort((st,pt)=>st.t-pt.t).map(st=>st.id),ct]},k=[];for(const tt of $)for(let ct=0;ct<3;ct++){const ht=P(tt[ct],tt[(ct+1)%3]);for(let kt=0;kt+1<ht.length;kt++)k.push([ht[kt],ht[kt+1]])}const W=new Map;for(const[tt,ct]of k){const ht=tt<ct?`${tt},${ct}`:`${ct},${tt}`;W.set(ht,(W.get(ht)??0)+1)}const V=new Map;for(const[tt,ct]of k)W.get(tt<ct?`${tt},${ct}`:`${ct},${tt}`)===1&&V.set(tt,[...V.get(tt)??[],ct]);if([...V.values()].some(tt=>tt.length!==1))continue;const D=[],f=new Set(V.keys());for(;f.size;){const tt=f.values().next().value,ct=[];let ht=tt,kt=0;do ct.push(E[ht]),f.delete(ht),ht=V.get(ht)[0];while(ht!==tt&&kt++<1e5&&V.has(ht));if(ht!==tt||ct.length<3){D.length=0;break}const te=ct.filter((Wt,at)=>{const st=ct[(at-1+ct.length)%ct.length],pt=ct[(at+1)%ct.length];return Math.abs((Wt[0]-st[0])*(pt[1]-st[1])-(Wt[1]-st[1])*(pt[0]-st[0]))>1e-7});D.push(te.map(([Wt,at])=>[Oe(Wt,1e-5),Oe(at,1e-5)]))}if(D.length===0||D.some(tt=>tt.length<3))continue;const Tt=tt=>{const ct=new Set;for(let ht=0;ht<e;ht++)Math.abs(s.v[ht*3+i]-tt)<=.001&&ct.add(`${Math.round(s.v[ht*3+p]*304.8)},${Math.round(s.v[ht*3+d]*304.8)}`);return ct},nt=(tt,ct)=>{const[ht,kt]=ct.split(",").map(Number);for(let te=-1;te<=1;te++)for(let Wt=-1;Wt<=1;Wt++)if(tt.has(`${ht+te},${kt+Wt}`))return!0;return!1},wt=Tt(r),Pt=Tt(a);if(!(Pt.size<3||[...wt].some(tt=>!nt(Pt,tt))||[...Pt].some(tt=>!nt(wt,tt))))return{axis:i,from:r,length:a-r,loops:D}}return null}function Jl(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let i=1/0,r=-1/0;const a=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const E=d.matrix,b=$=>{const P=c.verts[$*3],k=c.verts[$*3+1],W=c.verts[$*3+2];return[E[0]*P+E[4]*k+E[8]*W+E[12],E[1]*P+E[5]*k+E[9]*W+E[13],E[2]*P+E[6]*k+E[10]*W+E[14]]};for(let $=0;$+2<c.tris.length;$+=3){const P=[b(c.tris[$]),b(c.tris[$+1]),b(c.tris[$+2])];for(const k of P)i=Math.min(i,k[2]),r=Math.max(r,k[2]);a.push(P)}}if(!Number.isFinite(i)||r-i<.1)continue;let l=null,p=0;for(const d of a){if(!d.every(E=>Math.abs(E[2]-i)<.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>p&&(p=c,l=d)}l&&e.push({key:`${t}:${n.gid}:room`,at:[(l[0][0]+l[1][0]+l[2][0])/3,(l[0][1]+l[1][1]+l[2][1])/3,i],height:r-i,number:n.name??"",name:n.longName??n.name??""})}return e}function ql(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const d of s){const c=Math.hypot(d[0]-s[0][0],d[1]-s[0][1]);c>n&&(n=c,e=d)}n=0;for(const d of s){const c=Math.hypot(d[0]-e[0],d[1]-e[1]);c>n&&(n=c,t=d)}if(n<.1)return;const i=[...new Map(s.map(d=>[`${Math.round(d[0]*1e3)},${Math.round(d[1]*1e3)}`,[d[0],d[1]]])).values()].sort((d,c)=>d[0]-c[0]||d[1]-c[1]),r=(d,c,E)=>(c[0]-d[0])*(E[1]-d[1])-(c[1]-d[1])*(E[0]-d[0]),a=d=>{const c=[];for(const E of d){for(;c.length>=2&&r(c[c.length-2],c[c.length-1],E)<=0;)c.pop();c.push(E)}return c.pop(),c},l=i.length>=3?[...a(i),...a([...i].reverse())]:i;let p;for(let d=0;d<l.length;d++){const c=l[d],E=l[(d+1)%l.length],b=Math.hypot(E[0]-c[0],E[1]-c[1]);if(b<.001)continue;const $=[(E[0]-c[0])/b,(E[1]-c[1])/b],P=l.map(f=>f[0]*$[0]+f[1]*$[1]),k=l.map(f=>-f[0]*$[1]+f[1]*$[0]),W=Math.max(...P)-Math.min(...P),V=Math.max(...k)-Math.min(...k),D=W*V;(!p||D<p.area-1e-9)&&(p={area:D,u:W>=V?$:[-$[1],$[0]]})}if(p){const d=p.u;return d[0]*(e[0]-t[0])+d[1]*(e[1]-t[1])<0&&(d[0]=-d[0],d[1]=-d[1]),{a:t,u:d}}return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function ei(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],i=[],r=new Map;for(const c of e.pieces){const E=s.geometries.get(c.geometry);if(!E)continue;const b=c.matrix,$=[];for(let P=0;P<E.verts.length;P+=3){const k=E.verts[P],W=E.verts[P+1],V=E.verts[P+2],D=[b[0]*k+b[4]*W+b[8]*V+b[12],b[1]*k+b[5]*W+b[9]*V+b[13],b[2]*k+b[6]*W+b[10]*V+b[14]],f=D.map(nt=>Math.round(nt*1e4)).join(",");let Tt=r.get(f);Tt===void 0&&(Tt=n.length,r.set(f,Tt),n.push(D)),$.push(Tt)}for(let P=0;P+2<E.tris.length;P+=3)i.push($[E.tris[P]],$[E.tris[P+1]],$[E.tris[P+2]])}const a=n.map((c,E)=>E),l=c=>{for(;a[c]!==c;)a[c]=a[a[c]],c=a[c];return c};for(let c=0;c<i.length;c+=3){const E=l(i[c]);a[l(i[c+1])]=E,a[l(i[c+2])]=E}const p=new Map;for(let c=0;c<i.length;c+=3){const E=l(i[c]);let b=p.get(E);b||(b={pts:new Set,volume:0},p.set(E,b));const[$,P,k]=[n[i[c]],n[i[c+1]],n[i[c+2]]];b.volume+=An($,rn(P,k))/6,b.pts.add(i[c]),b.pts.add(i[c+1]),b.pts.add(i[c+2])}const d=[...p.values()];return d.map((c,E)=>({pts:[...c.pts].map(b=>n[b]),volume:c.volume,index:E,of:d.length}))}function Gl(s,t,e,n,i,r){const a=s.elements.get(t);if(!a)return null;const l=E=>(E[0]-e[0])*n[0]+(E[1]-e[1])*n[1],p=E=>-(E[0]-e[0])*n[1]+(E[1]-e[1])*n[0];let d=1/0,c=-1/0;for(const E of a.pieces){const b=s.geometries.get(E.geometry);if(!b)continue;const $=E.matrix,P=k=>{const W=b.verts[k*3],V=b.verts[k*3+1],D=b.verts[k*3+2];return[$[0]*W+$[4]*V+$[8]*D+$[12],$[1]*W+$[5]*V+$[9]*D+$[13],$[2]*W+$[6]*V+$[10]*D+$[14]]};for(let k=0;k+2<b.tris.length;k+=3){const W=[P(b.tris[k]),P(b.tris[k+1]),P(b.tris[k+2])],V=[];for(let nt=0;nt<3;nt++){const wt=W[nt],Pt=W[(nt+1)%3],tt=l(wt)-i,ct=l(Pt)-i;if(tt<0==ct<0||tt===ct)continue;const ht=tt/(tt-ct);V.push([p(wt)+ht*(p(Pt)-p(wt)),wt[2]+ht*(Pt[2]-wt[2])])}if(V.length!==2)continue;const[D,f]=V;if((D[1]-r)*(f[1]-r)>0||D[1]===f[1])continue;const Tt=D[0]+(r-D[1])/(f[1]-D[1])*(f[0]-D[0]);d=Math.min(d,Tt),c=Math.max(c,Tt)}}return Number.isFinite(d)?{lo:d,hi:c}:null}function Qt(s,t,e){const n=s.elements.get(t),i=[];if(!n)return i;for(const r of e===void 0?n.pieces:[n.pieces[e]]){const a=s.geometries.get(r.geometry);if(!a)continue;const l=r.matrix;for(let p=0;p<a.verts.length;p+=3){const d=a.verts[p],c=a.verts[p+1],E=a.verts[p+2];i.push([l[0]*d+l[4]*c+l[8]*E+l[12],l[1]*d+l[5]*c+l[9]*E+l[13],l[2]*d+l[6]*c+l[10]*E+l[14]])}}return i}function Hl(s,t,e,n){var r;const i=[];for(const a of s.elements.values()){if(a.parent!==t||!/^IFC(PLATE|COVERING|BUILDINGELEMENTPROXY)$/i.test(a.ifcClass)||a.pieces.length===0)continue;const l=Qt(s,a.gid);if(l.length===0)continue;let p=0;for(const b of a.pieces)p+=(((r=s.geometries.get(b.geometry))==null?void 0:r.tris.length)??0)/3;const d=[1/0,1/0,1/0],c=[-1/0,-1/0,-1/0];for(const b of l)for(let $=0;$<3;$++)d[$]=Math.min(d[$],b[$]),c[$]=Math.max(c[$],b[$]);const E=a.pieces.length===1&&p<=12;if(E&&n){const b=s.geometries.get(a.pieces[0].geometry),$=a.pieces[0].matrix;let P=0,k=null;if(b)for(let W=0;W+2<b.tris.length;W+=3){const V=Pt=>{const tt=b.verts[Pt*3],ct=b.verts[Pt*3+1],ht=b.verts[Pt*3+2];return[$[0]*tt+$[4]*ct+$[8]*ht,$[1]*tt+$[5]*ct+$[9]*ht,$[2]*tt+$[6]*ct+$[10]*ht]},D=V(b.tris[W]),f=V(b.tris[W+1]),Tt=V(b.tris[W+2]),nt=rn([f[0]-D[0],f[1]-D[1],f[2]-D[2]],[Tt[0]-D[0],Tt[1]-D[1],Tt[2]-D[2]]),wt=Math.hypot(nt[0],nt[1],nt[2]);wt>P&&(P=wt,k=nt.map(Pt=>Pt/wt))}if(k&&Math.abs(k[0]*n[0]+k[1]*n[1])<.996){i.push({gid:a.gid,centre:[(d[0]+c[0])/2,(d[1]+c[1])/2,(d[2]+c[2])/2]});continue}}E||i.push({gid:a.gid,centre:[(d[0]+c[0])/2,(d[1]+c[1])/2,(d[2]+c[2])/2]})}return i}function Ss(s,t,e,n,i=!1){const r=s.elements.get(t);if(!r)return null;const a=Math.hypot(n[0]-e[0],n[1]-e[1]);if(!(a>.1))return null;const l=[(n[0]-e[0])/a,(n[1]-e[1])/a],p=[-l[1],l[0]],d=[];for(const at of r.pieces){const st=s.geometries.get(at.geometry);if(!st)continue;const pt=at.matrix,Bt=Gt=>{const jt=st.verts[Gt*3],Kt=st.verts[Gt*3+1],Yt=st.verts[Gt*3+2];return[pt[0]*jt+pt[4]*Kt+pt[8]*Yt+pt[12],pt[1]*jt+pt[5]*Kt+pt[9]*Yt+pt[13],pt[2]*jt+pt[6]*Kt+pt[10]*Yt+pt[14]]};for(let Gt=0;Gt+2<st.tris.length;Gt+=3){const jt=Bt(st.tris[Gt]),Kt=Bt(st.tris[Gt+1]),Yt=Bt(st.tris[Gt+2]),zt=rn([Kt[0]-jt[0],Kt[1]-jt[1],Kt[2]-jt[2]],[Yt[0]-jt[0],Yt[1]-jt[1],Yt[2]-jt[2]]),U=Math.hypot(zt[0],zt[1],zt[2]);if(U<1e-9||Math.abs((zt[0]*p[0]+zt[1]*p[1])/U)<.995)continue;const Z=((jt[0]+Kt[0]+Yt[0])/3-e[0])*p[0]+((jt[1]+Kt[1]+Yt[1])/3-e[1])*p[1];d.push({a:jt,b:Kt,c:Yt,across:Z})}}if(d.length<2)return null;const c=at=>{const st=(at[0]-e[0])*l[0]+(at[1]-e[1])*l[1];return`${Math.round(st*1e3)},${Math.round(at[2]*1e3)}`},E=at=>at.split(",").map(st=>Number(st)/1e3),b=at=>{const st=new Map,pt=(zt,U)=>zt<U?`${zt}|${U}`:`${U}|${zt}`;for(const zt of at){const U=[c(zt.a),c(zt.b),c(zt.c)];for(let Z=0;Z<3;Z++){const B=U[Z],ut=U[(Z+1)%3];if(B===ut)continue;const X=pt(B,ut);st.set(X,(st.get(X)??0)+1)}}const Bt=new Map;for(const[zt,U]of st){if(U!==1)continue;const[Z,B]=zt.split("|");(Bt.get(Z)??Bt.set(Z,[]).get(Z)).push(B),(Bt.get(B)??Bt.set(B,[]).get(B)).push(Z)}if(Bt.size<3||Bt.size>4e3)return null;const Gt=new Set;let jt=null,Kt=0;const Yt=[];for(const zt of Bt.keys()){if(Gt.has(zt))continue;const U=[zt];Gt.add(zt);let Z="",B=zt;for(let dt=0;dt<5e3;dt++){const Mt=(Bt.get(B)??[]).find(rt=>rt!==Z&&!Gt.has(rt))??null;if(!Mt)break;U.push(Mt),Gt.add(Mt),Z=B,B=Mt}if(U.length<3)continue;const ut=U.map(E);let X=0;for(let dt=0;dt<ut.length;dt++){const Mt=ut[dt],rt=ut[(dt+1)%ut.length];X+=Mt[0]*rt[1]-rt[0]*Mt[1]}Yt.push({pts:ut,area:Math.abs(X)/2}),Math.abs(X)/2>Kt&&(Kt=Math.abs(X)/2,jt=ut)}return jt?{best:jt,bestArea:Kt,allLoops:Yt}:null},$=Math.max(...d.map(at=>at.across));let P=b(d.filter(at=>at.across>$-.005));const k=[...new Set(d.map(at=>Math.round(at.across*200)))].map(at=>at/200);if(k.length>1&&k.length<=24)for(const at of k){if(Math.abs(at-$)<.005)continue;const st=b(d.filter(pt=>Math.abs(pt.across-at)<.0025));st&&P&&st.bestArea>P.bestArea*1.2&&(P=st)}if(!P)return null;const{best:W,allLoops:V}=P;if(!W||W.length<3)return null;const D=Math.min(...W.map(at=>at[0])),f=Math.max(...W.map(at=>at[0])),Tt=Math.min(...W.map(at=>at[1])),nt=Math.max(...W.map(at=>at[1]));if(!(f-D>.1)||!(nt-Tt>.1))return null;if(i){const at=W.filter((U,Z,B)=>{const ut=B[(Z-1+B.length)%B.length],X=B[(Z+1)%B.length];return Math.abs((X[0]-ut[0])*(U[1]-ut[1])-(X[1]-ut[1])*(U[0]-ut[0]))>1e-4*Math.hypot(X[0]-ut[0],X[1]-ut[1])}),st=(U,Z)=>{let B=!1;for(let ut=0,X=Z.length-1;ut<Z.length;X=ut++)Z[ut][1]>U[1]!=Z[X][1]>U[1]&&U[0]<(Z[X][0]-Z[ut][0])*(U[1]-Z[ut][1])/(Z[X][1]-Z[ut][1])+Z[ut][0]&&(B=!B);return B},pt=U=>[U.reduce((Z,B)=>Z+B[0],0)/U.length,U.reduce((Z,B)=>Z+B[1],0)/U.length],Bt=V.filter(U=>U.pts!==W&&U.area>=.01&&U.pts.length<=200&&(U.area>=.1||!st(pt(U.pts),W))).map(U=>U.pts),Gt=Bt.filter(U=>!st(pt(U),W)),jt=U=>{let Z=0;for(let B=0;B<U.length;B++){const ut=U[B],X=U[(B+1)%U.length];Z+=ut[0]*X[1]-X[0]*ut[1]}return Math.abs(Z)/2},Kt=$-Math.min(...d.map(U=>U.across));let Yt=0;for(const U of r.pieces){const Z=s.geometries.get(U.geometry);if(!Z)continue;const B=U.matrix,ut=X=>{const dt=Z.verts[X*3],Mt=Z.verts[X*3+1],rt=Z.verts[X*3+2];return[B[0]*dt+B[4]*Mt+B[8]*rt+B[12],B[1]*dt+B[5]*Mt+B[9]*rt+B[13],B[2]*dt+B[6]*Mt+B[10]*rt+B[14]]};for(let X=0;X+2<Z.tris.length;X+=3){const dt=ut(Z.tris[X]),Mt=ut(Z.tris[X+1]),rt=ut(Z.tris[X+2]);Yt+=(dt[0]*(Mt[1]*rt[2]-Mt[2]*rt[1])-dt[1]*(Mt[0]*rt[2]-Mt[2]*rt[0])+dt[2]*(Mt[0]*rt[1]-Mt[1]*rt[0]))/6}}const zt=(jt(at)-Bt.filter(U=>!Gt.includes(U)).reduce((U,Z)=>U+jt(Z),0)+Gt.reduce((U,Z)=>U+jt(Z),0))*Kt;return Kt>.01&&Math.abs(Yt)>1e-6&&Math.abs(zt-Math.abs(Yt))>.15*Math.abs(Yt)?null:Gt.length?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:Bt.filter(U=>!Gt.includes(U)),pieces:Gt}:(at.length>4||Bt.length)&&at.length<=200?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:Bt}:null}const wt=at=>W.map((st,pt)=>({p:st,i:pt})).filter(({p:st})=>Math.abs(st[0]-at)<.003).sort((st,pt)=>pt.p[1]-st.p[1])[0],Pt=wt(D),tt=wt(f);if(!Pt||!tt)return null;const ct=at=>{const st=[];for(let pt=Pt.i,Bt=0;Bt<=W.length;pt=(pt+at+W.length)%W.length,Bt++)if(st.push(W[pt]),pt===tt.i)return st;return null},ht=ct(1),kt=ct(-1),te=at=>at?at.reduce((st,pt)=>st+pt[1],0)/at.length:-1/0;let Wt=te(ht)>=te(kt)?ht:kt;if(!Wt||Wt.length<2||(Wt=Wt.filter((at,st,pt)=>{if(st===0||st===pt.length-1)return!0;const Bt=pt[st-1],Gt=pt[st+1];return Math.abs((Gt[0]-Bt[0])*(at[1]-Bt[1])-(Gt[1]-Bt[1])*(at[0]-Bt[0]))>1e-4*Math.hypot(Gt[0]-Bt[0],Gt[1]-Bt[1])}),Wt.every(at=>Math.abs(at[1]-nt)<.005)))return null;for(let at=1;at<Wt.length;at++)if(Wt[at][0]<Wt[at-1][0]-.003)return null;return Wt.length>200?null:{lo:D,hi:f,bottom:Tt,chain:Wt}}function Vl(s,t,e){const n=Qt(s,t);if(n.length<4||e.length===0)return;let i=n[0],r=n[0],a=0;for(const V of n){const D=Math.hypot(V[0]-n[0][0],V[1]-n[0][1]);D>a&&(a=D,r=V)}a=0;for(const V of n){const D=Math.hypot(V[0]-r[0],V[1]-r[1]);D>a&&(a=D,i=V)}if(a<.3)return;const l=(r[0]-i[0])/a,p=(r[1]-i[1])/a,d=V=>(V[0]-i[0])*l+(V[1]-i[1])*p,c=Math.max(...n.map(V=>V[2])),E=V=>Math.max(...n.filter(D=>Math.abs(d(D)-V)<.05).map(D=>D[2]),-1/0),b=E(0),$=E(a);if(Math.abs(b-$)<.05&&c-Math.max(b,$)<.05)return;const P=(i[0]+r[0])/2,k=(i[1]+r[1])/2;let W;for(const V of e){const D=Qt(s,V.gid);if(D.length===0)continue;const f=D.map(Pt=>Pt[0]),Tt=D.map(Pt=>Pt[1]),nt=D.map(Pt=>Pt[2]);if(P<Math.min(...f)-.2||P>Math.max(...f)+.2||k<Math.min(...Tt)-.2||k>Math.max(...Tt)+.2)continue;const wt=Math.min(...nt)-c;wt>1.5||Math.max(...nt)<c-.05||(!W||Math.abs(wt)<Math.abs(W.gap))&&(W={id:V.id,gap:wt})}return W==null?void 0:W.id}const De={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function xn(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 i=t.slice(e+1,n).trim();return i?{family:t.slice(0,e).trim(),type:i}:null}function Ho(s){const t=xn(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 Vo=180/Math.PI;function zo(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 Ct=s=>String(s);function zl(s){const t=s.slice(),e=(n,i,r)=>Math.abs((i[0]-n[0])*(r[1]-n[1])-(r[0]-n[0])*(i[1]-n[1]))/2;for(let n=!0;n&&t.length>3;){n=!1;for(let i=0;i<t.length&&t.length>3;i++){const r=t[(i-1+t.length)%t.length],a=t[i],l=t[(i+1)%t.length],p=Math.min(Math.hypot(a[0]-r[0],a[1]-r[1]),Math.hypot(l[0]-a[0],l[1]-a[1]))<.02;(e(r,a,l)<1e-8||p&&e(r,a,l)<2e-4)&&(t.splice(i,1),n=!0,i--)}}return t}function Ua(s){return async t=>{var Ri,Oi,ki,Ni,Fi,Pi,Li,Bi,ji,Di,Ui,Ji,qi,Gi,Hi,Vi,zi,Wi,Yi,Ki,Xi,Zi,Qi,tr,er,nr,sr,ir,rr,or,ar,cr,lr,hr,fr,dr,ur,pr,mr,gr,yr,wr,br,vr,Er,Tr,Mr,$r,Ir,Sr,xr,_r,Ar,Cr,Rr,Or,kr,Nr,Fr,Pr,Lr,Br,jr,Dr,Ur,Jr,qr,Gr,Hr,Vr,zr,Wr,Yr,Kr,Xr,Zr,Qr,to,eo,no,so,io,ro,oo,ao,co,lo,ho,fo,uo,po,mo,go,yo,wo,bo,vo,Eo,To,Mo,$o;const{picked:e,contents:n,site:i,shapes:r}=await mi(t,t.input),a=$a(n.items),l=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),p=l&&i?[i.east*sn,i.north*sn,i.elevation*sn,i.angleDeg].map(o=>o.toFixed(6)).join(","):void 0;if(a.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:E}=t.settings,b=t.settings.createLevels!==!1;if(E&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const $=ui(a),P=Ia(a);if(typeof process<"u"&&((Ri=process.env)!=null&&Ri.RECIPE_STYLE))for(const[o,h]of P)o.includes(process.env.RECIPE_STYLE)&&console.error(`[style] ${o}: ${JSON.stringify(h).slice(0,1500)}`);const k=`recipe:${s}-to-revit`,W=new Map,V=pi(t,W);t.progress("Writing the changes for Revit");const D=new fs({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:k}),f=sn,Tt=new Map;{const o=new Map;for(const h of a){const w=h.item.guid;if(!w)continue;const m=`${w}:${h.kind}`,F=o.get(m)??0;o.set(m,F+1),Tt.set(h.id,`${e.fileId}:${m}${F?`:${F}`:""}`)}}const nt=o=>Tt.get(o)??`${e.fileId}:${o}`,wt=new Set,Pt=new Set;let tt=0,ct=0;const ht=Array.isArray(t.settings.focus)?new Set(t.settings.focus):null,kt=[],te=()=>{var R;if(!ht)return;const o=O=>O?O.split(":")[1]:void 0,h=new Set,w=O=>(O.LocationLine??"").split(";").map(q=>q.split(",").map(Number)).filter(q=>q.length>=2&&q.every(Number.isFinite)),m=O=>{h.has(O)||(h.add(O),F=!0)};let F=!0;kt.forEach((O,q)=>{ht.has(o(O.sourceKey)??"")&&m(q)});for(let O=0;F&&O<2;O++){F=!1;const q=new Set([...h].map($t=>`${kt[$t].attrs.CategoryId}|${kt[$t].attrs.Type??""}`)),u=new Set([...h].map($t=>o(kt[$t].sourceKey))),x=new Set([...h].map($t=>kt[$t].sourceKey)),gt=[...h].flatMap($t=>w(kt[$t].attrs));kt.forEach(($t,Rt)=>{var yt;if(h.has(Rt))return;const It=$t.attrs;if(It.Type&&q.has(`${It.CategoryId}|${It.Type}`)||(yt=$t.placement)!=null&&yt.host&&(x.has($t.placement.host)||u.has(o($t.placement.host)))||It.AttachTop&&x.has(It.AttachTop)||It.CutBy&&It.CutBy.split("|").some(A=>x.has(A))||O===0&&w(It).some(A=>gt.some(Ot=>Math.hypot(A[0]-Ot[0],A[1]-Ot[1])<1)))return m(Rt)});for(const $t of[...h]){const Rt=(R=kt[$t].placement)==null?void 0:R.host,It=kt[$t].attrs.AttachTop,yt=(kt[$t].attrs.CutBy??"").split("|");kt.forEach((A,Ot)=>{(A.sourceKey===Rt||A.sourceKey===It||yt.includes(A.sourceKey))&&m(Ot)})}}kt.forEach((O,q)=>{/^[0-9A-Za-z_$]{22}$/.test(o(O.sourceKey)??"")||h.add(q)});for(const O of[...h].sort((q,u)=>q-u))D.add(kt[O].attrs,{...kt[O].placement,source:kt[O].sourceKey});typeof process<"u"&&console.error(`[focus] ${ht.size} asked, ${h.size} of ${kt.length} change(s) written`)},Wt=(o,h,w)=>{if(!V.has(o))return!1;const m=W.get(o),F=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h;return!m||m===es({attrs:F,placement:w??{}})},at=new Map,st=(o,h,w)=>{wt.add(o),at.set(o,h);const m=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h,F=es({attrs:m,placement:w??{}}),R=V.get(o);if(R){const O=W.get(o);return!O||O===F?(tt++,!1):(D.remove(R),D.add({...m,"flow:print":F},{...w,source:o}),ct++,!1)}return ht?(kt.push({sourceKey:o,attrs:{...m,"flow:print":F},placement:w}),!0):(D.add({...m,"flow:print":F},{...w,source:o}),!0)},pt=o=>{const h=typeof o=="string"?P.get(o):void 0,w=h==null?void 0:h.params.thickness;return typeof w=="number"&&w>0?w*f:void 0},Bt=o=>{var it,ft;const h=de(o,"extrusion"),w=$.get(String((h==null?void 0:h.level)??o.params.level??"")),m=h==null?void 0:h.slopes,F=((ft=(it=h==null?void 0:h.profile)==null?void 0:it.outline)==null?void 0:ft.curves)??[],R=Array.isArray(m)?m.map(mt=>typeof mt=="number"):[],O=R.indexOf(!0);if(o.params.of!=="roof"||!w||F.length!==4||R.filter(Boolean).length!==2||O<0||O>1||!R[O+2])return null;const[q,u]=[F[O],F[O+2]],x=q.from,gt=q.to,$t=Math.hypot(gt[0]-x[0],gt[1]-x[1]),Rt=[(gt[0]-x[0])/$t,(gt[1]-x[1])/$t];let It=[-Rt[1],Rt[0]];const yt=(u.from[0]-x[0])*It[0]+(u.from[1]-x[1])*It[1];yt<0&&(It=[-It[0],-It[1]]);const A=Math.abs(yt),[Ot,lt]=[m[O],m[O+2]],bt=w.at+(typeof o.params.base=="number"?o.params.base:0),K=(h==null?void 0:h.eaves)??[],[G,et]=[bt+(Number(K[O])||0),bt+(Number(K[O+2])||0)],H=(et-G+lt*A)/(Ot+lt);return{A:x,u:Rt,n:It,L:$t,W:A,si:Ot,sj:lt,ridge:H,top:bt,ti:G,tj:et,zAt:(mt,At)=>{const xt=(mt-x[0])*It[0]+(At-x[1])*It[1];return Math.min(G+Ot*xt,et+lt*(A-xt))}}},Gt=new Map(a.filter(o=>o.kind==="extrusion"&&o.params.of==="roof").map(o=>[o.id,o])),jt=[...Gt.values()].filter(o=>o.item.guid).map(o=>({id:o.id,gid:o.item.guid}));let Kt=0;if(b)for(const[o,h]of $){const w={CategoryId:De.levels,Name:h.name,Elevation:Ct(h.at*f)},m=es({attrs:l?{...w,Frame:"shared",...p?{SharedAt:p}:{}}:w,placement:{}}),F=(Oi=[...W].find(([R,O])=>O===m&&V.has(R)))==null?void 0:Oi[0];st(F??nt(o),w)&&Kt++}let Yt=0,zt=0;const U=new Map,Z=new Map;let B=null;const ut=()=>B??(B=r?[...r.elements.values()].filter(o=>/^IFC(SLAB|ROOF)/i.test(o.ifcClass)).flatMap(o=>{const h=Qt(r,o.gid);if(!h.length)return[];const w=a.find(m=>m.kind==="extrusion"&&m.item.guid===o.gid);return[{keys:[...w?[nt(w.id)]:[],`${e.fileId}:${o.gid}:shape`],box:[0,1,2].map(m=>Math.min(...h.map(F=>F[m]))).concat([0,1,2].map(m=>Math.max(...h.map(F=>F[m]))))}]}):[]),X=[];for(const o of a){if(o.kind!=="run"||o.params.of!=="wall")continue;const h=de(o,"run"),w=((Ni=(ki=h==null?void 0:h.run)==null?void 0:ki.line)==null?void 0:Ni.curves)??[],m=o.params.lookRef,F=$.get(String((h==null?void 0:h.level)??o.params.level??""));if(typeof m!="string"||typeof(h==null?void 0:h.height)!="number"||!F){zt++;continue}const R=(pt(m)??0)/f,O=u=>{var x;if(u.kind==="segment"&&Array.isArray(u.from)&&u.to)return{from:[...u.from],to:[...u.to]};if(u.kind==="arc"&&u.centre&&typeof u.radius=="number"&&typeof u.from=="number"&&typeof u.sweep=="number"){const gt=$t=>[u.centre[0]+u.radius*Math.cos($t),u.centre[1]+u.radius*Math.sin($t)];return typeof process<"u"&&((x=process.env)!=null&&x.RECIPE_TRACE)&&console.error(`[wall-arc] ${o.item.guid}: radius ${u.radius.toFixed(2)}, sweep ${(u.sweep*180/Math.PI).toFixed(1)}°`),{from:gt(u.from),to:gt(u.from+u.sweep),arcMid:gt(u.from+u.sweep/2)}}return null},q=w.map(O).filter(u=>u!==null);zt+=w.length-q.length,q.forEach((u,x)=>X.push({record:o,i:x,width:R,from:u.from,to:u.to,..."arcMid"in u?{arcMid:u.arcMid}:{},joinStart:x===0&&String(o.params.meetsAtStart)==="true",joinEnd:x===q.length-1&&String(o.params.meetsAtEnd)==="true"}))}const dt=(o,h)=>{const w=[o.to[0]-o.from[0],o.to[1]-o.from[1]],m=[h.to[0]-h.from[0],h.to[1]-h.from[1]],F=w[0]*m[1]-w[1]*m[0];if(Math.abs(F)<1e-9*Math.hypot(...w)*Math.hypot(...m)*1e3)return null;const R=((h.from[0]-o.from[0])*m[1]-(h.from[1]-o.from[1])*m[0])/F;return[o.from[0]+R*w[0],o.from[1]+R*w[1]]},Mt=(o,h)=>{const w=h.to[0]-h.from[0],m=h.to[1]-h.from[1],F=w*w+m*m||1,R=Math.max(0,Math.min(1,((o[0]-h.from[0])*w+(o[1]-h.from[1])*m)/F));return Math.hypot(o[0]-(h.from[0]+R*w),o[1]-(h.from[1]+R*m))},rt=(o,h)=>{const w=de(o.record,"run"),m=de(h.record,"run"),F=[w.base,w.base+w.height],R=[m.base,m.base+m.height],O=$.get(String((w==null?void 0:w.level)??o.record.params.level)).at,q=$.get(String((m==null?void 0:m.level)??h.record.params.level)).at;return Math.min(O+F[1],q+R[1])>Math.max(O+F[0],q+R[0])},_t=1,ie=new Map,Nt=new Map;for(const o of X){const h=[["from",o.joinStart],["to",o.joinEnd]],w={from:o.from,to:o.to};for(const[m,F]of h){if(!F)continue;const R=o[m];let O=null,q=1/0;for(const gt of X){if(gt===o||gt.arcMid||!rt(o,gt))continue;const $t=Mt(R,gt);$t<q&&(q=$t,O=gt)}if(!O||q>_t)continue;const u=dt(o,O);if(!u)continue;const x=Math.min(_t,2*Math.max(o.width,O.width)+.02);Math.hypot(u[0]-R[0],u[1]-R[1])>x||Mt(u,O)>O.width+.01||(w[m]=u,Nt.set(o,{...Nt.get(o),[m]:O.width/2}))}ie.set(o,w)}const le=new Map;if(r){const o=w=>{const m=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]);return{L:m,d:[(w.to[0]-w.from[0])/m,(w.to[1]-w.from[1])/m]}},h=(w,m,F)=>{const R=w.record.item.guid;if(!R||X.filter(x=>x.record===w.record).length!==1)return null;const{d:O}=o(w),q=Qt(r,R).map(x=>x[2]);if(!q.length)return null;const u=Gl(r,R,w.from,O,(m+F)/2,(Math.min(...q)+Math.max(...q))/2);return u?u.hi-u.lo:null};for(const w of X){if(w.arcMid||!(w.width>0))continue;const m=o(w);if(!(m.L<.3))for(const F of X){if(F===w||F.arcMid||!(F.width>0)||!rt(w,F))continue;const R=o(F);if(R.L<.3||Math.abs(m.d[0]*R.d[1]-m.d[1]*R.d[0])>.02)continue;const O=Math.abs(-(F.from[0]-w.from[0])*m.d[1]+(F.from[1]-w.from[1])*m.d[0]);if(O>(w.width+F.width)/2-.01)continue;const q=[F.from,F.to].map($t=>($t[0]-w.from[0])*m.d[0]+($t[1]-w.from[1])*m.d[1]),u=Math.max(0,Math.min(...q)),x=Math.min(m.L,Math.max(...q));if(x-u<.3)continue;const gt=h(w,u,x);typeof process<"u"&&((Pi=(Fi=process.env)==null?void 0:Fi.RECIPE_WALL)!=null&&Pi.split(",").includes(w.record.item.guid??""))&&console.error(`[cut-by?] ${w.record.item.guid} by ${F.record.item.guid}: off ${O.toFixed(3)}, along ${u.toFixed(2)}..${x.toFixed(2)}, shape ${gt}`),!(gt===null||gt>w.width-.01)&&(typeof process<"u"&&((Li=process.env)!=null&&Li.RECIPE_TRACE)&&console.error(`[cut-by] ${w.record.item.guid} (${(w.width*1e3).toFixed(0)} mm, its shape ${(gt*1e3).toFixed(0)}) cut by ${F.record.item.guid} over ${(x-u).toFixed(2)} m`),le.set(w,[...le.get(w)??[],F]))}}}const me=(o,h)=>{var F;if(!r||!o)return null;const w=[-h[1],h[0]],m=[];for(const R of r.elements.values()){if(R.parent!==o||!/^IFCPLATE$/i.test(R.ifcClass)||R.pieces.length!==1)continue;const O=r.geometries.get(R.pieces[0].geometry);if(!O||O.tris.length/3>12)continue;const q=Qt(r,R.gid);if(q.length<4)continue;const u=q.map(gt=>gt[0]*w[0]+gt[1]*w[1]),x=Math.max(...u)-Math.min(...u);x>.002&&x<.2&&m.push(x)}return m.length?(m.sort((R,O)=>R-O),typeof process<"u"&&((F=process.env)!=null&&F.RECIPE_TRACE)&&console.error(`[glass] ${o}: ${m.length} panel(s), median ${(m[Math.floor(m.length/2)]*1e3).toFixed(1)} mm`),m[Math.floor(m.length/2)]*f):null},Le=(o,h)=>{var O;if(!r||!o)return null;const w=[-h[1],h[0]],m=[],F=[];for(const q of r.elements.values()){if(q.parent!==o||!/^IFCMEMBER$/i.test(q.ifcClass))continue;const u=Qt(r,q.gid);if(u.length<4)continue;const x=u.map(A=>A[0]*h[0]+A[1]*h[1]),gt=u.map(A=>A[0]*w[0]+A[1]*w[1]),$t=u.map(A=>A[2]),Rt=A=>Math.max(...A)-Math.min(...A),It=Math.min(Rt(x),Rt($t)),yt=Rt(gt);It>.005&&It<.5&&yt>.005&&yt<1&&(m.push(It),F.push(yt))}if(!m.length)return null;m.sort((q,u)=>q-u),F.sort((q,u)=>q-u);const R={width:m[Math.floor(m.length/2)],depth:F[Math.floor(F.length/2)]};return typeof process<"u"&&((O=process.env)!=null&&O.RECIPE_TRACE)&&console.error(`[mullion] ${o}: ${m.length} member(s), median ${(R.width*1e3).toFixed(1)} × ${(R.depth*1e3).toFixed(1)} mm`),{width:R.width*f,depth:R.depth*f}},re=(()=>{if(!r)return 0;const o=[];for(const w of X){const m=w.record.item.guid;if(!m||!r.elements.has(m))continue;const F=de(w.record,"run"),R=$.get(String((F==null?void 0:F.level)??w.record.params.level??""));if(!F||!R)continue;const O=Qt(r,m);if(!O.length)continue;let q=1/0;for(const u of O)q=Math.min(q,u[2]);o.push(q-(R.at+(typeof F.base=="number"?F.base:0)))}o.sort((w,m)=>w-m);const h=o.length?o[Math.floor(o.length/2)]:0;return Math.abs(h)>.5?h:0})();for(const o of X){const{record:h}=o;let w=[];const m=de(h,"run");typeof process<"u"&&((ji=(Bi=process.env)==null?void 0:Bi.RECIPE_WALL)!=null&&ji.split(",").includes(h.item.guid??""))&&console.error(`[wall] ${h.item.guid}: params ${JSON.stringify(h.params).slice(0,800)} seg ${JSON.stringify({from:o.from,to:o.to,i:o.i})}`);const F=typeof m.base=="number"?m.base:0,R=m.height,O=$.get(String(m.level??h.params.level??"")),q=h.params.lookRef;let{from:u,to:x}=o.arcMid?{from:o.from,to:o.to}:ie.get(o);Math.hypot(x[0]-u[0],x[1]-u[1])<.01&&({from:u,to:x}=o);const gt=new Set;if(!o.arcMid&&X.filter(L=>L.record===h).length===1){const L=m.asCut,_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(L&&_>.05){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=(S,C)=>{const J=C==null?void 0:C.through,j=C==null?void 0:C.keep;if(!J||!j)return null;const z=y[0]*j[0]+y[1]*j[1];return Math.abs(z)<.5?null:((J[0]-S[0])*j[0]+(J[1]-S[1])*j[1])/z},T=h.params.wantedAtStart==="square"?g(u,(Di=L.start)==null?void 0:Di[0]):null,v=h.params.wantedAtEnd==="square"?g(x,(Ui=L.end)==null?void 0:Ui[0]):null;T!==null&&T>.005&&T<Math.min(1,_/2)&&(u=[u[0]+y[0]*T,u[1]+y[1]*T],gt.add("start")),v!==null&&v<-.005&&v>-Math.min(1,_/2)&&(x=[x[0]+y[0]*v,x[1]+y[1]*v],gt.add("end")),typeof process<"u"&&((Ji=process.env)!=null&&Ji.RECIPE_CUT_OUT)&&(T!==null&&T<-.005&&T>-1&&(u=[u[0]+y[0]*T,u[1]+y[1]*T],gt.add("start")),v!==null&&v>.005&&v<1&&(x=[x[0]+y[0]*v,x[1]+y[1]*v],gt.add("end"))),typeof process<"u"&&((qi=process.env)!=null&&qi.RECIPE_TRACE)&&(T!==null&&Math.abs(T)>.005&&Math.abs(T)<1||v!==null&&Math.abs(v)>.005&&Math.abs(v)<1)&&console.error(`[wall-to-cut] ${h.item.guid} ${q}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`),typeof process<"u"&&((Hi=(Gi=process.env)==null?void 0:Gi.RECIPE_WALL)!=null&&Hi.split(",").includes(h.item.guid??""))&&console.error(`[wall-cut] ${h.item.guid}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`)}}const $t=new Set(gt),Rt=!o.arcMid&&r&&h.item.guid&&X.filter(L=>L.record===h).length===1?r.elements.get(h.item.guid):void 0;if(Rt){const L=Qt(r,h.item.guid),_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(L.length>=4&&_>.05){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=L.map(z=>(z[0]-u[0])*y[0]+(z[1]-u[1])*y[1]),T=Math.min(...g),v=Math.max(...g),S=L.map(z=>-(z[0]-u[0])*y[1]+(z[1]-u[1])*y[0]),C=Math.max(...S)-Math.min(...S),J=z=>{const M=S.filter((ot,Q)=>Math.abs(g[Q]-z)<.002);return M.length>=2&&Math.max(...M)-Math.min(...M)>.9*C},j=u;J(T)&&(u=[j[0]+y[0]*T,j[1]+y[1]*T],$t.add("start")),J(v)&&(x=[j[0]+y[0]*v,j[1]+y[1]*v],$t.add("end"))}}const It=(O.at+F)*f,yt=`${Ct(u[0]*f)},${Ct(u[1]*f)},${Ct(It)};${Ct(x[0]*f)},${Ct(x[1]*f)},${Ct(It)}`,A={CategoryId:De.walls,Type:((Vi=xn(h))==null?void 0:Vi.type)??q,LocationLine:yt,Level:O.name,BaseOffset:Ct(F*f),Height:Ct(R*f),...o.arcMid?{LocationArc:`${Ct(o.arcMid[0]*f)},${Ct(o.arcMid[1]*f)},${Ct(It)}`}:{}},Ot=le.get(o);Ot&&(A.CutBy=Ot.flatMap(L=>{const _=`${nt(L.record.id)}#${L.i}`,y=V.get(_);return y?[_,y]:[_]}).join("|"));const lt=o.arcMid?[]:[u!==o.from||o.joinStart?"start":"",x!==o.to||o.joinEnd?"end":""].filter(L=>!!L&&!$t.has(L));lt.length&&(A.JoinEnds=lt.join(","));const bt=lt.filter(L=>h.params[L==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");bt.length&&(A.Mitre=bt.join(","));const K=$.get(String(h.params.topLevel??""));K&&(A.TopLevel=K.name,A.TopOffset=Ct((O.at+F+R-K.at)*f));const G=m.profile;let et=Array.isArray(G)?zl(G):G;if((h.params.wantedAtStart==="mitre"||h.params.wantedAtEnd==="mitre")&&Array.isArray(et)&&et.length===4){const L=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),_=m.height,y=(T,v)=>Math.abs(T)<1e-4?"lo":Math.abs(T-v)<.001?"hi":null,g=et.map(([T,v])=>[y(T,L),y(v,_)]);g.every(([T,v])=>T&&v)&&new Set(g.map(([T,v])=>`${T}${v}`)).size===4&&(et=void 0)}if(typeof process<"u"&&((zi=process.env)!=null&&zi.RECIPE_LAYER_EXT)&&Array.isArray(et)&&et.length>=4&&r&&h.item.guid&&typeof m.height=="number"){const L=(()=>{var _,y;try{return JSON.parse(String(((y=(_=P.get(q))==null?void 0:_.params)==null?void 0:y.definition)??"null"))}catch{return null}})();if(((L==null?void 0:L.layers)??[]).some(_=>(_.topExtension??0)>.001||(_.baseExtension??0)>.001)){const _=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),y=m.height,g=[(o.to[0]-o.from[0])/_,(o.to[1]-o.from[1])/_],T=O.at+F+re,v=[...r.elements.values()].filter(M=>M.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(M.ifcClass)).map(M=>{const ot=Qt(r,M.gid).map(Q=>[(Q[0]-o.from[0])*g[0]+(Q[1]-o.from[1])*g[1],Q[2]-T]);return ot.length?[Math.min(...ot.map(Q=>Q[0])),Math.max(...ot.map(Q=>Q[0])),Math.min(...ot.map(Q=>Q[1])),Math.max(...ot.map(Q=>Q[1]))]:null}).filter(M=>M!==null),S=Math.min(...et.map(([M])=>M)),C=Math.max(...et.map(([M])=>M)),J=([M,ot])=>(Math.abs(M-S)<.005||Math.abs(M-C)<.005)&&(Math.abs(ot)<.005||Math.abs(ot-y)<.005),j=([M,ot])=>v.some(Q=>M>=Q[0]-.03&&M<=Q[1]+.03&&ot>=Q[2]-.15&&ot<=Q[3]+.03),z=et.filter(M=>!J(M));et.filter(J).length===4&&(z.length===0||v.length&&z.every(j))&&(typeof process<"u"&&((Wi=process.env)!=null&&Wi.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${q}: its outline's ${z.length} notch corner(s) filled by what it hosts → a plain wall`),et=void 0)}}if(!o.arcMid&&Array.isArray(et)&&et.length>=3&&o.i===0&&!X.some(L=>L!==o&&L.record===h)){const L=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),_=[(o.to[0]-o.from[0])/L,(o.to[1]-o.from[1])/L],y=[];let g=-((u[0]-o.from[0])*_[0]+(u[1]-o.from[1])*_[1]),T=(x[0]-o.to[0])*_[0]+(x[1]-o.to[1])*_[1];const v=g,S=T;{const M=Nt.get(o),ot=[],Q=r&&h.item.guid?Qt(r,h.item.guid).map(ne=>(ne[0]-o.from[0])*_[0]+(ne[1]-o.from[1])*_[1]):[],Ft=Q.length?Math.max(0,-Math.min(...Q))-g:1/0,Dt=Q.length?Math.max(0,Math.max(...Q)-L)-T:1/0,Ht=(M==null?void 0:M.from)??(Ft<.6?Ft:0),ee=(M==null?void 0:M.to)??(Dt<.6?Dt:0);Ht&&lt.includes("start")&&Ft>.005&&(g+=Math.min(Ht,Ft),ot.push("start")),ee&&lt.includes("end")&&Dt>.005&&(T+=Math.min(ee,Dt),ot.push("end"));const Zt=lt.filter(ne=>!ot.includes(ne));if(ot.length&&(Zt.length?A.JoinEnds=Zt.join(","):delete A.JoinEnds),ot.length&&A.Mitre){const ne=A.Mitre.split(",").filter(Ut=>Zt.includes(Ut));ne.length?A.Mitre=ne.join(","):delete A.Mitre}ot.length&&typeof process<"u"&&((Yi=process.env)!=null&&Yi.RECIPE_TRACE)&&console.error(`[profile-face] ${h.item.guid} ${q}: ${ot.join(",")} to the far face`)}const C=(M,ot)=>et.map(([Q,Ft],Dt)=>{const Ht=Math.abs(Q)<1e-6,ee=Math.abs(Q-L)<1e-6;let Zt=Q,ne=Ft;if(Ht||ee){Zt=Ht?-M:L+ot;const Ut=[et[(Dt-1+et.length)%et.length],et[(Dt+1)%et.length]].find(([fe])=>Math.abs(fe-Q)>1e-6);Ut&&(ne=Ft+(Ut[1]-Ft)/(Ut[0]-Q)*(Zt-Q))}return[Zt,ne]}),J=M=>{const ot=M.length,Q=M.map((Dt,Ht)=>[Dt,M[(Ht+1)%ot]]);if(Q.some(([Dt,Ht])=>Math.hypot(Ht[0]-Dt[0],Ht[1]-Dt[1])<.001))return!1;for(let Dt=0;Dt<ot;Dt++){const[Ht,ee]=Q[Dt],[,Zt]=Q[(Dt+1)%ot],ne=[ee[0]-Ht[0],ee[1]-Ht[1]],Ut=[Zt[0]-ee[0],Zt[1]-ee[1]];if((ne[0]*Ut[0]+ne[1]*Ut[1])/(Math.hypot(...ne)*Math.hypot(...Ut))<-.999)return!1}const Ft=(Dt,Ht,ee)=>(Ht[0]-Dt[0])*(ee[1]-Dt[1])-(Ht[1]-Dt[1])*(ee[0]-Dt[0]);for(let Dt=0;Dt<ot;Dt++)for(let Ht=Dt+1;Ht<ot;Ht++){if(Ht===Dt+1||Dt===0&&Ht===ot-1)continue;const[ee,Zt]=Q[Dt],[ne,Ut]=Q[Ht],fe=Ft(ne,Ut,ee),Be=Ft(ne,Ut,Zt),mn=Ft(ee,Zt,ne),Io=Ft(ee,Zt,Ut);if((fe>1e-9&&Be<-1e-9||fe<-1e-9&&Be>1e-9)&&(mn>1e-9&&Io<-1e-9||mn<-1e-9&&Io>1e-9))return!1}return!0};let j=C(g,T);if(!J(j)){const ot=[[v,S],[0,0]].find(([Q,Ft])=>J(C(Q,Ft)));typeof process<"u"&&((Ki=process.env)!=null&&Ki.RECIPE_TRACE)&&console.error(`[profile-folded] ${h.item.guid} ${q}: ends ${g.toFixed(3)}/${T.toFixed(3)} fold it → ${ot?ot.map(Q=>Q.toFixed(3)).join("/"):"as given"}`),j=ot?C(...ot):et.map(([Q,Ft])=>[Q,Ft])}const z=M=>M.flatMap(([ot,Q])=>{const Ft=[o.from[0]+ot*_[0],o.from[1]+ot*_[1]];return[Ft[0]*f,Ft[1]*f,(O.at+F+Q)*f]});for(const M of z(j))y.push(M);if(A.Profile=JSON.stringify([y]),j.length===8){const M=j.map(([,Ut])=>Ut),ot=Math.max(...M),Q=Math.min(...M),Ft=j.map(([Ut])=>Ut),Dt=Math.min(...Ft),Ht=Math.max(...Ft),ee=j.filter(([Ut])=>Ut>Dt+.005&&Ut<Ht-.005),Zt=[...new Set(ee.map(([Ut])=>+Ut.toFixed(4)))].sort((Ut,fe)=>Ut-fe);if(j.filter(([Ut,fe])=>(Math.abs(Ut-Dt)<.005||Math.abs(Ut-Ht)<.005)&&(Math.abs(fe-ot)<.005||Math.abs(fe-Q)<.005)).length===4&&ee.length===4&&Zt.length===2&&Zt[1]-Zt[0]<.3&&ee.some(([,Ut])=>Math.abs(Ut-Q)<.005)&&ee.every(([,Ut])=>Math.abs(Ut-Q)<.005||ot-Ut<.3)){const Ut=(fe,Be)=>[[fe,Q],[Be,Q],[Be,ot],[fe,ot]];A.Profile=JSON.stringify([z(Ut(Dt,Zt[0]))]),w=[JSON.stringify([z(Ut(Zt[1],Ht))])],typeof process<"u"&&((Xi=process.env)!=null&&Xi.RECIPE_TRACE)&&console.error(`[slit-split] ${h.item.guid} ${q}: a slit ${((Zt[1]-Zt[0])*100).toFixed(0)} cm wide at ${Zt[0].toFixed(2)}, two walls`)}}delete A.TopLevel,delete A.TopOffset}const St=h.params.topAttachedTo,it=h.params.topAttachedAt==="top"||m.topAttachedAt==="top",ft=!o.arcMid&&typeof St=="string"&&it&&!A.Profile&&Gt.has(St)?Bt(Gt.get(St)):null;if(ft){const L=Math.hypot(x[0]-u[0],x[1]-u[1]),_=J=>[u[0]+(x[0]-u[0])*J/L,u[1]+(x[1]-u[1])*J/L],y=(u[0]-ft.A[0])*ft.n[0]+(u[1]-ft.A[1])*ft.n[1],g=(x[0]-ft.A[0])*ft.n[0]+(x[1]-ft.A[1])*ft.n[1],T=[0,L];(y-ft.ridge)*(g-ft.ridge)<0&&T.splice(1,0,(ft.ridge-y)/(g-y)*L);const v=O.at+F,S=[],C=(J,j)=>{const z=_(J);S.push(z[0]*f,z[1]*f,j*f)};C(0,v),C(L,v);for(const J of[...T].reverse()){const j=_(J);C(J,ft.zAt(j[0],j[1]))}A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}const mt=typeof St=="string"?St:r&&h.item.guid?Vl(r,h.item.guid,jt):void 0;if(mt&&!A.Profile){A.AttachTop=nt(mt);const L=V.get(nt(mt));L&&(A.AttachTopMade=L)}if(mt&&typeof St!="string"&&typeof process<"u"&&((Zi=process.env)!=null&&Zi.RECIPE_TRACE)&&console.error(`[attach] ${h.item.guid} ${h.item.name??""} → ${mt}`),!A.Profile&&!A.AttachTop&&Rt){const L=[...r.elements.values()].filter(T=>T.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(T.ifcClass));let _=Ss(r,h.item.guid,u,x,!0);const y=T=>{const v=[];for(const S of T)(!v.length||Math.hypot(S[0]-v[v.length-1][0],S[1]-v[v.length-1][1])>=.02)&&v.push(S);for(;v.length>1&&Math.hypot(v[0][0]-v[v.length-1][0],v[0][1]-v[v.length-1][1])<.02;)v.pop();return v};if(_!=null&&_.outline){const T=y(_.outline);_=T.length>=3?{..._,outline:T,holes:(_.holes??[]).map(y).filter(v=>v.length>=3)}:null}if(L.length&&(_!=null&&_.outline)){const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=L.map(j=>{const z=Qt(r,j.gid).map(M=>[(M[0]-u[0])*v[0]+(M[1]-u[1])*v[1],M[2]]);return z.length?[Math.min(...z.map(M=>M[0])),Math.max(...z.map(M=>M[0])),Math.min(...z.map(M=>M[1])),Math.max(...z.map(M=>M[1]))]:null}).filter(j=>j!==null),C=j=>{const z=Math.min(...j.map(Ft=>Ft[0])),M=Math.max(...j.map(Ft=>Ft[0])),ot=Math.min(...j.map(Ft=>Ft[1])),Q=Math.max(...j.map(Ft=>Ft[1]));return S.some(Ft=>Math.min(M,Ft[1])-Math.max(z,Ft[0])>.01&&Math.min(Q,Ft[3])-Math.max(ot,Ft[2])>.01)},J=(_.holes??[]).filter(j=>!C(j));_=!((Qi=_.pieces)!=null&&Qi.length)&&(J.length||_.outline.length>4)?{..._,holes:J}:null,_&&typeof process<"u"&&((tr=process.env)!=null&&tr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid}: ${L.length} hosted, ${J.length} empty hole(s) kept`)}const g=_!=null&&_.outline?null:Ss(r,h.item.guid,u,x);if(g){typeof process<"u"&&((er=process.env)!=null&&er.RECIPE_TRACE)&&console.error(`[wall-top] ${h.item.guid} ${h.item.name??""}: ${g.chain.map(([J,j])=>`${J.toFixed(2)}/${j.toFixed(2)}`).join(" ")}`);const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=[],C=(J,j)=>{S.push((u[0]+J*v[0])*f,(u[1]+J*v[1])*f,j*f)};C(g.lo,g.bottom-re),C(g.hi,g.bottom-re);for(const[J,j]of[...g.chain].reverse())C(J,j-re);A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}if(_!=null&&_.outline){typeof process<"u"&&((nr=process.env)!=null&&nr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid} ${h.item.name??""}: ${_.outline.length} corners`);const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=C=>C.flatMap(([J,j])=>[(u[0]+J*v[0])*f,(u[1]+J*v[1])*f,(j-re)*f]);A.Profile=JSON.stringify([S(_.outline),...(_.holes??[]).map(S)]),delete A.TopLevel,delete A.TopOffset,w=(_.pieces??[]).map(C=>JSON.stringify([S(C)]))}}else if(A.Profile&&Rt&&!A.AttachTop){const _=[...r.elements.values()].some(y=>y.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(y.ifcClass))?null:Ss(r,h.item.guid,u,x,!0);if((sr=_==null?void 0:_.holes)!=null&&sr.length&&!((ir=_.pieces)!=null&&ir.length)){const y=Math.hypot(x[0]-u[0],x[1]-u[1]),g=[(x[0]-u[0])/y,(x[1]-u[1])/y],T=v=>v.flatMap(([S,C])=>[(u[0]+S*g[0])*f,(u[1]+S*g[1])*f,(C-re)*f]);try{const v=JSON.parse(A.Profile);A.Profile=JSON.stringify([...v,..._.holes.map(T)]),typeof process<"u"&&((rr=process.env)!=null&&rr.RECIPE_TRACE)&&console.error(`[wall-holes] ${h.item.guid} ${h.item.name??""}: ${_.holes.length} hole(s) added to the converter's profile`)}catch{}}}const At=(m.clippedBy??[]).filter(L=>Array.isArray(L.through)&&Array.isArray(L.keep)&&Math.abs(L.keep[2])>.05);if(!o.arcMid&&At.length&&!A.AttachTop)try{const L=Math.hypot(x[0]-u[0],x[1]-u[1]),_=O.at+F,y=A.Profile?JSON.parse(A.Profile):[[u[0]*f,u[1]*f,_*f,x[0]*f,x[1]*f,_*f,x[0]*f,x[1]*f,(_+R)*f,u[0]*f,u[1]*f,(_+R)*f]];let g=[];for(let C=0;C+2<y[0].length;C+=3)g.push([y[0][C]/f,y[0][C+1]/f,y[0][C+2]/f]);const T=C=>{const J=[(x[0]-u[0])/L,(x[1]-u[1])/L];let j=0;for(let z=0;z<C.length;z++){const M=C[z],ot=C[(z+1)%C.length];j+=(M[0]*J[0]+M[1]*J[1])*ot[2]-(ot[0]*J[0]+ot[1]*J[1])*M[2]}return Math.abs(j)/2},v=T(g);for(const C of At){const J=z=>(z[0]-C.through[0])*C.keep[0]+(z[1]-C.through[1])*C.keep[1]+(z[2]-C.through[2])*C.keep[2],j=[];for(let z=0;z<g.length;z++){const M=g[z],ot=g[(z+1)%g.length],Q=J(M),Ft=J(ot);if(Q>=0&&j.push(M),Q>=0!=Ft>=0){const Dt=Q/(Q-Ft);j.push([0,1,2].map(Ht=>M[Ht]+Dt*(ot[Ht]-M[Ht])))}}g=j}const S=g.length>=3?T(g):0;S>.05&&v-S>.05&&(typeof process<"u"&&((or=process.env)!=null&&or.RECIPE_TRACE)&&console.error(`[wall-clip] ${h.item.guid} ${h.item.name??""}: ${At.length} plane(s), ${v.toFixed(2)} → ${S.toFixed(2)} m²`),A.Profile=JSON.stringify([g.flatMap(C=>[C[0]*f,C[1]*f,C[2]*f]),...y.slice(1)]),delete A.TopLevel,delete A.TopOffset)}catch{}if(!A.Profile&&Rt){const L=Qt(r,h.item.guid),_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(L.length>=8&&_>.5){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=[-y[1],y[0]],T=(J,j)=>{const z=L.filter(M=>{const ot=(M[0]-u[0])*y[0]+(M[1]-u[1])*y[1];return ot>=J*_&&ot<=j*_}).map(M=>(M[0]-u[0])*g[0]+(M[1]-u[1])*g[1]);return z.length>=2?{c:(Math.max(...z)+Math.min(...z))/2,w:Math.max(...z)-Math.min(...z)}:null},v=T(-.02,.06),S=T(.94,1.02),C=T(.45,.55);if(v&&S&&C){const J=(v.c+S.c)/2,j=C.c-J,z=L.map(Q=>{const Ft=Math.min(Math.max(((Q[0]-u[0])*y[0]+(Q[1]-u[1])*y[1])/_,0),1);return(Q[0]-u[0])*g[0]+(Q[1]-u[1])*g[1]-J-4*j*Ft*(1-Ft)}),M=Math.max(...z)-Math.min(...z),ot=M<(v.w+S.w)/2+.01&&C.w>.5*Math.min(v.w,S.w);if(typeof process<"u"&&((cr=(ar=process.env)==null?void 0:ar.RECIPE_WALL)!=null&&cr.split(",").includes(h.item.guid??""))&&console.error(`[arc-bands] ${JSON.stringify({b0:v,bm:C,b1:S,sag:j,spread:M})}`),ot&&Math.abs(j)>.02&&Math.abs(j)<_/2){const Q=[(u[0]+x[0])/2+g[0]*j,(u[1]+x[1])/2+g[1]*j];A.LocationArc=`${Ct(Q[0]*f)},${Ct(Q[1]*f)},${Ct(It)}`,typeof process<"u"&&((lr=process.env)!=null&&lr.RECIPE_TRACE)&&console.error(`[wall-arc] ${h.item.guid} ${h.item.name??""}: bows ${(j*100).toFixed(1)} cm over ${_.toFixed(2)} m`)}}}}const xt=pt(q);if(xt&&(A["Type.Width"]=Ct(xt)),xt){const L=U.get(A.Type);L===void 0?U.set(A.Type,xt):Math.abs(L-xt)>.001&&(A.Type=`${A.Type} · ${Math.round(xt/f*1e3)} mm`)}const Jt=h.item.guid?r==null?void 0:r.elements.get(h.item.guid):void 0;if(Jt!=null&&Jt.layers&&Jt.layers.length>1)A["Type.Layers"]=JSON.stringify([...Jt.layers].reverse().map(L=>[+Ct(L.thickness*f),L.material??"",L.function??""])),Jt.layersFlipped&&(A.FlipLayers="1");else if(typeof process<"u"&&((hr=process.env)!=null&&hr.RECIPE_PIECE_LAYERS)&&Jt&&Jt.pieces.length>=2&&xt&&h.item.guid){const L=Math.hypot(x[0]-u[0],x[1]-u[1]),_=[(x[0]-u[0])/L,(x[1]-u[1])/L],y=[];Jt.pieces.forEach((v,S)=>{const C=Qt(r,h.item.guid,S);if(C.length<4)return;const J=C.map(Q=>(Q[0]-u[0])*_[0]+(Q[1]-u[1])*_[1]),j=C.map(Q=>-(Q[0]-u[0])*_[1]+(Q[1]-u[1])*_[0]),z=C.map(Q=>Q[2]);if(Math.max(...J)-Math.min(...J)<Math.min(.3,.5*L)||Math.max(...z)-Math.min(...z)<.5*R)return;const M=Math.min(...j),ot=Math.max(...j);y.some(Q=>Math.abs(Q[0]-M)<.002&&Math.abs(Q[1]-ot)<.002)||y.push([M,ot])}),y.sort((v,S)=>S[1]-v[1]);const g=y.length?y[0][1]-y[y.length-1][0]:0,T=y.every((v,S)=>S===0||v[1]<=y[S-1][0]+.002);if(y.length>=2&&T&&Math.abs(g-xt/f)<.01){const v=[];y.forEach((j,z)=>{const M=ot=>+Ct(Math.round(ot*2e3)/2e3*f);z>0&&y[z-1][0]-j[1]>.003&&v.push([M(y[z-1][0]-j[1]),"","air"]),v.push([M(j[1]-j[0]),"",""])});const S=JSON.stringify(v),C=JSON.stringify([...v].reverse()),J=Z.get(A.Type);J===void 0&&Z.set(A.Type,S),J===void 0||J===S?A["Type.Layers"]=S:J===C&&(A["Type.Layers"]=J,A.FlipLayers="1"),typeof process<"u"&&((fr=process.env)!=null&&fr.RECIPE_TRACE)&&console.error(`[piece-layers] ${h.item.guid} ${A.Type}: ${S}${J&&J!==S?J===C?" (flipped)":" (the type stacks otherwise: kept)":""}`)}}if(!A["Type.Layers"]&&typeof process<"u"&&((dr=process.env)!=null&&dr.RECIPE_LAYER_EXT)){const L=(()=>{var y,g;try{return JSON.parse(String(((g=(y=P.get(q))==null?void 0:y.params)==null?void 0:g.definition)??"null"))}catch{return null}})(),_=(L==null?void 0:L.layers)??[];if(_.length>1&&_.some(y=>(y.topExtension??0)>.001||(y.baseExtension??0)>.001)){A["Type.Layers"]=JSON.stringify(_.map(C=>[+Ct((C.thickness??0)*f),C.material??"",C.function??"",+Ct((C.topExtension??0)*f),+Ct((C.baseExtension??0)*f)]));const y=Math.max(..._.map(C=>C.topExtension??0)),g=Math.max(..._.map(C=>C.baseExtension??0)),T=(C,J)=>{if(!r||!h.item.guid)return[];const j=Qt(r,h.item.guid);if(j.length<4)return[];const z=[Math.min(...j.map(M=>M[0])),Math.min(...j.map(M=>M[1])),Math.max(...j.map(M=>M[0])),Math.max(...j.map(M=>M[1]))];return ut().filter(M=>M.box[0]<z[2]-.01&&z[0]<M.box[3]-.01&&M.box[1]<z[3]-.01&&z[1]<M.box[4]-.01&&M.box[2]<J-.01&&C<M.box[5]-.01).flatMap(M=>M.keys)},v=O.at+F+re,S=typeof process<"u"&&((ur=process.env)!=null&&ur.RECIPE_EXT_CUT)&&!A.Profile&&y>.001&&g<.001?T(v+R,v+R+y):[];S.length&&(A.Height||A.TopOffset)?(A["Type.Layers"]=JSON.stringify(_.map(C=>[+Ct((C.thickness??0)*f),C.material??"",C.function??""])),A.TopOffset?A.TopOffset=Ct(Number(A.TopOffset)+y*f):A.Height=Ct(Number(A.Height)+y*f),A.CutBy=[...A.CutBy?A.CutBy.split("|"):[],...S].join("|"),typeof process<"u"&&((pr=process.env)!=null&&pr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: up ${y} to its finish's top, cut by ${S.length} slab(s)`)):(y>.001&&(A.TopExtension=Ct(y*f)),g>.001&&(A.BaseExtension=Ct(g*f))),typeof process<"u"&&((mr=process.env)!=null&&mr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: top ${y}, base ${g}`)}}typeof process<"u"&&((yr=(gr=process.env)==null?void 0:gr.RECIPE_WALL)!=null&&yr.split(",").includes(h.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(A).slice(0,1500)} style ${JSON.stringify(((wr=P.get(q))==null?void 0:wr.params)??null).slice(0,800)}`),st(`${nt(h.id)}#${o.i}`,A)&&Yt++,w.forEach((L,_)=>{st(`${nt(h.id)}#${o.i}p${_+1}`,{...A,Profile:L})&&Yt++})}const Xe=(o,h,w)=>{if(!(h>0)||h>=o)return[];const m=o-Math.floor(o/h+1e-9)*h,F=w==="beginning"?0:w==="end"?m:w==="centreLine"?o/2%h:m/2,R=[];for(let O=F;O<=o+1e-4;O+=h)O>1e-4&&O<o-1e-4&&R.push(O);return R};let Dn=0,Ti=0;const Mi=new Map;for(const o of a){if(o.kind!=="run"||o.params.of!=="curtainWall")continue;Ti++;const h=de(o,"run"),w=(Er=(vr=(br=h==null?void 0:h.run)==null?void 0:br.line)==null?void 0:vr.curves)==null?void 0:Er[0],m=$.get(String((h==null?void 0:h.level)??o.params.level??"")),F=o.params.lookRef,R=typeof F=="string"?(Tr=P.get(F))==null?void 0:Tr.params:void 0;if(!(w!=null&&w.from)||!w.to||typeof(h==null?void 0:h.height)!="number"||!m||!R)continue;const O=y=>typeof y=="number"?y:Number(y)||0,q=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]),u=[(w.to[0]-w.from[0])/q,(w.to[1]-w.from[1])/q],x=O(R.uprightWidth)>0?null:Le(o.item.guid??void 0,u),gt=(O(R.uprightWidth)||(x?x.width/f:0))/2,$t=(O(R.horizontalWidth)||(x?x.width/f:0))/2,Rt={start:!1,end:!1,bottom:!1,top:!1};let It=[];if(r&&o.item.guid&&!Array.isArray(h.profile)){const y=[...r.elements.values()].filter(S=>S.parent===o.item.guid),g=S=>{const C=Qt(r,S);if(!C.length)return null;const J=C.map(z=>(z[0]-w.from[0])*u[0]+(z[1]-w.from[1])*u[1]),j=C.map(z=>z[2]);return{t0:Math.min(...J),t1:Math.max(...J),z0:Math.min(...j),z1:Math.max(...j)}},T=y.map(S=>g(S.gid)).filter(S=>S!==null),v=y.filter(S=>/^IFCMEMBER$/i.test(S.ifcClass)).map(S=>g(S.gid)).filter(S=>S!==null);if(v.length&&T.length){const S=Math.min(...T.map(M=>M.t0)),C=Math.max(...T.map(M=>M.t1)),J=Math.min(...T.map(M=>M.z0)),j=Math.max(...T.map(M=>M.z1)),z=M=>M.t1-M.t0>M.z1-M.z0;Rt.bottom=!v.some(M=>z(M)&&Math.abs(M.z0-J)<.01),Rt.top=!v.some(M=>z(M)&&Math.abs(M.z1-j)<.01),Rt.start=!v.some(M=>!z(M)&&Math.abs(M.t0-S)<.01),Rt.end=!v.some(M=>!z(M)&&Math.abs(M.t1-C)<.01),It=[...new Set(v.filter(M=>!z(M)&&M.t0>S+.01&&M.t1<C-.01).map(M=>+((M.t0+M.t1)/2).toFixed(4)))].sort((M,ot)=>M-ot),Object.values(Rt).some(Boolean)&&typeof process<"u"&&((Mr=process.env)!=null&&Mr.RECIPE_TRACE)&&console.error(`[curtain-bare] ${o.item.guid}: no bar at its ${Object.entries(Rt).filter(([,M])=>M).map(([M])=>M).join(", ")}`)}}const yt=Rt.start?0:gt,A=Rt.end?0:gt,Ot=Rt.bottom?0:$t,lt=Rt.top?0:$t,bt=[w.from[0]-u[0]*yt,w.from[1]-u[1]*yt],K=[w.to[0]+u[0]*A,w.to[1]+u[1]*A],G=(typeof h.base=="number"?h.base:0)-Ot,et=h.height+Ot+lt,H=(m.at+G)*f,St=Xe(q,O(R.alongSpacing),R.alongJustify),it=!(($r=h.lines)!=null&&$r.along)&&It.length>0&&(It.length!==St.length||It.some((y,g)=>Math.abs(y-St[g])>.01));it&&typeof process<"u"&&((Ir=process.env)!=null&&Ir.RECIPE_TRACE)&&console.error(`[curtain-lines] ${o.item.guid}: ${It.length} from its bars, not the type's ${St.length}`);const ft=((Sr=h.lines)==null?void 0:Sr.along)??(it?It:St),mt=((xr=h.lines)==null?void 0:xr.up)??Xe(h.height,O(R.upSpacing),R.upJustify),At=(h.omitted??[]).flatMap(y=>{const g=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(y);if(!g)return[];const T=g[1]==="horizontal",v=Number(g[2])/1e3+(T?Ot:yt),S=Number(g[3])/1e3+(T?yt:Ot);return[{horizontal:T,at:v*f,from:S*f}]}),xt=Rt.start&&Rt.end&&Rt.bottom&&Rt.top;if(!xt){const y=[0,...ft.map(v=>v+yt)],g=[0,...mt.map(v=>v+Ot)],T=q+yt+A;if(Rt.bottom)for(const v of y)At.push({horizontal:!0,at:0,from:v*f});if(Rt.top)for(const v of y)At.push({horizontal:!0,at:et*f,from:v*f});if(Rt.start)for(const v of g)At.push({horizontal:!1,at:0,from:v*f});if(Rt.end)for(const v of g)At.push({horizontal:!1,at:T*f,from:v*f})}const Jt=(h.omitted??[]).flatMap(y=>{const g=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(y);return g?[{along:(Number(g[1])/1e3+yt)*f,up:(Number(g[2])/1e3+Ot)*f}]:[]});if(r&&o.item.guid)for(const y of Hl(r,o.item.guid,O(R.panelDepth),[-u[1],u[0]])){const g=(y.centre[0]-w.from[0])*u[0]+(y.centre[1]-w.from[1])*u[1],T=y.centre[2]-re-(m.at+(typeof h.base=="number"?h.base:0));if(g<-.01||g>q+.01||T<-.01||T>h.height+.01)continue;const v=Math.max(0,...ft.filter(C=>C<=g+1e-6)),S=Math.max(0,...mt.filter(C=>C<=T+1e-6));Jt.push({along:(v+yt)*f,up:(S+Ot)*f}),Pt.add(y.gid)}const L={CategoryId:De.walls,Type:((_r=xn(o))==null?void 0:_r.type)??String(F),LocationLine:`${Ct(bt[0]*f)},${Ct(bt[1]*f)},${Ct(H)};${Ct(K[0]*f)},${Ct(K[1]*f)},${Ct(H)}`,Level:m.name,BaseOffset:Ct(G*f),Height:Ct(et*f),Curtain:JSON.stringify({along:ft.map(y=>(y+yt)*f),up:mt.map(y=>(y+Ot)*f),omit:At,empty:Jt,...xt?{noBorders:!0}:{},mullion:O(R.uprightWidth)>0?{width:O(R.uprightWidth)*f,depth:O(R.depth)*f}:x??{width:0,depth:O(R.depth)*f},panel:{thickness:me(o.item.guid??void 0,u)??O(R.panelDepth)*f,offset:-O(R.panelOffset)*f}})},_=h.profile;if(Array.isArray(_)&&_.length>=3){const g=_.reduce((C,J,j)=>{const z=_[(j+1)%_.length];return C+J[0]*z[1]-z[0]*J[1]},0)>0?1:-1,T=_.length,v=_.map((C,J)=>{const j=_[(J-1+T)%T],z=_[(J+1)%T],M=(Ht,ee)=>{const Zt=ee[0]-Ht[0],ne=ee[1]-Ht[1],Ut=Math.hypot(Zt,ne)||1,fe=g*ne/Ut,Be=-g*Zt/Ut,mn=Math.abs(fe)>Math.abs(Be)?gt:$t;return{p:[Ht[0]+fe*mn,Ht[1]+Be*mn],d:[Zt,ne]}},ot=M(j,C),Q=M(C,z),Ft=ot.d[0]*Q.d[1]-ot.d[1]*Q.d[0];if(Math.abs(Ft)<1e-12)return[Q.p[0],Q.p[1]];const Dt=((Q.p[0]-ot.p[0])*Q.d[1]-(Q.p[1]-ot.p[1])*Q.d[0])/Ft;return[ot.p[0]+Dt*ot.d[0],ot.p[1]+Dt*ot.d[1]]}),S=[];for(const[C,J]of v)S.push((w.from[0]+u[0]*C)*f,(w.from[1]+u[1]*C)*f,(m.at+G+$t+J)*f);L.Profile=JSON.stringify([S])}{const y=JSON.parse(L.Curtain),g=y.mullion,T=(Ar=y.panel)!=null&&Ar.thickness?`, ${Math.round(y.panel.thickness/f*1e3)} mm glass`:"",v=`${Math.round(g.width/f*1e3)} x ${Math.round(g.depth/f*1e3)}${T}${y.noBorders?", no borders":""}`,S=Mi.get(L.Type);S===void 0?Mi.set(L.Type,v):S!==v&&(typeof process<"u"&&((Cr=process.env)!=null&&Cr.RECIPE_TRACE)&&console.error(`[curtain-type] ${o.item.guid}: ${L.Type} first made with ${S}, this one ${v}`),L.Type=`${L.Type} · ${v}`)}st(nt(o.id),L)&&Dn++}let Un=0,$i=0;const Ii=(o,h,w)=>{if(!r||!o)return null;const m=Math.hypot(w[0]-h[0],w[1]-h[1]);if(!(m>0))return null;const F=[-(w[1]-h[1])/m,(w[0]-h[0])/m],R=[o,...[...r.elements.values()].filter(u=>u.parent===o).map(u=>u.gid)].flatMap(u=>Qt(r,u));if(R.length<4)return null;const O=R.map(u=>(u[0]-h[0])*F[0]+(u[1]-h[1])*F[1]),q=Math.max(...O)-Math.min(...O);return q>.3&&q<10?q:null};for(const o of a){if(o.kind!=="stair"||o.params.of!=="stair")continue;$i++;const h=de(o,"stair"),w=o.params.lookRef,m=typeof w=="string"?(Rr=P.get(w))==null?void 0:Rr.params:void 0,F=$.get(String((h==null?void 0:h.level)??o.params.level??""));if(!(h!=null&&h.start)||!h.end||!(Number(h.rise)>0)||!F||!m)continue;const R=K=>typeof K=="number"?K:Number(K)||0,O=Number(h.rise),q=R(m.maxRiser)>0?R(m.maxRiser):(kr=(Or=h.sketch)==null?void 0:Or.risers)!=null&&kr.length?O/(h.sketch.risers.length+1):.18,u=Math.max(1,Math.ceil(O/q-1e-6)),x=R(m.tread),gt=K=>[K[0]*f,K[1]*f];let $t=F.at+R(o.params.base),Rt=!1;if(r&&o.item.guid){const K=Qt(r,o.item.guid).map(H=>H[2]-re),G=O/u,et=K.length?Math.min(...K):$t;$t-et>.5*G&&$t-et<1.5*G&&(typeof process<"u"&&((Nr=process.env)!=null&&Nr.RECIPE_TRACE)&&console.error(`[stair-base] ${o.item.guid} ${o.item.name??""}: base ${$t.toFixed(3)} → its shape's ${et.toFixed(3)}`),$t=et,Rt=!0)}const It={family:(()=>{const K=String(w).split(":").map(G=>G.trim()).filter((G,et,H)=>et<H.length-1||!/^\d+$/.test(G));return K.length>=3&&/^(stairs?|escaleras?|treppen?)$/i.test(K[0])?K[1]:K[0]})(),base:$t*f,height:O*f,risers:u,tread:x*f,width:(R(m.width)>0?R(m.width):Ii(o.item.guid??void 0,h.start,h.end)??0)*f,endsWithRiser:(()=>{if(!r||!o.item.guid)return!1;const K=Qt(r,o.item.guid);if(K.length<4)return!1;const G=Math.max(...K.map(H=>H[2]))-re,et=F.at+R(o.params.base)+O;return et-G>.5*(O/u)&&et-G<1.5*(O/u)})(),sizes:{maxRiser:Math.ceil(O/u*1e3-1e-6)/1e3*f,minTread:x*f,waist:R(m.waist)*f,treadThickness:m.construction==="assembled"?R(m.treadThickness)*f:0,riserThickness:m.construction==="assembled"?R(m.riserThickness)*f:0,notchExtension:R(m.notchExtension)*f,notchThickness:R(m.notchThickness)*f,...m.nosing!==void 0&&Number.isFinite(Number(m.nosing))?{nosing:Number(m.nosing)*f}:{}}};typeof process<"u"&&((Fr=process.env)!=null&&Fr.RECIPE_TRACE)&&console.error(`[stair-end] ${o.item.guid} ${o.item.name??""}: ${u} risers, ends with riser ${It.endsWithRiser}`);const yt=h.sketch;if(yt!=null&&yt.boundary&&yt.risers&&yt.risers.length>=2){const K=it=>[(it[0][0]+it[1][0])/2,(it[0][1]+it[1][1])/2],G=yt.risers.filter((it,ft,mt)=>ft===0||Math.hypot(K(it)[0]-K(mt[ft-1])[0],K(it)[1]-K(mt[ft-1])[1])>.01),et=(it,ft)=>Math.hypot(it[0]-ft[0],it[1]-ft[1])<.01,H=yt.boundary,St=it=>H.some((ft,mt)=>{const At=H[(mt+1)%H.length];return et(ft,it[0])&&et(At,it[1])||et(ft,it[1])&&et(At,it[0])});if(G.length>=2&&!St(G[0])){const[it,ft]=[G[0],G[1]],mt=[it[1][0]-it[0][0],it[1][1]-it[0][1]],At=Math.hypot(mt[0],mt[1]),xt=K(it),Jt=K(ft),L=[xt[0]-Jt[0],xt[1]-Jt[1]];let _=null,y=1/0;for(let g=0;g<H.length;g++){const T=H[g],v=H[(g+1)%H.length],S=[v[0]-T[0],v[1]-T[1]],C=Math.hypot(S[0],S[1]);if(!(C>0)||Math.abs((S[0]*mt[1]-S[1]*mt[0])/(C*At))>.02)continue;const J=K([T,v]),j=(J[0]-xt[0])*L[0]+(J[1]-xt[1])*L[1];j>1e-4&&j<y&&(y=j,_=[T,v])}_&&G.unshift(_)}G.length!==yt.risers.length&&typeof process<"u"&&((Pr=process.env)!=null&&Pr.RECIPE_TRACE)&&console.error(`[stair-sketch] ${o.item.guid}: riser lines ${yt.risers.length} → ${G.length}`),yt.risers=G}if(yt!=null&&yt.boundary&&yt.boundary.length>=4&&yt.risers&&yt.risers.length>=2){const K=yt.risers[0],G=(g,T)=>Math.hypot(g[0]-T[0],g[1]-T[1])<.01,et=yt.boundary.findIndex((g,T,v)=>{const S=v[(T+1)%v.length];return G(g,K[0])&&G(S,K[1])||G(g,K[1])&&G(S,K[0])}),H=et>0?[...yt.boundary.slice(et),...yt.boundary.slice(0,et)]:yt.boundary;typeof process<"u"&&((Lr=process.env)==null?void 0:Lr.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] boundary ${JSON.stringify(H)} (turned by ${et}) risers ${JSON.stringify(yt.risers)} tread ${x}`);const St=yt.risers[yt.risers.length-1],it=g=>[(g[0][0]+g[1][0])/2,(g[0][1]+g[1][1])/2],ft=it(St);let mt=1,At=1/0;for(let g=1;g<H.length;g++){const T=it([H[g],H[(g+1)%H.length]]),v=Math.abs(Math.hypot(T[0]-ft[0],T[1]-ft[1])-x);v<At&&(At=v,mt=g)}{const g=[St[1][0]-St[0][0],St[1][1]-St[0][1]],T=Math.hypot(g[0],g[1]),v=it(yt.risers[0]);let S=-1/0,C=-1;for(let J=1;J<H.length;J++){const j=[H[(J+1)%H.length][0]-H[J][0],H[(J+1)%H.length][1]-H[J][1]],z=Math.hypot(j[0],j[1]);if(!(z>0)||Math.abs((j[0]*g[1]-j[1]*g[0])/(z*T))>.06)continue;const M=it([H[J],H[(J+1)%H.length]]),ot=Math.hypot(M[0]-v[0],M[1]-v[1]);ot>S+1e-6&&(S=ot,C=J)}C>0&&(mt=C)}const xt=(g,T)=>{const v=[];for(let S=g;S!==T;S=(S+1)%H.length)v.push([gt(H[S]),gt(H[(S+1)%H.length])]);return v},Jt=[...xt(1,mt),...xt((mt+1)%H.length,0)];typeof process<"u"&&((Br=process.env)==null?void 0:Br.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] end edge ${mt} of ${H.length}`);const L=yt.risers.map(([g,T])=>[gt(g),gt(T)]);gt(H[mt]),gt(H[(mt+1)%H.length]);const _=L.map(([g,T])=>[(g[0]+T[0])/2,(g[1]+T[1])/2]);if(It.sketch={boundary:Jt,risers:L,path:_},It.path=[_[0],_[_.length-1]],It.width||(It.width=Math.hypot(L[0][1][0]-L[0][0][0],L[0][1][1]-L[0][0][1])),typeof process<"u"&&((jr=process.env)!=null&&jr.RECIPE_TRACE)){const g=T=>Math.hypot(T[1][0]-T[0][0],T[1][1]-T[0][1])/f;console.error(`[stair] ${o.item.guid} ${o.item.name??""}: ${Jt.length} sides (shortest ${(Math.min(...Jt.map(g))*1e3).toFixed(2)} mm), ${L.length} risers (shortest ${(Math.min(...L.map(g))*1e3).toFixed(2)} mm), walk ${_.length} points (shortest step ${(Math.min(..._.slice(1).map((T,v)=>g([_[v],T])))*1e3).toFixed(2)} mm)`)}let y=1/0;for(let g=0;g+1<yt.risers.length;g++){const[T,v]=yt.risers[g],[S,C]=yt.risers[g+1],J=[v[0]-T[0],v[1]-T[1]],j=[C[0]-S[0],C[1]-S[1]],z=Math.hypot(J[0],J[1]),M=Math.hypot(j[0],j[1]);Math.abs((J[0]*j[1]-J[1]*j[0])/(z*M))>.001||(y=Math.min(y,Math.abs(((S[0]-T[0])*J[1]-(S[1]-T[1])*J[0])/z)))}if(Number.isFinite(y)&&(It.tread=y*f,It.sizes.minTread=y*f,Rt)){const g=It.path,T=Math.hypot(g[1][0]-g[0][0],g[1][1]-g[0][1]);T>0&&(It.path=[[g[0][0]-(g[1][0]-g[0][0])/T*y*f,g[0][1]-(g[1][1]-g[0][1])/T*y*f],g[1]])}}else{let K=[h.start[0],h.start[1]];if(Rt&&x>0){const G=h.end[0]-h.start[0],et=h.end[1]-h.start[1],H=Math.hypot(G,et);H>0&&(K=[K[0]-x*G/H,K[1]-x*et/H])}if(It.path=[gt(K),gt([h.end[0],h.end[1]])],!(x>0)){const G=Math.hypot(h.end[0]-h.start[0],h.end[1]-h.start[1])/u;It.tread=G*f,It.sizes.minTread=G*f}typeof process<"u"&&((Dr=process.env)!=null&&Dr.RECIPE_TRACE)&&console.error(`[stair] ${o.item.guid} ${o.item.name??""}: straight, ${Math.hypot(h.end[0]-h.start[0],h.end[1]-h.start[1]).toFixed(3)} m, rise ${O}, ${u} risers, width ${R(m.width)}, measured ${Ii(o.item.guid??void 0,h.start,h.end)}`)}const A=String(o.item.attrs.Name??""),Ot=A.replace(/ Run \d+$/,""),lt=[];for(const K of a){if(K.kind!=="extrusion"||Ot===A||!new RegExp(`^${Ot.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(K.item.attrs.Name??"")))continue;const G=de(K,"extrusion"),et=G==null?void 0:G.on,H=(((Jr=(Ur=G==null?void 0:G.profile)==null?void 0:Ur.outline)==null?void 0:Jr.curves)??[]).flatMap(S=>S.from?[S.from]:[]),St=pt(K.params.lookRef),it=$.get(String((G==null?void 0:G.level)??K.params.level??""));if(!(et!=null&&et.origin)||!et.u||!et.v||Math.abs(et.v[2]??0)<.99||!H.length||!St||!it)continue;const[ft,mt]=[Math.min(...H.map(S=>S[0])),Math.max(...H.map(S=>S[0]))],[At,xt]=[Math.min(...H.map(S=>S[1])),Math.max(...H.map(S=>S[1]))],Jt=et.origin,L=et.u;let _=[L[1],-L[0]];const y=[(h.start[0]+h.end[0])/2,(h.start[1]+h.end[1])/2];(y[0]-Jt[0])*_[0]+(y[1]-Jt[1])*_[1]<0&&(_=[-_[0],-_[1]]);const T=St/f,v=(S,C)=>[(Jt[0]+L[0]*S+_[0]*C)*f,(Jt[1]+L[1]*S+_[1]*C)*f];lt.push({outline:[v(ft,0),v(mt,0),v(mt,T),v(ft,T)],top:(it.at+R(K.params.base)+Jt[2]+xt)*f,thickness:(xt-At)*f})}lt.length&&(It.landings=lt);const bt={CategoryId:De.stairs,Type:((qr=xn(o))==null?void 0:qr.type)??String(w),Level:F.name,Stairs:JSON.stringify(It)};typeof process<"u"&&(((Gr=process.env)==null?void 0:Gr.RECIPE_STAIR)===o.item.guid||((Hr=process.env)==null?void 0:Hr.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${bt.Stairs} style ${JSON.stringify(m)}`),st(nt(o.id),bt)&&Un++}const Si=new Map,dn={floor:0,foundation:0,roof:0,ceiling:0},pe={floor:0,foundation:0,roof:0,ceiling:0},xi=a.flatMap(o=>{var R,O;if(o.kind!=="extrusion"||o.params.of!=="form")return[];const h=de(o,"extrusion"),w=$.get(String((h==null?void 0:h.level)??o.params.level??"")),m=(((O=(R=h==null?void 0:h.profile)==null?void 0:R.outline)==null?void 0:O.curves)??[]).flatMap(q=>q.from?[q.from]:[]);if(!(h!=null&&h.void)||!w||m.length<3)return[];const F=w.at+(Number(o.params.base)||0);return[{guid:o.item.guid,outline:m,from:F,to:F+(Number(h.depth??o.params.depth)||0)}]});for(const o of a){const h=o.params.of;if(o.kind!=="extrusion"||h!=="slab"&&h!=="roof"&&h!=="covering")continue;let w=h==="covering"?"ceiling":h==="roof"?"roof":Ho(o);if(w==="other"||r&&o.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((Vr=r.elements.get(o.item.guid))==null?void 0:Vr.ifcClass)??""))continue;const m=de(o,"extrusion"),F=m==null?void 0:m.on;if(F&&(Math.abs(((zr=F.u)==null?void 0:zr[2])??0)>.001||Math.abs(((Wr=F.v)==null?void 0:Wr[2])??0)>.001))continue;if(w==="roof"&&!Bt(o)){const lt=m,bt=((Kr=(Yr=m==null?void 0:m.profile)==null?void 0:Yr.outline)==null?void 0:Kr.curves)??[];if(lt!=null&&lt.slope&&typeof lt.slope.by=="number"&&Math.abs(lt.slope.by)>.001&&typeof lt.slope.toward=="number"&&!(Array.isArray(lt.slopes)&&lt.slopes.some(K=>typeof K=="number"))&&bt.length>=3){const K=[Math.cos(lt.slope.toward),Math.sin(lt.slope.toward)],G=bt.map(it=>it.from).filter(Boolean),et=G.map(it=>it[0]*K[0]+it[1]*K[1]),H=Math.min(...et);G.some((it,ft)=>Math.abs(et[ft]-H)<.01&&Math.abs(et[(ft+1)%G.length]-H)<.01)||(w="floor",typeof process<"u"&&((Xr=process.env)!=null&&Xr.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${o.item.guid} ${o.params.lookRef}: its low side a corner, a sloped floor`))}}dn[w]++,typeof process<"u"&&((Zr=process.env)==null?void 0:Zr.RECIPE_SLAB)===o.item.guid&&console.error(`[slab] ${o.item.guid}: params ${JSON.stringify(o.params).slice(0,600)} body ${JSON.stringify(m).slice(0,1500)}`);const R=typeof o.params.base=="number"?o.params.base:0,O=$.get(String((m==null?void 0:m.level)??o.params.level??"")),q=o.params.lookRef,u=lt=>{if(!(lt!=null&&lt.length))return null;const bt=[];for(const K of lt){if(K.kind!=="segment"||!K.from)return null;bt.push(K.from[0]*f,K.from[1]*f,R*f)}return bt.length>=9?bt:null},x=u((to=(Qr=m==null?void 0:m.profile)==null?void 0:Qr.outline)==null?void 0:to.curves);if(typeof q!="string"||!O||!x)continue;const gt=[x],$t=w==="roof"?Bt(o):null;for(const lt of((eo=m==null?void 0:m.profile)==null?void 0:eo.holes)??[]){const bt=u(lt==null?void 0:lt.curves);if(bt&&$t)for(let K=0;K+2<bt.length;K+=3)bt[K+2]=$t.zAt(bt[K]/f,bt[K+1]/f)*f;bt&&gt.push(bt)}const Rt=[...(m==null?void 0:m.cuts)??[]],It=O.at+R,yt=It+(Number(o.params.depth)||0);for(const lt of xi)lt.from<yt-.001&&It<lt.to-.001&&Rt.push({outline:lt.outline,through:[0,0,lt.to-lt.from]});for(const lt of Rt){const bt=lt.through,K=lt.outline;if(!Array.isArray(K)||K.length<3||!Array.isArray(bt)||Math.abs(bt[2])<.99*Math.hypot(bt[0],bt[1],bt[2]))continue;const G=K.filter((y,g)=>g===0||Math.hypot(y[0]-K[g-1][0],y[1]-K[g-1][1])>1e-4);if(G.length>3&&Math.hypot(G[0][0]-G[G.length-1][0],G[0][1]-G[G.length-1][1])<1e-4&&G.pop(),G.length<3)continue;const et=(y,g)=>{let T=!1;for(let v=0,S=x.length/3-1;v<x.length/3;S=v++){const C=x[3*v]/f,J=x[3*v+1]/f,j=x[3*S]/f,z=x[3*S+1]/f;J>g!=z>g&&y<(j-C)*(g-J)/(z-J)+C&&(T=!T)}return T};if(!G.every(y=>et(y[0],y[1]))){typeof process<"u"&&((no=process.env)!=null&&no.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut across its edge, left`);continue}const H=y=>[Math.min(...y.map(g=>g[0])),Math.min(...y.map(g=>g[1])),Math.max(...y.map(g=>g[0])),Math.max(...y.map(g=>g[1]))],St=y=>{const g=[];for(let T=0;T+2<y.length;T+=3)g.push([y[T]/f,y[T+1]/f]);return g},it=H(G),ft=(y,g,T)=>{let v=!1;for(let S=0,C=y.length-1;S<y.length;C=S++)y[S][1]>T!=y[C][1]>T&&g<(y[C][0]-y[S][0])*(T-y[S][1])/(y[C][1]-y[S][1])+y[S][0]&&(v=!v);return v},mt=(y,g,T)=>{const v=T[0]-g[0],S=T[1]-g[1],C=Math.max(0,Math.min(1,((y[0]-g[0])*v+(y[1]-g[1])*S)/(v*v+S*S||1)));return Math.hypot(y[0]-(g[0]+C*v),y[1]-(g[1]+C*S))},At=(y,g)=>y.some(T=>ft(g,T[0],T[1])||g.some((v,S)=>mt(T,v,g[(S+1)%g.length])<.01)),xt=gt.slice(1).some(y=>{const g=St(y),T=H(g);return it[0]<T[2]+.01&&T[0]<it[2]+.01&&it[1]<T[3]+.01&&T[1]<it[3]+.01&&(At(G,g)||At(g,G))}),Jt=St(x),L=G.some(y=>Jt.some((g,T)=>{const v=Jt[(T+1)%Jt.length],S=v[0]-g[0],C=v[1]-g[1],J=S*S+C*C||1,j=Math.max(0,Math.min(1,((y[0]-g[0])*S+(y[1]-g[1])*C)/J));return Math.hypot(y[0]-(g[0]+j*S),y[1]-(g[1]+j*C))<.01}));if(xt||L){typeof process<"u"&&((so=process.env)!=null&&so.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut ${xt?"over another hole":"at its edge"}, left`);continue}const _=G.flatMap(y=>[y[0]*f,y[1]*f,($t?$t.zAt(y[0],y[1]):R)*f]);gt.push(_),typeof process<"u"&&((io=process.env)!=null&&io.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid} ${o.item.name??""}: a hole of ${G.length} corners`)}const A={CategoryId:w==="roof"?De.roofs:w==="ceiling"?De.ceilings:w==="foundation"?De.structuralFoundations:De.floors,Type:((ro=xn(o))==null?void 0:ro.type)??q,Profile:JSON.stringify(gt),Level:O.name};let Ot=pt(q);if(w==="roof"&&r&&o.item.guid){const lt=(oo=r.elements.get(o.item.guid))==null?void 0:oo.layers,bt=(lt==null?void 0:lt.reduce((K,G)=>K+(G.thickness>0?G.thickness:0),0))??0;bt>0&&(!Ot||Math.abs(bt*f-Ot)>.2*Ot)&&(Ot=bt*f)}if(Ot&&(A["Type.Width"]=Ct(Ot)),Ot){const lt=Si.get(A.Type);lt===void 0?Si.set(A.Type,Ot):Math.abs(lt-Ot)>.001&&(A.Type=`${A.Type} · ${Math.round(Ot/f*1e3)} mm`)}if(w==="floor"&&r&&o.item.guid){const lt=Qt(r,o.item.guid);if(lt.length){const bt=[0,1,2].map(G=>Math.min(...lt.map(et=>et[G]))).concat([0,1,2].map(G=>Math.max(...lt.map(et=>et[G])))),K=X.flatMap(G=>{const et=G.record.item.guid?Qt(r,G.record.item.guid):[];if(et.length<4)return[];const H=[0,1,2].map(At=>Math.min(...et.map(xt=>xt[At]))).concat([0,1,2].map(At=>Math.max(...et.map(xt=>xt[At])))),St=H[2]>bt[2]+.01&&H[2]<bt[5]-.01&&H[5]>bt[5]&&lt.some(At=>Math.abs(At[2]-H[2])<.005),it=H[0]<bt[3]-.01&&bt[0]<H[3]-.01&&H[1]<bt[4]-.01&&bt[1]<H[4]-.01;if(!St||!it)return[];const ft=`${nt(G.record.id)}#${G.i}`,mt=V.get(ft);return mt?[ft,mt]:[ft]});K.length&&(A.CutBy=[...new Set(K)].join("|"),typeof process<"u"&&((ao=process.env)!=null&&ao.RECIPE_TRACE)&&console.error(`[floor-cut] ${o.item.guid} ${o.item.name??""}: cut by ${K.length} wall(s)`))}}if(w==="roof"||w==="ceiling"){A.BaseOffset=Ct(R*f);const lt=Number(o.params.drop??((co=m==null?void 0:m.said)==null?void 0:co.drop));if(w==="ceiling"&&Number.isFinite(lt)&&Ot){const H=[...$.values()].filter(St=>St.at>O.at+1e-6).sort((St,it)=>St.at-it.at)[0];H&&(A.BaseOffset=Ct((H.at-lt-Ot/f-O.at)*f))}const bt=m==null?void 0:m.slopes;if(w==="roof"&&Array.isArray(bt)&&bt.some(H=>typeof H=="number")){A.Slopes=JSON.stringify(bt.map(it=>typeof it=="number"?it:null));const H=Math.max(...bt.filter(it=>typeof it=="number").map(it=>Math.abs(it)));Ot&&H>0&&(A.BaseOffset=Ct(R*f-Ot*Math.sqrt(1+H*H)));const St=r&&o.item.guid?Qt(r,o.item.guid):[];if(Ot&&H>0&&St.length>=4){const it=St.map(Jt=>Jt[2]-re),ft=Math.min(...it),mt=O.at+R,At=mt-Ot/f*Math.sqrt(1+H*H),xt=mt-ft;if(ft-At>.01&&xt>.01){const Jt=St.filter((z,M)=>it[M]<ft+.002),L=z=>[Math.min(...z.map(M=>M[0])),Math.min(...z.map(M=>M[1])),Math.max(...z.map(M=>M[0])),Math.max(...z.map(M=>M[1]))],[_,y,g,T]=L(St),[v,S,C,J]=L(Jt),j=v-_>.01&&S-y>.01&&g-C>.01&&T-J>.01;A.EaveCut=j?"TwoCutSquare":"TwoCutPlumb",A.FasciaDepth=Ct((j?xt*Math.sqrt(1+H*H):xt)*f)}typeof process<"u"&&((lo=process.env)!=null&&lo.RECIPE_TRACE)&&console.error(`[roof-eave] ${o.item.guid} ${q}: plumb low ${At.toFixed(3)}, its lowest ${ft.toFixed(3)} → ${A.EaveCut??"plumb"}${A.FasciaDepth?`, fascia ${(Number(A.FasciaDepth)/f).toFixed(3)}`:""}`)}typeof process<"u"&&((ho=process.env)!=null&&ho.RECIPE_TRACE)&&console.error(`[roof] ${o.item.guid} ${q}: slopes ${JSON.stringify(bt)} base ${R} width ${Ot} edges ${gt[0]?gt[0].length/3:0} profile ${JSON.stringify((fo=gt[0])==null?void 0:fo.map(it=>+it.toFixed(2)))}`)}const K=w==="roof"?Bt(o):null;if(K){const{A:H,n:St,u:it,W:ft,ridge:mt,si:At,ti:xt,tj:Jt,L}=K,_=(y,g)=>[(H[0]+St[0]*y)*f,(H[1]+St[1]*y)*f,g*f];A.Extrusion=JSON.stringify({profile:[_(0,xt),_(mt,xt+At*mt),_(ft,Jt)],along:[it[0],it[1]],length:L*f}),delete A.Slopes}const G=m==null?void 0:m.slope,et=((po=(uo=m==null?void 0:m.profile)==null?void 0:uo.outline)==null?void 0:po.curves)??[];if(w==="roof"&&!K&&!A.Slopes&&G&&typeof G.by=="number"&&Math.abs(G.by)>.001&&typeof G.toward=="number"&&et.length>=3){const H=[Math.cos(G.toward),Math.sin(G.toward)],St=et.map(At=>At.from).filter(Boolean),it=St.map(At=>At[0]*H[0]+At[1]*H[1]),ft=Math.min(...it),mt=St.map((At,xt)=>Math.abs(it[xt]-ft)<.01&&Math.abs(it[(xt+1)%St.length]-ft)<.01);if(St.length===et.length&&mt.some(Boolean)){A.Slopes=JSON.stringify(mt.map(xt=>xt?Math.tan(Math.abs(G.by)):null)),A.BaseOffset=Ct(R*f);const At=r&&o.item.guid?Qt(r,o.item.guid):[];if(At.length>=4){const xt=Math.min(...At.map(Jt=>Jt[2]))-re;O.at+R-xt>.5*Math.tan(Math.abs(G.by))*(Math.max(...it)-ft)&&(A.BaseOffset=Ct((xt-O.at)*f))}}typeof process<"u"&&((mo=process.env)!=null&&mo.RECIPE_TRACE)&&console.error(`[roof-plane] ${o.item.guid} ${q}: ${(G.by*180/Math.PI).toFixed(1)}° toward ${(G.toward*180/Math.PI).toFixed(1)}°, eaves ${JSON.stringify(mt)}`)}}else if(Ot){A.HeightOffset=Ct(R*f+Ot);const lt=m==null?void 0:m.slope,bt=((yo=(go=m==null?void 0:m.profile)==null?void 0:go.outline)==null?void 0:yo.curves)??[];if(lt&&typeof lt.by=="number"&&Math.abs(lt.by)>1e-4&&typeof lt.toward=="number"&&bt.length>=3){const K=[Math.cos(lt.toward),Math.sin(lt.toward)],G=bt.map(mt=>mt.from).filter(Boolean),et=G.map(mt=>mt[0]*K[0]+mt[1]*K[1]),H=Math.min(...et),St=Math.max(...et),it=G[et.indexOf(H)],ft=Math.tan(lt.by);if(St-H>.001){A.Slope=Ct(ft),A.SlopeArrow=JSON.stringify([it[0]*f,it[1]*f,(it[0]+K[0]*(St-H))*f,(it[1]+K[1]*(St-H))*f]),A.HeightOffset=Ct(R*f+Ot-ft*(St-H)*f);const mt=r&&o.item.guid?Qt(r,o.item.guid):[];if(mt.length>=4){const At=Math.min(...mt.map(xt=>xt[2]))-re;A.HeightOffset=Ct((At-O.at)*f+Ot*Math.sqrt(1+ft*ft)),typeof process<"u"&&((wo=process.env)!=null&&wo.RECIPE_TRACE)&&console.error(`[slab-slope] ${o.item.guid} ${q}: lowest ${At.toFixed(3)} level ${O.at.toFixed(3)} base ${R.toFixed(3)} rise ${(ft*(St-H)).toFixed(3)}: top at its low corner ${(At+Ot*Math.sqrt(1+ft*ft)/f).toFixed(3)} (by base ${(O.at+R+Ot/f-ft*(St-H)).toFixed(3)})`)}}}}st(nt(o.id),A)&&pe[w]++}let Jn=0,_i=0;for(const o of a){if(o.kind!=="member"||o.params.of!=="column")continue;_i++;const h=de(o,"member"),w=h==null?void 0:h.start;if(!w||w.length!==3)continue;const m=c?zo(o.params.lookRef):null;if(c&&!m||!m&&!d)continue;const F=m??{family:d.family,type:d.type},R=$.get(String((h==null?void 0:h.level)??""));st(nt(o.id),{...d&&!m?{CategoryId:d.categoryId}:{},Family:F.family,Type:F.type,...R?{Level:R.name}:{}},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:(Number((h==null?void 0:h.roll)??0)||0)*Vo})&&Jn++}let qn=0,Ai=0,ps=0;for(const o of a){if(o.kind!=="familyInstance")continue;if(o.params.host){ps++;continue}if(Ai++,!E)continue;const h=de(o,"instance"),w=(bo=h==null?void 0:h.placement)==null?void 0:bo.at;if(!w||w.length!==3)continue;const m=zo(o.params.type);if(!m)continue;const F=(vo=h==null?void 0:h.placement)==null?void 0:vo.right,R=F?Math.atan2(F[1],F[0])*Vo:0;st(nt(o.id),{Family:m.family,Type:m.type},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:R})&&qn++}Pt.size&&typeof process<"u"&&((Eo=process.env)!=null&&Eo.RECIPE_TRACE)&&console.error(`[shaped-panels] ${Pt.size} curtain panel(s) made as families of their shape`);const un=r?Bl(r,wt,e.fileId,Pt).filter(o=>!xi.some(h=>h.guid&&o.key.includes(h.guid))):[];if(typeof process<"u"&&((To=process.env)!=null&&To.RECIPE_GID))for(const o of un.filter(h=>h.key.includes(process.env.RECIPE_GID)))console.error(`[shaped] ${o.key} at ${o.at} turn ${o.rotationDeg} host ${o.host} ${JSON.stringify({...o.attrs,Shape:o.attrs.Shape?"…":void 0})}`);let Gn=0;const Hn=new Map;for(const o of un){if(!o.attrs.Family||Hn.has(o.attrs.Family))continue;const h={};for(const w of["Shape","Prism"])o.attrs[w]&&(h[w]=o.attrs[w]);Object.keys(h).length&&Hn.set(o.attrs.Family,h)}const Ci=new Set;for(const o of un){const h=o.attrs.Family;!h||!Hn.has(h)||!(o.attrs.Shape||o.attrs.Prism)||Wt(o.key,o.host&&V.get(o.host)?{...o.attrs,HostMade:V.get(o.host)}:o.attrs,{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}})&&Ci.add(h)}for(const o of un){const h=o.attrs.Family,w={position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}},m=o.host&&V.get(o.host)?{...o.attrs,HostMade:V.get(o.host)}:o.attrs,F=h&&Ci.has(h)&&!(o.attrs.Shape||o.attrs.Prism)&&!Wt(o.key,m,w)?{...o.attrs,...Hn.get(h)}:o.attrs;st(o.key,o.host&&V.get(o.host)?{...F,HostMade:V.get(o.host)}:F,{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}})&&Gn++}if(r)for(const o of jl(r,wt,e.fileId)){const h=(Mo=at.get(o.host))==null?void 0:Mo.Profile;if(h)try{const w=JSON.parse(h),m=[];for(let q=0;q+2<o.box.length;q+=3)m.push([o.box[q]*f,o.box[q+1]*f,(o.box[q+2]-re)*f]);const F=(q,u)=>[Math.min(...q.map(x=>x[u])),Math.max(...q.map(x=>x[u]))],R=[0,1,2].map(q=>F(m,q));if(w.slice(1).some(q=>{const u=[];for(let x=0;x+2<q.length;x+=3)u.push([q[x],q[x+1],q[x+2]]);return u.length>=3&&[0,1,2].every(x=>{const gt=F(u,x);return gt[0]<R[x][1]+.03&&R[x][0]<gt[1]+.03})})){typeof process<"u"&&(($o=process.env)!=null&&$o.RECIPE_TRACE)&&console.error(`[opening] ${o.key}: its wall's outline has its holes`);continue}}catch{}st(o.key,{WallOpening:o.box.map((w,m)=>Ct((m%3===2?w-re:w)*f)).join(","),...V.get(o.host)?{HostMade:V.get(o.host)}:{}},{host:o.host})}if(r)for(const o of Jl(r,e.fileId))st(o.key,{Room:"1",Name:o.name,Number:o.number,Height:Ct(o.height*f)},{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f]});let ms=0;const za=new Set(["slab","roof","covering"]);for(const o of a){const h=o.params.of;(o.kind==="footing"||o.kind==="ramp"||o.kind==="stair"&&h!=="stair"||o.kind==="extrusion"&&!za.has(String(h))||o.kind==="extrusion"&&h==="slab"&&Ho(o)==="other"&&!/ Landing \d+$/.test(String(o.item.attrs.Name??""))||o.kind==="run"&&h!=="wall"&&h!=="curtainWall")&&ms++}te();let pn=0;for(const[o,h]of V)!o.startsWith(`${e.fileId}:`)||wt.has(o)||(D.remove(h),pn++);if(D.length===0)throw new yi(`Up to date: "${e.name}" holds ${tt} element(s) this recipe already made, ${ps+ms} waiting on the applier, and nothing is left to remove.`);const Wa=[Kt?`${Kt} level(s)`:"",Yt?`${Yt} wall(s)`:"",Dn?`${Dn} curtain wall(s)`:"",pe.floor?`${pe.floor} floor(s)`:"",pe.foundation?`${pe.foundation} foundation slab(s)`:"",pe.roof?`${pe.roof} roof(s)`:"",pe.ceiling?`${pe.ceiling} ceiling(s)`:"",Un?`${Un} stair(s)`:"",Jn?`${Jn} column(s)`:"",qn?`${qn} instance(s)`:"",Gn?`${Gn} family instance(s)`:"",ct?`${ct} changed`:"",pn?`${pn} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${Wa.join(", ")}`,verb:D.summary,targets:D.length,payload:new Blob([await D.build(t.opId)]),ruleTallies:[{read:$.size,written:Kt},{read:X.length+zt,written:Yt},{read:Ti,written:Dn},{read:dn.floor+dn.foundation,written:pe.floor+pe.foundation},{read:dn.roof,written:pe.roof},{read:dn.ceiling,written:pe.ceiling},{read:$i,written:Un},{read:_i,written:Jn},{read:Ai,written:qn},{read:un.length,written:Gn},{read:pn,written:pn},{read:ps+ms,written:0}]}}}const Wl={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}}},Yl=[{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"}],Ja=`
1
+ "use strict";var Xa=Object.create;var ys=Object.defineProperty;var Za=Object.getOwnPropertyDescriptor;var Qa=Object.getOwnPropertyNames;var tc=Object.getPrototypeOf,ec=Object.prototype.hasOwnProperty;var xo=s=>{throw TypeError(s)};var nc=(s,t,e)=>t in s?ys(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var sc=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Qa(t))!ec.call(s,i)&&i!==e&&ys(s,i,{get:()=>t[i],enumerable:!(n=Za(t,i))||n.enumerable});return s};var zn=(s,t,e)=>(e=s!=null?Xa(tc(s)):{},sc(t||!s||!s.__esModule?ys(e,"default",{value:s,enumerable:!0}):e,s));var he=(s,t,e)=>nc(s,typeof t!="symbol"?t+"":t,e),ws=(s,t,e)=>t.has(s)||xo("Cannot "+e);var N=(s,t,e)=>(ws(s,t,"read from private field"),e?e.call(s):t.get(s)),qt=(s,t,e)=>t.has(s)?xo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),Xt=(s,t,e,n)=>(ws(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),I=(s,t,e)=>(ws(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=Object.create(null);_e.open="0";_e.close="1";_e.ping="2";_e.pong="3";_e.message="4";_e.upgrade="5";_e.noop="6";const Xn=Object.create(null);Object.keys(_e).forEach(s=>{Xn[_e[s]]=s});const _s={type:"error",data:"parser error"},Yo=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ko=typeof ArrayBuffer=="function",Xo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,si=({type:s,data:t},e,n)=>Yo&&t instanceof Blob?e?n(t):_o(t,n):Ko&&(t instanceof ArrayBuffer||Xo(t))?e?n(t):_o(new Blob([t]),n):n(_e[s]+(t||"")),_o=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function Ao(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let bs;function ic(s,t){if(Yo&&s.data instanceof Blob)return s.data.arrayBuffer().then(Ao).then(t);if(Ko&&(s.data instanceof ArrayBuffer||Xo(s.data)))return t(Ao(s.data));si(s,!1,e=>{bs||(bs=new TextEncoder),t(bs.encode(e))})}const Co="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Mn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Co.length;s++)Mn[Co.charCodeAt(s)]=s;const rc=s=>{let t=s.length*.75,e=s.length,n,i=0,r,a,l,p;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)r=Mn[s.charCodeAt(n)],a=Mn[s.charCodeAt(n+1)],l=Mn[s.charCodeAt(n+2)],p=Mn[s.charCodeAt(n+3)],c[i++]=r<<2|a>>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|p&63;return d},oc=typeof ArrayBuffer=="function",ii=(s,t)=>{if(typeof s!="string")return{type:"message",data:Zo(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:ac(s.substring(1),t)}:Xn[e]?s.length>1?{type:Xn[e],data:s.substring(1)}:{type:Xn[e]}:_s},ac=(s,t)=>{if(oc){const e=rc(s);return Zo(e,t)}else return{base64:!0,data:s}},Zo=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Qo="",cc=(s,t)=>{const e=s.length,n=new Array(e);let i=0;s.forEach((r,a)=>{si(r,!1,l=>{n[a]=l,++i===e&&t(n.join(Qo))})})},lc=(s,t)=>{const e=s.split(Qo),n=[];for(let i=0;i<e.length;i++){const r=ii(e[i],t);if(n.push(r),r.type==="error")break}return n};function hc(){return new TransformStream({transform(s,t){ic(s,e=>{const n=e.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,n)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(e)})}})}let vs;function Wn(s){return s.reduce((t,e)=>t+e.length,0)}function Yn(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)e[i]=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 fc(s,t){vs||(vs=new TextDecoder);const e=[];let n=0,i=-1,r=!1;return new TransformStream({transform(a,l){for(e.push(a);;){if(n===0){if(Wn(e)<1)break;const p=Yn(e,1);r=(p[0]&128)===128,i=p[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(Wn(e)<2)break;const p=Yn(e,2);i=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),n=3}else if(n===2){if(Wn(e)<8)break;const p=Yn(e,8),d=new DataView(p.buffer,p.byteOffset,p.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){l.enqueue(_s);break}i=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(Wn(e)<i)break;const p=Yn(e,i);l.enqueue(ii(r?p:vs.decode(p),t)),n=0}if(i===0||i>s){l.enqueue(_s);break}}}})}const ta=4;function oe(s){if(s)return dc(s)}function dc(s){for(var t in oe.prototype)s[t]=oe.prototype[t];return s}oe.prototype.on=oe.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};oe.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};oe.prototype.off=oe.prototype.removeListener=oe.prototype.removeAllListeners=oe.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,i=0;i<e.length;i++)if(n=e[i],n===t||n.fn===t){e.splice(i,1);break}return e.length===0&&delete this._callbacks["$"+s],this};oe.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,i=e.length;n<i;++n)e[n].apply(this,t)}return this};oe.prototype.emitReserved=oe.prototype.emit;oe.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};oe.prototype.hasListeners=function(s){return!!this.listeners(s).length};const hs=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),we=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),uc="arraybuffer";function ea(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const pc=we.setTimeout,mc=we.clearTimeout;function fs(s,t){t.useNativeTimers?(s.setTimeoutFn=pc.bind(we),s.clearTimeoutFn=mc.bind(we)):(s.setTimeoutFn=we.setTimeout.bind(we),s.clearTimeoutFn=we.clearTimeout.bind(we))}const gc=1.33;function yc(s){return typeof s=="string"?wc(s):Math.ceil((s.byteLength||s.size)*gc)}function wc(s){let t=0,e=0;for(let n=0,i=s.length;n<i;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 na(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function bc(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function vc(s){let t={},e=s.split("&");for(let n=0,i=e.length;n<i;n++){let r=e[n].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}class Ec extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class ri extends oe{constructor(t){super(),this.writable=!1,fs(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 Ec(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=ii(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=bc(t);return e.length?"?"+e:""}}class Tc extends ri{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)};lc(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,cc(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]=na()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let sa=!1;try{sa=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Mc=sa;function $c(){}class Ic extends Tc{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",(i,r)=>{this.onError("xhr post error",i,r)})}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 xe extends oe{constructor(t,e,n){super(),this.createRequest=t,fs(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=ea(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 i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}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 i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.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(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=xe.requestsCount++,xe.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=$c,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete xe.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()}}xe.requestsCount=0;xe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ro);else if(typeof addEventListener=="function"){const s="onpagehide"in we?"pagehide":"unload";addEventListener(s,Ro,!1)}}function Ro(){for(let s in xe.requests)xe.requests.hasOwnProperty(s)&&xe.requests[s].abort()}const Sc=function(){const s=ia({xdomain:!1});return s&&s.responseType!==null}();class xc extends Ic{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Sc&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xe(ia,this.uri(),t)}}function ia(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Mc))return new XMLHttpRequest}catch{}if(!t)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ra=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class _c extends ri{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=ra?{}:ea(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(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=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],i=e===t.length-1;si(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}i&&hs(()=>{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]=na()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Es=we.WebSocket||we.MozWebSocket;class Ac extends _c{createSocket(t,e,n){return ra?new Es(t,e,n):e?new Es(t,e):new Es(t)}doWrite(t,e){this.ws.send(e)}}class Cc extends ri{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=fc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=hc();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const r=()=>{n.read().then(({done:l,value:p})=>{l||(this.onPacket(p),r())}).catch(l=>{})};r();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;this._writer.write(n).then(()=>{i&&hs(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Rc={websocket:Ac,webtransport:Cc,polling:xc},Oc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,kc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function As(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 i=Oc.exec(s||""),r={},a=14;for(;a--;)r[kc[a]]=i[a]||"";return e!=-1&&n!=-1&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Nc(r,r.path),r.queryKey=Fc(r,r.query),r}function Nc(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 Fc(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,r){i&&(e[i]=r)}),e}const Cs=typeof addEventListener=="function"&&typeof removeEventListener=="function",Zn=[];Cs&&addEventListener("offline",()=>{Zn.forEach(s=>s())},!1);class We extends oe{constructor(t,e){if(super(),this.binaryType=uc,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=As(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=As(e.host).host);fs(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 i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=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=vc(this.opts.query)),Cs&&(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"})},Zn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=ta,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&&We.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",We.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 i=this.writeBuffer[n].data;if(i&&(e+=yc(i)),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,hs(()=>{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,i){if(typeof e=="function"&&(i=e,e=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),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(We.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(),Cs&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Zn.indexOf(this._offlineEventListener);n!==-1&&Zn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}We.protocol=ta;class Pc extends We{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;We.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",E=>{if(!n)if(E.type==="pong"&&E.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;We.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 b=new Error("probe error");b.transport=e.name,this.emitReserved("upgradeError",b)}}))};function r(){n||(n=!0,c(),e.close(),e=null)}const a=E=>{const b=new Error("probe error: "+E);b.transport=e.name,r(),this.emitReserved("upgradeError",b)};function l(){a("transport closed")}function p(){a("socket closed")}function d(E){e&&E.name!==e.name&&r()}const c=()=>{e.removeListener("open",i),e.removeListener("error",a),e.removeListener("close",l),this.off("close",p),this.off("upgrading",d)};e.once("open",i),e.once("error",a),e.once("close",l),this.once("close",p),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 Lc=class extends Pc{constructor(t,e={}){const n=typeof t=="object",i=n?{...t}:{...e};(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(r=>Rc[r]).filter(r=>!!r)),super(n?i:t,i)}};function Bc(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=As(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 r=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port+t,n.href=n.protocol+"://"+r+(e&&e.port===n.port?"":":"+n.port),n}const jc=typeof ArrayBuffer=="function",Dc=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,oa=Object.prototype.toString,Uc=typeof Blob=="function"||typeof Blob<"u"&&oa.call(Blob)==="[object BlobConstructor]",Jc=typeof File=="function"||typeof File<"u"&&oa.call(File)==="[object FileConstructor]";function oi(s){return jc&&(s instanceof ArrayBuffer||Dc(s))||Uc&&s instanceof Blob||Jc&&s instanceof File}function Qn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(Qn(s[e]))return!0;return!1}if(oi(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Qn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&Qn(s[e]))return!0;return!1}function qc(s){const t=[],e=s.data,n=s;return n.data=Rs(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Rs(s,t){if(!s)return s;if(oi(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]=Rs(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]=Rs(s[n],t));return e}return s}function Gc(s,t){return s.data=Os(s.data,t),delete s.attachments,s}function Os(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]=Os(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Os(s[e],t));return s}const Hc=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Vt;(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"})(Vt||(Vt={}));class Vc{constructor(t){this.replacer=t}encode(t){return(t.type===Vt.EVENT||t.type===Vt.ACK)&&Qn(t)?this.encodeAsBinary({type:t.type===Vt.EVENT?Vt.BINARY_EVENT:Vt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===Vt.BINARY_EVENT||t.type===Vt.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=qc(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}}class ai extends oe{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===Vt.BINARY_EVENT;n||e.type===Vt.BINARY_ACK?(e.type=n?Vt.EVENT:Vt.ACK,this.reconstructor=new zc(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(oi(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(Vt[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Vt.BINARY_EVENT||n.type===Vt.BINARY_ACK){const r=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const a=t.substring(r,e);if(a!=Number(a)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const l=Number(a);if(!Wc(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=l}if(t.charAt(e+1)==="/"){const r=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(r,e)}else n.nsp="/";const i=t.charAt(e+1);if(i!==""&&Number(i)==i){const r=e+1;for(;++e;){const a=t.charAt(e);if(a==null||Number(a)!=a){--e;break}if(e===t.length)break}n.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(ai.isPayloadValid(n.type,r))n.data=r;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 Vt.CONNECT:return Oo(e);case Vt.DISCONNECT:return e===void 0;case Vt.CONNECT_ERROR:return typeof e=="string"||Oo(e);case Vt.EVENT:case Vt.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Hc.indexOf(e[0])===-1);case Vt.ACK:case Vt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class zc{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=Gc(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Wc=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Oo(s){return Object.prototype.toString.call(s)==="[object Object]"}const Yc=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ai,Encoder:Vc,get PacketType(){return Vt}},Symbol.toStringTag,{value:"Module"}));function Ee(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Kc=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class aa extends oe{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=[Ee(t,"open",this.onopen.bind(this)),Ee(t,"packet",this.onpacket.bind(this)),Ee(t,"error",this.onerror.bind(this)),Ee(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,i,r;if(Kc.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 a={type:Vt.EVENT,data:e};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,E=e.pop();this._registerAckCallback(c,E),a.id=c}const l=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,p=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!l||(p?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,e){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[t]=e;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);e.call(this,new Error("operation has timed out"))},i),a=(...l)=>{this.io.clearTimeoutFn(r),e.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...e){return new Promise((n,i)=>{const r=(a,l)=>a?i(a):n(l);r.withError=!0,e.push(r),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((i,...r)=>(this._queue[0],i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(i)):(this._queue.shift(),e&&e(null,...r)),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:Vt.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 Vt.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 Vt.EVENT:case Vt.BINARY_EVENT:this.onevent(t);break;case Vt.ACK:case Vt.BINARY_ACK:this.onack(t);break;case Vt.DISCONNECT:this.ondisconnect();break;case Vt.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(...i){n||(n=!0,e.packet({type:Vt.ACK,id:t,data:i}))}}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:Vt.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 dn(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}dn.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};dn.prototype.reset=function(){this.attempts=0};dn.prototype.setMin=function(s){this.ms=s};dn.prototype.setMax=function(s){this.max=s};dn.prototype.setJitter=function(s){this.jitter=s};class ks extends oe{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,fs(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 dn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||Yc;this.encoder=new i.Encoder,this.decoder=new i.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 Lc(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=Ee(e,"open",function(){n.onopen(),t&&t()}),r=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=Ee(e,"error",r);if(this._timeout!==!1){const l=this._timeout,p=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),e.close()},l);this.opts.autoUnref&&p.unref(),this.subs.push(()=>{this.clearTimeoutFn(p)})}return this.subs.push(i),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ee(t,"ping",this.onping.bind(this)),Ee(t,"data",this.ondata.bind(this)),Ee(t,"error",this.onerror.bind(this)),Ee(t,"close",this.onclose.bind(this)),Ee(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){hs(()=>{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 aa(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(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):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 yn={};function An(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Bc(s,t.path||"/socket.io"),n=e.source,i=e.id,r=e.path,a=yn[i]&&r in yn[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let p;return l?p=new ks(n,t):(yn[i]||(yn[i]=new ks(n,t)),p=yn[i]),e.query&&!t.query&&(t.query=e.queryKey),p.socket(e.path,t)}Object.assign(An,{Manager:ks,Socket:aa,io:An,connect:An});class Ns 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 ko="bimterop",Fs="revitflow_history.json",ca="revitflow_model.frag",la="revitflow_",Xc="bimterop-locks-anchor",wn=new Map;function Zc(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Qc(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 Ie(s){return String(s._id??s.id??"")}var ve,Ye,ke,On,kn,Ps;class ci{constructor(t,e){qt(this,kn);qt(this,ve);qt(this,Ye,new Map);qt(this,ke);qt(this,On,0);this.client=t,this.projectId=e}async docs(){const t=await I(this,kn,Ps).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const i of e){if(i.archived)continue;const r=String(i.name??""),a=r.indexOf("-");if(a<=0)continue;const p=(await this.client.listFiles({folderId:Ie(i)})).map(E=>String(E.name??"")),d=p.find(E=>E===ca)??p.find(E=>E.endsWith(".frag")&&!E.startsWith(la)),c=p.includes(Fs)||!!d;n.push({source:r.slice(0,a),docId:r.slice(a+1),folderId:Ie(i),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let i=N(this,Ye).get(n);return i||(i=new Ls(this.client,this,t,e),N(this,Ye).set(n,i)),i}document(t){const e=`platform-${t}`;let n=N(this,Ye).get(e);return n||(n=new Ls(this.client,this,"platform",t,t),N(this,Ye).set(e,n)),n}async childFolders(t,e=!1){return(e||!N(this,ke)||Date.now()-N(this,On)>3e4)&&(Xt(this,On,Date.now()),Xt(this,ke,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Zc(n,t))),N(this,ke).catch(()=>{Xt(this,ke,void 0)})),N(this,ke)}forgetFolders(){Xt(this,ke,void 0)}async rootFolderId(t=!1){if(N(this,ve))return N(this,ve);const e=await I(this,kn,Ps).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(ko,void 0,this.projectId);return Xt(this,ve,Ie(n)),N(this,ve)}}ve=new WeakMap,Ye=new WeakMap,ke=new WeakMap,On=new WeakMap,kn=new WeakSet,Ps=async function(){if(N(this,ve))return N(this,ve);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===ko&&!n.parentId);return e&&Xt(this,ve,Ie(e)),N(this,ve)};var Me,Et,Re,tn,Ue,$e,Nn,Bs,ts,Je,ha,fa,es,da,ua,pa;class Ls{constructor(t,e,n,i,r){qt(this,Et);qt(this,Me);qt(this,$e);qt(this,Nn,0);this.client=t,this.project=e,this.source=n,this.docId=i,Xt(this,Me,r)}async timeline(){const t=await I(this,Et,es).call(this);return li((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 I(this,Et,Je).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const e=await this.client.downloadFile(t.id);if(!e.ok)throw new Error(`Reading the model answered ${e.status}`);return await e.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,i=n?e.findIndex(c=>c.guid===n):e.length-1;if(i<0)throw new Error(`No version ${n} in this document's timeline.`);let r=0;for(let c=i;c>=0;c--)if(e[c].full){r=c;break}const a=await I(this,Et,Je).call(this);if(!a)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const l=e[r],p=e.slice(i+1).some(c=>c.full),d=e.slice(r+1,i+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(E=>E.type==="delete").map(E=>E.uniqueId)}));return{baseline:{fileId:a.id,guid:l.guid,current:!p,...l.version!==void 0?{storageVersion:l.version}:{}},steps:d,at:e[i].guid}}async folderId(){return await I(this,Et,Ue).call(this,!1)}async descriptor(){return await N(this,Et,Re).descriptor(await I(this,Et,Ue).call(this,!1))}async view(t){const e=await I(this,Et,Ue).call(this,!1),n=await N(this,Et,Re).descriptor(e);if(n){for(const r of t){const a=n.views.find(l=>l.format===r);if(a)return a}return null}if(!t.includes("frag"))return null;const i=await I(this,Et,Je).call(this);return i?{fileId:i.id,format:"frag"}:null}async addView(t){const e=await I(this,Et,Ue).call(this,!0);if(await N(this,Et,Re).descriptor(e)){await N(this,Et,Re).addView(e,t);return}const i=await I(this,Et,Je).call(this);await N(this,Et,Re).setDescriptor(e,{name:(i==null?void 0:i.name.replace(/\.frag$/,""))??N(this,Et,tn),views:[t]})}async ensureDescriptor(){const t=await I(this,Et,Ue).call(this,!1),e=await N(this,Et,Re).descriptor(t);if(e)return e;const n=await I(this,Et,Je).call(this);if(!n)return null;const i={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await N(this,Et,Re).setDescriptor(t,i),await N(this,Et,Re).descriptor(t)}async ownership(){const t=await I(this,Et,ts).call(this,Xc);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async a=>{try{const l=Ie(a),p=await this.client.downloadHiddenFile(l),d=JSON.parse(await p.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}})),i=new Set,r=new Map;for(const a of n)if(a)for(const l of a.keys){if(!l||i.has(l))continue;i.add(l);const p=r.get(a.owner)??[];p.push(l),r.set(a.owner,p)}return[...r.entries()].map(([a,l])=>({owner:a,elements:l}))}async sync(t){var l,p,d;const e=await I(this,Et,Ue).call(this,!0);let n=await I(this,Et,es).call(this)??{model:this.docId,commits:[]};const i=No(n.commits);if(t.expectedLatestGuid!==void 0&&(i==null?void 0:i.guid)!==t.expectedLatestGuid)throw new Ns(t.expectedLatestGuid,i==null?void 0:i.guid);const r={guid:hi(),...i?{parents:[i.guid]}:{},author:t.author,source:t.source,timestamp:t.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}:{},...(l=t.origins)!=null&&l.length?{origins:t.origins}:{},changes:t.changes,counts:tl(t.changes)};if(t.model&&(await I(this,Et,pa).call(this,e,t.model),r.full=!0),t.delta){const c=((p=await I(this,Et,Je).call(this))==null?void 0:p.id)??((d=t.file)==null?void 0:d.fileId)??void 0;if(!c)throw new Error("A delta needs the model file to hang from: sync a full model first.");const E=await this.client.createHiddenFile(t.delta,c);r.deltaId=Qc(E)}const a=await I(this,Et,es).call(this);if(a){n=a;const c=No(n.commits);if(t.expectedLatestGuid!==void 0&&(c==null?void 0:c.guid)!==t.expectedLatestGuid)throw new Ns(t.expectedLatestGuid,c==null?void 0:c.guid);c&&!r.parents&&(r.parents=[c.guid])}return n.commits.push(r),await I(this,Et,da).call(this,e,Fs,n),r}}Me=new WeakMap,Et=new WeakSet,Re=function(){return new di(this.client,this.project.projectId)},tn=function(){return`${this.source}-${this.docId}`},Ue=async function(t){if(N(this,Me))return N(this,Me);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=a=>a.find(l=>String(l.name??"")===N(this,Et,tn)),i=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(i)return Xt(this,Me,Ie(i)),N(this,Me);if(!t)throw new Error(`Document ${N(this,Et,tn)} does not exist in this project.`);const r=await this.client.createFolder(N(this,Et,tn),e,this.project.projectId);return this.project.forgetFolders(),Xt(this,Me,Ie(r)),N(this,Me)},$e=new WeakMap,Nn=new WeakMap,Bs=async function(){return(!N(this,$e)||Date.now()-N(this,Nn)>5e3)&&(Xt(this,Nn,Date.now()),Xt(this,$e,(async()=>{const t=await I(this,Et,Ue).call(this,!1);return t?(await this.client.listFiles({folderId:t,versions:!0})).map(n=>({id:Ie(n),name:String(n.name??""),stamp:cs(n)})):[]})()),N(this,$e).catch(()=>{Xt(this,$e,void 0)})),N(this,$e)},ts=async function(t){try{return(await I(this,Et,Bs).call(this)).find(e=>e.name===t)}catch{return}},Je=async function(){try{const t=await I(this,Et,Bs).call(this);return t.find(e=>e.name===ca)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(la))}catch{return}},ha=async function(t){const e=await I(this,Et,ts).call(this,t);if(!e)return;const n=e.stamp?wn.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const i=I(this,Et,fa).call(this,e,t);return e.stamp&&(wn.set(e.id,{stamp:e.stamp,value:i}),i.catch(()=>{var r;((r=wn.get(e.id))==null?void 0:r.value)===i&&wn.delete(e.id)})),structuredClone(await i)},fa=async function(t,e){const n=await this.client.downloadFile(t.id);if(!n.ok)throw new Error(`Reading ${e} answered ${n.status}`);const i=await n.text();if(i.trim())return JSON.parse(i)},es=function(){return I(this,Et,ha).call(this,Fs)},da=async function(t,e,n){const i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,Et,ts).call(this,e);return r?(wn.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)}),r):await I(this,Et,ua).call(this,t,e,n)},ua=async function(t,e,n){const i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await this.client.createFile({file:i,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Xt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:e}},pa=async function(t,e){const n=await I(this,Et,Je).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const i=`${N(this,Et,tn)}.frag`,r=await this.client.createFile({file:e,name:i,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Xt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:i}};function tl(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 li(s){var p;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=(p=d.parents)==null?void 0:p[0];if(c&&t.has(c)){const E=e.get(c)??[];E.push(d),e.set(c,E)}else n.push(d)}const i=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(i);const r=[],a=[...n].reverse(),l=new Set;for(;a.length;){const d=a.pop();if(l.has(d.guid))continue;l.add(d.guid),r.push(d);const c=(e.get(d.guid)??[]).sort(i);for(let E=c.length-1;E>=0;E--)a.push(c[E])}for(const d of s)l.has(d.guid)||r.push(d);return r.forEach((d,c)=>d.ordinal=c),r}function No(s){const t=li(s);return t[t.length-1]}function hi(){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 fi={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawing set",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"}},el={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 js(s){var e;if(s.type&&s.type in fi)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 i=n?el[n.toLowerCase()]:void 0;if(i)return i}return"generic"}const Rn="thatopen/document@1",$n="document.json",ma=["pdf","txt","md","json","csv","tsv","frag"];function be(s){return String(s._id??s.id??"")}const Ze=new Map;let Fo=!1;const cs=s=>{const t=s,e=[...t.versions??[]].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0],n=(e==null?void 0:e.tag)??t.versionTag;return n==null?void 0:String(n)};var se,ga,ya,Ds,wa,ba,va,Ea,In;class di{constructor(t,e){qt(this,se);this.client=t,this.projectId=e}async list(t){const e=await I(this,se,ga).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(i=>n.includes(js(i.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),i=String(n.name??""),r=Ts(i,n.fileExtension),a=(e==null?void 0:e.name)??i.replace(/\.[^.]+$/,"")??i,l=new Set((await this.list().catch(()=>[])).map(k=>String(k.descriptor.name??"").toLowerCase())),p=n.folderId?String(n.folderId):void 0;let d=a,c="";for(let k=1;k<100;k++){if(d=k===1?a:`${a} (${k})`,l.has(d.toLowerCase()))continue;const Y=await this.client.createFolder(d,p,this.projectId);if(c=be(Y),!await I(this,se,In).call(this,c))break}await this.client.updateFile(t,{parentFolderId:c});const E=[],b=await I(this,se,ba).call(this,n);if(b)try{const k=await this.client.getFile(b);await this.client.updateFile(b,{parentFolderId:c}),E.push({fileId:b,format:Ts(String(k.name??""),k.fileExtension)})}catch{}((e==null?void 0:e.selfView)??ma.includes(r))&&E.push({fileId:t,format:r});const P={schema:Rn,name:d,native:{fileId:t,format:r},views:E};return P.type=(e==null?void 0:e.type)??js(P),await this.setDescriptor(c,P),await this.recordUpload(c,{fileId:t,name:i,format:r},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:c,descriptor:P}}async recordUpload(t,e,n){const i=new ci(this.client,this.projectId).document(t),r=(await i.timeline()).length===0;await i.sync({author:n||"unknown",source:"platform",kind:"upload",message:r?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Ts(e.name,void 0)},changes:[]})}async descriptor(t){const e=await I(this,se,In).call(this,t);return e?I(this,se,Ds).call(this,e.id,e.stamp):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const i of e){const r=n.views.find(a=>a.format===i);if(r)return r}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(i=>i.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:Rn,views:e.views??[]},i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,se,In).call(this,t);if(r){Ze.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)});return}await this.client.createFile({file:i,name:$n,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new Ta(this.client,()=>I(this,se,In).call(this,t))}}se=new WeakSet,ga=async function(){const t=await I(this,se,ya).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===$n);return(await Promise.all(n.map(async r=>{const a=r,l=String(a.folderId??a.parentFolderId??"");if(!l)return null;const p=await I(this,se,Ds).call(this,be(r),cs(r));return p?{folderId:l,descriptor:p}:null}))).filter(r=>r!==null)},ya=async function(){if(Fo)return null;let t;try{t=await this.client.listDocumentDescriptors(this.projectId)}catch(n){const i=n.status;if(i===404||i===400||i===405)return Fo=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const i=Lo(n.descriptor);!i||!n.folderId||(n.fileId&&n.versionTag&&Ze.set(n.fileId,{stamp:n.versionTag,value:Promise.resolve(i)}),e.push({folderId:String(n.folderId),descriptor:i}))}return e},Ds=function(t,e){const n=e?Ze.get(t):void 0;if(n&&n.stamp===e)return n.value;const i=I(this,se,wa).call(this,t);return e&&(Ze.set(t,{stamp:e,value:i}),i.catch(()=>{var r;((r=Ze.get(t))==null?void 0:r.value)===i&&Ze.delete(t)})),i},wa=async function(t){const e=await this.client.downloadFile(t);if(!e.ok)throw new Error(`Reading a document's descriptor answered ${e.status}`);const n=await e.text();if(!n.trim())return null;let i;try{i=JSON.parse(n)}catch{return null}return Lo(i)},ba=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const d=n.find(c=>be(c)===be(t));e=(d==null?void 0:d.versions)??[]}const i=await I(this,se,Ea).call(this,t,e);if(i)return i;const r=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!r)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const a=d=>String(d.folderId??d.parentFolderId??""),l=new Set(n.filter(d=>String(d.name??"")===$n).map(a)),p=n.filter(d=>String(d.name??"").toLowerCase()===`${r}.frag`&&!d.archived&&be(d)!==be(t)&&!l.has(a(d)));for(const d of p){const c=await I(this,se,va).call(this,d);if(c===void 0||c===be(t))return be(d)}},va=async function(t){const n=[...t.versions??[]].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0];if(n)try{const i=await this.client.getFileVersionMetadata(be(t),n.tag);return typeof(i==null?void 0:i.sourceIfcId)=="string"&&i.sourceIfcId?i.sourceIfcId:void 0}catch{return}},Ea=async function(t,e){const n=[...e].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")));for(const i of n)try{const r=await this.client.getFileVersionMetadata(be(t),i.tag),a=r==null?void 0:r.derivedFileId;if(typeof a=="string"&&a)return a}catch{}},In=async function(t){if(!t)return;const n=(await this.client.listFiles({folderId:t,versions:!0})).find(i=>String(i.name??"")===$n);return n?{id:be(n),stamp:cs(n)}:void 0};const Us="draft:",en="TODRAFT1";var Se,Sn,Js;class Ta{constructor(t,e){qt(this,Se);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 I(this,Se,Sn).call(this,t.id)){const i=e.get(n.userId);(!i||n.savedAt>i.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,i)=>+i.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const i=(await I(this,Se,Sn).call(this,e.id)).filter(p=>!(t!=null&&t.userId)||p.userId===t.userId).sort((p,d)=>+d.savedAt-+p.savedAt)[0];if(!i)return null;const r=await this.client.downloadHiddenFile(i.hiddenId),{meta:a,blob:l}=await il(await r.blob());return{userId:i.userId,savedAt:i.savedAt,meta:a,blob:l}}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 i=nl(e.userId),r=(await I(this,Se,Sn).call(this,n.id)).filter(p=>p.userId===e.userId),l=(await this.client.createHiddenFile(await sl(t,e.meta??{}),n.id,i)).hiddenFileId;if(!l)throw new Error("The draft upload answered without a hiddenFileId.");return await I(this,Se,Js).call(this,r.map(p=>p.hiddenId)),{userId:e.userId,savedAt:Po(l)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await I(this,Se,Sn).call(this,e.id)).filter(i=>i.userId===t.userId);await I(this,Se,Js).call(this,n.map(i=>i.hiddenId))}}Se=new WeakSet,Sn=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(Us)).map(n=>{const i=String(n._id);return{hiddenId:i,userId:n.tag.slice(Us.length),savedAt:Po(i)}})},Js=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function nl(s){const t=`${Us}${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 Po(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function sl(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(en),n,e,s])}async function il(s){const t=new Uint8Array(await s.slice(0,en.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,en.length))!==en)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(en.length,!0),n=en.length+4,i=await s.slice(n,n+e).text();let r={};try{r=JSON.parse(i)}catch{}return{meta:r,blob:s.slice(n+e)}}function Ts(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Lo(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Rn||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(l=>!!l&&typeof l=="object"&&typeof l.fileId=="string"&&typeof l.format=="string"):[],n=t.native,i=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",r=typeof t.type=="string"&&t.type in fi?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:Rn,name:t.name,...r?{type:r}:{},...i?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const rl="flow:",ol="flow:op",al="flow:source",cl="flow:host",ll="flow:print",ui="revitflow/op@2",Bo="REVITFLOWCHANGE",jo="REVITFLOWOPERATION";class ds{constructor(t){he(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:ui,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,i]=await hl();return fl(this.flatbuffer(n,i,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[i,r]of Object.entries(t??{}))i.startsWith(rl)&&i!==ll||(n[i]=String(r));return e.position&&(n.Position=e.position.map(Do).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Do(e.rotationDeg)),e.source&&(n[al]=e.source),e.host&&(n[cl]=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,i){const{Attribute:r,Meshes:a,Model:l,SpatialStructure:p,Transform:d}=e,c=new t.Builder(1024),E=this.changes.length,b=new Uint32Array(E);let $=1;for(let rt=0;rt<E;rt++)b[rt]=$++;const P=$++,k=rt=>(rt(c,0),c.endVector()),Y=a.createShellsVector(c,[]),V=a.createCircleExtrusionsVector(c,[]),D=k(a.startSamplesVector),f=k(a.startRepresentationsVector),Tt=k(a.startMaterialsVector),nt=k(a.startLocalTransformsVector),wt=k(a.startGlobalTransformsVector),Pt=a.createMeshesItemsVector(c,[]),tt=a.createMaterialIdsVector(c,[]),ct=a.createRepresentationIdsVector(c,[]),ht=a.createSampleIdsVector(c,[]),kt=a.createLocalTransformIdsVector(c,[]),te=a.createGlobalTransformIdsVector(c,[]);a.startMeshes(c),a.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),a.addGlobalTransforms(c,wt),a.addShells(c,Y),a.addRepresentations(c,f),a.addSamples(c,D),a.addLocalTransforms(c,nt),a.addMaterials(c,Tt),a.addCircleExtrusions(c,V),a.addMeshesItems(c,Pt),a.addRepresentationIds(c,ct),a.addSampleIds(c,ht),a.addMaterialIds(c,tt),a.addLocalTransformIds(c,kt),a.addGlobalTransformIds(c,te);const Wt=a.endMeshes(c),at=c.createString(i),st=new Set,pt=[];for(const rt of this.changes){const _t=[],ie={[ol]:rt.op,...rt.attrs};for(const[Nt,le]of Object.entries(ie)){const me=JSON.stringify([Nt,le,"IFCTEXT"]);st.add(me),_t.push(c.createString(me))}pt.push(r.createAttribute(c,r.createDataVector(c,_t)))}{const rt=JSON.stringify(["Name",n,"IFCLABEL"]);st.add(rt);const _t=r.createDataVector(c,[c.createString(rt)]);pt.push(r.createAttribute(c,_t))}const Bt=l.createAttributesVector(c,pt),Gt=l.createUniqueAttributesVector(c,[...st].map(rt=>c.createString(rt))),jt=this.changes.map(()=>c.createString(Bo));jt.push(c.createString(jo));const Kt=l.createCategoriesVector(c,jt),Yt=[],zt=[];this.changes.forEach((rt,_t)=>{rt.item&&(Yt.push(c.createString(rt.item)),zt.push(b[_t]))});const U=l.createGuidsVector(c,Yt),Z=l.createGuidsItemsVector(c,zt),B=l.createLocalIdsVector(c,[...b,P]),ut=this.changes.map((rt,_t)=>p.createSpatialStructure(c,b[_t],c.createString(Bo),0)),X=p.createSpatialStructure(c,P,c.createString(jo),p.createChildrenVector(c,ut)),dt=c.createString(n);l.startModel(c),l.addMeshes(c,Wt),l.addMetadata(c,at),l.addAttributes(c,Bt),l.addUniqueAttributes(c,Gt),l.addLocalIds(c,B),l.addCategories(c,Kt),l.addGuidsItems(c,Z),l.addGuids(c,U),l.addGuid(c,dt),l.addSpatialStructure(c,X),l.addMaxLocalId(c,$);const Mt=l.endModel(c);return l.finishModelBuffer(c,Mt),c.asUint8Array()}}async function hl(){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 Do(s){return Number.isFinite(s)?String(s):"0"}async function fl(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function us(s){const[t,e]=await dl(),n=e.Model.getRootAsModel(new t.ByteBuffer(await ul(s)));let i={};try{i=JSON.parse(n.metadata()??"{}")}catch{}const r=new Map;for(let l=0;l<n.guidsLength();l++){const p=n.guidsItems(l),d=n.guids(l);p!==null&&d&&r.set(p,d)}const a=[];for(let l=0;l<n.attributesLength();l++){const p=n.localIds(l);if(p===null)continue;const d={},c=n.attributes(l);for(let E=0;E<((c==null?void 0:c.dataLength())??0);E++){const b=c.data(E);if(b)try{const[$,P]=JSON.parse(b);d[$]=P}catch{}}a.push({localId:p,guid:r.get(p)??null,category:n.categories(l)??null,attrs:d})}return{metadata:i,items:a}}async function dl(){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 ul(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const Ma="Element",$a="Carried",sn=1/.3048;function Ia(s){const t=[];for(const e of s)for(const n of[Ma,$a]){const i=e.attrs[n];if(i)try{const r=JSON.parse(i);for(const a of Array.isArray(r)?r:[r]){const l=a;typeof(l==null?void 0:l.id)!="string"||typeof(l==null?void 0:l.kind)!="string"||t.push({id:l.id,kind:l.kind,params:l.params??{},item:e})}}catch{}}return t}function de(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function pl(s){const t=new Map;for(const[e,n]of pi(s))t.set(e,n.name);return t}function pi(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,i=e.params.at;typeof n=="string"&&typeof i=="number"&&t.set(e.id,{name:n,at:i})}return t}function Sa(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 mi(s,t){const e=new Map;for(const[n,i]of s.made)e.set(n,i.id),i.print&&(t==null||t.set(n,i.print));return e}function ns(s){const t=i=>Array.isArray(i)?i.map(t):i&&typeof i=="object"?Object.fromEntries(Object.keys(i).sort().map(r=>[r,t(i[r])])):i,e=JSON.stringify(t(s));let n=2166136261;for(let i=0;i<e.length;i++)n^=e.charCodeAt(i),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function gi(s,t){var a,l;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=((l=(a=/\.([^.]+)$/.exec(t.name))==null?void 0:a[1])==null?void 0:l.toLowerCase())??"frag";let i=null,r=null;if(n!=="frag"){const p=s.client.recipes.importerFor(n);if(!p)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(i=xa(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),r=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await p(e,t.name)}return{picked:t,contents:await us(e),site:i,shapes:r}}function xa(s){var wt;const t=new TextDecoder("latin1").decode(s),e=Pt=>new RegExp(`^${Pt}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=Pt=>[...Pt.matchAll(/#\d+|\$/g)].map(tt=>tt[0]),i=Pt=>[...Pt.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(tt=>Number(tt[0])),r=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!r)return null;const a=(wt=r[2].split(",")[5])==null?void 0:wt.trim();if(!(a!=null&&a.startsWith("#")))return null;const l=e(a);if((l==null?void 0:l[1])!=="IFCLOCALPLACEMENT")return null;const[p,d]=n(l[2]);if(p!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[E,,b]=n(c[2]),$=E&&E!=="$"?e(E):null;if(!$)return null;const[P=0,k=0,Y=0]=i($[2]);let V=0;const D=b&&b!=="$"?e(b):null;if(D){const[Pt=1,tt=0]=i(D[2]);V=Math.atan2(tt,Pt)*180/Math.PI}const f=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),Tt={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},nt=f?f[2]?Tt[f[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:P*nt,north:k*nt,elevation:Y*nt,angleDeg:V}}const yi="thatopen/recipe@1",Uo="__project_data",Jo="recipes",ml=s=>`${s}.recipe.json`,_a={OperationBuilder:ds,OP_SCHEMA:ui,readFrag:us,readPickedFrag:gi,recordsOf:Ia,innerJson:de,levelsOf:pi,levelNames:pl,stylesOf:Sa,printOf:ns,siteLocationOf:xa,whatItMadeBefore:mi,ELEMENT_FIELD:Ma,CARRIED_FIELD:$a,FEET_PER_METRE:sn},Aa=/^[a-z0-9][a-z0-9-]{1,62}$/;async function Ca(s,t,e){const n=d=>[...d].sort((c,E)=>String(c._id).localeCompare(String(E._id)))[0],i=await s.listFolders({projectId:t,archived:!1});let r=n(i.filter(d=>d.name===Uo&&!d.parentId));if(!r){if(!e)return null;r=await s.createFolder(Uo,void 0,t)}const a=String(r._id),l=await s.listFolders({parentFolderId:a,projectId:t,archived:!1});let p=n(l.filter(d=>d.name===Jo&&String(d.parentId)===a));if(!p){if(!e)return null;p=await s.createFolder(Jo,a,t)}return String(p._id)}const gl=s=>String(s._id??s.id??""),yl=s=>String(s.tag??s.versionTag??""),qs=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function bn(s,t){const e=await Ca(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),i=new Map;for(const r of n){const a=String(r.name??"");a.endsWith(".recipe.json")&&i.set(a.slice(0,-12),{id:gl(r)})}return i}async function Kn(s,t,e){var r;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),i=JSON.parse(await n.text());if((i==null?void 0:i.schema)!==yi||!((r=i.manifest)!=null&&r.name)||typeof i.code!="string")throw new Error(`This is not a recipe this library can read (${String(i==null?void 0:i.schema)}).`);return i}async function vn(s,t){return(await s.listVersions(t)).map(n=>({tag:yl(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,i)=>qs(n.tag)-qs(i.tag))}var Fn;class Ra{constructor(t,e){qt(this,Fn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await bn(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:i}])=>{var r;try{const a=await vn(this.client,i),l=(r=a[a.length-1])==null?void 0:r.tag,p=await Kn(this.client,i,l);return{manifest:p.manifest,origin:"project",version:l,author:p.author,savedAt:p.savedAt}}catch{return null}}))).filter(i=>i!==null)}async versions(t,e){const n=(await bn(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const i=await vn(this.client,n.id);return await Promise.all(i.map(async({tag:r,createdAt:a})=>{try{const l=await Kn(this.client,n.id,r);return{version:r,author:l.author,note:l.note,savedAt:l.savedAt??a}}catch{return{version:r,savedAt:a}}}))}async source(t,e,n){var a;const i=(await bn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((a=(await vn(this.client,i.id)).pop())==null?void 0:a.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);return{...await Kn(this.client,i.id,r),version:r}}async save(t,e,n){const{manifest:i,code:r}=e;if(!Aa.test((i==null?void 0:i.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(i.name))throw new Error(`"${i.name}" is a built-in recipe. Give yours a name of its own.`);if(!i.to||!i.description||!Array.isArray(i.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await Gs(i,r);const a={schema:yi,manifest:i,code:r,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},l=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),p=(await bn(this.client,t)).get(i.name);if(p){const c=await vn(this.client,p.id),E=`v${Math.max(0,...c.map(b=>qs(b.tag)))+1}`;return await this.client.createVersion(p.id,l,E),E}const d=await Ca(this.client,t,!0);return await this.client.createFile({file:l,name:ml(i.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var p;const i=(await bn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((p=(await vn(this.client,i.id)).pop())==null?void 0:p.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);const a=`${i.id}@${r}`;let l=N(this,Fn).get(a);if(!l){const d=await Kn(this.client,i.id,r);l=await Gs(d.manifest,d.code),N(this,Fn).set(a,l)}return{recipe:l,version:r}}}Fn=new WeakMap;async function Gs(s,t){var i;let e;try{e=await import(`data:text/javascript;base64,${wl(t)}`)}catch(r){throw new Error(`The recipe's code does not load: ${r instanceof Error?r.message:String(r)}`)}const n=e.run??((i=e.default)==null?void 0:i.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:r=>n({...r,kit:_a})}}function wl(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 bl(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await us(t),i=e.filter(r=>r.attrs["flow:op"]).map(r=>{const a={};for(const[l,p]of Object.entries(r.attrs))l.startsWith("flow:")||(a[l]=p);return{op:r.attrs["flow:op"],...r.guid?{target:r.guid}:{},...r.attrs["flow:source"]?{source:r.attrs["flow:source"]}:{},attrs:a}});return{envelope:n??{},changes:i}}class wi extends Error{constructor(t){super(t),this.name="UpToDate"}}var Ne,Pn,Ln;class Oa{constructor(t){qt(this,Ne,new Map);qt(this,Pn,new Map);qt(this,Ln,new Map);he(this,"project");this.client=t,this.project=new Ra(t,()=>new Set(N(this,Ne).keys()))}provideImporter(t,e){N(this,Pn).set(t.toLowerCase(),e)}provideShapes(t,e){N(this,Ln).set(t.toLowerCase(),e)}shapesFor(t){return N(this,Ln).get(t.toLowerCase())}importerFor(t){return N(this,Pn).get(t.toLowerCase())}register(t){if(N(this,Ne).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);N(this,Ne).set(t.name,t)}list(t){return[...N(this,Ne).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return N(this,Ne).get(t)}async catalog(t,e){const n=this.list(e).map(r=>({manifest:r,origin:"builtin"}));let i=[];try{i=(await this.project.list(t)).filter(r=>!(e!=null&&e.to)||r.manifest.to===e.to)}catch{}return[...n,...i.sort((r,a)=>r.manifest.name.localeCompare(a.manifest.name))]}async resolve(t,e,n){const i=N(this,Ne).get(t);return i?{recipe:i,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),i=n.source;if((i==null?void 0:i.kind)!=="project-file")return[];const r=(i.extensions??[]).map(d=>d.toLowerCase()),l=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(r.length===0||r.includes(d.descriptor.native.format.toLowerCase()))),p=await ka(this.client,l.map(d=>d.descriptor.native.fileId));return l.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:p.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??hi(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}Ne=new WeakMap,Pn=new WeakMap,Ln=new WeakMap;async function ka(s,t){const e=new Map;if(t.length===0)return e;const n=r=>{var a;return Number(((a=/(\d+)/.exec(String(r??"")))==null?void 0:a[1])??-1)},i=r=>{const l=r.slice().sort((p,d)=>{const c=p!=null&&p.createdAt?new Date(String(p.createdAt)).getTime():NaN,E=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(E)&&c!==E?E-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((p==null?void 0:p.tag)??(p==null?void 0:p.versionTag))})[0];return l?String(l.tag??l.versionTag??"v1"):"v1"};return await Promise.all(t.map(async r=>{try{e.set(r,i(await s.listVersions(r)))}catch{e.set(r,"v1")}})),e}const Hs=100;function vl(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 El(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class ps extends Error{constructor(e,n,i,r){const a=vl(i);super(a.message??`${n||"Request failed"} (${e})`);he(this,"status");he(this,"code");he(this,"details");he(this,"body");he(this,"retryAfter");this.name="RequestError",this.status=e,this.code=a.code,this.details=a.details,this.body=i,this.retryAfter=r??El(a.details)}}const Te="item/folder",Lt="item",je="processor",Tl="npm-registry",Ae="hidden",Ms="FILE",$s="TOOL",Is="APP",Ml=500,qo=3e4,$l=2e3,Il=15e3,Sl=s=>/^\/?project\/permissions\/check/.test(s),xl=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),En=new Map,_l=.25,Al=s=>new Promise(t=>setTimeout(t,s));function Cl(s){var i,r;const t=(r=(i=s.headers)==null?void 0:i.get)==null?void 0:r.call(i,"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 Rl(s){return s instanceof ps?s.status===429||s.status>=500:!0}function Ol(s,t){const e=Math.min(Ml*2**t,qo),n=e*_l*Math.random(),i=s instanceof ps&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return i!=null?Math.min(i,qo)+n:e+n}var W,ss,vt,Vs,qe,on,Na,Bn,xn,is,rs,zs,Ws,Ys;const Ei=class Ei{constructor(t,e,n){qt(this,W);he(this,"apiUrl");he(this,"accessToken");he(this,"wsUrl");he(this,"retries");he(this,"useBearer");he(this,"builtInGlobals",null);he(this,"localServerUrl",null);he(this,"context");qt(this,on,new Map);qt(this,Bn);const{retries:i=0,useBearer:r=!1,localServerUrl:a}=n||{};let l=e;if(l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.apiUrl=`${l}/api`,this.accessToken=t,this.wsUrl=l,this.retries=i,this.useBearer=r,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},a){let p=a;p.charAt(p.length-1)==="/"&&(p=p.slice(0,-1)),this.localServerUrl=p}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Ei(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 I(this,W,vt).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:i,versions:r}=t||{};return e?await I(this,W,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ms,archived:n,...r&&{showVersions:!0}}}):await I(this,W,vt).call(this,"GET",`${Lt}`,{query:{itemType:Ms,archived:n,...i&&{projectId:i}}})}async listDocumentDescriptors(t){const e=N(this,on).get(t);if(e)return await e;const n=I(this,W,Na).call(this,t);N(this,on).set(t,n);try{return await n}finally{N(this,on).delete(t)}}async exportProjectDocuments(t,e){return(e==null?void 0:e.format)==="csv"?(await(await I(this,W,vt).call(this,"GET",`${Lt}/export`,{query:{projectId:t,format:"csv"},responseType:"blob"})).text()).replace(/^/,""):await I(this,W,vt).call(this,"GET",`${Lt}/export`,{query:{projectId:t}})}async getFile(t,e){return await I(this,W,Ws).call(this,t,e)}async createFile(t){return await I(this,W,rs).call(this,t,Ms)}async updateFile(t,e){return await I(this,W,zs).call(this,t,e)}async archiveFile(t){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${t}`)}async recoverFile(t){return await I(this,W,vt).call(this,"PUT",`${Lt}/${t}/recover`)}async downloadFile(t,e){return await I(this,W,is).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:i}=n||{};return await I(this,W,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...i&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await I(this,W,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await I(this,W,xn).call(this,t,async i=>(await I(this,W,vt).call(this,"POST",`${Lt}/batch/version-metadata`,{body:JSON.stringify({entries:i,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:i}=t||{};return await I(this,W,vt).call(this,"GET",Te,{query:{parentFolderId:n,archived:e,...i&&{projectId:i}}})}async getFolder(t){return await I(this,W,vt).call(this,"GET",`${Te}/${t}`)}async getFoldersBatch(t){return await I(this,W,xn).call(this,t,async e=>(await I(this,W,vt).call(this,"POST",`${Lt}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await I(this,W,vt).call(this,"POST",Te,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await I(this,W,vt).call(this,"PUT",`${Te}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await I(this,W,vt).call(this,"DELETE",`${Te}/${t}`)}async recoverFolder(t){return await I(this,W,vt).call(this,"PUT",`${Te}/${t}/recover`)}async downloadFolder(t){return await I(this,W,qe).call(this,`${Te}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:i}=t||{};return e?await I(this,W,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:$s,...n&&{ShowVersions:n}}}):await I(this,W,vt).call(this,"GET",`${Lt}`,{query:{itemType:$s,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async getComponent(t,e){return await I(this,W,Ws).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await I(this,W,rs).call(this,t,$s,e)}async updateComponent(t,e){const{componentProps:n}=e;return await I(this,W,zs).call(this,t,e,n)}async downloadComponent(t,e){return await I(this,W,is).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,W,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}})}async archiveComponent(t){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${t}`)}async recoverComponent(t){return await I(this,W,vt).call(this,"PUT",`${Lt}/${t}/recover`)}async getBuiltInComponent(t){return await(await I(this,W,qe).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const i=await this.getBuiltInComponent(t.uuid),r=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},a=Object.keys(r),l=a.map(E=>r[E]),d=new Function(...a,`${i}
2
+ return main;`)(...l),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 a,l;const n=t.OBC,i=t.BUI;if(!(n!=null&&n.Components))throw new Error("globals.OBC must include Components");if(!(i!=null&&i.Manager))throw new Error("globals.BUI must include Manager");const r=new n.Components;return i.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(r,...e),r.init(),(l=(a=this.context.appEventOrchestrator)==null?void 0:a.appLoaded)==null||l.call(a),{components:r}}throwError(t,e){var n,i;(i=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||i.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:i}=t||{};return e?await I(this,W,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Is,...n&&{ShowVersions:n}}}):await I(this,W,vt).call(this,"GET",`${Lt}`,{query:{itemType:Is,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async createApp(t){const{appProps:e}=t;return await I(this,W,rs).call(this,t,Is,e)}async downloadApp(t,e){return await I(this,W,is).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,W,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}})}async archiveApp(t){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${t}`)}async getNpmCredentials(){return await I(this,W,vt).call(this,"GET",`${Tl}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const i=`${this.localServerUrl}/api/${je}/${t}/execute`,r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const a=await r.text().catch(()=>"");throw new Error(`Local server request failed: ${r.status} - ${a}`)}return await r.json()}return await I(this,W,vt).call(this,"POST",`${je}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${i}`)}return await n.json()}return await I(this,W,vt).call(this,"POST",`${je}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",i=`${this.localServerUrl}/api/${je}/${t}/progress${n}`,r=await fetch(i);if(!r.ok){const a=await r.text().catch(()=>"");throw new Error(`Local server request failed: ${r.status} - ${a}`)}return await r.json()}return await I(this,W,vt).call(this,"GET",`${je}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/progress/${t}`,n=await fetch(e);if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${i}`)}return await n.json()}return await I(this,W,vt).call(this,"GET",`${je}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,i=await An(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});i.on("connect",function(){i.emit("executionSubscription",JSON.stringify({executionId:t})),i.on("execution",r=>{e(r)})}),i.on("connect_error",function(r){console.log(r)})}documents(t){return new di(this,t)}history(t){return new ci(this,t)}get recipes(){return N(this,Bn)??Xt(this,Bn,new Oa(this)),N(this,Bn)}async createHiddenFile(t,e,n){const i=new FormData;return i.append("file",t),i.append("parentItemId",e),n!=null&&i.append("tag",n),await I(this,W,vt).call(this,"POST",`${Lt}/${Ae}`,{body:i})}async createHiddenFilesBatch(t,e,n){const i=new FormData;for(const r of t)i.append("files",r);return i.append("parentItemId",e),n!=null&&i.append("tag",n),await I(this,W,vt).call(this,"POST",`${Lt}/${Ae}/batch`,{body:i})}async deleteHiddenFile(t){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${Ae}/${t}`)}async getHiddenFile(t){return await I(this,W,vt).call(this,"GET",`${Lt}/${Ae}/${t}`)}async downloadHiddenFile(t){return await I(this,W,qe).call(this,`${Lt}/${Ae}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await I(this,W,vt).call(this,"GET",`${Lt}/${Ae}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await I(this,W,xn).call(this,t,async n=>(await I(this,W,vt).call(this,"POST",`${Lt}/${Ae}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await I(this,W,vt).call(this,"GET",`${Lt}/${t}/${Ae}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${t}/${Ae}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await I(this,W,vt).call(this,"PUT",`${Lt}/${t}/icon`,{body:n})}async getItemIcon(t){return await I(this,W,qe).call(this,`${Lt}/${t}/icon`)}async removeItemIcon(t){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${t}/icon`)}async updateItem(t,e){return await I(this,W,vt).call(this,"PUT",`${Lt}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,i,r){const a=new FormData;a.append("file",e),a.append("versionTag",n),i&&a.append("extraProps",JSON.stringify(i));const l=await I(this,W,vt).call(this,"POST",`${Lt}/${t}/version`,{body:a});return r&&await this.updateFileVersionMetadata(t,(l==null?void 0:l.tag)??n,r),l}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 i of e){const r=/^v(\d{1,6})$/.exec(String(i.tag??i.versionTag??""));r&&(n=Math.max(n,Number(r[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await I(this,W,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await I(this,W,xn).call(this,t,async i=>(await I(this,W,vt).call(this,"POST",`${Lt}/batch/versions`,{body:JSON.stringify({itemIds:i,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await I(this,W,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await I(this,W,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await I(this,W,vt).call(this,"DELETE",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};W=new WeakSet,ss=function(t){return`${this.apiUrl}/${t}`},vt=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const i=`${I(this,W,ss).call(this,e)}?${new URLSearchParams(I(this,W,Ys).call(this,n==null?void 0:n.query)).toString()}`,r=Date.now(),a=En.get(i);if(a&&(a.pending||r-a.at<(xl(e)?Il:$l)))return a.answer.then(p=>p===void 0?p:structuredClone(p));const l={at:r,pending:!0,answer:I(this,W,Vs).call(this,t,e,n)};return En.set(i,l),l.answer.then(()=>{l.pending=!1,l.at=Date.now()},()=>{En.get(i)===l&&En.delete(i)}),l.answer.then(p=>p===void 0?p:structuredClone(p))}return t!=="GET"&&!Sl(e)&&En.clear(),I(this,W,Vs).call(this,t,e,n)},Vs=async function(t,e,n){const{body:i,query:r,contentType:a,retries:l,responseType:p,retryAttempt:d}=n||{},c=I(this,W,ss).call(this,e),E=I(this,W,Ys).call(this,r),b=await this.resolveAccessToken(),$={...E,...this.useBearer?{}:{accessToken:b}};try{const P=await fetch(c+"?"+new URLSearchParams($).toString(),{method:t,headers:{Accept:"application/json",...a&&{"Content-Type":a},...this.useBearer&&{Authorization:`Bearer ${b}`}},...i&&{body:i}});if(!P.ok){const k=await P.text().then(Y=>Y).catch(()=>"");throw new ps(P.status,P.statusText,k,Cl(P))}return p==="blob"?await P.blob():P.json().then(k=>k).catch(()=>{})}catch(P){const k=l??this.retries;if(k>0&&Rl(P)){const Y=d??0;return await Al(Ol(P,Y)),await I(this,W,vt).call(this,t,e,{...n,retries:k-1,retryAttempt:Y+1})}throw P}},qe=async function(t,e){const{query:n}=e||{},i=I(this,W,ss).call(this,t),r=await this.resolveAccessToken(),a={...n,...this.useBearer?{}:{accessToken:r}};return await fetch(i+"?"+new URLSearchParams(a).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${r}`}}})},on=new WeakMap,Na=async function(t){return await I(this,W,vt).call(this,"GET",`${Lt}/documents`,{query:{projectId:t}})},Bn=new WeakMap,xn=async function(t,e){if(!t.length)return[];const n=[];for(let r=0;r<t.length;r+=Hs)n.push(t.slice(r,r+Hs));return(await Promise.all(n.map(e))).flat()},is=async function(t,e){const{versionTag:n,withDraft:i}=e||{},r=await I(this,W,qe).call(this,`${Lt}/${t}/download`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}});if(r.status===429||r.status>=500)throw new Error(`Downloading ${t} answered ${r.status}${r.status===429?" (rate limited)":""}`);return r},rs=async function(t,e,n){const{name:i,versionTag:r,parentFolderId:a,projectId:l,file:p,metadata:d}=t,c=new FormData;return c.append("file",p),c.append("name",i),c.append("versionTag",r),c.append("itemType",e),a&&c.append("folderId",a),l&&c.append("projectId",l),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await I(this,W,vt).call(this,"POST",Lt,{body:c})},zs=async function(t,e,n){const{name:i,versionTag:r,parentFolderId:a,file:l,metadata:p}=e;let d,c;if(l){const E=new FormData;E.append("file",l),r&&E.append("versionTag",r),n&&E.append("extraProps",JSON.stringify(n)),c=await I(this,W,vt).call(this,"POST",`${Lt}/${t}/version`,{body:E});const b=(c==null?void 0:c.tag)??r;p&&b&&await this.updateFileVersionMetadata(t,b,p)}if(i||a){const E={...i&&{name:i},...a&&{folderId:a}},b=JSON.stringify(E);d=await I(this,W,vt).call(this,"PUT",`${Lt}/${t}`,{body:b,contentType:"application/json"})}return{item:d,version:c}},Ws=async function(t,e){const{showVersions:n=!1}=e||{};return await I(this,W,vt).call(this,"GET",`${Lt}/${t}`,{query:{showVersions:n}})},Ys=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,i])=>(e[n]=i,e),{})};let ls=Ei;function Fa(){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 Ks="channel:",kl=1e4;function os(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var Fe,ge,ye,an,cn,ln,ue,Xs,Zs,nn;class bi{constructor(t,e){qt(this,ue);qt(this,Fe,!1);qt(this,ge,[]);qt(this,ye,[]);qt(this,an,new Set);qt(this,cn,new Set);qt(this,ln,new Set);this.transport=t,this.controls=e}get joined(){return N(this,Fe)}get peers(){return N(this,ge)}join(){return N(this,Fe)?Promise.resolve():I(this,ue,Xs).call(this,"joined",this.controls.join)}leave(){return!N(this,Fe)&&!N(this,ye).some(t=>t.want==="joined")?Promise.resolve():I(this,ue,Xs).call(this,"left",this.controls.leave)}onChange(t){return N(this,an).add(t),()=>void N(this,an).delete(t)}onPeerJoined(t){return N(this,cn).add(t),()=>void N(this,cn).delete(t)}onPeerLeft(t){return N(this,ln).add(t),()=>void N(this,ln).delete(t)}applyJoined(){Xt(this,Fe,!0),I(this,ue,Zs).call(this,"joined"),I(this,ue,nn).call(this)}applyLeft(){Xt(this,Fe,!1),Xt(this,ge,[]),I(this,ue,Zs).call(this,"left"),I(this,ue,nn).call(this)}applyPeers(t){Xt(this,ge,t),I(this,ue,nn).call(this)}applyPeerJoined(t){!N(this,Fe)||N(this,ge).some(e=>e.from===t.from)||(Xt(this,ge,[...N(this,ge),t]),N(this,cn).forEach(e=>os(()=>e(t))),I(this,ue,nn).call(this))}applyPeerLeft(t){const e=N(this,ge).find(n=>n.from===t);e&&(Xt(this,ge,N(this,ge).filter(n=>n.from!==t)),N(this,ln).forEach(n=>os(()=>n(e))),I(this,ue,nn).call(this))}failPending(t){const e=N(this,ye);return Xt(this,ye,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}Fe=new WeakMap,ge=new WeakMap,ye=new WeakMap,an=new WeakMap,cn=new WeakMap,ln=new WeakMap,ue=new WeakSet,Xs=function(t,e){return new Promise((n,i)=>{const r={want:t,resolve:n,reject:i,timer:setTimeout(()=>{Xt(this,ye,N(this,ye).filter(a=>a!==r)),i(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},kl)};N(this,ye).push(r),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},Zs=function(t){const e=N(this,ye).filter(n=>n.want===t);Xt(this,ye,N(this,ye).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},nn=function(){N(this,an).forEach(t=>os(t))};var hn;class Pa extends bi{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});qt(this,hn,new Map)}on(e,n){const i=N(this,hn).get(e)??new Set;return i.add(n),N(this,hn).set(e,i),()=>void i.delete(n)}send(e,n){if(e.startsWith(Ks))throw new Error(`Message types starting with '${Ks}' 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=N(this,hn).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const i=Ba(e);return n.forEach(r=>os(()=>r(e.payload,i))),{handled:!0}}}hn=new WeakMap;var Ge;class La extends bi{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});qt(this,Ge,new Map);this.kind=n}on(e,n){if(N(this,Ge).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return N(this,Ge).set(e,n),()=>void N(this,Ge).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 N(this,Ge).size>0}async handle(e){const n=N(this,Ge).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Ba(e))}}catch(i){return{handled:!0,error:i instanceof Error?i.message:String(i)}}}}Ge=new WeakMap;function Ba(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Nl(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 Ke,jn,Pe,He,Ve,ce,Qs,as,Da,Ua,Ja,ti;class ja{constructor(t){qt(this,ce);qt(this,Ke);qt(this,jn);qt(this,Pe);qt(this,He,new Map);qt(this,Ve,new Set);Xt(this,Ke,t),Xt(this,jn,t.listen(e=>void I(this,ce,Da).call(this,e)))}collab(){return N(this,Pe)??Xt(this,Pe,new Pa(N(this,Ke))),N(this,Pe)}external(t){const e=t??"";let n=N(this,He).get(e);return n||(n=new La(N(this,Ke),t),N(this,He).set(e,n)),n}dispose(){N(this,jn).call(this)}}Ke=new WeakMap,jn=new WeakMap,Pe=new WeakMap,He=new WeakMap,Ve=new WeakMap,ce=new WeakSet,Qs=function(){return[...N(this,Pe)?[N(this,Pe)]:[],...N(this,He).values()]},as=function(t,e){if(t==="collab")return N(this,Pe);if(t==="external")return N(this,He).get(typeof e=="string"?e:"")},Da=async function(t){const e=Nl(t);if(e){if(e.type.startsWith(Ks)){I(this,ce,Ua).call(this,e);return}await I(this,ce,Ja).call(this,e)}},Ua=function(t){var n,i,r;const e=t.payload??{};switch(t.type){case"channel:joined":(n=I(this,ce,as).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(i=I(this,ce,as).call(this,e.scope,e.kind))==null||i.applyLeft();break;case"channel:peers":(r=I(this,ce,as).call(this,e.scope,e.kind))==null||r.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const a=e.scope==="collab"?[N(this,Pe)]:[...N(this,He).values()].filter(l=>l.accepts("external",e.kind));for(const l of a)t.type==="channel:peer-joined"?l==null||l.applyPeerJoined({from:e.from,kind:e.kind}):l==null||l.applyPeerLeft(e.from);break}case"channel:error":{const a=new Error(String(t.payload));I(this,ce,Qs).call(this).map(p=>p.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ja=async function(t){const e=I(this,ce,Qs).call(this).filter(r=>r.accepts(t.scope,t.kind));let n=!1;for(const r of e){const a=await r.handle(t);a.handled&&(n=!0,t.requestId&&I(this,ce,ti).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&I(this,ce,ti).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},ti=function(t,e){N(this,Ve).has(t)||(N(this,Ve).add(t),N(this,Ve).size>500&&N(this,Ve).delete(N(this,Ve).values().next().value),N(this,Ke).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 ae="project",Qe="notifications",Tn="tokens",Fl=6e4;var fn,Dn,ze;const Ti=class Ti extends ls{constructor(e,n,i){super(typeof e=="string"?e:"",n,{...i,useBearer:!0});qt(this,fn);qt(this,Dn);qt(this,ze,new Map);typeof e=="function"&&Xt(this,fn,e)}async resolveAccessToken(){return N(this,fn)?await N(this,fn).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},i=new Ti(n.accessToken,n.apiUrl,e);return i.context=n,i}get channel(){return N(this,Dn)??Xt(this,Dn,new ja(Fa())),N(this,Dn)}async listProjects(){return await this.request("GET",ae)}async getProject(e){return await this.request("GET",`${ae}/${e}`)}async getProjectData(e){const n=N(this,ze).get(e);if(n&&Date.now()-n.at<Fl)return await n.data;const i=this.request("GET",`${ae}/${e}/data`);return N(this,ze).set(e,{at:Date.now(),data:i}),i.catch(()=>{var r;((r=N(this,ze).get(e))==null?void 0:r.data)===i&&N(this,ze).delete(e)}),await i}async request(e,n,i){return e.toUpperCase()!=="GET"&&N(this,ze).clear(),await super.request(e,n,i)}async listMembers(e){return await this.request("GET",`${ae}/${e}/users`)}async addMember(e,n,i){return await this.request("POST",`${ae}/${e}/user`,{body:JSON.stringify({accountId:n,...i&&{projectRoleId:i}}),contentType:"application/json"})}async setMemberRole(e,n,i){return await this.request("PUT",`${ae}/${e}/user/${n}`,{body:JSON.stringify({projectRoleId:i}),contentType:"application/json"})}async removeMember(e,n){return await this.request("DELETE",`${ae}/${e}/user/${n}`)}async inviteMember(e,n,i){return await this.request("POST",`${ae}/${e}/invite`,{body:JSON.stringify({email:n,...i&&{projectRoleId:i}}),contentType:"application/json"})}async listInvitations(e){return await this.request("GET",`${ae}/${e}/invites`)}async cancelInvitation(e,n){return await this.request("DELETE",`${ae}/${e}/invite/${n}`)}async listRoles(e){return await this.request("GET",`${ae}/${e}/roles`)}async createRole(e,n){return await this.request("POST",`${ae}/${e}/role`,{body:JSON.stringify(n),contentType:"application/json"})}async updateRole(e,n){return await this.request("PUT",`${ae}/role/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async deleteRole(e){return await this.request("DELETE",`${ae}/role/${e}`)}async getPermissionMatrix(e){const[n,i]=await Promise.all([this.listRoles(e),this.listMembers(e)]);return n.map(r=>({role:r,permissions:r.permissions??[],members:i.filter(a=>{var l;return String((l=a.role)==null?void 0:l._id)===String(r._id)}).map(a=>a.user)}))}async listTokens(){return await this.request("GET",Tn)}async getTokenSecret(e){return await(await this.request("GET",`${Tn}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",Tn,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,n){return await this.request("PUT",`${Tn}/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${Tn}/${e}`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${ae}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${ae}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Qe,{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",`${Qe}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Qe}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Qe}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Qe}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Qe}/subscriptions/${e}`)}async subscribeToAutomation(e,n,i){return await this.request("POST",`${ae}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(i??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,i){return await this.request("PATCH",`${ae}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(i),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),i=An(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return i.on("notification.created",r=>e({type:"created",id:r==null?void 0:r.id})),i.on("notification.read",r=>e({type:"read",id:r==null?void 0:r.id})),i.on("notifications.allRead",r=>e({type:"allRead",batch:r==null?void 0:r.batch})),()=>i.disconnect()}};fn=new WeakMap,Dn=new WeakMap,ze=new WeakMap;let ei=Ti;const Ce=1/.3048,Pl={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"},Ll="OST_GenericModel",Bl=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Oe=(s,t)=>Math.round(s/t)*t,jl=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]]}),Cn=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Ss=s=>Math.sqrt(Cn(s,s)),rn=(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 Dl(s,t,e,n){var d,c,E;const i=new Set,r=new Map;for(const b of t){const[,$,P]=b.split(":");$&&(/^datum/.test(P??"")||(i.add($),r.has($)||r.set($,b)))}const a=new Map,l=new Map,p=[];for(const b of s.elements.values()){if(i.has(b.gid)||Bl.has(b.ifcClass.toUpperCase())||b.parent&&i.has(b.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(b.ifcClass)&&!(n!=null&&n.has(b.gid))||b.pieces.length===0)continue;const P=/^IFCCOLUMN$/i.test(b.ifcClass)&&(b.loadBearing||/structural|estructural|结构柱|tragend|tragwerk/i.test(`${b.typeName??""} ${b.objectType??""} ${b.name??""}`))?"OST_StructuralColumns":Pl[b.ifcClass.toUpperCase()]??Ll,k=jl(b.pieces[0].matrix),Y=Ss(k.x),V=Ss(k.y),D=Ss(k.z),f=k.z.map(U=>U/(D||1)),Tt=Math.abs(f[2]-1)<1e-6&&Cn(rn(k.x,k.y),k.z)>0&&Math.abs(Y-V)<1e-6&&Math.abs(Y-D)<1e-6,nt=Cn(rn(k.x,k.y),k.z)>0&&Math.abs(Y-V)<1e-6&&Math.abs(Y-D)<1e-6,wt=[k.x,k.y,k.z].map(U=>U.map(Z=>Z/(Y||1))),Pt=nt&&!Tt&&wt.some(U=>Math.abs(Math.abs(U[2])-1)<1e-6)?wt.find(U=>Math.abs(U[2])<1e-6):void 0,tt=Tt?Math.atan2(k.x[1],k.x[0]):Pt?Math.atan2(Pt[1],Pt[0]):0,ct=Math.cos(-tt),ht=Math.sin(-tt),kt=[k.t[0],k.t[1],k.t[2]],te=/COLUMN/i.test(P),Wt=U=>{const Z=U[0]-kt[0],B=U[1]-kt[1];return[ct*Z-ht*B,ht*Z+ct*B,U[2]-kt[2]]},at=[],st=[P];for(const U of b.pieces){const Z=s.geometries.get(U.geometry);if(!Z)continue;const B=U.matrix,ut=[];for(let Nt=0;Nt<Z.verts.length;Nt+=3){const le=Z.verts[Nt],me=Z.verts[Nt+1],Le=Z.verts[Nt+2],re=[B[0]*le+B[4]*me+B[8]*Le+B[12],B[1]*le+B[5]*me+B[9]*Le+B[13],B[2]*le+B[6]*me+B[10]*Le+B[14]],Xe=Wt(re);ut.push(Oe(Xe[0]*Ce,1e-5),Oe(Xe[1]*Ce,1e-5),Oe(Xe[2]*Ce,1e-5))}const X=Cn(rn([B[0],B[1],B[2]],[B[4],B[5],B[6]]),[B[8],B[9],B[10]])<0,dt=[];for(let Nt=0;Nt+2<Z.tris.length;Nt+=3)X?dt.push(Z.tris[Nt],Z.tris[Nt+2],Z.tris[Nt+1]):dt.push(Z.tris[Nt],Z.tris[Nt+1],Z.tris[Nt+2]);dt.length&&at.push({v:ut,t:dt});const Mt=Wt([B[12],B[13],B[14]]),rt=[ct*B[0]-ht*B[1],ht*B[0]+ct*B[1],B[2]],_t=[ct*B[4]-ht*B[5],ht*B[4]+ct*B[5],B[6]],ie=[ct*B[8]-ht*B[9],ht*B[8]+ct*B[9],B[10]];st.push(`${U.geometry}@${[...Mt,...rt,..._t,...ie].map(Nt=>Oe(Nt,1e-4).toFixed(4)).join(",")}`)}if(at.length===0)continue;const pt=!b.host&&at.length===1?ql(at[0]):null;if(pt){const U=Jl(pt),Z=U.key,B=`prism|${P}|${U.axis}|${Z}`;let ut=a.get(B);if(!ut){const le=Go(b.typeName??b.objectType??b.name??b.ifcClass),me=(l.get(le.toLowerCase())??0)+1;l.set(le.toLowerCase(),me);const Le=me===1?le:`${le} (${me})`;ut={family:Le,type:Le,first:!0,key:Ho(B)},a.set(B,ut)}const X={ShapeCategory:P,Family:ut.family,Type:ut.type,ShapeKey:ut.key,PrismLength:String(Oe(pt.length,1e-5)),...te?{ColumnFree:"1"}:{}};ut.first&&(X.Prism=JSON.stringify({axis:U.axis,loops:U.loops}),ut.first=!1);const dt=[0,0,0];dt[pt.axis]=(U.flipped?pt.from+pt.length:pt.from)/Ce;const Mt=(pt.axis+1)%3,rt=(pt.axis+2)%3;dt[Mt]+=U.centre[0]/Ce,dt[rt]+=U.centre[1]/Ce;const _t=Math.cos(tt),ie=Math.sin(tt),Nt=[kt[0]+_t*dt[0]-ie*dt[1],kt[1]+ie*dt[0]+_t*dt[1],kt[2]+dt[2]];p.push({key:`${e}:${b.gid}:shape`,attrs:X,at:Nt,rotationDeg:(tt+U.turn)*180/Math.PI});continue}const Bt=`${P}|${at.map(U=>`${U.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${U.t.join(",")}`).join("|")}`,Gt=st.join("|");let jt=a.get(Gt)??a.get(Bt);if(jt&&(a.set(Gt,jt),a.set(Bt,jt)),!jt){const U=Go(b.typeName??b.objectType??b.name??b.ifcClass),Z=(l.get(U.toLowerCase())??0)+1;l.set(U.toLowerCase(),Z);const B=Z===1?U:`${U} (${Z})`;jt={family:B,type:B,first:!0,key:Ho(Bt)},a.set(Bt,jt),a.set(Gt,jt)}const Kt={ShapeCategory:P,Family:jt.family,Type:jt.type,ShapeKey:jt.key,...te?{ColumnFree:"1"}:{}};jt.first&&(Kt.Shape=JSON.stringify({pieces:at}),jt.first=!1);const Yt=b.host?r.get(b.host):void 0,zt=b.opening?s.elements.get(b.opening):void 0;if(Yt&&zt){const U=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const B of zt.pieces){const ut=s.geometries.get(B.geometry);if(!ut)continue;const X=B.matrix;for(let dt=0;dt<ut.verts.length;dt+=3){const Mt=ut.verts[dt],rt=ut.verts[dt+1],_t=ut.verts[dt+2],ie=Wt([X[0]*Mt+X[4]*rt+X[8]*_t+X[12],X[1]*Mt+X[5]*rt+X[9]*_t+X[13],X[2]*Mt+X[6]*rt+X[10]*_t+X[14]]);for(let Nt=0;Nt<3;Nt++)U[Nt]=Math.min(U[Nt],ie[Nt]*Ce),Z[Nt]=Math.max(Z[Nt],ie[Nt]*Ce)}}{const B=ni(s,zt.gid).flatMap(dt=>dt.pts).map(dt=>Wt(dt).map(Mt=>Mt*Ce)),ut=new Map;for(const dt of B){const Mt=Math.round(dt[1]*200);ut.set(Mt,[...ut.get(Mt)??[],dt])}let X=null;for(const dt of ut.values()){if(dt.length<4)continue;const Mt=[Math.min(...dt.map(rt=>rt[0])),Math.max(...dt.map(rt=>rt[0])),Math.min(...dt.map(rt=>rt[2])),Math.max(...dt.map(rt=>rt[2]))];Mt[1]-Mt[0]<.1||Mt[3]-Mt[2]<.1||(!X||(Mt[1]-Mt[0])*(Mt[3]-Mt[2])<(X[1]-X[0])*(X[3]-X[2])-1e-6)&&(X=Mt)}if(X&&ut.size>2&&(U[0]=X[0],Z[0]=X[1],U[2]=X[2],Z[2]=X[3]),X&&ut.size>2){const dt=[...ut.entries()].sort((rt,_t)=>rt[0]-_t[0]).map(([,rt])=>({y:rt[0][1],r:[Math.min(...rt.map(_t=>_t[0])),Math.max(...rt.map(_t=>_t[0])),Math.min(...rt.map(_t=>_t[2])),Math.max(...rt.map(_t=>_t[2]))]})),Mt=[];for(let rt=0;rt+1<dt.length;rt++){const _t=dt[rt].r,ie=dt[rt+1].r,Nt=[Math.max(_t[0],ie[0]),Math.min(_t[1],ie[1]),Math.max(_t[2],ie[2]),Math.min(_t[3],ie[3])];Nt[1]-Nt[0]<.1||Nt[3]-Nt[2]<.1||dt[rt+1].y-dt[rt].y<.01||(Nt[0]<X[0]-.016||Nt[1]>X[1]+.016||Nt[2]<X[2]-.016||Nt[3]>X[3]+.016)&&Mt.push([Nt[0],dt[rt].y,Nt[2],Nt[1],dt[rt+1].y,Nt[3]].map(le=>Oe(le,1e-5)))}Mt.length&&(Kt.OpeningSteps=JSON.stringify(Mt)),typeof process<"u"&&((d=process.env)!=null&&d.RECIPE_TRACE)&&console.error(`[opening-steps] ${b.gid}: ${dt.length} planes, narrowest ${JSON.stringify(X.map(rt=>+rt.toFixed(3)))}, steps ${JSON.stringify(Mt)}`)}}if(Number.isFinite(U[0])&&(Kt.Opening=[...U,...Z].map(B=>Oe(B,1e-5)).join(",")),typeof process<"u"&&((c=process.env)!=null&&c.RECIPE_CUT_LOST)&&b.host&&Number.isFinite(U[0])){const B=ni(s,zt.gid).flatMap(X=>X.pts),ut=Qt(s,b.host);if(B.length&&ut.length){const X=[0,1,2].map(_t=>Math.min(...B.map(ie=>ie[_t]))-.01),dt=[0,1,2].map(_t=>Math.max(...B.map(ie=>ie[_t]))+.01),Mt=Math.min(...ut.map(_t=>_t[2]))+.01,rt=ut.filter(_t=>_t[0]>X[0]&&_t[0]<dt[0]&&_t[1]>X[1]&&_t[1]<dt[1]&&_t[2]>Math.max(X[2],Mt)&&_t[2]<dt[2]).length;rt>=4&&(Kt.CutIfLost="1"),(E=process.env)!=null&&E.RECIPE_TRACE&&console.error(`[cut-if-lost] ${b.gid}: ${rt} of its wall's corners in its opening → ${rt>=4?"cut":"not"}`)}}}p.push({key:`${e}:${b.gid}:shape`,attrs:Kt,at:[kt[0],kt[1],kt[2]],rotationDeg:tt*180/Math.PI,...Yt?{host:Yt}:{}})}return p}function Go(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Ho(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 Ul(s,t,e){var r,a;const n=new Map;for(const l of t){const[,p,d]=l.split(":");p&&/^run/.test(d??"")&&!n.has(p)&&n.set(p,l)}const i=[];for(const l of s.elements.values()){if(l.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!l.host)continue;const p=n.get(l.host),d=typeof process<"u"&&((r=process.env)==null?void 0:r.RECIPE_TRACE);if(!p){d&&console.error(`[opening] ${l.gid}: its wall ${l.host} not written as a run`);continue}for(const c of ni(s,l.gid)){const E=c.pts;if(E.length<4)continue;const b=Hl(Qt(s,l.host));if(!b)continue;const $=E.map(D=>(D[0]-b.a[0])*b.u[0]+(D[1]-b.a[1])*b.u[1]),P=E.map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]),k=D=>Math.max(...D)-Math.min(...D),Y=k($)*k(P)*k(E.map(D=>D[2]));if(!(Y>0)||Math.abs(c.volume)<.75*Y){d&&console.error(`[opening] ${l.gid}: not a box (${c.volume.toFixed(3)} of ${Y.toFixed(3)}: ${k($).toFixed(3)} along ${k(P).toFixed(3)} across ${k(E.map(D=>D[2])).toFixed(3)} up, axis ${JSON.stringify(b.u.map(D=>+D.toFixed(3)))})`);continue}const V=Qt(s,l.host).map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]);if(V.length&&(Math.min(...P)>Math.min(...V)+.005||Math.max(...P)<Math.max(...V)-.005)){d&&console.error(`[opening] ${l.gid}: not through its wall (across ${Math.min(...P).toFixed(3)}..${Math.max(...P).toFixed(3)}, its wall ${Math.min(...V).toFixed(3)}..${Math.max(...V).toFixed(3)})`);continue}d&&((a=process.env)==null?void 0:a.RECIPE_GID)===l.gid&&console.error(`[opening] ${l.gid} part ${c.index}/${c.of}: a box (${c.volume.toFixed(4)} of ${Y.toFixed(4)}: ${k($).toFixed(3)} along ${k(P).toFixed(3)} across ${k(E.map(D=>D[2])).toFixed(3)} up, ${E.length} points)`),i.push({key:`${e}:${l.gid}:opening${c.index===0&&c.of===1?"":`#${c.index}`}`,host:p,box:E.flat()})}}return i}function Jl(s){const t=s.loops.flat(),e=[t.reduce((b,$)=>b+$[0],0)/t.length,t.reduce((b,$)=>b+$[1],0)/t.length],n=s.loops.map(b=>{const $=b.map(([f,Tt])=>[f-e[0],Tt-e[1]]),P=$.map(([f,Tt])=>Math.hypot(f,Tt)),k=P.reduce((f,Tt)=>f+Tt,0)/P.length;if($.length<8||k<=0||P.some(f=>Math.abs(f-k)>.02*k))return $;const Y=2*Math.PI/$.length;for(let f=0;f<$.length;f++){const Tt=Math.atan2($[f][1],$[f][0]),nt=Math.atan2($[(f+1)%$.length][1],$[(f+1)%$.length][0]),wt=Math.abs(Math.atan2(Math.sin(nt-Tt),Math.cos(nt-Tt)));if(Math.abs(wt-Y)>.1*Y)return $}const D=$.reduce((f,Tt,nt)=>{const wt=$[(nt+1)%$.length];return f+Tt[0]*wt[1]-wt[0]*Tt[1]},0)>=0?1:-1;return $.map((f,Tt)=>[k*Math.cos(D*2*Math.PI*Tt/$.length),k*Math.sin(D*2*Math.PI*Tt/$.length)])}),i=b=>b.map(P=>{const k=P.map(([V,D])=>`${Math.round(V*304.8)},${Math.round(D*304.8)}`);let Y=0;for(let V=1;V<k.length;V++)k[V]<k[Y]&&(Y=V);return[...k.slice(Y),...k.slice(0,Y)].join(";")}).sort().join("|"),r=(b,$)=>{const P=Math.cos(-$),k=Math.sin(-$);return b.map(Y=>Y.map(([V,D])=>[P*V-k*D,k*V+P*D]))},a=[];let l=s.axis,p=0,d=n;if(l===1&&(l=0,p=Math.PI/2,d=n.map(b=>b.map(([$,P])=>[-P,$]))),l===2){let b=0,$=0,P=0;const k=n.flat();for(const[nt,wt]of k)b+=nt*nt,$+=wt*wt,P+=nt*wt;const Y=new Set,V=.5*Math.atan2(2*P,b-$);for(let nt=0;nt<4;nt++)Y.add(V+nt*Math.PI/2);const D=k.map(([nt,wt])=>Math.hypot(nt,wt)),f=Math.max(...D),Tt=k.filter((nt,wt)=>D[wt]>f-.003);if(Math.abs(b-$)<.001*(b+$)||Tt.length>4)for(const[nt,wt]of Tt.slice(0,64))Y.add(Math.atan2(wt,nt));for(const nt of Y)a.push({loops:r(n,nt),turn:nt,flipped:!1})}else a.push({loops:d,turn:0,flipped:!1}),a.push({loops:d.map(b=>b.map(([$,P])=>[-$,P]).reverse()),turn:Math.PI,flipped:!0});let c=a[0],E=i(c.loops);for(const b of a.slice(1)){const $=i(b.loops);$<E&&(c=b,E=$)}return{axis:l,loops:c.loops,key:E,centre:e,turn:p+c.turn,flipped:c.flipped}}function ql(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(i=>{let r=1/0,a=-1/0;for(let l=0;l<e;l++){const p=s.v[l*3+i];r=Math.min(r,p),a=Math.max(a,p)}return a-r});for(const i of[0,1,2].sort((r,a)=>n[a]-n[r])){let r=1/0,a=-1/0;for(let tt=0;tt<e;tt++){const ct=s.v[tt*3+i];r=Math.min(r,ct),a=Math.max(a,ct)}if(a-r<.01)continue;let l=!0;for(let tt=0;tt<e&&l;tt++){const ct=s.v[tt*3+i];Math.abs(ct-r)>.001&&Math.abs(ct-a)>.001&&(l=!1)}if(!l)continue;const p=(i+1)%3,d=(i+2)%3,c=new Map,E=[],b=tt=>{const ct=[s.v[tt*3+p],s.v[tt*3+d]],ht=`${Math.round(ct[0]*3048)},${Math.round(ct[1]*3048)}`;return c.has(ht)||(c.set(ht,E.length),E.push(ct)),c.get(ht)},$=[];for(let tt=0;tt+2<s.t.length;tt+=3){const ct=[s.t[tt],s.t[tt+1],s.t[tt+2]];if(!ct.every(kt=>Math.abs(s.v[kt*3+i]-r)<=.001))continue;const ht=ct.map(b);ht[0]===ht[1]||ht[1]===ht[2]||ht[0]===ht[2]||$.push(ht)}if($.length===0)continue;const P=(tt,ct)=>{const[ht,kt]=[E[tt],E[ct]],te=[kt[0]-ht[0],kt[1]-ht[1]],Wt=te[0]*te[0]+te[1]*te[1],at=[];if(E.length<=3e3)for(let st=0;st<E.length;st++){if(st===tt||st===ct)continue;const pt=((E[st][0]-ht[0])*te[0]+(E[st][1]-ht[1])*te[1])/Wt;if(pt<=1e-6||pt>=1-1e-6)continue;Math.abs((E[st][0]-ht[0])*te[1]-(E[st][1]-ht[1])*te[0])/Math.sqrt(Wt)<3e-4&&at.push({t:pt,id:st})}return[tt,...at.sort((st,pt)=>st.t-pt.t).map(st=>st.id),ct]},k=[];for(const tt of $)for(let ct=0;ct<3;ct++){const ht=P(tt[ct],tt[(ct+1)%3]);for(let kt=0;kt+1<ht.length;kt++)k.push([ht[kt],ht[kt+1]])}const Y=new Map;for(const[tt,ct]of k){const ht=tt<ct?`${tt},${ct}`:`${ct},${tt}`;Y.set(ht,(Y.get(ht)??0)+1)}const V=new Map;for(const[tt,ct]of k)Y.get(tt<ct?`${tt},${ct}`:`${ct},${tt}`)===1&&V.set(tt,[...V.get(tt)??[],ct]);if([...V.values()].some(tt=>tt.length!==1))continue;const D=[],f=new Set(V.keys());for(;f.size;){const tt=f.values().next().value,ct=[];let ht=tt,kt=0;do ct.push(E[ht]),f.delete(ht),ht=V.get(ht)[0];while(ht!==tt&&kt++<1e5&&V.has(ht));if(ht!==tt||ct.length<3){D.length=0;break}const te=ct.filter((Wt,at)=>{const st=ct[(at-1+ct.length)%ct.length],pt=ct[(at+1)%ct.length];return Math.abs((Wt[0]-st[0])*(pt[1]-st[1])-(Wt[1]-st[1])*(pt[0]-st[0]))>1e-7});D.push(te.map(([Wt,at])=>[Oe(Wt,1e-5),Oe(at,1e-5)]))}if(D.length===0||D.some(tt=>tt.length<3))continue;const Tt=tt=>{const ct=new Set;for(let ht=0;ht<e;ht++)Math.abs(s.v[ht*3+i]-tt)<=.001&&ct.add(`${Math.round(s.v[ht*3+p]*304.8)},${Math.round(s.v[ht*3+d]*304.8)}`);return ct},nt=(tt,ct)=>{const[ht,kt]=ct.split(",").map(Number);for(let te=-1;te<=1;te++)for(let Wt=-1;Wt<=1;Wt++)if(tt.has(`${ht+te},${kt+Wt}`))return!0;return!1},wt=Tt(r),Pt=Tt(a);if(!(Pt.size<3||[...wt].some(tt=>!nt(Pt,tt))||[...Pt].some(tt=>!nt(wt,tt))))return{axis:i,from:r,length:a-r,loops:D}}return null}function Gl(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let i=1/0,r=-1/0;const a=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const E=d.matrix,b=$=>{const P=c.verts[$*3],k=c.verts[$*3+1],Y=c.verts[$*3+2];return[E[0]*P+E[4]*k+E[8]*Y+E[12],E[1]*P+E[5]*k+E[9]*Y+E[13],E[2]*P+E[6]*k+E[10]*Y+E[14]]};for(let $=0;$+2<c.tris.length;$+=3){const P=[b(c.tris[$]),b(c.tris[$+1]),b(c.tris[$+2])];for(const k of P)i=Math.min(i,k[2]),r=Math.max(r,k[2]);a.push(P)}}if(!Number.isFinite(i)||r-i<.1)continue;let l=null,p=0;for(const d of a){if(!d.every(E=>Math.abs(E[2]-i)<.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>p&&(p=c,l=d)}l&&e.push({key:`${t}:${n.gid}:room`,at:[(l[0][0]+l[1][0]+l[2][0])/3,(l[0][1]+l[1][1]+l[2][1])/3,i],height:r-i,number:n.name??"",name:n.longName??n.name??""})}return e}function Hl(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const d of s){const c=Math.hypot(d[0]-s[0][0],d[1]-s[0][1]);c>n&&(n=c,e=d)}n=0;for(const d of s){const c=Math.hypot(d[0]-e[0],d[1]-e[1]);c>n&&(n=c,t=d)}if(n<.1)return;const i=[...new Map(s.map(d=>[`${Math.round(d[0]*1e3)},${Math.round(d[1]*1e3)}`,[d[0],d[1]]])).values()].sort((d,c)=>d[0]-c[0]||d[1]-c[1]),r=(d,c,E)=>(c[0]-d[0])*(E[1]-d[1])-(c[1]-d[1])*(E[0]-d[0]),a=d=>{const c=[];for(const E of d){for(;c.length>=2&&r(c[c.length-2],c[c.length-1],E)<=0;)c.pop();c.push(E)}return c.pop(),c},l=i.length>=3?[...a(i),...a([...i].reverse())]:i;let p;for(let d=0;d<l.length;d++){const c=l[d],E=l[(d+1)%l.length],b=Math.hypot(E[0]-c[0],E[1]-c[1]);if(b<.001)continue;const $=[(E[0]-c[0])/b,(E[1]-c[1])/b],P=l.map(f=>f[0]*$[0]+f[1]*$[1]),k=l.map(f=>-f[0]*$[1]+f[1]*$[0]),Y=Math.max(...P)-Math.min(...P),V=Math.max(...k)-Math.min(...k),D=Y*V;(!p||D<p.area-1e-9)&&(p={area:D,u:Y>=V?$:[-$[1],$[0]]})}if(p){const d=p.u;return d[0]*(e[0]-t[0])+d[1]*(e[1]-t[1])<0&&(d[0]=-d[0],d[1]=-d[1]),{a:t,u:d}}return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function ni(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],i=[],r=new Map;for(const c of e.pieces){const E=s.geometries.get(c.geometry);if(!E)continue;const b=c.matrix,$=[];for(let P=0;P<E.verts.length;P+=3){const k=E.verts[P],Y=E.verts[P+1],V=E.verts[P+2],D=[b[0]*k+b[4]*Y+b[8]*V+b[12],b[1]*k+b[5]*Y+b[9]*V+b[13],b[2]*k+b[6]*Y+b[10]*V+b[14]],f=D.map(nt=>Math.round(nt*1e4)).join(",");let Tt=r.get(f);Tt===void 0&&(Tt=n.length,r.set(f,Tt),n.push(D)),$.push(Tt)}for(let P=0;P+2<E.tris.length;P+=3)i.push($[E.tris[P]],$[E.tris[P+1]],$[E.tris[P+2]])}const a=n.map((c,E)=>E),l=c=>{for(;a[c]!==c;)a[c]=a[a[c]],c=a[c];return c};for(let c=0;c<i.length;c+=3){const E=l(i[c]);a[l(i[c+1])]=E,a[l(i[c+2])]=E}const p=new Map;for(let c=0;c<i.length;c+=3){const E=l(i[c]);let b=p.get(E);b||(b={pts:new Set,volume:0},p.set(E,b));const[$,P,k]=[n[i[c]],n[i[c+1]],n[i[c+2]]];b.volume+=Cn($,rn(P,k))/6,b.pts.add(i[c]),b.pts.add(i[c+1]),b.pts.add(i[c+2])}const d=[...p.values()];return d.map((c,E)=>({pts:[...c.pts].map(b=>n[b]),volume:c.volume,index:E,of:d.length}))}function Vl(s,t,e,n,i,r){const a=s.elements.get(t);if(!a)return null;const l=E=>(E[0]-e[0])*n[0]+(E[1]-e[1])*n[1],p=E=>-(E[0]-e[0])*n[1]+(E[1]-e[1])*n[0];let d=1/0,c=-1/0;for(const E of a.pieces){const b=s.geometries.get(E.geometry);if(!b)continue;const $=E.matrix,P=k=>{const Y=b.verts[k*3],V=b.verts[k*3+1],D=b.verts[k*3+2];return[$[0]*Y+$[4]*V+$[8]*D+$[12],$[1]*Y+$[5]*V+$[9]*D+$[13],$[2]*Y+$[6]*V+$[10]*D+$[14]]};for(let k=0;k+2<b.tris.length;k+=3){const Y=[P(b.tris[k]),P(b.tris[k+1]),P(b.tris[k+2])],V=[];for(let nt=0;nt<3;nt++){const wt=Y[nt],Pt=Y[(nt+1)%3],tt=l(wt)-i,ct=l(Pt)-i;if(tt<0==ct<0||tt===ct)continue;const ht=tt/(tt-ct);V.push([p(wt)+ht*(p(Pt)-p(wt)),wt[2]+ht*(Pt[2]-wt[2])])}if(V.length!==2)continue;const[D,f]=V;if((D[1]-r)*(f[1]-r)>0||D[1]===f[1])continue;const Tt=D[0]+(r-D[1])/(f[1]-D[1])*(f[0]-D[0]);d=Math.min(d,Tt),c=Math.max(c,Tt)}}return Number.isFinite(d)?{lo:d,hi:c}:null}function Qt(s,t,e){const n=s.elements.get(t),i=[];if(!n)return i;for(const r of e===void 0?n.pieces:[n.pieces[e]]){const a=s.geometries.get(r.geometry);if(!a)continue;const l=r.matrix;for(let p=0;p<a.verts.length;p+=3){const d=a.verts[p],c=a.verts[p+1],E=a.verts[p+2];i.push([l[0]*d+l[4]*c+l[8]*E+l[12],l[1]*d+l[5]*c+l[9]*E+l[13],l[2]*d+l[6]*c+l[10]*E+l[14]])}}return i}function zl(s,t,e,n){var r;const i=[];for(const a of s.elements.values()){if(a.parent!==t||!/^IFC(PLATE|COVERING|BUILDINGELEMENTPROXY)$/i.test(a.ifcClass)||a.pieces.length===0)continue;const l=Qt(s,a.gid);if(l.length===0)continue;let p=0;for(const b of a.pieces)p+=(((r=s.geometries.get(b.geometry))==null?void 0:r.tris.length)??0)/3;const d=[1/0,1/0,1/0],c=[-1/0,-1/0,-1/0];for(const b of l)for(let $=0;$<3;$++)d[$]=Math.min(d[$],b[$]),c[$]=Math.max(c[$],b[$]);const E=a.pieces.length===1&&p<=12;if(E&&n){const b=s.geometries.get(a.pieces[0].geometry),$=a.pieces[0].matrix;let P=0,k=null;if(b)for(let Y=0;Y+2<b.tris.length;Y+=3){const V=Pt=>{const tt=b.verts[Pt*3],ct=b.verts[Pt*3+1],ht=b.verts[Pt*3+2];return[$[0]*tt+$[4]*ct+$[8]*ht,$[1]*tt+$[5]*ct+$[9]*ht,$[2]*tt+$[6]*ct+$[10]*ht]},D=V(b.tris[Y]),f=V(b.tris[Y+1]),Tt=V(b.tris[Y+2]),nt=rn([f[0]-D[0],f[1]-D[1],f[2]-D[2]],[Tt[0]-D[0],Tt[1]-D[1],Tt[2]-D[2]]),wt=Math.hypot(nt[0],nt[1],nt[2]);wt>P&&(P=wt,k=nt.map(Pt=>Pt/wt))}if(k&&Math.abs(k[0]*n[0]+k[1]*n[1])<.996){i.push({gid:a.gid,centre:[(d[0]+c[0])/2,(d[1]+c[1])/2,(d[2]+c[2])/2]});continue}}E||i.push({gid:a.gid,centre:[(d[0]+c[0])/2,(d[1]+c[1])/2,(d[2]+c[2])/2]})}return i}function xs(s,t,e,n,i=!1){const r=s.elements.get(t);if(!r)return null;const a=Math.hypot(n[0]-e[0],n[1]-e[1]);if(!(a>.1))return null;const l=[(n[0]-e[0])/a,(n[1]-e[1])/a],p=[-l[1],l[0]],d=[];for(const at of r.pieces){const st=s.geometries.get(at.geometry);if(!st)continue;const pt=at.matrix,Bt=Gt=>{const jt=st.verts[Gt*3],Kt=st.verts[Gt*3+1],Yt=st.verts[Gt*3+2];return[pt[0]*jt+pt[4]*Kt+pt[8]*Yt+pt[12],pt[1]*jt+pt[5]*Kt+pt[9]*Yt+pt[13],pt[2]*jt+pt[6]*Kt+pt[10]*Yt+pt[14]]};for(let Gt=0;Gt+2<st.tris.length;Gt+=3){const jt=Bt(st.tris[Gt]),Kt=Bt(st.tris[Gt+1]),Yt=Bt(st.tris[Gt+2]),zt=rn([Kt[0]-jt[0],Kt[1]-jt[1],Kt[2]-jt[2]],[Yt[0]-jt[0],Yt[1]-jt[1],Yt[2]-jt[2]]),U=Math.hypot(zt[0],zt[1],zt[2]);if(U<1e-9||Math.abs((zt[0]*p[0]+zt[1]*p[1])/U)<.995)continue;const Z=((jt[0]+Kt[0]+Yt[0])/3-e[0])*p[0]+((jt[1]+Kt[1]+Yt[1])/3-e[1])*p[1];d.push({a:jt,b:Kt,c:Yt,across:Z})}}if(d.length<2)return null;const c=at=>{const st=(at[0]-e[0])*l[0]+(at[1]-e[1])*l[1];return`${Math.round(st*1e3)},${Math.round(at[2]*1e3)}`},E=at=>at.split(",").map(st=>Number(st)/1e3),b=at=>{const st=new Map,pt=(zt,U)=>zt<U?`${zt}|${U}`:`${U}|${zt}`;for(const zt of at){const U=[c(zt.a),c(zt.b),c(zt.c)];for(let Z=0;Z<3;Z++){const B=U[Z],ut=U[(Z+1)%3];if(B===ut)continue;const X=pt(B,ut);st.set(X,(st.get(X)??0)+1)}}const Bt=new Map;for(const[zt,U]of st){if(U!==1)continue;const[Z,B]=zt.split("|");(Bt.get(Z)??Bt.set(Z,[]).get(Z)).push(B),(Bt.get(B)??Bt.set(B,[]).get(B)).push(Z)}if(Bt.size<3||Bt.size>4e3)return null;const Gt=new Set;let jt=null,Kt=0;const Yt=[];for(const zt of Bt.keys()){if(Gt.has(zt))continue;const U=[zt];Gt.add(zt);let Z="",B=zt;for(let dt=0;dt<5e3;dt++){const Mt=(Bt.get(B)??[]).find(rt=>rt!==Z&&!Gt.has(rt))??null;if(!Mt)break;U.push(Mt),Gt.add(Mt),Z=B,B=Mt}if(U.length<3)continue;const ut=U.map(E);let X=0;for(let dt=0;dt<ut.length;dt++){const Mt=ut[dt],rt=ut[(dt+1)%ut.length];X+=Mt[0]*rt[1]-rt[0]*Mt[1]}Yt.push({pts:ut,area:Math.abs(X)/2}),Math.abs(X)/2>Kt&&(Kt=Math.abs(X)/2,jt=ut)}return jt?{best:jt,bestArea:Kt,allLoops:Yt}:null},$=Math.max(...d.map(at=>at.across));let P=b(d.filter(at=>at.across>$-.005));const k=[...new Set(d.map(at=>Math.round(at.across*200)))].map(at=>at/200);if(k.length>1&&k.length<=24)for(const at of k){if(Math.abs(at-$)<.005)continue;const st=b(d.filter(pt=>Math.abs(pt.across-at)<.0025));st&&P&&st.bestArea>P.bestArea*1.2&&(P=st)}if(!P)return null;const{best:Y,allLoops:V}=P;if(!Y||Y.length<3)return null;const D=Math.min(...Y.map(at=>at[0])),f=Math.max(...Y.map(at=>at[0])),Tt=Math.min(...Y.map(at=>at[1])),nt=Math.max(...Y.map(at=>at[1]));if(!(f-D>.1)||!(nt-Tt>.1))return null;if(i){const at=Y.filter((U,Z,B)=>{const ut=B[(Z-1+B.length)%B.length],X=B[(Z+1)%B.length];return Math.abs((X[0]-ut[0])*(U[1]-ut[1])-(X[1]-ut[1])*(U[0]-ut[0]))>1e-4*Math.hypot(X[0]-ut[0],X[1]-ut[1])}),st=(U,Z)=>{let B=!1;for(let ut=0,X=Z.length-1;ut<Z.length;X=ut++)Z[ut][1]>U[1]!=Z[X][1]>U[1]&&U[0]<(Z[X][0]-Z[ut][0])*(U[1]-Z[ut][1])/(Z[X][1]-Z[ut][1])+Z[ut][0]&&(B=!B);return B},pt=U=>[U.reduce((Z,B)=>Z+B[0],0)/U.length,U.reduce((Z,B)=>Z+B[1],0)/U.length],Bt=V.filter(U=>U.pts!==Y&&U.area>=.01&&U.pts.length<=200&&(U.area>=.1||!st(pt(U.pts),Y))).map(U=>U.pts),Gt=Bt.filter(U=>!st(pt(U),Y)),jt=U=>{let Z=0;for(let B=0;B<U.length;B++){const ut=U[B],X=U[(B+1)%U.length];Z+=ut[0]*X[1]-X[0]*ut[1]}return Math.abs(Z)/2},Kt=$-Math.min(...d.map(U=>U.across));let Yt=0;for(const U of r.pieces){const Z=s.geometries.get(U.geometry);if(!Z)continue;const B=U.matrix,ut=X=>{const dt=Z.verts[X*3],Mt=Z.verts[X*3+1],rt=Z.verts[X*3+2];return[B[0]*dt+B[4]*Mt+B[8]*rt+B[12],B[1]*dt+B[5]*Mt+B[9]*rt+B[13],B[2]*dt+B[6]*Mt+B[10]*rt+B[14]]};for(let X=0;X+2<Z.tris.length;X+=3){const dt=ut(Z.tris[X]),Mt=ut(Z.tris[X+1]),rt=ut(Z.tris[X+2]);Yt+=(dt[0]*(Mt[1]*rt[2]-Mt[2]*rt[1])-dt[1]*(Mt[0]*rt[2]-Mt[2]*rt[0])+dt[2]*(Mt[0]*rt[1]-Mt[1]*rt[0]))/6}}const zt=(jt(at)-Bt.filter(U=>!Gt.includes(U)).reduce((U,Z)=>U+jt(Z),0)+Gt.reduce((U,Z)=>U+jt(Z),0))*Kt;return Kt>.01&&Math.abs(Yt)>1e-6&&Math.abs(zt-Math.abs(Yt))>.15*Math.abs(Yt)?null:Gt.length?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:Bt.filter(U=>!Gt.includes(U)),pieces:Gt}:(at.length>4||Bt.length)&&at.length<=200?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:Bt}:null}const wt=at=>Y.map((st,pt)=>({p:st,i:pt})).filter(({p:st})=>Math.abs(st[0]-at)<.003).sort((st,pt)=>pt.p[1]-st.p[1])[0],Pt=wt(D),tt=wt(f);if(!Pt||!tt)return null;const ct=at=>{const st=[];for(let pt=Pt.i,Bt=0;Bt<=Y.length;pt=(pt+at+Y.length)%Y.length,Bt++)if(st.push(Y[pt]),pt===tt.i)return st;return null},ht=ct(1),kt=ct(-1),te=at=>at?at.reduce((st,pt)=>st+pt[1],0)/at.length:-1/0;let Wt=te(ht)>=te(kt)?ht:kt;if(!Wt||Wt.length<2||(Wt=Wt.filter((at,st,pt)=>{if(st===0||st===pt.length-1)return!0;const Bt=pt[st-1],Gt=pt[st+1];return Math.abs((Gt[0]-Bt[0])*(at[1]-Bt[1])-(Gt[1]-Bt[1])*(at[0]-Bt[0]))>1e-4*Math.hypot(Gt[0]-Bt[0],Gt[1]-Bt[1])}),Wt.every(at=>Math.abs(at[1]-nt)<.005)))return null;for(let at=1;at<Wt.length;at++)if(Wt[at][0]<Wt[at-1][0]-.003)return null;return Wt.length>200?null:{lo:D,hi:f,bottom:Tt,chain:Wt}}function Wl(s,t,e){const n=Qt(s,t);if(n.length<4||e.length===0)return;let i=n[0],r=n[0],a=0;for(const V of n){const D=Math.hypot(V[0]-n[0][0],V[1]-n[0][1]);D>a&&(a=D,r=V)}a=0;for(const V of n){const D=Math.hypot(V[0]-r[0],V[1]-r[1]);D>a&&(a=D,i=V)}if(a<.3)return;const l=(r[0]-i[0])/a,p=(r[1]-i[1])/a,d=V=>(V[0]-i[0])*l+(V[1]-i[1])*p,c=Math.max(...n.map(V=>V[2])),E=V=>Math.max(...n.filter(D=>Math.abs(d(D)-V)<.05).map(D=>D[2]),-1/0),b=E(0),$=E(a);if(Math.abs(b-$)<.05&&c-Math.max(b,$)<.05)return;const P=(i[0]+r[0])/2,k=(i[1]+r[1])/2;let Y;for(const V of e){const D=Qt(s,V.gid);if(D.length===0)continue;const f=D.map(Pt=>Pt[0]),Tt=D.map(Pt=>Pt[1]),nt=D.map(Pt=>Pt[2]);if(P<Math.min(...f)-.2||P>Math.max(...f)+.2||k<Math.min(...Tt)-.2||k>Math.max(...Tt)+.2)continue;const wt=Math.min(...nt)-c;wt>1.5||Math.max(...nt)<c-.05||(!Y||Math.abs(wt)<Math.abs(Y.gap))&&(Y={id:V.id,gap:wt})}return Y==null?void 0:Y.id}const De={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function _n(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 i=t.slice(e+1,n).trim();return i?{family:t.slice(0,e).trim(),type:i}:null}function Vo(s){const t=_n(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 zo=180/Math.PI;function Wo(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 Ct=s=>String(s);function Yl(s){const t=s.slice(),e=(n,i,r)=>Math.abs((i[0]-n[0])*(r[1]-n[1])-(r[0]-n[0])*(i[1]-n[1]))/2;for(let n=!0;n&&t.length>3;){n=!1;for(let i=0;i<t.length&&t.length>3;i++){const r=t[(i-1+t.length)%t.length],a=t[i],l=t[(i+1)%t.length],p=Math.min(Math.hypot(a[0]-r[0],a[1]-r[1]),Math.hypot(l[0]-a[0],l[1]-a[1]))<.02;(e(r,a,l)<1e-8||p&&e(r,a,l)<2e-4)&&(t.splice(i,1),n=!0,i--)}}return t}function qa(s){return async t=>{var Oi,ki,Ni,Fi,Pi,Li,Bi,ji,Di,Ui,Ji,qi,Gi,Hi,Vi,zi,Wi,Yi,Ki,Xi,Zi,Qi,tr,er,nr,sr,ir,rr,or,ar,cr,lr,hr,fr,dr,ur,pr,mr,gr,yr,wr,br,vr,Er,Tr,Mr,$r,Ir,Sr,xr,_r,Ar,Cr,Rr,Or,kr,Nr,Fr,Pr,Lr,Br,jr,Dr,Ur,Jr,qr,Gr,Hr,Vr,zr,Wr,Yr,Kr,Xr,Zr,Qr,to,eo,no,so,io,ro,oo,ao,co,lo,ho,fo,uo,po,mo,go,yo,wo,bo,vo,Eo,To,Mo,$o,Io;const{picked:e,contents:n,site:i,shapes:r}=await gi(t,t.input),a=Ia(n.items),l=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),p=l&&i?[i.east*sn,i.north*sn,i.elevation*sn,i.angleDeg].map(o=>o.toFixed(6)).join(","):void 0;if(a.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:E}=t.settings,b=t.settings.createLevels!==!1;if(E&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const $=pi(a),P=Sa(a);if(typeof process<"u"&&((Oi=process.env)!=null&&Oi.RECIPE_STYLE))for(const[o,h]of P)o.includes(process.env.RECIPE_STYLE)&&console.error(`[style] ${o}: ${JSON.stringify(h).slice(0,1500)}`);const k=`recipe:${s}-to-revit`,Y=new Map,V=mi(t,Y);t.progress("Writing the changes for Revit");const D=new ds({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:k}),f=sn,Tt=new Map;{const o=new Map;for(const h of a){const w=h.item.guid;if(!w)continue;const m=`${w}:${h.kind}`,F=o.get(m)??0;o.set(m,F+1),Tt.set(h.id,`${e.fileId}:${m}${F?`:${F}`:""}`)}}const nt=o=>Tt.get(o)??`${e.fileId}:${o}`,wt=new Set,Pt=new Set;let tt=0,ct=0;const ht=Array.isArray(t.settings.focus)?new Set(t.settings.focus):null,kt=[],te=()=>{var R;if(!ht)return;const o=O=>O?O.split(":")[1]:void 0,h=new Set,w=O=>(O.LocationLine??"").split(";").map(q=>q.split(",").map(Number)).filter(q=>q.length>=2&&q.every(Number.isFinite)),m=O=>{h.has(O)||(h.add(O),F=!0)};let F=!0;kt.forEach((O,q)=>{ht.has(o(O.sourceKey)??"")&&m(q)});for(let O=0;F&&O<2;O++){F=!1;const q=new Set([...h].map($t=>`${kt[$t].attrs.CategoryId}|${kt[$t].attrs.Type??""}`)),u=new Set([...h].map($t=>o(kt[$t].sourceKey))),x=new Set([...h].map($t=>kt[$t].sourceKey)),gt=[...h].flatMap($t=>w(kt[$t].attrs));kt.forEach(($t,Rt)=>{var yt;if(h.has(Rt))return;const It=$t.attrs;if(It.Type&&q.has(`${It.CategoryId}|${It.Type}`)||(yt=$t.placement)!=null&&yt.host&&(x.has($t.placement.host)||u.has(o($t.placement.host)))||It.AttachTop&&x.has(It.AttachTop)||It.CutBy&&It.CutBy.split("|").some(A=>x.has(A))||O===0&&w(It).some(A=>gt.some(Ot=>Math.hypot(A[0]-Ot[0],A[1]-Ot[1])<1)))return m(Rt)});for(const $t of[...h]){const Rt=(R=kt[$t].placement)==null?void 0:R.host,It=kt[$t].attrs.AttachTop,yt=(kt[$t].attrs.CutBy??"").split("|");kt.forEach((A,Ot)=>{(A.sourceKey===Rt||A.sourceKey===It||yt.includes(A.sourceKey))&&m(Ot)})}}kt.forEach((O,q)=>{/^[0-9A-Za-z_$]{22}$/.test(o(O.sourceKey)??"")||h.add(q)});for(const O of[...h].sort((q,u)=>q-u))D.add(kt[O].attrs,{...kt[O].placement,source:kt[O].sourceKey});typeof process<"u"&&console.error(`[focus] ${ht.size} asked, ${h.size} of ${kt.length} change(s) written`)},Wt=(o,h,w)=>{if(!V.has(o))return!1;const m=Y.get(o),F=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h;return!m||m===ns({attrs:F,placement:w??{}})},at=new Map,st=(o,h,w)=>{wt.add(o),at.set(o,h);const m=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h,F=ns({attrs:m,placement:w??{}}),R=V.get(o);if(R){const O=Y.get(o);return!O||O===F?(tt++,!1):(D.remove(R),D.add({...m,"flow:print":F},{...w,source:o}),ct++,!1)}return ht?(kt.push({sourceKey:o,attrs:{...m,"flow:print":F},placement:w}),!0):(D.add({...m,"flow:print":F},{...w,source:o}),!0)},pt=o=>{const h=typeof o=="string"?P.get(o):void 0,w=h==null?void 0:h.params.thickness;return typeof w=="number"&&w>0?w*f:void 0},Bt=o=>{var it,ft;const h=de(o,"extrusion"),w=$.get(String((h==null?void 0:h.level)??o.params.level??"")),m=h==null?void 0:h.slopes,F=((ft=(it=h==null?void 0:h.profile)==null?void 0:it.outline)==null?void 0:ft.curves)??[],R=Array.isArray(m)?m.map(mt=>typeof mt=="number"):[],O=R.indexOf(!0);if(o.params.of!=="roof"||!w||F.length!==4||R.filter(Boolean).length!==2||O<0||O>1||!R[O+2])return null;const[q,u]=[F[O],F[O+2]],x=q.from,gt=q.to,$t=Math.hypot(gt[0]-x[0],gt[1]-x[1]),Rt=[(gt[0]-x[0])/$t,(gt[1]-x[1])/$t];let It=[-Rt[1],Rt[0]];const yt=(u.from[0]-x[0])*It[0]+(u.from[1]-x[1])*It[1];yt<0&&(It=[-It[0],-It[1]]);const A=Math.abs(yt),[Ot,lt]=[m[O],m[O+2]],bt=w.at+(typeof o.params.base=="number"?o.params.base:0),K=(h==null?void 0:h.eaves)??[],[G,et]=[bt+(Number(K[O])||0),bt+(Number(K[O+2])||0)],H=(et-G+lt*A)/(Ot+lt);return{A:x,u:Rt,n:It,L:$t,W:A,si:Ot,sj:lt,ridge:H,top:bt,ti:G,tj:et,zAt:(mt,At)=>{const xt=(mt-x[0])*It[0]+(At-x[1])*It[1];return Math.min(G+Ot*xt,et+lt*(A-xt))}}},Gt=new Map(a.filter(o=>o.kind==="extrusion"&&o.params.of==="roof").map(o=>[o.id,o])),jt=[...Gt.values()].filter(o=>o.item.guid).map(o=>({id:o.id,gid:o.item.guid}));let Kt=0;if(b)for(const[o,h]of $){const w={CategoryId:De.levels,Name:h.name,Elevation:Ct(h.at*f)},m=ns({attrs:l?{...w,Frame:"shared",...p?{SharedAt:p}:{}}:w,placement:{}}),F=(ki=[...Y].find(([R,O])=>O===m&&V.has(R)))==null?void 0:ki[0];st(F??nt(o),w)&&Kt++}let Yt=0,zt=0;const U=new Map,Z=new Map;let B=null;const ut=()=>B??(B=r?[...r.elements.values()].filter(o=>/^IFC(SLAB|ROOF)/i.test(o.ifcClass)).flatMap(o=>{const h=Qt(r,o.gid);if(!h.length)return[];const w=a.find(m=>m.kind==="extrusion"&&m.item.guid===o.gid);return[{keys:[...w?[nt(w.id)]:[],`${e.fileId}:${o.gid}:shape`],box:[0,1,2].map(m=>Math.min(...h.map(F=>F[m]))).concat([0,1,2].map(m=>Math.max(...h.map(F=>F[m]))))}]}):[]),X=[];for(const o of a){if(o.kind!=="run"||o.params.of!=="wall")continue;const h=de(o,"run"),w=((Fi=(Ni=h==null?void 0:h.run)==null?void 0:Ni.line)==null?void 0:Fi.curves)??[],m=o.params.lookRef,F=$.get(String((h==null?void 0:h.level)??o.params.level??""));if(typeof m!="string"||typeof(h==null?void 0:h.height)!="number"||!F){zt++;continue}const R=(pt(m)??0)/f,O=u=>{var x;if(u.kind==="segment"&&Array.isArray(u.from)&&u.to)return{from:[...u.from],to:[...u.to]};if(u.kind==="arc"&&u.centre&&typeof u.radius=="number"&&typeof u.from=="number"&&typeof u.sweep=="number"){const gt=$t=>[u.centre[0]+u.radius*Math.cos($t),u.centre[1]+u.radius*Math.sin($t)];return typeof process<"u"&&((x=process.env)!=null&&x.RECIPE_TRACE)&&console.error(`[wall-arc] ${o.item.guid}: radius ${u.radius.toFixed(2)}, sweep ${(u.sweep*180/Math.PI).toFixed(1)}°`),{from:gt(u.from),to:gt(u.from+u.sweep),arcMid:gt(u.from+u.sweep/2)}}return null},q=w.map(O).filter(u=>u!==null);zt+=w.length-q.length,q.forEach((u,x)=>X.push({record:o,i:x,width:R,from:u.from,to:u.to,..."arcMid"in u?{arcMid:u.arcMid}:{},joinStart:x===0&&String(o.params.meetsAtStart)==="true",joinEnd:x===q.length-1&&String(o.params.meetsAtEnd)==="true"}))}const dt=(o,h)=>{const w=[o.to[0]-o.from[0],o.to[1]-o.from[1]],m=[h.to[0]-h.from[0],h.to[1]-h.from[1]],F=w[0]*m[1]-w[1]*m[0];if(Math.abs(F)<1e-9*Math.hypot(...w)*Math.hypot(...m)*1e3)return null;const R=((h.from[0]-o.from[0])*m[1]-(h.from[1]-o.from[1])*m[0])/F;return[o.from[0]+R*w[0],o.from[1]+R*w[1]]},Mt=(o,h)=>{const w=h.to[0]-h.from[0],m=h.to[1]-h.from[1],F=w*w+m*m||1,R=Math.max(0,Math.min(1,((o[0]-h.from[0])*w+(o[1]-h.from[1])*m)/F));return Math.hypot(o[0]-(h.from[0]+R*w),o[1]-(h.from[1]+R*m))},rt=(o,h)=>{const w=de(o.record,"run"),m=de(h.record,"run"),F=[w.base,w.base+w.height],R=[m.base,m.base+m.height],O=$.get(String((w==null?void 0:w.level)??o.record.params.level)).at,q=$.get(String((m==null?void 0:m.level)??h.record.params.level)).at;return Math.min(O+F[1],q+R[1])>Math.max(O+F[0],q+R[0])},_t=1,ie=new Map,Nt=new Map;for(const o of X){const h=[["from",o.joinStart],["to",o.joinEnd]],w={from:o.from,to:o.to};for(const[m,F]of h){if(!F)continue;const R=o[m];let O=null,q=1/0;for(const gt of X){if(gt===o||gt.arcMid||!rt(o,gt))continue;const $t=Mt(R,gt);$t<q&&(q=$t,O=gt)}if(!O||q>_t)continue;const u=dt(o,O);if(!u)continue;const x=Math.min(_t,2*Math.max(o.width,O.width)+.02);Math.hypot(u[0]-R[0],u[1]-R[1])>x||Mt(u,O)>O.width+.01||(w[m]=u,Nt.set(o,{...Nt.get(o),[m]:O.width/2}))}ie.set(o,w)}const le=new Map;if(r){const o=w=>{const m=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]);return{L:m,d:[(w.to[0]-w.from[0])/m,(w.to[1]-w.from[1])/m]}},h=(w,m,F)=>{const R=w.record.item.guid;if(!R||X.filter(x=>x.record===w.record).length!==1)return null;const{d:O}=o(w),q=Qt(r,R).map(x=>x[2]);if(!q.length)return null;const u=Vl(r,R,w.from,O,(m+F)/2,(Math.min(...q)+Math.max(...q))/2);return u?u.hi-u.lo:null};for(const w of X){if(w.arcMid||!(w.width>0))continue;const m=o(w);if(!(m.L<.3))for(const F of X){if(F===w||F.arcMid||!(F.width>0)||!rt(w,F))continue;const R=o(F);if(R.L<.3||Math.abs(m.d[0]*R.d[1]-m.d[1]*R.d[0])>.02)continue;const O=Math.abs(-(F.from[0]-w.from[0])*m.d[1]+(F.from[1]-w.from[1])*m.d[0]);if(O>(w.width+F.width)/2-.01)continue;const q=[F.from,F.to].map($t=>($t[0]-w.from[0])*m.d[0]+($t[1]-w.from[1])*m.d[1]),u=Math.max(0,Math.min(...q)),x=Math.min(m.L,Math.max(...q));if(x-u<.3)continue;const gt=h(w,u,x);typeof process<"u"&&((Li=(Pi=process.env)==null?void 0:Pi.RECIPE_WALL)!=null&&Li.split(",").includes(w.record.item.guid??""))&&console.error(`[cut-by?] ${w.record.item.guid} by ${F.record.item.guid}: off ${O.toFixed(3)}, along ${u.toFixed(2)}..${x.toFixed(2)}, shape ${gt}`),!(gt===null||gt>w.width-.01)&&(typeof process<"u"&&((Bi=process.env)!=null&&Bi.RECIPE_TRACE)&&console.error(`[cut-by] ${w.record.item.guid} (${(w.width*1e3).toFixed(0)} mm, its shape ${(gt*1e3).toFixed(0)}) cut by ${F.record.item.guid} over ${(x-u).toFixed(2)} m`),le.set(w,[...le.get(w)??[],F]))}}}const me=(o,h)=>{var F;if(!r||!o)return null;const w=[-h[1],h[0]],m=[];for(const R of r.elements.values()){if(R.parent!==o||!/^IFCPLATE$/i.test(R.ifcClass)||R.pieces.length!==1)continue;const O=r.geometries.get(R.pieces[0].geometry);if(!O||O.tris.length/3>12)continue;const q=Qt(r,R.gid);if(q.length<4)continue;const u=q.map(gt=>gt[0]*w[0]+gt[1]*w[1]),x=Math.max(...u)-Math.min(...u);x>.002&&x<.2&&m.push(x)}return m.length?(m.sort((R,O)=>R-O),typeof process<"u"&&((F=process.env)!=null&&F.RECIPE_TRACE)&&console.error(`[glass] ${o}: ${m.length} panel(s), median ${(m[Math.floor(m.length/2)]*1e3).toFixed(1)} mm`),m[Math.floor(m.length/2)]*f):null},Le=(o,h)=>{var O;if(!r||!o)return null;const w=[-h[1],h[0]],m=[],F=[];for(const q of r.elements.values()){if(q.parent!==o||!/^IFCMEMBER$/i.test(q.ifcClass))continue;const u=Qt(r,q.gid);if(u.length<4)continue;const x=u.map(A=>A[0]*h[0]+A[1]*h[1]),gt=u.map(A=>A[0]*w[0]+A[1]*w[1]),$t=u.map(A=>A[2]),Rt=A=>Math.max(...A)-Math.min(...A),It=Math.min(Rt(x),Rt($t)),yt=Rt(gt);It>.005&&It<.5&&yt>.005&&yt<1&&(m.push(It),F.push(yt))}if(!m.length)return null;m.sort((q,u)=>q-u),F.sort((q,u)=>q-u);const R={width:m[Math.floor(m.length/2)],depth:F[Math.floor(F.length/2)]};return typeof process<"u"&&((O=process.env)!=null&&O.RECIPE_TRACE)&&console.error(`[mullion] ${o}: ${m.length} member(s), median ${(R.width*1e3).toFixed(1)} × ${(R.depth*1e3).toFixed(1)} mm`),{width:R.width*f,depth:R.depth*f}},re=(()=>{if(!r)return 0;const o=[];for(const w of X){const m=w.record.item.guid;if(!m||!r.elements.has(m))continue;const F=de(w.record,"run"),R=$.get(String((F==null?void 0:F.level)??w.record.params.level??""));if(!F||!R)continue;const O=Qt(r,m);if(!O.length)continue;let q=1/0;for(const u of O)q=Math.min(q,u[2]);o.push(q-(R.at+(typeof F.base=="number"?F.base:0)))}o.sort((w,m)=>w-m);const h=o.length?o[Math.floor(o.length/2)]:0;return Math.abs(h)>.5?h:0})();for(const o of X){const{record:h}=o;let w=[];const m=de(h,"run");typeof process<"u"&&((Di=(ji=process.env)==null?void 0:ji.RECIPE_WALL)!=null&&Di.split(",").includes(h.item.guid??""))&&console.error(`[wall] ${h.item.guid}: params ${JSON.stringify(h.params).slice(0,800)} seg ${JSON.stringify({from:o.from,to:o.to,i:o.i})}`);const F=typeof m.base=="number"?m.base:0,R=m.height,O=$.get(String(m.level??h.params.level??"")),q=h.params.lookRef;let{from:u,to:x}=o.arcMid?{from:o.from,to:o.to}:ie.get(o);Math.hypot(x[0]-u[0],x[1]-u[1])<.01&&({from:u,to:x}=o);const gt=new Set;if(!o.arcMid&&X.filter(L=>L.record===h).length===1){const L=m.asCut,_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(L&&_>.05){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=(S,C)=>{const J=C==null?void 0:C.through,j=C==null?void 0:C.keep;if(!J||!j)return null;const z=y[0]*j[0]+y[1]*j[1];return Math.abs(z)<.5?null:((J[0]-S[0])*j[0]+(J[1]-S[1])*j[1])/z},T=h.params.wantedAtStart==="square"?g(u,(Ui=L.start)==null?void 0:Ui[0]):null,v=h.params.wantedAtEnd==="square"?g(x,(Ji=L.end)==null?void 0:Ji[0]):null;T!==null&&T>.005&&T<Math.min(1,_/2)&&(u=[u[0]+y[0]*T,u[1]+y[1]*T],gt.add("start")),v!==null&&v<-.005&&v>-Math.min(1,_/2)&&(x=[x[0]+y[0]*v,x[1]+y[1]*v],gt.add("end")),typeof process<"u"&&((qi=process.env)!=null&&qi.RECIPE_CUT_OUT)&&(T!==null&&T<-.005&&T>-1&&(u=[u[0]+y[0]*T,u[1]+y[1]*T],gt.add("start")),v!==null&&v>.005&&v<1&&(x=[x[0]+y[0]*v,x[1]+y[1]*v],gt.add("end"))),typeof process<"u"&&((Gi=process.env)!=null&&Gi.RECIPE_TRACE)&&(T!==null&&Math.abs(T)>.005&&Math.abs(T)<1||v!==null&&Math.abs(v)>.005&&Math.abs(v)<1)&&console.error(`[wall-to-cut] ${h.item.guid} ${q}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`),typeof process<"u"&&((Vi=(Hi=process.env)==null?void 0:Hi.RECIPE_WALL)!=null&&Vi.split(",").includes(h.item.guid??""))&&console.error(`[wall-cut] ${h.item.guid}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`)}}const $t=new Set(gt),Rt=!o.arcMid&&r&&h.item.guid&&X.filter(L=>L.record===h).length===1?r.elements.get(h.item.guid):void 0;if(Rt){const L=Qt(r,h.item.guid),_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(L.length>=4&&_>.05){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=L.map(z=>(z[0]-u[0])*y[0]+(z[1]-u[1])*y[1]),T=Math.min(...g),v=Math.max(...g),S=L.map(z=>-(z[0]-u[0])*y[1]+(z[1]-u[1])*y[0]),C=Math.max(...S)-Math.min(...S),J=z=>{const M=S.filter((ot,Q)=>Math.abs(g[Q]-z)<.002);return M.length>=2&&Math.max(...M)-Math.min(...M)>.9*C},j=u;J(T)&&(u=[j[0]+y[0]*T,j[1]+y[1]*T],$t.add("start")),J(v)&&(x=[j[0]+y[0]*v,j[1]+y[1]*v],$t.add("end"))}}const It=(O.at+F)*f,yt=`${Ct(u[0]*f)},${Ct(u[1]*f)},${Ct(It)};${Ct(x[0]*f)},${Ct(x[1]*f)},${Ct(It)}`,A={CategoryId:De.walls,Type:((zi=_n(h))==null?void 0:zi.type)??q,LocationLine:yt,Level:O.name,BaseOffset:Ct(F*f),Height:Ct(R*f),...o.arcMid?{LocationArc:`${Ct(o.arcMid[0]*f)},${Ct(o.arcMid[1]*f)},${Ct(It)}`}:{}},Ot=le.get(o);Ot&&(A.CutBy=Ot.flatMap(L=>{const _=`${nt(L.record.id)}#${L.i}`,y=V.get(_);return y?[_,y]:[_]}).join("|"));const lt=o.arcMid?[]:[u!==o.from||o.joinStart?"start":"",x!==o.to||o.joinEnd?"end":""].filter(L=>!!L&&!$t.has(L));lt.length&&(A.JoinEnds=lt.join(","));const bt=lt.filter(L=>h.params[L==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");bt.length&&(A.Mitre=bt.join(","));const K=$.get(String(h.params.topLevel??""));K&&(A.TopLevel=K.name,A.TopOffset=Ct((O.at+F+R-K.at)*f));const G=m.profile;let et=Array.isArray(G)?Yl(G):G;if((h.params.wantedAtStart==="mitre"||h.params.wantedAtEnd==="mitre")&&Array.isArray(et)&&et.length===4){const L=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),_=m.height,y=(T,v)=>Math.abs(T)<1e-4?"lo":Math.abs(T-v)<.001?"hi":null,g=et.map(([T,v])=>[y(T,L),y(v,_)]);g.every(([T,v])=>T&&v)&&new Set(g.map(([T,v])=>`${T}${v}`)).size===4&&(et=void 0)}if(typeof process<"u"&&((Wi=process.env)!=null&&Wi.RECIPE_LAYER_EXT)&&Array.isArray(et)&&et.length>=4&&r&&h.item.guid&&typeof m.height=="number"){const L=(()=>{var _,y;try{return JSON.parse(String(((y=(_=P.get(q))==null?void 0:_.params)==null?void 0:y.definition)??"null"))}catch{return null}})();if(((L==null?void 0:L.layers)??[]).some(_=>(_.topExtension??0)>.001||(_.baseExtension??0)>.001)){const _=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),y=m.height,g=[(o.to[0]-o.from[0])/_,(o.to[1]-o.from[1])/_],T=O.at+F+re,v=[...r.elements.values()].filter(M=>M.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(M.ifcClass)).map(M=>{const ot=Qt(r,M.gid).map(Q=>[(Q[0]-o.from[0])*g[0]+(Q[1]-o.from[1])*g[1],Q[2]-T]);return ot.length?[Math.min(...ot.map(Q=>Q[0])),Math.max(...ot.map(Q=>Q[0])),Math.min(...ot.map(Q=>Q[1])),Math.max(...ot.map(Q=>Q[1]))]:null}).filter(M=>M!==null),S=Math.min(...et.map(([M])=>M)),C=Math.max(...et.map(([M])=>M)),J=([M,ot])=>(Math.abs(M-S)<.005||Math.abs(M-C)<.005)&&(Math.abs(ot)<.005||Math.abs(ot-y)<.005),j=([M,ot])=>v.some(Q=>M>=Q[0]-.03&&M<=Q[1]+.03&&ot>=Q[2]-.15&&ot<=Q[3]+.03),z=et.filter(M=>!J(M));et.filter(J).length===4&&(z.length===0||v.length&&z.every(j))&&(typeof process<"u"&&((Yi=process.env)!=null&&Yi.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${q}: its outline's ${z.length} notch corner(s) filled by what it hosts → a plain wall`),et=void 0)}}if(!o.arcMid&&Array.isArray(et)&&et.length>=3&&o.i===0&&!X.some(L=>L!==o&&L.record===h)){const L=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),_=[(o.to[0]-o.from[0])/L,(o.to[1]-o.from[1])/L],y=[];let g=-((u[0]-o.from[0])*_[0]+(u[1]-o.from[1])*_[1]),T=(x[0]-o.to[0])*_[0]+(x[1]-o.to[1])*_[1];const v=g,S=T;{const M=Nt.get(o),ot=[],Q=r&&h.item.guid?Qt(r,h.item.guid).map(ne=>(ne[0]-o.from[0])*_[0]+(ne[1]-o.from[1])*_[1]):[],Ft=Q.length?Math.max(0,-Math.min(...Q))-g:1/0,Dt=Q.length?Math.max(0,Math.max(...Q)-L)-T:1/0,Ht=(M==null?void 0:M.from)??(Ft<.6?Ft:0),ee=(M==null?void 0:M.to)??(Dt<.6?Dt:0);Ht&&lt.includes("start")&&Ft>.005&&(g+=Math.min(Ht,Ft),ot.push("start")),ee&&lt.includes("end")&&Dt>.005&&(T+=Math.min(ee,Dt),ot.push("end"));const Zt=lt.filter(ne=>!ot.includes(ne));if(ot.length&&(Zt.length?A.JoinEnds=Zt.join(","):delete A.JoinEnds),ot.length&&A.Mitre){const ne=A.Mitre.split(",").filter(Ut=>Zt.includes(Ut));ne.length?A.Mitre=ne.join(","):delete A.Mitre}ot.length&&typeof process<"u"&&((Ki=process.env)!=null&&Ki.RECIPE_TRACE)&&console.error(`[profile-face] ${h.item.guid} ${q}: ${ot.join(",")} to the far face`)}const C=(M,ot)=>et.map(([Q,Ft],Dt)=>{const Ht=Math.abs(Q)<1e-6,ee=Math.abs(Q-L)<1e-6;let Zt=Q,ne=Ft;if(Ht||ee){Zt=Ht?-M:L+ot;const Ut=[et[(Dt-1+et.length)%et.length],et[(Dt+1)%et.length]].find(([fe])=>Math.abs(fe-Q)>1e-6);Ut&&(ne=Ft+(Ut[1]-Ft)/(Ut[0]-Q)*(Zt-Q))}return[Zt,ne]}),J=M=>{const ot=M.length,Q=M.map((Dt,Ht)=>[Dt,M[(Ht+1)%ot]]);if(Q.some(([Dt,Ht])=>Math.hypot(Ht[0]-Dt[0],Ht[1]-Dt[1])<.001))return!1;for(let Dt=0;Dt<ot;Dt++){const[Ht,ee]=Q[Dt],[,Zt]=Q[(Dt+1)%ot],ne=[ee[0]-Ht[0],ee[1]-Ht[1]],Ut=[Zt[0]-ee[0],Zt[1]-ee[1]];if((ne[0]*Ut[0]+ne[1]*Ut[1])/(Math.hypot(...ne)*Math.hypot(...Ut))<-.999)return!1}const Ft=(Dt,Ht,ee)=>(Ht[0]-Dt[0])*(ee[1]-Dt[1])-(Ht[1]-Dt[1])*(ee[0]-Dt[0]);for(let Dt=0;Dt<ot;Dt++)for(let Ht=Dt+1;Ht<ot;Ht++){if(Ht===Dt+1||Dt===0&&Ht===ot-1)continue;const[ee,Zt]=Q[Dt],[ne,Ut]=Q[Ht],fe=Ft(ne,Ut,ee),Be=Ft(ne,Ut,Zt),gn=Ft(ee,Zt,ne),So=Ft(ee,Zt,Ut);if((fe>1e-9&&Be<-1e-9||fe<-1e-9&&Be>1e-9)&&(gn>1e-9&&So<-1e-9||gn<-1e-9&&So>1e-9))return!1}return!0};let j=C(g,T);if(!J(j)){const ot=[[v,S],[0,0]].find(([Q,Ft])=>J(C(Q,Ft)));typeof process<"u"&&((Xi=process.env)!=null&&Xi.RECIPE_TRACE)&&console.error(`[profile-folded] ${h.item.guid} ${q}: ends ${g.toFixed(3)}/${T.toFixed(3)} fold it → ${ot?ot.map(Q=>Q.toFixed(3)).join("/"):"as given"}`),j=ot?C(...ot):et.map(([Q,Ft])=>[Q,Ft])}const z=M=>M.flatMap(([ot,Q])=>{const Ft=[o.from[0]+ot*_[0],o.from[1]+ot*_[1]];return[Ft[0]*f,Ft[1]*f,(O.at+F+Q)*f]});for(const M of z(j))y.push(M);if(A.Profile=JSON.stringify([y]),j.length===8){const M=j.map(([,Ut])=>Ut),ot=Math.max(...M),Q=Math.min(...M),Ft=j.map(([Ut])=>Ut),Dt=Math.min(...Ft),Ht=Math.max(...Ft),ee=j.filter(([Ut])=>Ut>Dt+.005&&Ut<Ht-.005),Zt=[...new Set(ee.map(([Ut])=>+Ut.toFixed(4)))].sort((Ut,fe)=>Ut-fe);if(j.filter(([Ut,fe])=>(Math.abs(Ut-Dt)<.005||Math.abs(Ut-Ht)<.005)&&(Math.abs(fe-ot)<.005||Math.abs(fe-Q)<.005)).length===4&&ee.length===4&&Zt.length===2&&Zt[1]-Zt[0]<.3&&ee.some(([,Ut])=>Math.abs(Ut-Q)<.005)&&ee.every(([,Ut])=>Math.abs(Ut-Q)<.005||ot-Ut<.3)){const Ut=(fe,Be)=>[[fe,Q],[Be,Q],[Be,ot],[fe,ot]];A.Profile=JSON.stringify([z(Ut(Dt,Zt[0]))]),w=[JSON.stringify([z(Ut(Zt[1],Ht))])],typeof process<"u"&&((Zi=process.env)!=null&&Zi.RECIPE_TRACE)&&console.error(`[slit-split] ${h.item.guid} ${q}: a slit ${((Zt[1]-Zt[0])*100).toFixed(0)} cm wide at ${Zt[0].toFixed(2)}, two walls`)}}delete A.TopLevel,delete A.TopOffset}const St=h.params.topAttachedTo,it=h.params.topAttachedAt==="top"||m.topAttachedAt==="top",ft=!o.arcMid&&typeof St=="string"&&it&&!A.Profile&&Gt.has(St)?Bt(Gt.get(St)):null;if(ft){const L=Math.hypot(x[0]-u[0],x[1]-u[1]),_=J=>[u[0]+(x[0]-u[0])*J/L,u[1]+(x[1]-u[1])*J/L],y=(u[0]-ft.A[0])*ft.n[0]+(u[1]-ft.A[1])*ft.n[1],g=(x[0]-ft.A[0])*ft.n[0]+(x[1]-ft.A[1])*ft.n[1],T=[0,L];(y-ft.ridge)*(g-ft.ridge)<0&&T.splice(1,0,(ft.ridge-y)/(g-y)*L);const v=O.at+F,S=[],C=(J,j)=>{const z=_(J);S.push(z[0]*f,z[1]*f,j*f)};C(0,v),C(L,v);for(const J of[...T].reverse()){const j=_(J);C(J,ft.zAt(j[0],j[1]))}A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}const mt=typeof St=="string"?St:r&&h.item.guid?Wl(r,h.item.guid,jt):void 0;if(mt&&!A.Profile){A.AttachTop=nt(mt);const L=V.get(nt(mt));L&&(A.AttachTopMade=L)}if(mt&&typeof St!="string"&&typeof process<"u"&&((Qi=process.env)!=null&&Qi.RECIPE_TRACE)&&console.error(`[attach] ${h.item.guid} ${h.item.name??""} → ${mt}`),!A.Profile&&!A.AttachTop&&Rt){const L=[...r.elements.values()].filter(T=>T.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(T.ifcClass));let _=xs(r,h.item.guid,u,x,!0);const y=T=>{const v=[];for(const S of T)(!v.length||Math.hypot(S[0]-v[v.length-1][0],S[1]-v[v.length-1][1])>=.02)&&v.push(S);for(;v.length>1&&Math.hypot(v[0][0]-v[v.length-1][0],v[0][1]-v[v.length-1][1])<.02;)v.pop();return v};if(_!=null&&_.outline){const T=y(_.outline);_=T.length>=3?{..._,outline:T,holes:(_.holes??[]).map(y).filter(v=>v.length>=3)}:null}if(L.length&&(_!=null&&_.outline)){const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=L.map(j=>{const z=Qt(r,j.gid).map(M=>[(M[0]-u[0])*v[0]+(M[1]-u[1])*v[1],M[2]]);return z.length?[Math.min(...z.map(M=>M[0])),Math.max(...z.map(M=>M[0])),Math.min(...z.map(M=>M[1])),Math.max(...z.map(M=>M[1]))]:null}).filter(j=>j!==null),C=j=>{const z=Math.min(...j.map(Ft=>Ft[0])),M=Math.max(...j.map(Ft=>Ft[0])),ot=Math.min(...j.map(Ft=>Ft[1])),Q=Math.max(...j.map(Ft=>Ft[1]));return S.some(Ft=>Math.min(M,Ft[1])-Math.max(z,Ft[0])>.01&&Math.min(Q,Ft[3])-Math.max(ot,Ft[2])>.01)},J=(_.holes??[]).filter(j=>!C(j));_=!((tr=_.pieces)!=null&&tr.length)&&(J.length||_.outline.length>4)?{..._,holes:J}:null,_&&typeof process<"u"&&((er=process.env)!=null&&er.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid}: ${L.length} hosted, ${J.length} empty hole(s) kept`)}const g=_!=null&&_.outline?null:xs(r,h.item.guid,u,x);if(g){typeof process<"u"&&((nr=process.env)!=null&&nr.RECIPE_TRACE)&&console.error(`[wall-top] ${h.item.guid} ${h.item.name??""}: ${g.chain.map(([J,j])=>`${J.toFixed(2)}/${j.toFixed(2)}`).join(" ")}`);const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=[],C=(J,j)=>{S.push((u[0]+J*v[0])*f,(u[1]+J*v[1])*f,j*f)};C(g.lo,g.bottom-re),C(g.hi,g.bottom-re);for(const[J,j]of[...g.chain].reverse())C(J,j-re);A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}if(_!=null&&_.outline){typeof process<"u"&&((sr=process.env)!=null&&sr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid} ${h.item.name??""}: ${_.outline.length} corners`);const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=C=>C.flatMap(([J,j])=>[(u[0]+J*v[0])*f,(u[1]+J*v[1])*f,(j-re)*f]);A.Profile=JSON.stringify([S(_.outline),...(_.holes??[]).map(S)]),delete A.TopLevel,delete A.TopOffset,w=(_.pieces??[]).map(C=>JSON.stringify([S(C)]))}}else if(A.Profile&&Rt&&!A.AttachTop){const _=[...r.elements.values()].some(y=>y.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(y.ifcClass))?null:xs(r,h.item.guid,u,x,!0);if((ir=_==null?void 0:_.holes)!=null&&ir.length&&!((rr=_.pieces)!=null&&rr.length)){const y=Math.hypot(x[0]-u[0],x[1]-u[1]),g=[(x[0]-u[0])/y,(x[1]-u[1])/y],T=v=>v.flatMap(([S,C])=>[(u[0]+S*g[0])*f,(u[1]+S*g[1])*f,(C-re)*f]);try{const v=JSON.parse(A.Profile);A.Profile=JSON.stringify([...v,..._.holes.map(T)]),typeof process<"u"&&((or=process.env)!=null&&or.RECIPE_TRACE)&&console.error(`[wall-holes] ${h.item.guid} ${h.item.name??""}: ${_.holes.length} hole(s) added to the converter's profile`)}catch{}}}const At=(m.clippedBy??[]).filter(L=>Array.isArray(L.through)&&Array.isArray(L.keep)&&Math.abs(L.keep[2])>.05);if(!o.arcMid&&At.length&&!A.AttachTop)try{const L=Math.hypot(x[0]-u[0],x[1]-u[1]),_=O.at+F,y=A.Profile?JSON.parse(A.Profile):[[u[0]*f,u[1]*f,_*f,x[0]*f,x[1]*f,_*f,x[0]*f,x[1]*f,(_+R)*f,u[0]*f,u[1]*f,(_+R)*f]];let g=[];for(let C=0;C+2<y[0].length;C+=3)g.push([y[0][C]/f,y[0][C+1]/f,y[0][C+2]/f]);const T=C=>{const J=[(x[0]-u[0])/L,(x[1]-u[1])/L];let j=0;for(let z=0;z<C.length;z++){const M=C[z],ot=C[(z+1)%C.length];j+=(M[0]*J[0]+M[1]*J[1])*ot[2]-(ot[0]*J[0]+ot[1]*J[1])*M[2]}return Math.abs(j)/2},v=T(g);for(const C of At){const J=z=>(z[0]-C.through[0])*C.keep[0]+(z[1]-C.through[1])*C.keep[1]+(z[2]-C.through[2])*C.keep[2],j=[];for(let z=0;z<g.length;z++){const M=g[z],ot=g[(z+1)%g.length],Q=J(M),Ft=J(ot);if(Q>=0&&j.push(M),Q>=0!=Ft>=0){const Dt=Q/(Q-Ft);j.push([0,1,2].map(Ht=>M[Ht]+Dt*(ot[Ht]-M[Ht])))}}g=j}const S=g.length>=3?T(g):0;S>.05&&v-S>.05&&(typeof process<"u"&&((ar=process.env)!=null&&ar.RECIPE_TRACE)&&console.error(`[wall-clip] ${h.item.guid} ${h.item.name??""}: ${At.length} plane(s), ${v.toFixed(2)} → ${S.toFixed(2)} m²`),A.Profile=JSON.stringify([g.flatMap(C=>[C[0]*f,C[1]*f,C[2]*f]),...y.slice(1)]),delete A.TopLevel,delete A.TopOffset)}catch{}if(!A.Profile&&Rt){const L=Qt(r,h.item.guid),_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(L.length>=8&&_>.5){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=[-y[1],y[0]],T=(J,j)=>{const z=L.filter(M=>{const ot=(M[0]-u[0])*y[0]+(M[1]-u[1])*y[1];return ot>=J*_&&ot<=j*_}).map(M=>(M[0]-u[0])*g[0]+(M[1]-u[1])*g[1]);return z.length>=2?{c:(Math.max(...z)+Math.min(...z))/2,w:Math.max(...z)-Math.min(...z)}:null},v=T(-.02,.06),S=T(.94,1.02),C=T(.45,.55);if(v&&S&&C){const J=(v.c+S.c)/2,j=C.c-J,z=L.map(Q=>{const Ft=Math.min(Math.max(((Q[0]-u[0])*y[0]+(Q[1]-u[1])*y[1])/_,0),1);return(Q[0]-u[0])*g[0]+(Q[1]-u[1])*g[1]-J-4*j*Ft*(1-Ft)}),M=Math.max(...z)-Math.min(...z),ot=M<(v.w+S.w)/2+.01&&C.w>.5*Math.min(v.w,S.w);if(typeof process<"u"&&((lr=(cr=process.env)==null?void 0:cr.RECIPE_WALL)!=null&&lr.split(",").includes(h.item.guid??""))&&console.error(`[arc-bands] ${JSON.stringify({b0:v,bm:C,b1:S,sag:j,spread:M})}`),ot&&Math.abs(j)>.02&&Math.abs(j)<_/2){const Q=[(u[0]+x[0])/2+g[0]*j,(u[1]+x[1])/2+g[1]*j];A.LocationArc=`${Ct(Q[0]*f)},${Ct(Q[1]*f)},${Ct(It)}`,typeof process<"u"&&((hr=process.env)!=null&&hr.RECIPE_TRACE)&&console.error(`[wall-arc] ${h.item.guid} ${h.item.name??""}: bows ${(j*100).toFixed(1)} cm over ${_.toFixed(2)} m`)}}}}const xt=pt(q);if(xt&&(A["Type.Width"]=Ct(xt)),xt){const L=U.get(A.Type);L===void 0?U.set(A.Type,xt):Math.abs(L-xt)>.001&&(A.Type=`${A.Type} · ${Math.round(xt/f*1e3)} mm`)}const Jt=h.item.guid?r==null?void 0:r.elements.get(h.item.guid):void 0;if(Jt!=null&&Jt.layers&&Jt.layers.length>1)A["Type.Layers"]=JSON.stringify([...Jt.layers].reverse().map(L=>[+Ct(L.thickness*f),L.material??"",L.function??""])),Jt.layersFlipped&&(A.FlipLayers="1");else if(typeof process<"u"&&((fr=process.env)!=null&&fr.RECIPE_PIECE_LAYERS)&&Jt&&Jt.pieces.length>=2&&xt&&h.item.guid){const L=Math.hypot(x[0]-u[0],x[1]-u[1]),_=[(x[0]-u[0])/L,(x[1]-u[1])/L],y=[];Jt.pieces.forEach((v,S)=>{const C=Qt(r,h.item.guid,S);if(C.length<4)return;const J=C.map(Q=>(Q[0]-u[0])*_[0]+(Q[1]-u[1])*_[1]),j=C.map(Q=>-(Q[0]-u[0])*_[1]+(Q[1]-u[1])*_[0]),z=C.map(Q=>Q[2]);if(Math.max(...J)-Math.min(...J)<Math.min(.3,.5*L)||Math.max(...z)-Math.min(...z)<.5*R)return;const M=Math.min(...j),ot=Math.max(...j);y.some(Q=>Math.abs(Q[0]-M)<.002&&Math.abs(Q[1]-ot)<.002)||y.push([M,ot])}),y.sort((v,S)=>S[1]-v[1]);const g=y.length?y[0][1]-y[y.length-1][0]:0,T=y.every((v,S)=>S===0||v[1]<=y[S-1][0]+.002);if(y.length>=2&&T&&Math.abs(g-xt/f)<.01){const v=[];y.forEach((j,z)=>{const M=ot=>+Ct(Math.round(ot*2e3)/2e3*f);z>0&&y[z-1][0]-j[1]>.003&&v.push([M(y[z-1][0]-j[1]),"","air"]),v.push([M(j[1]-j[0]),"",""])});const S=JSON.stringify(v),C=JSON.stringify([...v].reverse()),J=Z.get(A.Type);J===void 0&&Z.set(A.Type,S),J===void 0||J===S?A["Type.Layers"]=S:J===C&&(A["Type.Layers"]=J,A.FlipLayers="1"),typeof process<"u"&&((dr=process.env)!=null&&dr.RECIPE_TRACE)&&console.error(`[piece-layers] ${h.item.guid} ${A.Type}: ${S}${J&&J!==S?J===C?" (flipped)":" (the type stacks otherwise: kept)":""}`)}}if(!A["Type.Layers"]&&typeof process<"u"&&((ur=process.env)!=null&&ur.RECIPE_LAYER_EXT)){const L=(()=>{var y,g;try{return JSON.parse(String(((g=(y=P.get(q))==null?void 0:y.params)==null?void 0:g.definition)??"null"))}catch{return null}})(),_=(L==null?void 0:L.layers)??[];if(_.length>1&&_.some(y=>(y.topExtension??0)>.001||(y.baseExtension??0)>.001)){A["Type.Layers"]=JSON.stringify(_.map(C=>[+Ct((C.thickness??0)*f),C.material??"",C.function??"",+Ct((C.topExtension??0)*f),+Ct((C.baseExtension??0)*f)]));const y=Math.max(..._.map(C=>C.topExtension??0)),g=Math.max(..._.map(C=>C.baseExtension??0)),T=(C,J)=>{if(!r||!h.item.guid)return[];const j=Qt(r,h.item.guid);if(j.length<4)return[];const z=[Math.min(...j.map(M=>M[0])),Math.min(...j.map(M=>M[1])),Math.max(...j.map(M=>M[0])),Math.max(...j.map(M=>M[1]))];return ut().filter(M=>M.box[0]<z[2]-.01&&z[0]<M.box[3]-.01&&M.box[1]<z[3]-.01&&z[1]<M.box[4]-.01&&M.box[2]<J-.01&&C<M.box[5]-.01).flatMap(M=>M.keys)},v=O.at+F+re,S=typeof process<"u"&&((pr=process.env)!=null&&pr.RECIPE_EXT_CUT)&&!A.Profile&&y>.001&&g<.001?T(v+R,v+R+y):[];S.length&&(A.Height||A.TopOffset)?(A["Type.Layers"]=JSON.stringify(_.map(C=>[+Ct((C.thickness??0)*f),C.material??"",C.function??""])),A.TopOffset?A.TopOffset=Ct(Number(A.TopOffset)+y*f):A.Height=Ct(Number(A.Height)+y*f),A.CutBy=[...A.CutBy?A.CutBy.split("|"):[],...S].join("|"),typeof process<"u"&&((mr=process.env)!=null&&mr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: up ${y} to its finish's top, cut by ${S.length} slab(s)`)):(y>.001&&(A.TopExtension=Ct(y*f)),g>.001&&(A.BaseExtension=Ct(g*f))),typeof process<"u"&&((gr=process.env)!=null&&gr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: top ${y}, base ${g}`)}}typeof process<"u"&&((wr=(yr=process.env)==null?void 0:yr.RECIPE_WALL)!=null&&wr.split(",").includes(h.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(A).slice(0,1500)} style ${JSON.stringify(((br=P.get(q))==null?void 0:br.params)??null).slice(0,800)}`),st(`${nt(h.id)}#${o.i}`,A)&&Yt++,w.forEach((L,_)=>{st(`${nt(h.id)}#${o.i}p${_+1}`,{...A,Profile:L})&&Yt++})}const Xe=(o,h,w)=>{if(!(h>0)||h>=o)return[];const m=o-Math.floor(o/h+1e-9)*h,F=w==="beginning"?0:w==="end"?m:w==="centreLine"?o/2%h:m/2,R=[];for(let O=F;O<=o+1e-4;O+=h)O>1e-4&&O<o-1e-4&&R.push(O);return R};let Un=0,Mi=0;const $i=new Map;for(const o of a){if(o.kind!=="run"||o.params.of!=="curtainWall")continue;Mi++;const h=de(o,"run"),w=(Tr=(Er=(vr=h==null?void 0:h.run)==null?void 0:vr.line)==null?void 0:Er.curves)==null?void 0:Tr[0],m=$.get(String((h==null?void 0:h.level)??o.params.level??"")),F=o.params.lookRef,R=typeof F=="string"?(Mr=P.get(F))==null?void 0:Mr.params:void 0;if(!(w!=null&&w.from)||!w.to||typeof(h==null?void 0:h.height)!="number"||!m||!R)continue;const O=y=>typeof y=="number"?y:Number(y)||0,q=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]),u=[(w.to[0]-w.from[0])/q,(w.to[1]-w.from[1])/q],x=O(R.uprightWidth)>0?null:Le(o.item.guid??void 0,u),gt=(O(R.uprightWidth)||(x?x.width/f:0))/2,$t=(O(R.horizontalWidth)||(x?x.width/f:0))/2,Rt={start:!1,end:!1,bottom:!1,top:!1};let It=[];if(r&&o.item.guid&&!Array.isArray(h.profile)){const y=[...r.elements.values()].filter(S=>S.parent===o.item.guid),g=S=>{const C=Qt(r,S);if(!C.length)return null;const J=C.map(z=>(z[0]-w.from[0])*u[0]+(z[1]-w.from[1])*u[1]),j=C.map(z=>z[2]);return{t0:Math.min(...J),t1:Math.max(...J),z0:Math.min(...j),z1:Math.max(...j)}},T=y.map(S=>g(S.gid)).filter(S=>S!==null),v=y.filter(S=>/^IFCMEMBER$/i.test(S.ifcClass)).map(S=>g(S.gid)).filter(S=>S!==null);if(v.length&&T.length){const S=Math.min(...T.map(M=>M.t0)),C=Math.max(...T.map(M=>M.t1)),J=Math.min(...T.map(M=>M.z0)),j=Math.max(...T.map(M=>M.z1)),z=M=>M.t1-M.t0>M.z1-M.z0;Rt.bottom=!v.some(M=>z(M)&&Math.abs(M.z0-J)<.01),Rt.top=!v.some(M=>z(M)&&Math.abs(M.z1-j)<.01),Rt.start=!v.some(M=>!z(M)&&Math.abs(M.t0-S)<.01),Rt.end=!v.some(M=>!z(M)&&Math.abs(M.t1-C)<.01),It=[...new Set(v.filter(M=>!z(M)&&M.t0>S+.01&&M.t1<C-.01).map(M=>+((M.t0+M.t1)/2).toFixed(4)))].sort((M,ot)=>M-ot),Object.values(Rt).some(Boolean)&&typeof process<"u"&&(($r=process.env)!=null&&$r.RECIPE_TRACE)&&console.error(`[curtain-bare] ${o.item.guid}: no bar at its ${Object.entries(Rt).filter(([,M])=>M).map(([M])=>M).join(", ")}`)}}const yt=Rt.start?0:gt,A=Rt.end?0:gt,Ot=Rt.bottom?0:$t,lt=Rt.top?0:$t,bt=[w.from[0]-u[0]*yt,w.from[1]-u[1]*yt],K=[w.to[0]+u[0]*A,w.to[1]+u[1]*A],G=(typeof h.base=="number"?h.base:0)-Ot,et=h.height+Ot+lt,H=(m.at+G)*f,St=Xe(q,O(R.alongSpacing),R.alongJustify),it=!((Ir=h.lines)!=null&&Ir.along)&&It.length>0&&(It.length!==St.length||It.some((y,g)=>Math.abs(y-St[g])>.01));it&&typeof process<"u"&&((Sr=process.env)!=null&&Sr.RECIPE_TRACE)&&console.error(`[curtain-lines] ${o.item.guid}: ${It.length} from its bars, not the type's ${St.length}`);const ft=((xr=h.lines)==null?void 0:xr.along)??(it?It:St),mt=((_r=h.lines)==null?void 0:_r.up)??Xe(h.height,O(R.upSpacing),R.upJustify),At=(h.omitted??[]).flatMap(y=>{const g=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(y);if(!g)return[];const T=g[1]==="horizontal",v=Number(g[2])/1e3+(T?Ot:yt),S=Number(g[3])/1e3+(T?yt:Ot);return[{horizontal:T,at:v*f,from:S*f}]}),xt=Rt.start&&Rt.end&&Rt.bottom&&Rt.top;if(!xt){const y=[0,...ft.map(v=>v+yt)],g=[0,...mt.map(v=>v+Ot)],T=q+yt+A;if(Rt.bottom)for(const v of y)At.push({horizontal:!0,at:0,from:v*f});if(Rt.top)for(const v of y)At.push({horizontal:!0,at:et*f,from:v*f});if(Rt.start)for(const v of g)At.push({horizontal:!1,at:0,from:v*f});if(Rt.end)for(const v of g)At.push({horizontal:!1,at:T*f,from:v*f})}const Jt=(h.omitted??[]).flatMap(y=>{const g=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(y);return g?[{along:(Number(g[1])/1e3+yt)*f,up:(Number(g[2])/1e3+Ot)*f}]:[]});if(r&&o.item.guid)for(const y of zl(r,o.item.guid,O(R.panelDepth),[-u[1],u[0]])){const g=(y.centre[0]-w.from[0])*u[0]+(y.centre[1]-w.from[1])*u[1],T=y.centre[2]-re-(m.at+(typeof h.base=="number"?h.base:0));if(g<-.01||g>q+.01||T<-.01||T>h.height+.01)continue;const v=Math.max(0,...ft.filter(C=>C<=g+1e-6)),S=Math.max(0,...mt.filter(C=>C<=T+1e-6));Jt.push({along:(v+yt)*f,up:(S+Ot)*f}),Pt.add(y.gid)}const L={CategoryId:De.walls,Type:((Ar=_n(o))==null?void 0:Ar.type)??String(F),LocationLine:`${Ct(bt[0]*f)},${Ct(bt[1]*f)},${Ct(H)};${Ct(K[0]*f)},${Ct(K[1]*f)},${Ct(H)}`,Level:m.name,BaseOffset:Ct(G*f),Height:Ct(et*f),Curtain:JSON.stringify({along:ft.map(y=>(y+yt)*f),up:mt.map(y=>(y+Ot)*f),omit:At,empty:Jt,...xt?{noBorders:!0}:{},mullion:O(R.uprightWidth)>0?{width:O(R.uprightWidth)*f,depth:O(R.depth)*f}:x??{width:0,depth:O(R.depth)*f},panel:{thickness:me(o.item.guid??void 0,u)??O(R.panelDepth)*f,offset:-O(R.panelOffset)*f}})},_=h.profile;if(Array.isArray(_)&&_.length>=3){const g=_.reduce((C,J,j)=>{const z=_[(j+1)%_.length];return C+J[0]*z[1]-z[0]*J[1]},0)>0?1:-1,T=_.length,v=_.map((C,J)=>{const j=_[(J-1+T)%T],z=_[(J+1)%T],M=(Ht,ee)=>{const Zt=ee[0]-Ht[0],ne=ee[1]-Ht[1],Ut=Math.hypot(Zt,ne)||1,fe=g*ne/Ut,Be=-g*Zt/Ut,gn=Math.abs(fe)>Math.abs(Be)?gt:$t;return{p:[Ht[0]+fe*gn,Ht[1]+Be*gn],d:[Zt,ne]}},ot=M(j,C),Q=M(C,z),Ft=ot.d[0]*Q.d[1]-ot.d[1]*Q.d[0];if(Math.abs(Ft)<1e-12)return[Q.p[0],Q.p[1]];const Dt=((Q.p[0]-ot.p[0])*Q.d[1]-(Q.p[1]-ot.p[1])*Q.d[0])/Ft;return[ot.p[0]+Dt*ot.d[0],ot.p[1]+Dt*ot.d[1]]}),S=[];for(const[C,J]of v)S.push((w.from[0]+u[0]*C)*f,(w.from[1]+u[1]*C)*f,(m.at+G+$t+J)*f);L.Profile=JSON.stringify([S])}{const y=JSON.parse(L.Curtain),g=y.mullion,T=(Cr=y.panel)!=null&&Cr.thickness?`, ${Math.round(y.panel.thickness/f*1e3)} mm glass`:"",v=`${Math.round(g.width/f*1e3)} x ${Math.round(g.depth/f*1e3)}${T}${y.noBorders?", no borders":""}`,S=$i.get(L.Type);S===void 0?$i.set(L.Type,v):S!==v&&(typeof process<"u"&&((Rr=process.env)!=null&&Rr.RECIPE_TRACE)&&console.error(`[curtain-type] ${o.item.guid}: ${L.Type} first made with ${S}, this one ${v}`),L.Type=`${L.Type} · ${v}`)}st(nt(o.id),L)&&Un++}let Jn=0,Ii=0;const Si=(o,h,w)=>{if(!r||!o)return null;const m=Math.hypot(w[0]-h[0],w[1]-h[1]);if(!(m>0))return null;const F=[-(w[1]-h[1])/m,(w[0]-h[0])/m],R=[o,...[...r.elements.values()].filter(u=>u.parent===o).map(u=>u.gid)].flatMap(u=>Qt(r,u));if(R.length<4)return null;const O=R.map(u=>(u[0]-h[0])*F[0]+(u[1]-h[1])*F[1]),q=Math.max(...O)-Math.min(...O);return q>.3&&q<10?q:null};for(const o of a){if(o.kind!=="stair"||o.params.of!=="stair")continue;Ii++;const h=de(o,"stair"),w=o.params.lookRef,m=typeof w=="string"?(Or=P.get(w))==null?void 0:Or.params:void 0,F=$.get(String((h==null?void 0:h.level)??o.params.level??""));if(!(h!=null&&h.start)||!h.end||!(Number(h.rise)>0)||!F||!m)continue;const R=K=>typeof K=="number"?K:Number(K)||0,O=Number(h.rise),q=R(m.maxRiser)>0?R(m.maxRiser):(Nr=(kr=h.sketch)==null?void 0:kr.risers)!=null&&Nr.length?O/(h.sketch.risers.length+1):.18,u=Math.max(1,Math.ceil(O/q-1e-6)),x=R(m.tread),gt=K=>[K[0]*f,K[1]*f];let $t=F.at+R(o.params.base),Rt=!1;if(r&&o.item.guid){const K=Qt(r,o.item.guid).map(H=>H[2]-re),G=O/u,et=K.length?Math.min(...K):$t;$t-et>.5*G&&$t-et<1.5*G&&(typeof process<"u"&&((Fr=process.env)!=null&&Fr.RECIPE_TRACE)&&console.error(`[stair-base] ${o.item.guid} ${o.item.name??""}: base ${$t.toFixed(3)} → its shape's ${et.toFixed(3)}`),$t=et,Rt=!0)}const It={family:(()=>{const K=String(w).split(":").map(G=>G.trim()).filter((G,et,H)=>et<H.length-1||!/^\d+$/.test(G));return K.length>=3&&/^(stairs?|escaleras?|treppen?)$/i.test(K[0])?K[1]:K[0]})(),base:$t*f,height:O*f,risers:u,tread:x*f,width:(R(m.width)>0?R(m.width):Si(o.item.guid??void 0,h.start,h.end)??0)*f,endsWithRiser:(()=>{if(!r||!o.item.guid)return!1;const K=Qt(r,o.item.guid);if(K.length<4)return!1;const G=Math.max(...K.map(H=>H[2]))-re,et=F.at+R(o.params.base)+O;return et-G>.5*(O/u)&&et-G<1.5*(O/u)})(),sizes:{maxRiser:Math.ceil(O/u*1e3-1e-6)/1e3*f,minTread:x*f,waist:R(m.waist)*f,treadThickness:m.construction==="assembled"?R(m.treadThickness)*f:0,riserThickness:m.construction==="assembled"?R(m.riserThickness)*f:0,notchExtension:R(m.notchExtension)*f,notchThickness:R(m.notchThickness)*f,...m.nosing!==void 0&&Number.isFinite(Number(m.nosing))?{nosing:Number(m.nosing)*f}:{}}};typeof process<"u"&&((Pr=process.env)!=null&&Pr.RECIPE_TRACE)&&console.error(`[stair-end] ${o.item.guid} ${o.item.name??""}: ${u} risers, ends with riser ${It.endsWithRiser}`);const yt=h.sketch;if(yt!=null&&yt.boundary&&yt.risers&&yt.risers.length>=2){const K=it=>[(it[0][0]+it[1][0])/2,(it[0][1]+it[1][1])/2],G=yt.risers.filter((it,ft,mt)=>ft===0||Math.hypot(K(it)[0]-K(mt[ft-1])[0],K(it)[1]-K(mt[ft-1])[1])>.01),et=(it,ft)=>Math.hypot(it[0]-ft[0],it[1]-ft[1])<.01,H=yt.boundary,St=it=>H.some((ft,mt)=>{const At=H[(mt+1)%H.length];return et(ft,it[0])&&et(At,it[1])||et(ft,it[1])&&et(At,it[0])});if(G.length>=2&&!St(G[0])){const[it,ft]=[G[0],G[1]],mt=[it[1][0]-it[0][0],it[1][1]-it[0][1]],At=Math.hypot(mt[0],mt[1]),xt=K(it),Jt=K(ft),L=[xt[0]-Jt[0],xt[1]-Jt[1]];let _=null,y=1/0;for(let g=0;g<H.length;g++){const T=H[g],v=H[(g+1)%H.length],S=[v[0]-T[0],v[1]-T[1]],C=Math.hypot(S[0],S[1]);if(!(C>0)||Math.abs((S[0]*mt[1]-S[1]*mt[0])/(C*At))>.02)continue;const J=K([T,v]),j=(J[0]-xt[0])*L[0]+(J[1]-xt[1])*L[1];j>1e-4&&j<y&&(y=j,_=[T,v])}_&&G.unshift(_)}G.length!==yt.risers.length&&typeof process<"u"&&((Lr=process.env)!=null&&Lr.RECIPE_TRACE)&&console.error(`[stair-sketch] ${o.item.guid}: riser lines ${yt.risers.length} → ${G.length}`),yt.risers=G}if(yt!=null&&yt.boundary&&yt.boundary.length>=4&&yt.risers&&yt.risers.length>=2){const K=yt.risers[0],G=(g,T)=>Math.hypot(g[0]-T[0],g[1]-T[1])<.01,et=yt.boundary.findIndex((g,T,v)=>{const S=v[(T+1)%v.length];return G(g,K[0])&&G(S,K[1])||G(g,K[1])&&G(S,K[0])}),H=et>0?[...yt.boundary.slice(et),...yt.boundary.slice(0,et)]:yt.boundary;typeof process<"u"&&((Br=process.env)==null?void 0:Br.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] boundary ${JSON.stringify(H)} (turned by ${et}) risers ${JSON.stringify(yt.risers)} tread ${x}`);const St=yt.risers[yt.risers.length-1],it=g=>[(g[0][0]+g[1][0])/2,(g[0][1]+g[1][1])/2],ft=it(St);let mt=1,At=1/0;for(let g=1;g<H.length;g++){const T=it([H[g],H[(g+1)%H.length]]),v=Math.abs(Math.hypot(T[0]-ft[0],T[1]-ft[1])-x);v<At&&(At=v,mt=g)}{const g=[St[1][0]-St[0][0],St[1][1]-St[0][1]],T=Math.hypot(g[0],g[1]),v=it(yt.risers[0]);let S=-1/0,C=-1;for(let J=1;J<H.length;J++){const j=[H[(J+1)%H.length][0]-H[J][0],H[(J+1)%H.length][1]-H[J][1]],z=Math.hypot(j[0],j[1]);if(!(z>0)||Math.abs((j[0]*g[1]-j[1]*g[0])/(z*T))>.06)continue;const M=it([H[J],H[(J+1)%H.length]]),ot=Math.hypot(M[0]-v[0],M[1]-v[1]);ot>S+1e-6&&(S=ot,C=J)}C>0&&(mt=C)}const xt=(g,T)=>{const v=[];for(let S=g;S!==T;S=(S+1)%H.length)v.push([gt(H[S]),gt(H[(S+1)%H.length])]);return v},Jt=[...xt(1,mt),...xt((mt+1)%H.length,0)];typeof process<"u"&&((jr=process.env)==null?void 0:jr.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] end edge ${mt} of ${H.length}`);const L=yt.risers.map(([g,T])=>[gt(g),gt(T)]);gt(H[mt]),gt(H[(mt+1)%H.length]);const _=L.map(([g,T])=>[(g[0]+T[0])/2,(g[1]+T[1])/2]);if(It.sketch={boundary:Jt,risers:L,path:_},It.path=[_[0],_[_.length-1]],It.width||(It.width=Math.hypot(L[0][1][0]-L[0][0][0],L[0][1][1]-L[0][0][1])),typeof process<"u"&&((Dr=process.env)!=null&&Dr.RECIPE_TRACE)){const g=T=>Math.hypot(T[1][0]-T[0][0],T[1][1]-T[0][1])/f;console.error(`[stair] ${o.item.guid} ${o.item.name??""}: ${Jt.length} sides (shortest ${(Math.min(...Jt.map(g))*1e3).toFixed(2)} mm), ${L.length} risers (shortest ${(Math.min(...L.map(g))*1e3).toFixed(2)} mm), walk ${_.length} points (shortest step ${(Math.min(..._.slice(1).map((T,v)=>g([_[v],T])))*1e3).toFixed(2)} mm)`)}let y=1/0;for(let g=0;g+1<yt.risers.length;g++){const[T,v]=yt.risers[g],[S,C]=yt.risers[g+1],J=[v[0]-T[0],v[1]-T[1]],j=[C[0]-S[0],C[1]-S[1]],z=Math.hypot(J[0],J[1]),M=Math.hypot(j[0],j[1]);Math.abs((J[0]*j[1]-J[1]*j[0])/(z*M))>.001||(y=Math.min(y,Math.abs(((S[0]-T[0])*J[1]-(S[1]-T[1])*J[0])/z)))}if(Number.isFinite(y)&&(It.tread=y*f,It.sizes.minTread=y*f,Rt)){const g=It.path,T=Math.hypot(g[1][0]-g[0][0],g[1][1]-g[0][1]);T>0&&(It.path=[[g[0][0]-(g[1][0]-g[0][0])/T*y*f,g[0][1]-(g[1][1]-g[0][1])/T*y*f],g[1]])}}else{let K=[h.start[0],h.start[1]];if(Rt&&x>0){const G=h.end[0]-h.start[0],et=h.end[1]-h.start[1],H=Math.hypot(G,et);H>0&&(K=[K[0]-x*G/H,K[1]-x*et/H])}if(It.path=[gt(K),gt([h.end[0],h.end[1]])],!(x>0)){const G=Math.hypot(h.end[0]-h.start[0],h.end[1]-h.start[1])/u;It.tread=G*f,It.sizes.minTread=G*f}typeof process<"u"&&((Ur=process.env)!=null&&Ur.RECIPE_TRACE)&&console.error(`[stair] ${o.item.guid} ${o.item.name??""}: straight, ${Math.hypot(h.end[0]-h.start[0],h.end[1]-h.start[1]).toFixed(3)} m, rise ${O}, ${u} risers, width ${R(m.width)}, measured ${Si(o.item.guid??void 0,h.start,h.end)}`)}const A=String(o.item.attrs.Name??""),Ot=A.replace(/ Run \d+$/,""),lt=[];for(const K of a){if(K.kind!=="extrusion"||Ot===A||!new RegExp(`^${Ot.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(K.item.attrs.Name??"")))continue;const G=de(K,"extrusion"),et=G==null?void 0:G.on,H=(((qr=(Jr=G==null?void 0:G.profile)==null?void 0:Jr.outline)==null?void 0:qr.curves)??[]).flatMap(S=>S.from?[S.from]:[]),St=pt(K.params.lookRef),it=$.get(String((G==null?void 0:G.level)??K.params.level??""));if(!(et!=null&&et.origin)||!et.u||!et.v||Math.abs(et.v[2]??0)<.99||!H.length||!St||!it)continue;const[ft,mt]=[Math.min(...H.map(S=>S[0])),Math.max(...H.map(S=>S[0]))],[At,xt]=[Math.min(...H.map(S=>S[1])),Math.max(...H.map(S=>S[1]))],Jt=et.origin,L=et.u;let _=[L[1],-L[0]];const y=[(h.start[0]+h.end[0])/2,(h.start[1]+h.end[1])/2];(y[0]-Jt[0])*_[0]+(y[1]-Jt[1])*_[1]<0&&(_=[-_[0],-_[1]]);const T=St/f,v=(S,C)=>[(Jt[0]+L[0]*S+_[0]*C)*f,(Jt[1]+L[1]*S+_[1]*C)*f];lt.push({outline:[v(ft,0),v(mt,0),v(mt,T),v(ft,T)],top:(it.at+R(K.params.base)+Jt[2]+xt)*f,thickness:(xt-At)*f})}lt.length&&(It.landings=lt);const bt={CategoryId:De.stairs,Type:((Gr=_n(o))==null?void 0:Gr.type)??String(w),Level:F.name,Stairs:JSON.stringify(It)};typeof process<"u"&&(((Hr=process.env)==null?void 0:Hr.RECIPE_STAIR)===o.item.guid||((Vr=process.env)==null?void 0:Vr.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${bt.Stairs} style ${JSON.stringify(m)}`),st(nt(o.id),bt)&&Jn++}const xi=new Map,un={floor:0,foundation:0,roof:0,ceiling:0},pe={floor:0,foundation:0,roof:0,ceiling:0},_i=a.flatMap(o=>{var R,O;if(o.kind!=="extrusion"||o.params.of!=="form")return[];const h=de(o,"extrusion"),w=$.get(String((h==null?void 0:h.level)??o.params.level??"")),m=(((O=(R=h==null?void 0:h.profile)==null?void 0:R.outline)==null?void 0:O.curves)??[]).flatMap(q=>q.from?[q.from]:[]);if(!(h!=null&&h.void)||!w||m.length<3)return[];const F=w.at+(Number(o.params.base)||0);return[{guid:o.item.guid,outline:m,from:F,to:F+(Number(h.depth??o.params.depth)||0)}]});for(const o of a){const h=o.params.of;if(o.kind!=="extrusion"||h!=="slab"&&h!=="roof"&&h!=="covering")continue;let w=h==="covering"?"ceiling":h==="roof"?"roof":Vo(o);if(w==="other"||r&&o.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((zr=r.elements.get(o.item.guid))==null?void 0:zr.ifcClass)??""))continue;const m=de(o,"extrusion"),F=m==null?void 0:m.on;if(F&&(Math.abs(((Wr=F.u)==null?void 0:Wr[2])??0)>.001||Math.abs(((Yr=F.v)==null?void 0:Yr[2])??0)>.001))continue;if(w==="roof"&&!Bt(o)){const lt=m,bt=((Xr=(Kr=m==null?void 0:m.profile)==null?void 0:Kr.outline)==null?void 0:Xr.curves)??[];if(lt!=null&&lt.slope&&typeof lt.slope.by=="number"&&Math.abs(lt.slope.by)>.001&&typeof lt.slope.toward=="number"&&!(Array.isArray(lt.slopes)&&lt.slopes.some(K=>typeof K=="number"))&&bt.length>=3){const K=[Math.cos(lt.slope.toward),Math.sin(lt.slope.toward)],G=bt.map(it=>it.from).filter(Boolean),et=G.map(it=>it[0]*K[0]+it[1]*K[1]),H=Math.min(...et);G.some((it,ft)=>Math.abs(et[ft]-H)<.01&&Math.abs(et[(ft+1)%G.length]-H)<.01)||(w="floor",typeof process<"u"&&((Zr=process.env)!=null&&Zr.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${o.item.guid} ${o.params.lookRef}: its low side a corner, a sloped floor`))}}un[w]++,typeof process<"u"&&((Qr=process.env)==null?void 0:Qr.RECIPE_SLAB)===o.item.guid&&console.error(`[slab] ${o.item.guid}: params ${JSON.stringify(o.params).slice(0,600)} body ${JSON.stringify(m).slice(0,1500)}`);const R=typeof o.params.base=="number"?o.params.base:0,O=$.get(String((m==null?void 0:m.level)??o.params.level??"")),q=o.params.lookRef,u=lt=>{if(!(lt!=null&&lt.length))return null;const bt=[];for(const K of lt){if(K.kind!=="segment"||!K.from)return null;bt.push(K.from[0]*f,K.from[1]*f,R*f)}return bt.length>=9?bt:null},x=u((eo=(to=m==null?void 0:m.profile)==null?void 0:to.outline)==null?void 0:eo.curves);if(typeof q!="string"||!O||!x)continue;const gt=[x],$t=w==="roof"?Bt(o):null;for(const lt of((no=m==null?void 0:m.profile)==null?void 0:no.holes)??[]){const bt=u(lt==null?void 0:lt.curves);if(bt&&$t)for(let K=0;K+2<bt.length;K+=3)bt[K+2]=$t.zAt(bt[K]/f,bt[K+1]/f)*f;bt&&gt.push(bt)}const Rt=[...(m==null?void 0:m.cuts)??[]],It=O.at+R,yt=It+(Number(o.params.depth)||0);for(const lt of _i)lt.from<yt-.001&&It<lt.to-.001&&Rt.push({outline:lt.outline,through:[0,0,lt.to-lt.from]});for(const lt of Rt){const bt=lt.through,K=lt.outline;if(!Array.isArray(K)||K.length<3||!Array.isArray(bt)||Math.abs(bt[2])<.99*Math.hypot(bt[0],bt[1],bt[2]))continue;const G=K.filter((y,g)=>g===0||Math.hypot(y[0]-K[g-1][0],y[1]-K[g-1][1])>1e-4);if(G.length>3&&Math.hypot(G[0][0]-G[G.length-1][0],G[0][1]-G[G.length-1][1])<1e-4&&G.pop(),G.length<3)continue;const et=(y,g)=>{let T=!1;for(let v=0,S=x.length/3-1;v<x.length/3;S=v++){const C=x[3*v]/f,J=x[3*v+1]/f,j=x[3*S]/f,z=x[3*S+1]/f;J>g!=z>g&&y<(j-C)*(g-J)/(z-J)+C&&(T=!T)}return T};if(!G.every(y=>et(y[0],y[1]))){typeof process<"u"&&((so=process.env)!=null&&so.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut across its edge, left`);continue}const H=y=>[Math.min(...y.map(g=>g[0])),Math.min(...y.map(g=>g[1])),Math.max(...y.map(g=>g[0])),Math.max(...y.map(g=>g[1]))],St=y=>{const g=[];for(let T=0;T+2<y.length;T+=3)g.push([y[T]/f,y[T+1]/f]);return g},it=H(G),ft=(y,g,T)=>{let v=!1;for(let S=0,C=y.length-1;S<y.length;C=S++)y[S][1]>T!=y[C][1]>T&&g<(y[C][0]-y[S][0])*(T-y[S][1])/(y[C][1]-y[S][1])+y[S][0]&&(v=!v);return v},mt=(y,g,T)=>{const v=T[0]-g[0],S=T[1]-g[1],C=Math.max(0,Math.min(1,((y[0]-g[0])*v+(y[1]-g[1])*S)/(v*v+S*S||1)));return Math.hypot(y[0]-(g[0]+C*v),y[1]-(g[1]+C*S))},At=(y,g)=>y.some(T=>ft(g,T[0],T[1])||g.some((v,S)=>mt(T,v,g[(S+1)%g.length])<.01)),xt=gt.slice(1).some(y=>{const g=St(y),T=H(g);return it[0]<T[2]+.01&&T[0]<it[2]+.01&&it[1]<T[3]+.01&&T[1]<it[3]+.01&&(At(G,g)||At(g,G))}),Jt=St(x),L=G.some(y=>Jt.some((g,T)=>{const v=Jt[(T+1)%Jt.length],S=v[0]-g[0],C=v[1]-g[1],J=S*S+C*C||1,j=Math.max(0,Math.min(1,((y[0]-g[0])*S+(y[1]-g[1])*C)/J));return Math.hypot(y[0]-(g[0]+j*S),y[1]-(g[1]+j*C))<.01}));if(xt||L){typeof process<"u"&&((io=process.env)!=null&&io.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut ${xt?"over another hole":"at its edge"}, left`);continue}const _=G.flatMap(y=>[y[0]*f,y[1]*f,($t?$t.zAt(y[0],y[1]):R)*f]);gt.push(_),typeof process<"u"&&((ro=process.env)!=null&&ro.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid} ${o.item.name??""}: a hole of ${G.length} corners`)}const A={CategoryId:w==="roof"?De.roofs:w==="ceiling"?De.ceilings:w==="foundation"?De.structuralFoundations:De.floors,Type:((oo=_n(o))==null?void 0:oo.type)??q,Profile:JSON.stringify(gt),Level:O.name};let Ot=pt(q);if(w==="roof"&&r&&o.item.guid){const lt=(ao=r.elements.get(o.item.guid))==null?void 0:ao.layers,bt=(lt==null?void 0:lt.reduce((K,G)=>K+(G.thickness>0?G.thickness:0),0))??0;bt>0&&(!Ot||Math.abs(bt*f-Ot)>.2*Ot)&&(Ot=bt*f)}if(Ot&&(A["Type.Width"]=Ct(Ot)),Ot){const lt=xi.get(A.Type);lt===void 0?xi.set(A.Type,Ot):Math.abs(lt-Ot)>.001&&(A.Type=`${A.Type} · ${Math.round(Ot/f*1e3)} mm`)}if(w==="floor"&&r&&o.item.guid){const lt=Qt(r,o.item.guid);if(lt.length){const bt=[0,1,2].map(G=>Math.min(...lt.map(et=>et[G]))).concat([0,1,2].map(G=>Math.max(...lt.map(et=>et[G])))),K=X.flatMap(G=>{const et=G.record.item.guid?Qt(r,G.record.item.guid):[];if(et.length<4)return[];const H=[0,1,2].map(At=>Math.min(...et.map(xt=>xt[At]))).concat([0,1,2].map(At=>Math.max(...et.map(xt=>xt[At])))),St=H[2]>bt[2]+.01&&H[2]<bt[5]-.01&&H[5]>bt[5]&&lt.some(At=>Math.abs(At[2]-H[2])<.005),it=H[0]<bt[3]-.01&&bt[0]<H[3]-.01&&H[1]<bt[4]-.01&&bt[1]<H[4]-.01;if(!St||!it)return[];const ft=`${nt(G.record.id)}#${G.i}`,mt=V.get(ft);return mt?[ft,mt]:[ft]});K.length&&(A.CutBy=[...new Set(K)].join("|"),typeof process<"u"&&((co=process.env)!=null&&co.RECIPE_TRACE)&&console.error(`[floor-cut] ${o.item.guid} ${o.item.name??""}: cut by ${K.length} wall(s)`))}}if(w==="roof"||w==="ceiling"){A.BaseOffset=Ct(R*f);const lt=Number(o.params.drop??((lo=m==null?void 0:m.said)==null?void 0:lo.drop));if(w==="ceiling"&&Number.isFinite(lt)&&Ot){const H=[...$.values()].filter(St=>St.at>O.at+1e-6).sort((St,it)=>St.at-it.at)[0];H&&(A.BaseOffset=Ct((H.at-lt-Ot/f-O.at)*f))}const bt=m==null?void 0:m.slopes;if(w==="roof"&&Array.isArray(bt)&&bt.some(H=>typeof H=="number")){A.Slopes=JSON.stringify(bt.map(it=>typeof it=="number"?it:null));const H=Math.max(...bt.filter(it=>typeof it=="number").map(it=>Math.abs(it)));Ot&&H>0&&(A.BaseOffset=Ct(R*f-Ot*Math.sqrt(1+H*H)));const St=r&&o.item.guid?Qt(r,o.item.guid):[];if(Ot&&H>0&&St.length>=4){const it=St.map(Jt=>Jt[2]-re),ft=Math.min(...it),mt=O.at+R,At=mt-Ot/f*Math.sqrt(1+H*H),xt=mt-ft;if(ft-At>.01&&xt>.01){const Jt=St.filter((z,M)=>it[M]<ft+.002),L=z=>[Math.min(...z.map(M=>M[0])),Math.min(...z.map(M=>M[1])),Math.max(...z.map(M=>M[0])),Math.max(...z.map(M=>M[1]))],[_,y,g,T]=L(St),[v,S,C,J]=L(Jt),j=v-_>.01&&S-y>.01&&g-C>.01&&T-J>.01;A.EaveCut=j?"TwoCutSquare":"TwoCutPlumb",A.FasciaDepth=Ct((j?xt*Math.sqrt(1+H*H):xt)*f)}typeof process<"u"&&((ho=process.env)!=null&&ho.RECIPE_TRACE)&&console.error(`[roof-eave] ${o.item.guid} ${q}: plumb low ${At.toFixed(3)}, its lowest ${ft.toFixed(3)} → ${A.EaveCut??"plumb"}${A.FasciaDepth?`, fascia ${(Number(A.FasciaDepth)/f).toFixed(3)}`:""}`)}typeof process<"u"&&((fo=process.env)!=null&&fo.RECIPE_TRACE)&&console.error(`[roof] ${o.item.guid} ${q}: slopes ${JSON.stringify(bt)} base ${R} width ${Ot} edges ${gt[0]?gt[0].length/3:0} profile ${JSON.stringify((uo=gt[0])==null?void 0:uo.map(it=>+it.toFixed(2)))}`)}const K=w==="roof"?Bt(o):null;if(K){const{A:H,n:St,u:it,W:ft,ridge:mt,si:At,ti:xt,tj:Jt,L}=K,_=(y,g)=>[(H[0]+St[0]*y)*f,(H[1]+St[1]*y)*f,g*f];A.Extrusion=JSON.stringify({profile:[_(0,xt),_(mt,xt+At*mt),_(ft,Jt)],along:[it[0],it[1]],length:L*f}),delete A.Slopes}const G=m==null?void 0:m.slope,et=((mo=(po=m==null?void 0:m.profile)==null?void 0:po.outline)==null?void 0:mo.curves)??[];if(w==="roof"&&!K&&!A.Slopes&&G&&typeof G.by=="number"&&Math.abs(G.by)>.001&&typeof G.toward=="number"&&et.length>=3){const H=[Math.cos(G.toward),Math.sin(G.toward)],St=et.map(At=>At.from).filter(Boolean),it=St.map(At=>At[0]*H[0]+At[1]*H[1]),ft=Math.min(...it),mt=St.map((At,xt)=>Math.abs(it[xt]-ft)<.01&&Math.abs(it[(xt+1)%St.length]-ft)<.01);if(St.length===et.length&&mt.some(Boolean)){A.Slopes=JSON.stringify(mt.map(xt=>xt?Math.tan(Math.abs(G.by)):null)),A.BaseOffset=Ct(R*f);const At=r&&o.item.guid?Qt(r,o.item.guid):[];if(At.length>=4){const xt=Math.min(...At.map(Jt=>Jt[2]))-re;O.at+R-xt>.5*Math.tan(Math.abs(G.by))*(Math.max(...it)-ft)&&(A.BaseOffset=Ct((xt-O.at)*f))}}typeof process<"u"&&((go=process.env)!=null&&go.RECIPE_TRACE)&&console.error(`[roof-plane] ${o.item.guid} ${q}: ${(G.by*180/Math.PI).toFixed(1)}° toward ${(G.toward*180/Math.PI).toFixed(1)}°, eaves ${JSON.stringify(mt)}`)}}else if(Ot){A.HeightOffset=Ct(R*f+Ot);const lt=m==null?void 0:m.slope,bt=((wo=(yo=m==null?void 0:m.profile)==null?void 0:yo.outline)==null?void 0:wo.curves)??[];if(lt&&typeof lt.by=="number"&&Math.abs(lt.by)>1e-4&&typeof lt.toward=="number"&&bt.length>=3){const K=[Math.cos(lt.toward),Math.sin(lt.toward)],G=bt.map(mt=>mt.from).filter(Boolean),et=G.map(mt=>mt[0]*K[0]+mt[1]*K[1]),H=Math.min(...et),St=Math.max(...et),it=G[et.indexOf(H)],ft=Math.tan(lt.by);if(St-H>.001){A.Slope=Ct(ft),A.SlopeArrow=JSON.stringify([it[0]*f,it[1]*f,(it[0]+K[0]*(St-H))*f,(it[1]+K[1]*(St-H))*f]),A.HeightOffset=Ct(R*f+Ot-ft*(St-H)*f);const mt=r&&o.item.guid?Qt(r,o.item.guid):[];if(mt.length>=4){const At=Math.min(...mt.map(xt=>xt[2]))-re;A.HeightOffset=Ct((At-O.at)*f+Ot*Math.sqrt(1+ft*ft)),typeof process<"u"&&((bo=process.env)!=null&&bo.RECIPE_TRACE)&&console.error(`[slab-slope] ${o.item.guid} ${q}: lowest ${At.toFixed(3)} level ${O.at.toFixed(3)} base ${R.toFixed(3)} rise ${(ft*(St-H)).toFixed(3)}: top at its low corner ${(At+Ot*Math.sqrt(1+ft*ft)/f).toFixed(3)} (by base ${(O.at+R+Ot/f-ft*(St-H)).toFixed(3)})`)}}}}st(nt(o.id),A)&&pe[w]++}let qn=0,Ai=0;for(const o of a){if(o.kind!=="member"||o.params.of!=="column")continue;Ai++;const h=de(o,"member"),w=h==null?void 0:h.start;if(!w||w.length!==3)continue;const m=c?Wo(o.params.lookRef):null;if(c&&!m||!m&&!d)continue;const F=m??{family:d.family,type:d.type},R=$.get(String((h==null?void 0:h.level)??""));st(nt(o.id),{...d&&!m?{CategoryId:d.categoryId}:{},Family:F.family,Type:F.type,...R?{Level:R.name}:{}},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:(Number((h==null?void 0:h.roll)??0)||0)*zo})&&qn++}let Gn=0,Ci=0,ms=0;for(const o of a){if(o.kind!=="familyInstance")continue;if(o.params.host){ms++;continue}if(Ci++,!E)continue;const h=de(o,"instance"),w=(vo=h==null?void 0:h.placement)==null?void 0:vo.at;if(!w||w.length!==3)continue;const m=Wo(o.params.type);if(!m)continue;const F=(Eo=h==null?void 0:h.placement)==null?void 0:Eo.right,R=F?Math.atan2(F[1],F[0])*zo:0;st(nt(o.id),{Family:m.family,Type:m.type},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:R})&&Gn++}Pt.size&&typeof process<"u"&&((To=process.env)!=null&&To.RECIPE_TRACE)&&console.error(`[shaped-panels] ${Pt.size} curtain panel(s) made as families of their shape`);const pn=r?Dl(r,wt,e.fileId,Pt).filter(o=>!_i.some(h=>h.guid&&o.key.includes(h.guid))):[];if(typeof process<"u"&&((Mo=process.env)!=null&&Mo.RECIPE_GID))for(const o of pn.filter(h=>h.key.includes(process.env.RECIPE_GID)))console.error(`[shaped] ${o.key} at ${o.at} turn ${o.rotationDeg} host ${o.host} ${JSON.stringify({...o.attrs,Shape:o.attrs.Shape?"…":void 0})}`);let Hn=0;const Vn=new Map;for(const o of pn){if(!o.attrs.Family||Vn.has(o.attrs.Family))continue;const h={};for(const w of["Shape","Prism"])o.attrs[w]&&(h[w]=o.attrs[w]);Object.keys(h).length&&Vn.set(o.attrs.Family,h)}const Ri=new Set;for(const o of pn){const h=o.attrs.Family;!h||!Vn.has(h)||!(o.attrs.Shape||o.attrs.Prism)||Wt(o.key,o.host&&V.get(o.host)?{...o.attrs,HostMade:V.get(o.host)}:o.attrs,{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}})&&Ri.add(h)}for(const o of pn){const h=o.attrs.Family,w={position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}},m=o.host&&V.get(o.host)?{...o.attrs,HostMade:V.get(o.host)}:o.attrs,F=h&&Ri.has(h)&&!(o.attrs.Shape||o.attrs.Prism)&&!Wt(o.key,m,w)?{...o.attrs,...Vn.get(h)}:o.attrs;st(o.key,o.host&&V.get(o.host)?{...F,HostMade:V.get(o.host)}:F,{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}})&&Hn++}if(r)for(const o of Ul(r,wt,e.fileId)){const h=($o=at.get(o.host))==null?void 0:$o.Profile;if(h)try{const w=JSON.parse(h),m=[];for(let q=0;q+2<o.box.length;q+=3)m.push([o.box[q]*f,o.box[q+1]*f,(o.box[q+2]-re)*f]);const F=(q,u)=>[Math.min(...q.map(x=>x[u])),Math.max(...q.map(x=>x[u]))],R=[0,1,2].map(q=>F(m,q));if(w.slice(1).some(q=>{const u=[];for(let x=0;x+2<q.length;x+=3)u.push([q[x],q[x+1],q[x+2]]);return u.length>=3&&[0,1,2].every(x=>{const gt=F(u,x);return gt[0]<R[x][1]+.03&&R[x][0]<gt[1]+.03})})){typeof process<"u"&&((Io=process.env)!=null&&Io.RECIPE_TRACE)&&console.error(`[opening] ${o.key}: its wall's outline has its holes`);continue}}catch{}st(o.key,{WallOpening:o.box.map((w,m)=>Ct((m%3===2?w-re:w)*f)).join(","),...V.get(o.host)?{HostMade:V.get(o.host)}:{}},{host:o.host})}if(r)for(const o of Gl(r,e.fileId))st(o.key,{Room:"1",Name:o.name,Number:o.number,Height:Ct(o.height*f)},{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-re)*f]});let gs=0;const Ya=new Set(["slab","roof","covering"]);for(const o of a){const h=o.params.of;(o.kind==="footing"||o.kind==="ramp"||o.kind==="stair"&&h!=="stair"||o.kind==="extrusion"&&!Ya.has(String(h))||o.kind==="extrusion"&&h==="slab"&&Vo(o)==="other"&&!/ Landing \d+$/.test(String(o.item.attrs.Name??""))||o.kind==="run"&&h!=="wall"&&h!=="curtainWall")&&gs++}te();let mn=0;for(const[o,h]of V)!o.startsWith(`${e.fileId}:`)||wt.has(o)||(D.remove(h),mn++);if(D.length===0)throw new wi(`Up to date: "${e.name}" holds ${tt} element(s) this recipe already made, ${ms+gs} waiting on the applier, and nothing is left to remove.`);const Ka=[Kt?`${Kt} level(s)`:"",Yt?`${Yt} wall(s)`:"",Un?`${Un} curtain wall(s)`:"",pe.floor?`${pe.floor} floor(s)`:"",pe.foundation?`${pe.foundation} foundation slab(s)`:"",pe.roof?`${pe.roof} roof(s)`:"",pe.ceiling?`${pe.ceiling} ceiling(s)`:"",Jn?`${Jn} stair(s)`:"",qn?`${qn} column(s)`:"",Gn?`${Gn} instance(s)`:"",Hn?`${Hn} family instance(s)`:"",ct?`${ct} changed`:"",mn?`${mn} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${Ka.join(", ")}`,verb:D.summary,targets:D.length,payload:new Blob([await D.build(t.opId)]),ruleTallies:[{read:$.size,written:Kt},{read:X.length+zt,written:Yt},{read:Mi,written:Un},{read:un.floor+un.foundation,written:pe.floor+pe.foundation},{read:un.roof,written:pe.roof},{read:un.ceiling,written:pe.ceiling},{read:Ii,written:Jn},{read:Ai,written:qn},{read:Ci,written:Gn},{read:pn.length,written:Hn},{read:mn,written:mn},{read:ms+gs,written:0}]}}}const Kl={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}}},Xl=[{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"}],Ga=`
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
- `,bi={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:Wl,rules:Yl,doc:Ja,run:Ua("frag")},qa={...bi,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:`
50
+ `,vi={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:Kl,rules:Xl,doc:Ga,run:qa("frag")},Ha={...vi,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
- `+Ja,run:Ua("ifc")},Kl={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},Ga="rhino-to-revit",Xl=`recipe:${Ga}`;function Zl(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 Ha={name:Ga,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:`
56
+ `+Ga,run:qa("ifc")},Zl={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},Va="rhino-to-revit",Ql=`recipe:${Va}`;function th(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 za={name:Va,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 Tt;const{picked:t,contents:e}=await mi(s,s.input),{layer:n,instanceType:i}=s.settings;if(!n||!i)throw new Error("Choose the layer and the Revit type.");const r=(Tt=e.metadata)==null?void 0:Tt.data,a=r==null?void 0:r.units,l=typeof a=="string"?Kl[a.trim().toLowerCase()]:void 0;if(!l)throw new Error(`"${t.name}" does not say what units its data is in${a?` ("${String(a)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const p=String((r==null?void 0:r.axes)??"z-up").toLowerCase();if(p!=="z-up")throw new Error(`"${t.name}" declares its data as "${p}"; this recipe only converts Z up.`);const d=l*sn,c=pi(s),E=new fs({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:Xl});let b=0,$=0,P=0;const k=new Set,W=[];for(const nt of e.items){if(!nt.guid||Object.keys(nt.attrs).length===0)continue;if((nt.attrs.Layer??"")!==n){P++;continue}const wt=Zl(nt);if(!wt)continue;k.add(nt.guid);const Pt=[wt[0]*d,wt[1]*d,wt[2]*d],tt=c.get(nt.guid);tt?W.push({instance:tt,object:nt.guid,position:Pt}):(E.add({CategoryId:i.categoryId,Family:i.family,Type:i.type},{position:Pt,source:nt.guid}),b++)}for(const nt of W)E.set(nt.instance,{},{position:nt.position,source:nt.object}),$++;let V=0;for(const[nt,wt]of c)k.has(nt)||(E.remove(wt),V++);const D=b+$+V;if(D===0)throw new yi(`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: ${[b?`${b} new`:"",$?`${$} moved`:"",V?`${V} gone`:""].filter(Boolean).join(", ")}`,verb:E.summary,targets:D,payload:new Blob([await E.build(s.opId)]),ruleTallies:[{read:b,written:b},{read:$,written:$},{read:V,written:V},{read:P,written:0}]}}},Va=[Ha,qa,bi];function Ql(s){for(const t of Va)s.recipes.register(t)}const th={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},eh={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},nh={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},sh={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ih={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},rh={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},oh={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},ah={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},ch={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},lh={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=eh;exports.ChannelClient=La;exports.ChannelRoom=wi;exports.ClashesManager=nh;exports.CollabRoom=Na;exports.DOCUMENT_FILE=Mn;exports.DOCUMENT_SCHEMA=Cn;exports.DOCUMENT_TYPES=hi;exports.DocumentDrafts=Ea;exports.EngineServicesClient=cs;exports.ExternalRoom=Fa;exports.FileList=sh;exports.FlowDoc=Ps;exports.GISManager=ih;exports.GitHistoryManager=rh;exports.HelloWorld=oh;exports.METADATA_LIMITS=th;exports.OP_SCHEMA=di;exports.OperationBuilder=fs;exports.PROJECT_RECIPE_SCHEMA=gi;exports.PlatformClient=ti;exports.ProjectDocuments=fi;exports.ProjectHistory=ai;exports.ProjectManager=ah;exports.ProjectRecipes=Ca;exports.RECIPE_NAME=_a;exports.RecipeKit=xa;exports.Recipes=Ra;exports.RequestError=us;exports.SELF_VIEWING_FORMATS=pa;exports.STORAGE_BATCH_MAX=Gs;exports.StaleHistoryError=ks;exports.TopicsManager=ch;exports.UIManager=lh;exports.UpToDate=yi;exports.builtinRecipes=Va;exports.compileRecipe=qs;exports.describeChanges=yl;exports.documentTypeOf=Bs;exports.fragToRevit=bi;exports.ifcToRevit=qa;exports.latestVersions=Oa;exports.mintGuid=li;exports.orderByGraph=ci;exports.readFrag=ds;exports.registerBuiltinRecipes=Ql;exports.rhinoToRevit=Ha;exports.stampOf=as;exports.windowTransport=ka;
83
+ `,async run(s){var Tt;const{picked:t,contents:e}=await gi(s,s.input),{layer:n,instanceType:i}=s.settings;if(!n||!i)throw new Error("Choose the layer and the Revit type.");const r=(Tt=e.metadata)==null?void 0:Tt.data,a=r==null?void 0:r.units,l=typeof a=="string"?Zl[a.trim().toLowerCase()]:void 0;if(!l)throw new Error(`"${t.name}" does not say what units its data is in${a?` ("${String(a)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const p=String((r==null?void 0:r.axes)??"z-up").toLowerCase();if(p!=="z-up")throw new Error(`"${t.name}" declares its data as "${p}"; this recipe only converts Z up.`);const d=l*sn,c=mi(s),E=new ds({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:Ql});let b=0,$=0,P=0;const k=new Set,Y=[];for(const nt of e.items){if(!nt.guid||Object.keys(nt.attrs).length===0)continue;if((nt.attrs.Layer??"")!==n){P++;continue}const wt=th(nt);if(!wt)continue;k.add(nt.guid);const Pt=[wt[0]*d,wt[1]*d,wt[2]*d],tt=c.get(nt.guid);tt?Y.push({instance:tt,object:nt.guid,position:Pt}):(E.add({CategoryId:i.categoryId,Family:i.family,Type:i.type},{position:Pt,source:nt.guid}),b++)}for(const nt of Y)E.set(nt.instance,{},{position:nt.position,source:nt.object}),$++;let V=0;for(const[nt,wt]of c)k.has(nt)||(E.remove(wt),V++);const D=b+$+V;if(D===0)throw new wi(`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: ${[b?`${b} new`:"",$?`${$} moved`:"",V?`${V} gone`:""].filter(Boolean).join(", ")}`,verb:E.summary,targets:D,payload:new Blob([await E.build(s.opId)]),ruleTallies:[{read:b,written:b},{read:$,written:$},{read:V,written:V},{read:P,written:0}]}}},Wa=[za,Ha,vi];function eh(s){for(const t of Wa)s.recipes.register(t)}const nh={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},sh={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},ih={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},rh={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},oh={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},ah={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},ch={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},lh={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},hh={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},fh={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=sh;exports.ChannelClient=ja;exports.ChannelRoom=bi;exports.ClashesManager=ih;exports.CollabRoom=Pa;exports.DOCUMENT_FILE=$n;exports.DOCUMENT_SCHEMA=Rn;exports.DOCUMENT_TYPES=fi;exports.DocumentDrafts=Ta;exports.EngineServicesClient=ls;exports.ExternalRoom=La;exports.FileList=rh;exports.FlowDoc=Ls;exports.GISManager=oh;exports.GitHistoryManager=ah;exports.HelloWorld=ch;exports.METADATA_LIMITS=nh;exports.OP_SCHEMA=ui;exports.OperationBuilder=ds;exports.PROJECT_RECIPE_SCHEMA=yi;exports.PlatformClient=ei;exports.ProjectDocuments=di;exports.ProjectHistory=ci;exports.ProjectManager=lh;exports.ProjectRecipes=Ra;exports.RECIPE_NAME=Aa;exports.RecipeKit=_a;exports.Recipes=Oa;exports.RequestError=ps;exports.SELF_VIEWING_FORMATS=ma;exports.STORAGE_BATCH_MAX=Hs;exports.StaleHistoryError=Ns;exports.TopicsManager=hh;exports.UIManager=fh;exports.UpToDate=wi;exports.builtinRecipes=Wa;exports.compileRecipe=Gs;exports.describeChanges=bl;exports.documentTypeOf=js;exports.fragToRevit=vi;exports.ifcToRevit=Ha;exports.latestVersions=ka;exports.mintGuid=hi;exports.orderByGraph=li;exports.readFrag=us;exports.registerBuiltinRecipes=eh;exports.rhinoToRevit=za;exports.stampOf=cs;exports.windowTransport=Fa;
84
84
  //# sourceMappingURL=index.cjs.js.map