@thatopen/services 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { ProjectDocuments } from './documents';
1
2
  import { ProjectHistory } from './history';
2
3
  import { Recipes } from './recipes';
3
4
  import { ExecutionEntity, ExecutionSuscriptionReturnType } from '../types/execution';
@@ -631,6 +632,12 @@ export declare class EngineServicesClient {
631
632
  * @param onUpdateCallback - Callback invoked on each progress/result event.
632
633
  */
633
634
  onExecutionProgress(executionId: string, onUpdateCallback: (data: ExecutionSuscriptionReturnType) => void): Promise<void>;
635
+ /**
636
+ * A project's documents. Every document is a FOLDER holding its files plus
637
+ * a `document.json` descriptor naming the document, its native form and its
638
+ * renderable views. See `src/core/documents.ts` for the model and schema.
639
+ */
640
+ documents(projectId: string): ProjectDocuments;
634
641
  /**
635
642
  * A project's history of connected documents (Revit models, AutoCAD
636
643
  * drawings…): their version timelines and their change requests. See
@@ -0,0 +1,59 @@
1
+ import { EngineServicesClient } from './client';
2
+
3
+ /** One renderable representation of a document. */
4
+ export interface DocumentView {
5
+ /** The view file's item id — ids survive renames, names do not. */
6
+ fileId: string;
7
+ /** Lowercase format name: 'frag', 'ifc', 'potree', 'pdf'… */
8
+ format: string;
9
+ }
10
+ /** The wire shape of `document.json`, schema `thatopen/document@1`. */
11
+ export interface DocumentDescriptor {
12
+ schema: typeof DOCUMENT_SCHEMA;
13
+ /** The document's own name — what a row shows. Not any file's name. */
14
+ name: string;
15
+ /**
16
+ * The native form, when the document has one (a .rvt, a .3dm). A document
17
+ * born on the platform (a loose .frag) may not.
18
+ */
19
+ native?: {
20
+ fileId: string;
21
+ format: string;
22
+ };
23
+ /** The renderable representations, in no particular order. */
24
+ views: DocumentView[];
25
+ }
26
+ export declare const DOCUMENT_SCHEMA = "thatopen/document@1";
27
+ export declare const DOCUMENT_FILE = "document.json";
28
+ /**
29
+ * Documents of one project. Get it from {@link EngineServicesClient.documents}.
30
+ * Every method takes the document's FOLDER id — the id interfaces know the
31
+ * document by.
32
+ */
33
+ export declare class ProjectDocuments {
34
+ #private;
35
+ private readonly client;
36
+ readonly projectId: string;
37
+ constructor(client: EngineServicesClient, projectId: string);
38
+ /**
39
+ * The document's descriptor, read and validated, or null when the folder
40
+ * has none yet (an old folder, or a plain folder that is not a document).
41
+ */
42
+ descriptor(folderId: string): Promise<DocumentDescriptor | null>;
43
+ /**
44
+ * The first view whose format appears in `formats` — searched in the ORDER
45
+ * OF THE LIST, so the caller's preference wins (ask `['frag', 'ifc']` and a
46
+ * document carrying both answers the frag). Null when none matches: that is
47
+ * where an interface offers "Process".
48
+ */
49
+ view(folderId: string, formats: string[]): Promise<DocumentView | null>;
50
+ /**
51
+ * Registers a renderable representation — a processor's last act. One view
52
+ * per format: an existing view of the same format is replaced (a re-run
53
+ * processor updates, it does not accumulate). The descriptor must exist;
54
+ * create it first with {@link setDescriptor}.
55
+ */
56
+ addView(folderId: string, view: DocumentView): Promise<void>;
57
+ /** Writes the descriptor, creating or replacing `document.json`. */
58
+ setDescriptor(folderId: string, descriptor: Omit<DocumentDescriptor, 'schema'> & Partial<Pick<DocumentDescriptor, 'schema'>>): Promise<void>;
59
+ }
@@ -1,4 +1,5 @@
1
1
  import { EngineServicesClient } from './client';
2
+ import { DocumentDescriptor, DocumentView } from './documents';
2
3
 
3
4
  /** One element mutation inside a version. Wire-compatible with the plugins. */
4
5
  export interface FlowChange {
@@ -53,6 +54,13 @@ export interface FlowVersion {
53
54
  */
54
55
  export interface FlowSuggestion {
55
56
  opId: string;
57
+ /**
58
+ * The application that receives and executes it: 'revit', 'autocad', or a
59
+ * platform app like 'designer'. A suggestion without a recipient is not a
60
+ * suggestion; absent only in entries written before this field existed,
61
+ * where the recipient is the document's own source.
62
+ */
63
+ to?: string;
56
64
  /** Groups the suggestions one authored action produced across several docs. */
57
65
  batchId?: string;
58
66
  /** Hidden-file id of the payload .frag (envelope `revitflow/op@2`). */
@@ -81,6 +89,11 @@ export interface FlowDocInfo {
81
89
  source: string;
82
90
  /** The document's own id within that application. */
83
91
  docId: string;
92
+ /**
93
+ * The document folder's item id — the id the CDE and the documents API
94
+ * ({@link EngineServicesClient.documents}) know this document by.
95
+ */
96
+ folderId: string;
84
97
  /** The visible model file's name, when one exists yet. */
85
98
  modelName?: string;
86
99
  /**
@@ -91,6 +104,19 @@ export interface FlowDocInfo {
91
104
  */
92
105
  empty?: boolean;
93
106
  }
107
+ /**
108
+ * One person's current hold on a document's elements, read from the lock
109
+ * registry the native plugins arbitrate through. Element keys are the native
110
+ * application's own ids (Revit UniqueIds). Workset-level ownership lives in
111
+ * Revit's own binary worksharing files (the ownership mirror) and is not
112
+ * readable here — what IS here is every element-level claim.
113
+ */
114
+ export interface FlowOwner {
115
+ /** The native application's user name, as the plugin claimed with. */
116
+ owner: string;
117
+ /** The element keys this person currently holds, arbitration applied. */
118
+ elements: string[];
119
+ }
94
120
  /** What `sync` needs: the change list plus whatever the writer knows. */
95
121
  export interface SyncInput {
96
122
  author: string;
@@ -114,6 +140,11 @@ export interface SyncInput {
114
140
  }
115
141
  /** What `suggest` needs. */
116
142
  export interface SuggestInput {
143
+ /**
144
+ * The application that receives and executes it. Defaults to the document's
145
+ * own source — the native app that owns the document.
146
+ */
147
+ to?: string;
117
148
  /**
118
149
  * The suggestion's id, when the caller minted it up front — a payload
119
150
  * (envelope `revitflow/op@2`) carries the opId INSIDE, so whoever builds
@@ -178,6 +209,33 @@ export declare class FlowDoc {
178
209
  delta(version: FlowVersion): Promise<Blob>;
179
210
  /** The visible model .frag as last fully exported. */
180
211
  model(): Promise<Blob>;
212
+ /** The document folder's item id — the id the CDE knows this document by. */
213
+ folderId(): Promise<string>;
214
+ /**
215
+ * The document descriptor (`document.json`), or null when the folder does
216
+ * not carry one yet — an old folder from before descriptors existed.
217
+ */
218
+ descriptor(): Promise<DocumentDescriptor | null>;
219
+ /**
220
+ * The first view whose format appears in `formats`, searched in the order
221
+ * of the list (the caller's preference wins). Falls back to the visible
222
+ * model .frag on a descriptor-less folder, so old documents keep viewing.
223
+ */
224
+ view(formats: string[]): Promise<DocumentView | null>;
225
+ /**
226
+ * Registers a renderable representation, creating the descriptor when the
227
+ * folder predates them (named after the model file, or the folder itself).
228
+ * One view per format: a same-format view is replaced, not accumulated.
229
+ */
230
+ addView(view: DocumentView): Promise<void>;
231
+ /**
232
+ * Who currently holds which elements, read from the lock registry the
233
+ * native plugins arbitrate through. Read-only: claiming and releasing stay
234
+ * with the plugins. Empty when nobody holds anything (or the document has
235
+ * no lock anchor yet). Arbitration is applied: a key contested by two
236
+ * claims counts only for the earliest one, matching the plugins' rule.
237
+ */
238
+ ownership(): Promise<FlowOwner[]>;
181
239
  /**
182
240
  * Appends one version: uploads the geometry it carries, then the updated
183
241
  * history. Give `expectedLatestGuid` whenever you built on a head you read,
package/dist/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var cs=Object.defineProperty;var Te=n=>{throw TypeError(n)};var hs=(n,t,e)=>t in n?cs(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var v=(n,t,e)=>hs(n,typeof t!="symbol"?t+"":t,e),Ft=(n,t,e)=>t.has(n)||Te("Cannot "+e);var l=(n,t,e)=>(Ft(n,t,"read from private field"),e?e.call(n):t.get(n)),b=(n,t,e)=>t.has(n)?Te("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),_=(n,t,e,s)=>(Ft(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),a=(n,t,e)=>(Ft(n,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=Object.create(null);P.open="0";P.close="1";P.ping="2";P.pong="3";P.message="4";P.upgrade="5";P.noop="6";const Et=Object.create(null);Object.keys(P).forEach(n=>{Et[P[n]]=n});const Gt={type:"error",data:"parser error"},Re=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ne=typeof ArrayBuffer=="function",Pe=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,fe=({type:n,data:t},e,s)=>Re&&t instanceof Blob?e?s(t):ve(t,s):Ne&&(t instanceof ArrayBuffer||Pe(t))?e?s(t):ve(new Blob([t]),s):s(P[n]+(t||"")),ve=(n,t)=>{const e=new FileReader;return e.onload=function(){const s=e.result.split(",")[1];t("b"+(s||""))},e.readAsDataURL(n)};function Se(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let qt;function ls(n,t){if(Re&&n.data instanceof Blob)return n.data.arrayBuffer().then(Se).then(t);if(Ne&&(n.data instanceof ArrayBuffer||Pe(n.data)))return t(Se(n.data));fe(n,!1,e=>{qt||(qt=new TextEncoder),t(qt.encode(e))})}const ke="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ot=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<ke.length;n++)ot[ke.charCodeAt(n)]=n;const us=n=>{let t=n.length*.75,e=n.length,s,r=0,i,o,h,u;n[n.length-1]==="="&&(t--,n[n.length-2]==="="&&t--);const f=new ArrayBuffer(t),p=new Uint8Array(f);for(s=0;s<e;s+=4)i=ot[n.charCodeAt(s)],o=ot[n.charCodeAt(s+1)],h=ot[n.charCodeAt(s+2)],u=ot[n.charCodeAt(s+3)],p[r++]=i<<2|o>>4,p[r++]=(o&15)<<4|h>>2,p[r++]=(h&3)<<6|u&63;return f},ds=typeof ArrayBuffer=="function",pe=(n,t)=>{if(typeof n!="string")return{type:"message",data:Be(n,t)};const e=n.charAt(0);return e==="b"?{type:"message",data:fs(n.substring(1),t)}:Et[e]?n.length>1?{type:Et[e],data:n.substring(1)}:{type:Et[e]}:Gt},fs=(n,t)=>{if(ds){const e=us(n);return Be(e,t)}else return{base64:!0,data:n}},Be=(n,t)=>{switch(t){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Le="",ps=(n,t)=>{const e=n.length,s=new Array(e);let r=0;n.forEach((i,o)=>{fe(i,!1,h=>{s[o]=h,++r===e&&t(s.join(Le))})})},ys=(n,t)=>{const e=n.split(Le),s=[];for(let r=0;r<e.length;r++){const i=pe(e[r],t);if(s.push(i),i.type==="error")break}return s};function ms(){return new TransformStream({transform(n,t){ls(n,e=>{const s=e.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Dt;function wt(n){return n.reduce((t,e)=>t+e.length,0)}function bt(n,t){if(n[0].length===t)return n.shift();const e=new Uint8Array(t);let s=0;for(let r=0;r<t;r++)e[r]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),e}function gs(n,t){Dt||(Dt=new TextDecoder);const e=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,h){for(e.push(o);;){if(s===0){if(wt(e)<1)break;const u=bt(e,1);i=(u[0]&128)===128,r=u[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(wt(e)<2)break;const u=bt(e,2);r=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),s=3}else if(s===2){if(wt(e)<8)break;const u=bt(e,8),f=new DataView(u.buffer,u.byteOffset,u.length),p=f.getUint32(0);if(p>Math.pow(2,21)-1){h.enqueue(Gt);break}r=p*Math.pow(2,32)+f.getUint32(4),s=3}else{if(wt(e)<r)break;const u=bt(e,r);h.enqueue(pe(i?u:Dt.decode(u),t)),s=0}if(r===0||r>n){h.enqueue(Gt);break}}}})}const Fe=4;function E(n){if(n)return ws(n)}function ws(n){for(var t in E.prototype)n[t]=E.prototype[t];return n}E.prototype.on=E.prototype.addEventListener=function(n,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(t),this};E.prototype.once=function(n,t){function e(){this.off(n,e),t.apply(this,arguments)}return e.fn=t,this.on(n,e),this};E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(n,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+n];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,r=0;r<e.length;r++)if(s=e[r],s===t||s.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+n],this};E.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+n],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(e){e=e.slice(0);for(var s=0,r=e.length;s<r;++s)e[s].apply(this,t)}return this};E.prototype.emitReserved=E.prototype.emit;E.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};E.prototype.hasListeners=function(n){return!!this.listeners(n).length};const Pt=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),O=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),bs="arraybuffer";function qe(n,...t){return t.reduce((e,s)=>(n.hasOwnProperty(s)&&(e[s]=n[s]),e),{})}const _s=O.setTimeout,Es=O.clearTimeout;function Bt(n,t){t.useNativeTimers?(n.setTimeoutFn=_s.bind(O),n.clearTimeoutFn=Es.bind(O)):(n.setTimeoutFn=O.setTimeout.bind(O),n.clearTimeoutFn=O.clearTimeout.bind(O))}const Ts=1.33;function vs(n){return typeof n=="string"?Ss(n):Math.ceil((n.byteLength||n.size)*Ts)}function Ss(n){let t=0,e=0;for(let s=0,r=n.length;s<r;s++)t=n.charCodeAt(s),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(s++,e+=4);return e}function De(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ks(n){let t="";for(let e in n)n.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(n[e]));return t}function As(n){let t={},e=n.split("&");for(let s=0,r=e.length;s<r;s++){let i=e[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class Os extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class ye extends E{constructor(t){super(),this.writable=!1,Bt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new Os(t,e,s)),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=pe(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=ks(t);return e.length?"?"+e:""}}class Is extends ye{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 s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||e()})),this.writable||(s++,this.once("drain",function(){--s||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};ys(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,ps(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]=De()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Ue=!1;try{Ue=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const xs=Ue;function Cs(){}class $s extends Is{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let s=location.port;s||(s=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,s)=>{this.onError("xhr poll error",e,s)}),this.pollXhr=t}}class N extends E{constructor(t,e,s){super(),this.createRequest=t,Bt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const e=qe(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=N.requestsCount++,N.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=Cs,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete N.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()}}N.requestsCount=0;N.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ae);else if(typeof addEventListener=="function"){const n="onpagehide"in O?"pagehide":"unload";addEventListener(n,Ae,!1)}}function Ae(){for(let n in N.requests)N.requests.hasOwnProperty(n)&&N.requests[n].abort()}const Rs=function(){const n=Me({xdomain:!1});return n&&n.responseType!==null}();class Ns extends $s{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Rs&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new N(Me,this.uri(),t)}}function Me(n){const t=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||xs))return new XMLHttpRequest}catch{}if(!t)try{return new O[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const je=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ps extends ye{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=je?{}:qe(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=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 s=t[e],r=e===t.length-1;fe(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&Pt(()=>{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]=De()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Ut=O.WebSocket||O.MozWebSocket;class Bs extends Ps{createSocket(t,e,s){return je?new Ut(t,e,s):e?new Ut(t,e):new Ut(t)}doWrite(t,e){this.ws.send(e)}}class Ls extends ye{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=gs(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),r=ms();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:h,value:u})=>{h||(this.onPacket(u),i())}).catch(h=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;this._writer.write(s).then(()=>{r&&Pt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Fs={websocket:Bs,webtransport:Ls,polling:Ns},qs=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ds=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Vt(n){if(n.length>8e3)throw"URI too long";const t=n,e=n.indexOf("["),s=n.indexOf("]");e!=-1&&s!=-1&&(n=n.substring(0,e)+n.substring(e,s).replace(/:/g,";")+n.substring(s,n.length));let r=qs.exec(n||""),i={},o=14;for(;o--;)i[Ds[o]]=r[o]||"";return e!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Us(i,i.path),i.queryKey=Ms(i,i.query),i}function Us(n,t){const e=/\/{2,9}/g,s=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Ms(n,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(e[r]=i)}),e}const Jt=typeof addEventListener=="function"&&typeof removeEventListener=="function",Tt=[];Jt&&addEventListener("offline",()=>{Tt.forEach(n=>n())},!1);class J extends E{constructor(t,e){if(super(),this.binaryType=bs,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 s=Vt(t);e.hostname=s.host,e.secure=s.protocol==="https"||s.protocol==="wss",e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=Vt(e.host).host);Bt(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(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=As(this.opts.query)),Jt&&(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"})},Tt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Fe,e.transport=t,this.id&&(e.sid=this.id);const s=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](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&J.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",J.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 s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(e+=vs(r)),s>0&&e>this._maxPayload)return this.writeBuffer.slice(0,s);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Pt(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,r){if(typeof e=="function"&&(r=e,e=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{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?s():t()}):this.upgrading?s():t()),this}_onError(t){if(J.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(),Jt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Tt.indexOf(this._offlineEventListener);s!==-1&&Tt.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}J.protocol=Fe;class js extends J{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),s=!1;J.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",w=>{if(!s)if(w.type==="pong"&&w.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;J.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(p(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const $=new Error("probe error");$.transport=e.name,this.emitReserved("upgradeError",$)}}))};function i(){s||(s=!0,p(),e.close(),e=null)}const o=w=>{const $=new Error("probe error: "+w);$.transport=e.name,i(),this.emitReserved("upgradeError",$)};function h(){o("transport closed")}function u(){o("socket closed")}function f(w){e&&w.name!==e.name&&i()}const p=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",h),this.off("close",u),this.off("upgrading",f)};e.once("open",r),e.once("error",o),e.once("close",h),this.once("close",u),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let Hs=class extends js{constructor(t,e={}){const s=typeof t=="object",r=s?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>Fs[i]).filter(i=>!!i)),super(s?r:t,r)}};function Gs(n,t="",e){let s=n;e=e||typeof location<"u"&&location,n==null&&(n=e.protocol+"//"+e.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=e.protocol+n:n=e.host+n),/^(https?|wss?):\/\//.test(n)||(typeof e<"u"?n=e.protocol+"//"+n:n="https://"+n),s=Vt(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(e&&e.port===s.port?"":":"+s.port),s}const Vs=typeof ArrayBuffer=="function",Js=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,He=Object.prototype.toString,Ys=typeof Blob=="function"||typeof Blob<"u"&&He.call(Blob)==="[object BlobConstructor]",Ws=typeof File=="function"||typeof File<"u"&&He.call(File)==="[object FileConstructor]";function me(n){return Vs&&(n instanceof ArrayBuffer||Js(n))||Ys&&n instanceof Blob||Ws&&n instanceof File}function vt(n,t){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let e=0,s=n.length;e<s;e++)if(vt(n[e]))return!0;return!1}if(me(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return vt(n.toJSON(),!0);for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)&&vt(n[e]))return!0;return!1}function Xs(n){const t=[],e=n.data,s=n;return s.data=Yt(e,t),s.attachments=t.length,{packet:s,buffers:t}}function Yt(n,t){if(!n)return n;if(me(n)){const e={_placeholder:!0,num:t.length};return t.push(n),e}else if(Array.isArray(n)){const e=new Array(n.length);for(let s=0;s<n.length;s++)e[s]=Yt(n[s],t);return e}else if(typeof n=="object"&&!(n instanceof Date)){const e={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=Yt(n[s],t));return e}return n}function Ks(n,t){return n.data=Wt(n.data,t),delete n.attachments,n}function Wt(n,t){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<t.length)return t[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=Wt(n[e],t);else if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]=Wt(n[e],t));return n}const zs=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var g;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Qs{constructor(t){this.replacer=t}encode(t){return(t.type===g.EVENT||t.type===g.ACK)&&vt(t)?this.encodeAsBinary({type:t.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===g.BINARY_EVENT||t.type===g.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=Xs(t),s=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(s),r}}class ge extends E{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 s=e.type===g.BINARY_EVENT;s||e.type===g.BINARY_ACK?(e.type=s?g.EVENT:g.ACK,this.reconstructor=new Zs(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(me(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 s={type:Number(t.charAt(0))};if(g[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===g.BINARY_EVENT||s.type===g.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const h=Number(o);if(!tn(h)||h<0)throw new Error("Illegal attachments");if(h>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=h}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););s.nsp=t.substring(i,e)}else s.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(ge.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case g.CONNECT:return Oe(e);case g.DISCONNECT:return e===void 0;case g.CONNECT_ERROR:return typeof e=="string"||Oe(e);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&zs.indexOf(e[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Zs{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=Ks(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const tn=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Oe(n){return Object.prototype.toString.call(n)==="[object Object]"}const en=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ge,Encoder:Qs,get PacketType(){return g}},Symbol.toStringTag,{value:"Module"}));function C(n,t,e){return n.on(t,e),function(){n.off(t,e)}}const sn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ge extends E{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[C(t,"open",this.onopen.bind(this)),C(t,"packet",this.onpacket.bind(this)),C(t,"error",this.onerror.bind(this)),C(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 s,r,i;if(sn.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:g.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const p=this.ids++,w=e.pop();this._registerAckCallback(p,w),o.id=p}const h=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!h||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===t&&this.sendBuffer.splice(h,1);e.call(this,new Error("operation has timed out"))},r),o=(...h)=>{this.io.clearTimeoutFn(i),e.apply(this,h)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((s,r)=>{const i=(o,h)=>o?r(o):s(h);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),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:g.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(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case g.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 g.EVENT:case g.BINARY_EVENT:this.onevent(t);break;case g.ACK:case g.BINARY_ACK:this.onack(t);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);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 s of e)s.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 s=!1;return function(...r){s||(s=!0,e.packet({type:g.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.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 s=0;s<e.length;s++)if(t===e[s])return e.splice(s,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 s=0;s<e.length;s++)if(t===e[s])return e.splice(s,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 s of e)s.apply(this,t.data)}}}function rt(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}rt.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*n);n=Math.floor(t*10)&1?n+e:n-e}return Math.min(n,this.max)|0};rt.prototype.reset=function(){this.attempts=0};rt.prototype.setMin=function(n){this.ms=n};rt.prototype.setMax=function(n){this.max=n};rt.prototype.setJitter=function(n){this.jitter=n};class Xt extends E{constructor(t,e){var s;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,Bt(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((s=e.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new rt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||en;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Hs(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=C(e,"open",function(){s.onopen(),t&&t()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),t?t(h):this.maybeReconnectOnOpen()},o=C(e,"error",i);if(this._timeout!==!1){const h=this._timeout,u=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},h);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(C(t,"ping",this.onping.bind(this)),C(t,"data",this.ondata.bind(this)),C(t,"error",this.onerror.bind(this)),C(t,"close",this.onclose.bind(this)),C(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){Pt(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new Ge(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const s of e)if(this.nsps[s].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],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 s;this.cleanup(),(s=this.engine)===null||s===void 0||s.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 s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const it={};function ut(n,t){typeof n=="object"&&(t=n,n=void 0),t=t||{};const e=Gs(n,t.path||"/socket.io"),s=e.source,r=e.id,i=e.path,o=it[r]&&i in it[r].nsps,h=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let u;return h?u=new Xt(s,t):(it[r]||(it[r]=new Xt(s,t)),u=it[r]),e.query&&!t.query&&(t.query=e.queryKey),u.socket(e.path,t)}Object.assign(ut,{Manager:Xt,Socket:Ge,io:ut,connect:ut});class Kt 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 Ie="bimterop",zt="revitflow_history.json",z="revitflow_ops.json",xe="revitflow/ops@1",Ve="revitflow_model.frag",Je="revitflow_",_t=()=>`v-${Date.now()}`;function Ye(n,t){return n.filter(e=>String(e.parentId??"")===t)}function M(n){return String(n._id??n.id??"")}var x,dt,Qt;class We{constructor(t,e){b(this,dt);b(this,x);this.client=t,this.projectId=e}async docs(){const t=await a(this,dt,Qt).call(this);if(!t)return[];const e=await this.client.listFolders({parentFolderId:t,projectId:this.projectId}),s=[];for(const r of Ye(e,t)){const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const u=(await this.client.listFiles({folderId:M(r)})).map(w=>String(w.name??"")),f=u.find(w=>w===Ve)??u.find(w=>w.endsWith(".frag")&&!w.startsWith(Je)),p=u.includes(zt)||u.includes(z)||!!f;s.push({source:i.slice(0,o),docId:i.slice(o+1),modelName:f,...p?{}:{empty:!0}})}return s}doc(t,e){return new Xe(this.client,this,t,e)}async rootFolderId(t=!1){if(l(this,x))return l(this,x);const e=await a(this,dt,Qt).call(this);if(e)return e;if(!t)return;const s=await this.client.createFolder(Ie,void 0,this.projectId);return _(this,x,M(s)),l(this,x)}}x=new WeakMap,dt=new WeakSet,Qt=async function(){if(l(this,x))return l(this,x);const e=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===Ie&&!s.parentId);return e&&_(this,x,M(e)),l(this,x)};var L,y,at,ct,Zt,St,kt,te,At,ht,Ot,ee,Ke;class Xe{constructor(t,e,s,r){b(this,y);b(this,L);this.client=t,this.project=e,this.source=s,this.docId=r}async timeline(){const t=await a(this,y,At).call(this);return we((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 a(this,y,kt).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async sync(t){var h;const e=await a(this,y,ct).call(this,!0);let s=await a(this,y,At).call(this)??{model:this.docId,commits:[]};const r=Ce(s.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Kt(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Rt(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...(h=t.appliedOps)!=null&&h.length?{appliedOps:t.appliedOps}:{},changes:t.changes,counts:nn(t.changes)};if(t.model&&(await a(this,y,Ke).call(this,e,t.model),i.full=!0),t.delta){const u=await a(this,y,kt).call(this);if(!u)throw new Error("A delta needs the model file to hang from: sync a full model first.");const f=await this.client.createHiddenFile(t.delta,u.id);i.deltaId=String(f._id??f.id)}const o=await a(this,y,At).call(this);if(o){s=o;const u=Ce(s.commits);if(t.expectedLatestGuid!==void 0&&(u==null?void 0:u.guid)!==t.expectedLatestGuid)throw new Kt(t.expectedLatestGuid,u==null?void 0:u.guid);u&&!i.parents&&(i.parents=[u.guid])}return s.commits.push(i),await a(this,y,Ot).call(this,e,zt,s),i}async suggestions(){const t=await a(this,y,ht).call(this);return(t==null?void 0:t.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(t=>t.state==="pending")}async suggest(t){const e=await a(this,y,ct).call(this,!0),s=await a(this,y,ht).call(this)??{schema:xe,ops:[]},r=await a(this,y,St).call(this,z),i={opId:t.opId??Rt(),title:t.title,verb:t.verb,author:t.author,createdAt:new Date().toISOString(),state:"pending",...t.targets!==void 0?{targets:t.targets}:{},...t.batchId?{batchId:t.batchId}:{},...t.userId?{userId:t.userId}:{},...t.baseCommitGuid?{baseCommitGuid:t.baseCommitGuid}:{}};if(t.payload){const h=r??await a(this,y,ee).call(this,e,z,s),u=await this.client.createHiddenFile(t.payload,h.id);i.fragId=String(u._id??u.id)}const o=await a(this,y,ht).call(this)??s;return o.schema??(o.schema=xe),o.ops.push(i),await a(this,y,Ot).call(this,e,z,o),i}async suggestionPayload(t){if(!t.fragId)throw new Error(`Suggestion ${t.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(t.fragId)).blob()}async resolveSuggestion(t,e){const s=await a(this,y,ct).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await a(this,y,ht).call(this),i=r==null?void 0:r.ops.find(o=>o.opId===t);if(!r||!i)throw new Error(`No suggestion ${t} in this document's queue.`);return Object.assign(i,e),await a(this,y,Ot).call(this,s,z,r),i}}L=new WeakMap,y=new WeakSet,at=function(){return`${this.source}-${this.docId}`},ct=async function(t){if(l(this,L))return l(this,L);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=await this.client.listFolders({parentFolderId:e,projectId:this.project.projectId}),r=Ye(s,e).find(o=>String(o.name??"")===l(this,y,at));if(r)return _(this,L,M(r)),l(this,L);if(!t)throw new Error(`Document ${l(this,y,at)} does not exist in this project.`);const i=await this.client.createFolder(l(this,y,at),e,this.project.projectId);return _(this,L,M(i)),l(this,L)},Zt=async function(){const t=await a(this,y,ct).call(this,!1);return(await this.client.listFiles({folderId:t})).map(s=>({id:M(s),name:String(s.name??"")}))},St=async function(t){try{return(await a(this,y,Zt).call(this)).find(e=>e.name===t)}catch{return}},kt=async function(){try{const t=await a(this,y,Zt).call(this);return t.find(e=>e.name===Ve)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Je))}catch{return}},te=async function(t){const e=await a(this,y,St).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},At=function(){return a(this,y,te).call(this,zt)},ht=function(){return a(this,y,te).call(this,z)},Ot=async function(t,e,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,y,St).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:_t()}),i):await a(this,y,ee).call(this,t,e,s)},ee=async function(t,e,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:_t(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:M(o??i),name:e}},Ke=async function(t,e){const s=await a(this,y,kt).call(this);if(s)return await this.client.updateFile(s.id,{file:e,versionTag:_t()}),s;const r=`${l(this,y,at)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:_t(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:M(o??i),name:r}};function nn(n){const t={added:0,modified:0,removed:0};for(const e of n)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function we(n){var u;if(n.length<=1)return n.forEach((f,p)=>f.ordinal=p),[...n];const t=new Map(n.map(f=>[f.guid,f])),e=new Map,s=[];for(const f of n){const p=(u=f.parents)==null?void 0:u[0];if(p&&t.has(p)){const w=e.get(p)??[];w.push(f),e.set(p,w)}else s.push(f)}const r=(f,p)=>String(f.timestamp).localeCompare(String(p.timestamp));s.sort(r);const i=[],o=[...s].reverse(),h=new Set;for(;o.length;){const f=o.pop();if(h.has(f.guid))continue;h.add(f.guid),i.push(f);const p=(e.get(f.guid)??[]).sort(r);for(let w=p.length-1;w>=0;w--)o.push(p[w])}for(const f of n)h.has(f.guid)||i.push(f);return i.forEach((f,p)=>f.ordinal=p),i}function Ce(n){const t=we(n);return t[t.length-1]}function Rt(){const n=globalThis.crypto;return n!=null&&n.randomUUID?n.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)})}var j,ft,se;class ze{constructor(t){b(this,ft);b(this,j,new Map);this.client=t}register(t){if(l(this,j).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);l(this,j).set(t.name,t)}list(t){return[...l(this,j).values()].filter(s=>(!(t!=null&&t.to)||s.to===t.to)&&(!(t!=null&&t.input)||s.inputs.includes(t.input)))}get(t){return l(this,j).get(t)}async plan(t,e){const{base:s,opId:r,result:i}=await a(this,ft,se).call(this,t,e);return{opId:r,projectId:e.projectId,target:e.target,...s!=null&&s.guid?{baseCommitGuid:s.guid}:{},result:i}}async queue(t,e){return{suggestion:await this.client.history(t.projectId).doc(t.target.source,t.target.docId).suggest({opId:t.opId,title:t.result.title,verb:t.result.verb,author:e.author,payload:t.result.payload,targets:t.result.targets,userId:e.userId,baseCommitGuid:t.baseCommitGuid}),result:t.result}}async run(t,e){const{targetDoc:s,base:r,opId:i,result:o}=await a(this,ft,se).call(this,t,e);return{suggestion:await s.suggest({opId:i,title:o.title,verb:o.verb,author:e.author,payload:o.payload,targets:o.targets,userId:e.userId,baseCommitGuid:r==null?void 0:r.guid}),result:o}}}j=new WeakMap,ft=new WeakSet,se=async function(t,e){const s=l(this,j).get(t);if(!s)throw new Error(`No recipe named "${t}" is registered.`);if(s.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${s.to}, but the target document belongs to ${e.target.source}.`);const r=this.client.history(e.projectId).doc(e.target.source,e.target.docId),i=await r.latest(),o=Rt(),h=await s.run({client:this.client,projectId:e.projectId,targetDoc:r,opId:o,input:e.input,settings:e.settings??{}});return{recipe:s,targetDoc:r,base:i,opId:o,result:h}};const ne=100;function rn(n){try{const t=JSON.parse(n);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 on(n){if(!n||typeof n!="object")return;const t=n.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Lt extends Error{constructor(e,s,r,i){const o=rn(r);super(o.message??`${s||"Request failed"} (${e})`);v(this,"status");v(this,"code");v(this,"details");v(this,"body");v(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??on(o.details)}}const R="item/folder",m="item",D="processor",an="npm-registry",B="hidden",Mt="FILE",jt="TOOL",Ht="APP",cn=500,$e=3e4,hn=.25,ln=n=>new Promise(t=>setTimeout(t,n));function un(n){var r,i;const t=(i=(r=n.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function dn(n){return n instanceof Lt?n.status===429||n.status>=500:!0}function fn(n,t){const e=Math.min(cn*2**t,$e),s=e*hn*Math.random(),r=n instanceof Lt&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,$e)+s:e+s}var c,re,d,U,pt,lt,It,xt,ie,oe,Qe;const _e=class _e{constructor(t,e,s){b(this,c);v(this,"apiUrl");v(this,"accessToken");v(this,"wsUrl");v(this,"retries");v(this,"useBearer");v(this,"builtInGlobals",null);v(this,"localServerUrl",null);v(this,"context");b(this,pt);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=s||{};let h=e;if(h.charAt(h.length-1)==="/"&&(h=h.slice(0,-1)),this.apiUrl=`${h}/api`,this.accessToken=t,this.wsUrl=h,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let u=o;u.charAt(u.length-1)==="/"&&(u=u.slice(0,-1)),this.localServerUrl=u}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new _e(e.accessToken,e.apiUrl,{...t,useBearer:!0});return s.context=e,s}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,s){return a(this,c,d).call(this,t,e,s)}async listFiles(t){const{folderId:e,archived:s,projectId:r}=t||{};return e?await a(this,c,d).call(this,"GET",`${R}/${e}/items`,{query:{itemType:Mt,archived:s}}):await a(this,c,d).call(this,"GET",`${m}`,{query:{itemType:Mt,archived:s,...r&&{projectId:r}}})}async getFile(t,e){return await a(this,c,oe).call(this,t,e)}async createFile(t){return await a(this,c,xt).call(this,t,Mt)}async updateFile(t,e){return await a(this,c,ie).call(this,t,e)}async archiveFile(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}`)}async recoverFile(t){return await a(this,c,d).call(this,"PUT",`${m}/${t}/recover`)}async downloadFile(t,e){return await a(this,c,It).call(this,t,e)}async getFileVersionMetadata(t,e,s){const{withDraft:r}=s||{};return await a(this,c,d).call(this,"GET",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,s){return await a(this,c,d).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await a(this,c,d).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:s}=e||{};return await a(this,c,lt).call(this,t,async r=>(await a(this,c,d).call(this,"POST",`${m}/batch/version-metadata`,{body:JSON.stringify({entries:r,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:s,projectId:r}=t||{};return await a(this,c,d).call(this,"GET",R,{query:{parentFolderId:s,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await a(this,c,d).call(this,"GET",`${R}/${t}`)}async getFoldersBatch(t){return await a(this,c,lt).call(this,t,async e=>(await a(this,c,d).call(this,"POST",`${m}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,s){return await a(this,c,d).call(this,"POST",R,{body:JSON.stringify({name:t,...e&&{parentId:e},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(t,e){const{name:s}=e;return await a(this,c,d).call(this,"PUT",`${R}/${t}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(t){return await a(this,c,d).call(this,"DELETE",`${R}/${t}`)}async recoverFolder(t){return await a(this,c,d).call(this,"PUT",`${R}/${t}/recover`)}async downloadFolder(t){return await a(this,c,U).call(this,`${R}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:s,projectId:r}=t||{};return e?await a(this,c,d).call(this,"GET",`${R}/${e}/items`,{query:{itemType:jt,...s&&{ShowVersions:s}}}):await a(this,c,d).call(this,"GET",`${m}`,{query:{itemType:jt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(t,e){return await a(this,c,oe).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await a(this,c,xt).call(this,t,jt,e)}async updateComponent(t,e){const{componentProps:s}=e;return await a(this,c,ie).call(this,t,e,s)}async downloadComponent(t,e){return await a(this,c,It).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,c,U).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}`)}async recoverComponent(t){return await a(this,c,d).call(this,"PUT",`${m}/${t}/recover`)}async getBuiltInComponent(t){return await(await a(this,c,U).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,s){const r=await this.getBuiltInComponent(t.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),h=o.map(w=>i[w]),f=new Function(...o,`${r}
2
- return main;`)(...h),p=(f==null?void 0:f.componentDefinition)??f;e.get(p)}async initBuiltInComponents(t,...e){await Promise.all(e.map(s=>this.initBuiltInComponent(s,t)))}async setup(t,...e){var o,h;const s=t.OBC,r=t.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(h=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||h.call(o),{components:i}}throwError(t,e){var s,r;(r=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||r.call(s,t,e)}async listApps(t){const{folderId:e,ShowVersions:s,projectId:r}=t||{};return e?await a(this,c,d).call(this,"GET",`${R}/${e}/items`,{query:{itemType:Ht,...s&&{ShowVersions:s}}}):await a(this,c,d).call(this,"GET",`${m}`,{query:{itemType:Ht,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await a(this,c,xt).call(this,t,Ht,e)}async downloadApp(t,e){return await a(this,c,It).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,c,U).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}`)}async getNpmCredentials(){return await a(this,c,d).call(this,"GET",`${an}/credentials`)}async executeComponent(t,e,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${D}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,c,d).call(this,"POST",`${D}/${t}/execute`,{body:JSON.stringify(e),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${D}/progress/${t}/abort`,s=await fetch(e,{method:"POST"});if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,c,d).call(this,"POST",`${D}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const s=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${D}/${t}/progress${s}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,c,d).call(this,"GET",`${D}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${D}/progress/${t}`,s=await fetch(e);if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,c,d).call(this,"GET",`${D}/progress/${t}`)}async onExecutionProgress(t,e){const s=this.localServerUrl??this.wsUrl,r=await ut(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}history(t){return new We(this,t)}get recipes(){return l(this,pt)??_(this,pt,new ze(this)),l(this,pt)}async createHiddenFile(t,e,s){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),s!=null&&r.append("tag",s),await a(this,c,d).call(this,"POST",`${m}/${B}`,{body:r})}async createHiddenFilesBatch(t,e,s){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),s!=null&&r.append("tag",s),await a(this,c,d).call(this,"POST",`${m}/${B}/batch`,{body:r})}async deleteHiddenFile(t){return await a(this,c,d).call(this,"DELETE",`${m}/${B}/${t}`)}async getHiddenFile(t){return await a(this,c,d).call(this,"GET",`${m}/${B}/${t}`)}async downloadHiddenFile(t){return await a(this,c,U).call(this,`${m}/${B}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await a(this,c,d).call(this,"GET",`${m}/${B}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await a(this,c,lt).call(this,t,async s=>(await a(this,c,d).call(this,"POST",`${m}/${B}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await a(this,c,d).call(this,"GET",`${m}/${t}/${B}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}/${B}`)}async uploadItemIcon(t,e){const s=new FormData;return s.append("icon",e),await a(this,c,d).call(this,"PUT",`${m}/${t}/icon`,{body:s})}async getItemIcon(t){return await a(this,c,U).call(this,`${m}/${t}/icon`)}async removeItemIcon(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}/icon`)}async updateItem(t,e){return await a(this,c,d).call(this,"PUT",`${m}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,s,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",s),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await a(this,c,d).call(this,"POST",`${m}/${t}/version`,{body:o})}async listVersions(t,e={}){return await a(this,c,d).call(this,"GET",`${m}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:s}=e;return await a(this,c,lt).call(this,t,async r=>(await a(this,c,d).call(this,"POST",`${m}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await a(this,c,d).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await a(this,c,d).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await a(this,c,d).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};c=new WeakSet,re=function(t){return`${this.apiUrl}/${t}`},d=async function(t,e,s){const{body:r,query:i,contentType:o,retries:h,responseType:u,retryAttempt:f}=s||{},p=a(this,c,re).call(this,e),w=a(this,c,Qe).call(this,i),$=await this.resolveAccessToken(),as={...w,...this.useBearer?{}:{accessToken:$}};try{const I=await fetch(p+"?"+new URLSearchParams(as).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${$}`}},...r&&{body:r}});if(!I.ok){const X=await I.text().then(gt=>gt).catch(()=>"");throw new Lt(I.status,I.statusText,X,un(I))}return u==="blob"?await I.blob():I.json().then(X=>X).catch(()=>{})}catch(I){const X=h??this.retries;if(X>0&&dn(I)){const gt=f??0;return await ln(fn(I,gt)),await a(this,c,d).call(this,t,e,{...s,retries:X-1,retryAttempt:gt+1})}throw I}},U=async function(t,e){const{query:s}=e||{},r=a(this,c,re).call(this,t),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},pt=new WeakMap,lt=async function(t,e){if(!t.length)return[];const s=[];for(let i=0;i<t.length;i+=ne)s.push(t.slice(i,i+ne));return(await Promise.all(s.map(e))).flat()},It=async function(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,c,U).call(this,`${m}/${t}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},xt=async function(t,e,s){const{name:r,versionTag:i,parentFolderId:o,projectId:h,file:u,metadata:f}=t,p=new FormData;return p.append("file",u),p.append("name",r),p.append("versionTag",i),p.append("itemType",e),o&&p.append("folderId",o),h&&p.append("projectId",h),s&&p.append("extraProps",JSON.stringify(s)),f&&p.append("metadata",JSON.stringify(f)),await a(this,c,d).call(this,"POST",m,{body:p})},ie=async function(t,e,s){const{name:r,versionTag:i,parentFolderId:o,file:h,metadata:u}=e;let f,p;if(h){const w=new FormData;w.append("file",h),i&&w.append("versionTag",i),s&&w.append("extraProps",JSON.stringify(s)),u&&w.append("metadata",JSON.stringify(u)),p=await a(this,c,d).call(this,"POST",`${m}/${t}/version`,{body:w})}if(r||o){const w={...r&&{name:r},...o&&{folderId:o}},$=JSON.stringify(w);f=await a(this,c,d).call(this,"PUT",`${m}/${t}`,{body:$,contentType:"application/json"})}return{item:f,version:p}},oe=async function(t,e){const{showVersions:s=!1}=e||{};return await a(this,c,d).call(this,"GET",`${m}/${t}`,{query:{showVersions:s}})},Qe=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[s,r])=>(e[s]=r,e),{})};let Nt=_e;function Ze(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const t=e=>{e.source===window.parent&&n(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const ae="channel:",pn=1e4;function Ct(n){try{n()}catch(t){console.error("[channel] a listener threw:",t)}}var F,k,A,Z,tt,et,S,ce,he,Q;class be{constructor(t,e){b(this,S);b(this,F,!1);b(this,k,[]);b(this,A,[]);b(this,Z,new Set);b(this,tt,new Set);b(this,et,new Set);this.transport=t,this.controls=e}get joined(){return l(this,F)}get peers(){return l(this,k)}join(){return l(this,F)?Promise.resolve():a(this,S,ce).call(this,"joined",this.controls.join)}leave(){return!l(this,F)&&!l(this,A).some(t=>t.want==="joined")?Promise.resolve():a(this,S,ce).call(this,"left",this.controls.leave)}onChange(t){return l(this,Z).add(t),()=>void l(this,Z).delete(t)}onPeerJoined(t){return l(this,tt).add(t),()=>void l(this,tt).delete(t)}onPeerLeft(t){return l(this,et).add(t),()=>void l(this,et).delete(t)}applyJoined(){_(this,F,!0),a(this,S,he).call(this,"joined"),a(this,S,Q).call(this)}applyLeft(){_(this,F,!1),_(this,k,[]),a(this,S,he).call(this,"left"),a(this,S,Q).call(this)}applyPeers(t){_(this,k,t),a(this,S,Q).call(this)}applyPeerJoined(t){!l(this,F)||l(this,k).some(e=>e.from===t.from)||(_(this,k,[...l(this,k),t]),l(this,tt).forEach(e=>Ct(()=>e(t))),a(this,S,Q).call(this))}applyPeerLeft(t){const e=l(this,k).find(s=>s.from===t);e&&(_(this,k,l(this,k).filter(s=>s.from!==t)),l(this,et).forEach(s=>Ct(()=>s(e))),a(this,S,Q).call(this))}failPending(t){const e=l(this,A);return _(this,A,[]),e.forEach(s=>{clearTimeout(s.timer),s.reject(t)}),e.length>0}post(t){this.transport.post(t)}}F=new WeakMap,k=new WeakMap,A=new WeakMap,Z=new WeakMap,tt=new WeakMap,et=new WeakMap,S=new WeakSet,ce=function(t,e){return new Promise((s,r)=>{const i={want:t,resolve:s,reject:r,timer:setTimeout(()=>{_(this,A,l(this,A).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},pn)};l(this,A).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},he=function(t){const e=l(this,A).filter(s=>s.want===t);_(this,A,l(this,A).filter(s=>s.want!==t)),e.forEach(s=>{clearTimeout(s.timer),s.resolve()})},Q=function(){l(this,Z).forEach(t=>Ct(t))};var st;class ts extends be{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});b(this,st,new Map)}on(e,s){const r=l(this,st).get(e)??new Set;return r.add(s),l(this,st).set(e,r),()=>void r.delete(s)}send(e,s){if(e.startsWith(ae))throw new Error(`Message types starting with '${ae}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:s}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const s=l(this,st).get(e.type);if(!(s!=null&&s.size))return{handled:!1};const r=ss(e);return s.forEach(i=>Ct(()=>i(e.payload,r))),{handled:!0}}}st=new WeakMap;var H;class es extends be{constructor(e,s){super(e,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});b(this,H,new Map);this.kind=s}on(e,s){if(l(this,H).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return l(this,H).set(e,s),()=>void l(this,H).delete(e)}accepts(e,s){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===s}get hasHandlers(){return l(this,H).size>0}async handle(e){const s=l(this,H).get(e.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(e.payload,ss(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}H=new WeakMap;function ss(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function yn(n){const t=n;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 W,yt,q,G,V,T,le,$t,rs,is,os,ue;class ns{constructor(t){b(this,T);b(this,W);b(this,yt);b(this,q);b(this,G,new Map);b(this,V,new Set);_(this,W,t),_(this,yt,t.listen(e=>void a(this,T,rs).call(this,e)))}collab(){return l(this,q)??_(this,q,new ts(l(this,W))),l(this,q)}external(t){const e=t??"";let s=l(this,G).get(e);return s||(s=new es(l(this,W),t),l(this,G).set(e,s)),s}dispose(){l(this,yt).call(this)}}W=new WeakMap,yt=new WeakMap,q=new WeakMap,G=new WeakMap,V=new WeakMap,T=new WeakSet,le=function(){return[...l(this,q)?[l(this,q)]:[],...l(this,G).values()]},$t=function(t,e){if(t==="collab")return l(this,q);if(t==="external")return l(this,G).get(typeof e=="string"?e:"")},rs=async function(t){const e=yn(t);if(e){if(e.type.startsWith(ae)){a(this,T,is).call(this,e);return}await a(this,T,os).call(this,e)}},is=function(t){var s,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(s=a(this,T,$t).call(this,e.scope,e.kind))==null||s.applyJoined();break;case"channel:left":(r=a(this,T,$t).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=a(this,T,$t).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[l(this,q)]:[...l(this,G).values()].filter(h=>h.accepts("external",e.kind));for(const h of o)t.type==="channel:peer-joined"?h==null||h.applyPeerJoined({from:e.from,kind:e.kind}):h==null||h.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));a(this,T,le).call(this).map(u=>u.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},os=async function(t){const e=a(this,T,le).call(this).filter(i=>i.accepts(t.scope,t.kind));let s=!1;for(const i of e){const o=await i.handle(t);o.handled&&(s=!0,t.requestId&&a(this,T,ue).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!s&&a(this,T,ue).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},ue=function(t,e){l(this,V).has(t)||(l(this,V).add(t),l(this,V).size>500&&l(this,V).delete(l(this,V).values().next().value),l(this,W).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 Y="project",K="notifications";var nt,mt;const Ee=class Ee extends Nt{constructor(e,s,r){super(typeof e=="string"?e:"",s,{...r,useBearer:!0});b(this,nt);b(this,mt);typeof e=="function"&&_(this,nt,e)}async resolveAccessToken(){return l(this,nt)?await l(this,nt).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Ee(s.accessToken,s.apiUrl,e);return r.context=s,r}get channel(){return l(this,mt)??_(this,mt,new ns(Ze())),l(this,mt)}async listProjects(){return await this.request("GET",Y)}async getProject(e){return await this.request("GET",`${Y}/${e}`)}async getProjectData(e){return await this.request("GET",`${Y}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${Y}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${Y}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",K,{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",`${K}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${K}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${K}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${K}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${K}/subscriptions/${e}`)}async subscribeToAutomation(e,s,r){return await this.request("POST",`${Y}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,s,r){return await this.request("PATCH",`${Y}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const s=await this.resolveAccessToken(),r=ut(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};nt=new WeakMap,mt=new WeakMap;let de=Ee;const mn={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},gn={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},wn={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},bn={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},_n={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},En={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Tn={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},vn={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Sn={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},kn={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=gn;exports.ChannelClient=ns;exports.ChannelRoom=be;exports.ClashesManager=wn;exports.CollabRoom=ts;exports.EngineServicesClient=Nt;exports.ExternalRoom=es;exports.FileList=bn;exports.FlowDoc=Xe;exports.GISManager=_n;exports.GitHistoryManager=En;exports.HelloWorld=Tn;exports.METADATA_LIMITS=mn;exports.PlatformClient=de;exports.ProjectHistory=We;exports.ProjectManager=vn;exports.Recipes=ze;exports.RequestError=Lt;exports.STORAGE_BATCH_MAX=ne;exports.StaleHistoryError=Kt;exports.TopicsManager=Sn;exports.UIManager=kn;exports.mintGuid=Rt;exports.orderByGraph=we;exports.windowTransport=Ze;
1
+ "use strict";var ys=Object.defineProperty;var Ie=n=>{throw TypeError(n)};var ms=(n,t,e)=>t in n?ys(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var T=(n,t,e)=>ms(n,typeof t!="symbol"?t+"":t,e),Ut=(n,t,e)=>t.has(n)||Ie("Cannot "+e);var l=(n,t,e)=>(Ut(n,t,"read from private field"),e?e.call(n):t.get(n)),b=(n,t,e)=>t.has(n)?Ie("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),_=(n,t,e,s)=>(Ut(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),a=(n,t,e)=>(Ut(n,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=Object.create(null);B.open="0";B.close="1";B.ping="2";B.pong="3";B.message="4";B.upgrade="5";B.noop="6";const kt=Object.create(null);Object.keys(B).forEach(n=>{kt[B[n]]=n});const Yt={type:"error",data:"parser error"},De=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ue=typeof ArrayBuffer=="function",je=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,we=({type:n,data:t},e,s)=>De&&t instanceof Blob?e?s(t):Ce(t,s):Ue&&(t instanceof ArrayBuffer||je(t))?e?s(t):Ce(new Blob([t]),s):s(B[n]+(t||"")),Ce=(n,t)=>{const e=new FileReader;return e.onload=function(){const s=e.result.split(",")[1];t("b"+(s||""))},e.readAsDataURL(n)};function xe(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let jt;function gs(n,t){if(De&&n.data instanceof Blob)return n.data.arrayBuffer().then(xe).then(t);if(Ue&&(n.data instanceof ArrayBuffer||je(n.data)))return t(xe(n.data));we(n,!1,e=>{jt||(jt=new TextEncoder),t(jt.encode(e))})}const $e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lt=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<$e.length;n++)lt[$e.charCodeAt(n)]=n;const ws=n=>{let t=n.length*.75,e=n.length,s,r=0,i,o,c,u;n[n.length-1]==="="&&(t--,n[n.length-2]==="="&&t--);const f=new ArrayBuffer(t),y=new Uint8Array(f);for(s=0;s<e;s+=4)i=lt[n.charCodeAt(s)],o=lt[n.charCodeAt(s+1)],c=lt[n.charCodeAt(s+2)],u=lt[n.charCodeAt(s+3)],y[r++]=i<<2|o>>4,y[r++]=(o&15)<<4|c>>2,y[r++]=(c&3)<<6|u&63;return f},bs=typeof ArrayBuffer=="function",be=(n,t)=>{if(typeof n!="string")return{type:"message",data:Me(n,t)};const e=n.charAt(0);return e==="b"?{type:"message",data:_s(n.substring(1),t)}:kt[e]?n.length>1?{type:kt[e],data:n.substring(1)}:{type:kt[e]}:Yt},_s=(n,t)=>{if(bs){const e=ws(n);return Me(e,t)}else return{base64:!0,data:n}},Me=(n,t)=>{switch(t){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},He="",Es=(n,t)=>{const e=n.length,s=new Array(e);let r=0;n.forEach((i,o)=>{we(i,!1,c=>{s[o]=c,++r===e&&t(s.join(He))})})},vs=(n,t)=>{const e=n.split(He),s=[];for(let r=0;r<e.length;r++){const i=be(e[r],t);if(s.push(i),i.type==="error")break}return s};function Ts(){return new TransformStream({transform(n,t){gs(n,e=>{const s=e.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Mt;function vt(n){return n.reduce((t,e)=>t+e.length,0)}function Tt(n,t){if(n[0].length===t)return n.shift();const e=new Uint8Array(t);let s=0;for(let r=0;r<t;r++)e[r]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),e}function Ss(n,t){Mt||(Mt=new TextDecoder);const e=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,c){for(e.push(o);;){if(s===0){if(vt(e)<1)break;const u=Tt(e,1);i=(u[0]&128)===128,r=u[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(vt(e)<2)break;const u=Tt(e,2);r=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),s=3}else if(s===2){if(vt(e)<8)break;const u=Tt(e,8),f=new DataView(u.buffer,u.byteOffset,u.length),y=f.getUint32(0);if(y>Math.pow(2,21)-1){c.enqueue(Yt);break}r=y*Math.pow(2,32)+f.getUint32(4),s=3}else{if(vt(e)<r)break;const u=Tt(e,r);c.enqueue(be(i?u:Mt.decode(u),t)),s=0}if(r===0||r>n){c.enqueue(Yt);break}}}})}const Ge=4;function E(n){if(n)return ks(n)}function ks(n){for(var t in E.prototype)n[t]=E.prototype[t];return n}E.prototype.on=E.prototype.addEventListener=function(n,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(t),this};E.prototype.once=function(n,t){function e(){this.off(n,e),t.apply(this,arguments)}return e.fn=t,this.on(n,e),this};E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(n,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+n];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,r=0;r<e.length;r++)if(s=e[r],s===t||s.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+n],this};E.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+n],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(e){e=e.slice(0);for(var s=0,r=e.length;s<r;++s)e[s].apply(this,t)}return this};E.prototype.emitReserved=E.prototype.emit;E.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};E.prototype.hasListeners=function(n){return!!this.listeners(n).length};const Ft=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),A=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Os="arraybuffer";function Ve(n,...t){return t.reduce((e,s)=>(n.hasOwnProperty(s)&&(e[s]=n[s]),e),{})}const As=A.setTimeout,Is=A.clearTimeout;function qt(n,t){t.useNativeTimers?(n.setTimeoutFn=As.bind(A),n.clearTimeoutFn=Is.bind(A)):(n.setTimeoutFn=A.setTimeout.bind(A),n.clearTimeoutFn=A.clearTimeout.bind(A))}const Cs=1.33;function xs(n){return typeof n=="string"?$s(n):Math.ceil((n.byteLength||n.size)*Cs)}function $s(n){let t=0,e=0;for(let s=0,r=n.length;s<r;s++)t=n.charCodeAt(s),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(s++,e+=4);return e}function Je(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Rs(n){let t="";for(let e in n)n.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(n[e]));return t}function Ns(n){let t={},e=n.split("&");for(let s=0,r=e.length;s<r;s++){let i=e[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class Ps extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class _e extends E{constructor(t){super(),this.writable=!1,qt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new Ps(t,e,s)),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=be(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=Rs(t);return e.length?"?"+e:""}}class Bs extends _e{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 s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||e()})),this.writable||(s++,this.once("drain",function(){--s||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};vs(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,Es(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]=Je()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Ye=!1;try{Ye=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Ls=Ye;function Fs(){}class qs extends Bs{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let s=location.port;s||(s=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,s)=>{this.onError("xhr poll error",e,s)}),this.pollXhr=t}}class P extends E{constructor(t,e,s){super(),this.createRequest=t,qt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const e=Ve(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=P.requestsCount++,P.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=Fs,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete P.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()}}P.requestsCount=0;P.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Re);else if(typeof addEventListener=="function"){const n="onpagehide"in A?"pagehide":"unload";addEventListener(n,Re,!1)}}function Re(){for(let n in P.requests)P.requests.hasOwnProperty(n)&&P.requests[n].abort()}const Ds=function(){const n=We({xdomain:!1});return n&&n.responseType!==null}();class Us extends qs{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Ds&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new P(We,this.uri(),t)}}function We(n){const t=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Ls))return new XMLHttpRequest}catch{}if(!t)try{return new A[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ke=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class js extends _e{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=Ke?{}:Ve(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=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 s=t[e],r=e===t.length-1;we(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&Ft(()=>{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]=Je()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Ht=A.WebSocket||A.MozWebSocket;class Ms extends js{createSocket(t,e,s){return Ke?new Ht(t,e,s):e?new Ht(t,e):new Ht(t)}doWrite(t,e){this.ws.send(e)}}class Hs extends _e{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=Ss(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),r=Ts();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:c,value:u})=>{c||(this.onPacket(u),i())}).catch(c=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;this._writer.write(s).then(()=>{r&&Ft(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Gs={websocket:Ms,webtransport:Hs,polling:Us},Vs=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Js=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Wt(n){if(n.length>8e3)throw"URI too long";const t=n,e=n.indexOf("["),s=n.indexOf("]");e!=-1&&s!=-1&&(n=n.substring(0,e)+n.substring(e,s).replace(/:/g,";")+n.substring(s,n.length));let r=Vs.exec(n||""),i={},o=14;for(;o--;)i[Js[o]]=r[o]||"";return e!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Ys(i,i.path),i.queryKey=Ws(i,i.query),i}function Ys(n,t){const e=/\/{2,9}/g,s=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Ws(n,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(e[r]=i)}),e}const Kt=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ot=[];Kt&&addEventListener("offline",()=>{Ot.forEach(n=>n())},!1);class Y extends E{constructor(t,e){if(super(),this.binaryType=Os,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 s=Wt(t);e.hostname=s.host,e.secure=s.protocol==="https"||s.protocol==="wss",e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=Wt(e.host).host);qt(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(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ns(this.opts.query)),Kt&&(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"})},Ot.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Ge,e.transport=t,this.id&&(e.sid=this.id);const s=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](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Y.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",Y.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 s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(e+=xs(r)),s>0&&e>this._maxPayload)return this.writeBuffer.slice(0,s);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ft(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,r){if(typeof e=="function"&&(r=e,e=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{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?s():t()}):this.upgrading?s():t()),this}_onError(t){if(Y.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(),Kt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Ot.indexOf(this._offlineEventListener);s!==-1&&Ot.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Y.protocol=Ge;class Ks extends Y{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),s=!1;Y.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",w=>{if(!s)if(w.type==="pong"&&w.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Y.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(y(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const $=new Error("probe error");$.transport=e.name,this.emitReserved("upgradeError",$)}}))};function i(){s||(s=!0,y(),e.close(),e=null)}const o=w=>{const $=new Error("probe error: "+w);$.transport=e.name,i(),this.emitReserved("upgradeError",$)};function c(){o("transport closed")}function u(){o("socket closed")}function f(w){e&&w.name!==e.name&&i()}const y=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",c),this.off("close",u),this.off("upgrading",f)};e.once("open",r),e.once("error",o),e.once("close",c),this.once("close",u),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let Xs=class extends Ks{constructor(t,e={}){const s=typeof t=="object",r=s?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>Gs[i]).filter(i=>!!i)),super(s?r:t,r)}};function zs(n,t="",e){let s=n;e=e||typeof location<"u"&&location,n==null&&(n=e.protocol+"//"+e.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=e.protocol+n:n=e.host+n),/^(https?|wss?):\/\//.test(n)||(typeof e<"u"?n=e.protocol+"//"+n:n="https://"+n),s=Wt(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(e&&e.port===s.port?"":":"+s.port),s}const Qs=typeof ArrayBuffer=="function",Zs=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Xe=Object.prototype.toString,tn=typeof Blob=="function"||typeof Blob<"u"&&Xe.call(Blob)==="[object BlobConstructor]",en=typeof File=="function"||typeof File<"u"&&Xe.call(File)==="[object FileConstructor]";function Ee(n){return Qs&&(n instanceof ArrayBuffer||Zs(n))||tn&&n instanceof Blob||en&&n instanceof File}function At(n,t){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let e=0,s=n.length;e<s;e++)if(At(n[e]))return!0;return!1}if(Ee(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return At(n.toJSON(),!0);for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)&&At(n[e]))return!0;return!1}function sn(n){const t=[],e=n.data,s=n;return s.data=Xt(e,t),s.attachments=t.length,{packet:s,buffers:t}}function Xt(n,t){if(!n)return n;if(Ee(n)){const e={_placeholder:!0,num:t.length};return t.push(n),e}else if(Array.isArray(n)){const e=new Array(n.length);for(let s=0;s<n.length;s++)e[s]=Xt(n[s],t);return e}else if(typeof n=="object"&&!(n instanceof Date)){const e={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=Xt(n[s],t));return e}return n}function nn(n,t){return n.data=zt(n.data,t),delete n.attachments,n}function zt(n,t){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<t.length)return t[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=zt(n[e],t);else if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]=zt(n[e],t));return n}const rn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var g;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class on{constructor(t){this.replacer=t}encode(t){return(t.type===g.EVENT||t.type===g.ACK)&&At(t)?this.encodeAsBinary({type:t.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===g.BINARY_EVENT||t.type===g.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=sn(t),s=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(s),r}}class ve extends E{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 s=e.type===g.BINARY_EVENT;s||e.type===g.BINARY_ACK?(e.type=s?g.EVENT:g.ACK,this.reconstructor=new an(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Ee(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 s={type:Number(t.charAt(0))};if(g[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===g.BINARY_EVENT||s.type===g.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const c=Number(o);if(!cn(c)||c<0)throw new Error("Illegal attachments");if(c>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=c}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););s.nsp=t.substring(i,e)}else s.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(ve.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case g.CONNECT:return Ne(e);case g.DISCONNECT:return e===void 0;case g.CONNECT_ERROR:return typeof e=="string"||Ne(e);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&rn.indexOf(e[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class an{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=nn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const cn=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Ne(n){return Object.prototype.toString.call(n)==="[object Object]"}const hn=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ve,Encoder:on,get PacketType(){return g}},Symbol.toStringTag,{value:"Module"}));function x(n,t,e){return n.on(t,e),function(){n.off(t,e)}}const ln=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ze extends E{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[x(t,"open",this.onopen.bind(this)),x(t,"packet",this.onpacket.bind(this)),x(t,"error",this.onerror.bind(this)),x(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 s,r,i;if(ln.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:g.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const y=this.ids++,w=e.pop();this._registerAckCallback(y,w),o.id=y}const c=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===t&&this.sendBuffer.splice(c,1);e.call(this,new Error("operation has timed out"))},r),o=(...c)=>{this.io.clearTimeoutFn(i),e.apply(this,c)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((s,r)=>{const i=(o,c)=>o?r(o):s(c);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),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:g.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(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case g.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 g.EVENT:case g.BINARY_EVENT:this.onevent(t);break;case g.ACK:case g.BINARY_ACK:this.onack(t);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);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 s of e)s.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 s=!1;return function(...r){s||(s=!0,e.packet({type:g.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.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 s=0;s<e.length;s++)if(t===e[s])return e.splice(s,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 s=0;s<e.length;s++)if(t===e[s])return e.splice(s,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 s of e)s.apply(this,t.data)}}}function ct(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}ct.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*n);n=Math.floor(t*10)&1?n+e:n-e}return Math.min(n,this.max)|0};ct.prototype.reset=function(){this.attempts=0};ct.prototype.setMin=function(n){this.ms=n};ct.prototype.setMax=function(n){this.max=n};ct.prototype.setJitter=function(n){this.jitter=n};class Qt extends E{constructor(t,e){var s;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,qt(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((s=e.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new ct({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||hn;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Xs(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=x(e,"open",function(){s.onopen(),t&&t()}),i=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),t?t(c):this.maybeReconnectOnOpen()},o=x(e,"error",i);if(this._timeout!==!1){const c=this._timeout,u=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(x(t,"ping",this.onping.bind(this)),x(t,"data",this.ondata.bind(this)),x(t,"error",this.onerror.bind(this)),x(t,"close",this.onclose.bind(this)),x(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){Ft(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new ze(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const s of e)if(this.nsps[s].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],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 s;this.cleanup(),(s=this.engine)===null||s===void 0||s.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 s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const ht={};function pt(n,t){typeof n=="object"&&(t=n,n=void 0),t=t||{};const e=zs(n,t.path||"/socket.io"),s=e.source,r=e.id,i=e.path,o=ht[r]&&i in ht[r].nsps,c=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let u;return c?u=new Qt(s,t):(ht[r]||(ht[r]=new Qt(s,t)),u=ht[r]),e.query&&!t.query&&(t.query=e.queryKey),u.socket(e.path,t)}Object.assign(pt,{Manager:Qt,Socket:ze,io:pt,connect:pt});const Pt="thatopen/document@1",Zt="document.json",Pe=()=>`v-${Date.now()}`;function un(n){return String(n._id??n.id??"")}var yt,te;class Te{constructor(t,e){b(this,yt);this.client=t,this.projectId=e}async descriptor(t){const e=await a(this,yt,te).call(this,t);if(!e)return null;const r=await(await this.client.downloadFile(e.id)).text();if(!r.trim())return null;let i;try{i=JSON.parse(r)}catch{return null}return dn(i)}async view(t,e){const s=await this.descriptor(t);if(!s)return null;for(const r of e){const i=s.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const s=await this.descriptor(t);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.views=[...s.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,s)}async setDescriptor(t,e){const s={...e,schema:Pt,views:e.views??[]},r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,yt,te).call(this,t);if(i){await this.client.updateFile(i.id,{file:r,versionTag:Pe()});return}await this.client.createFile({file:r,name:Zt,versionTag:Pe(),parentFolderId:t,projectId:this.projectId})}}yt=new WeakSet,te=async function(t){const s=(await this.client.listFiles({folderId:t})).find(r=>String(r.name??"")===Zt);return s?{id:un(s)}:void 0};function dn(n){if(!n||typeof n!="object")return null;const t=n;if(t.schema!==Pt||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(i=>!!i&&typeof i=="object"&&typeof i.fileId=="string"&&typeof i.format=="string"):[],s=t.native,r=!!s&&typeof s=="object"&&typeof s.fileId=="string"&&typeof s.format=="string";return{schema:Pt,name:t.name,...r?{native:{fileId:s.fileId,format:s.format}}:{},views:e}}class ee 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 Be="bimterop",se="revitflow_history.json",Q="revitflow_ops.json",Le="revitflow/ops@1",Qe="revitflow_model.frag",Ze="revitflow_",fn="bimterop-locks-anchor",St=()=>`v-${Date.now()}`;function ts(n,t){return n.filter(e=>String(e.parentId??"")===t)}function N(n){return String(n._id??n.id??"")}var C,mt,ne;class es{constructor(t,e){b(this,mt);b(this,C);this.client=t,this.projectId=e}async docs(){const t=await a(this,mt,ne).call(this);if(!t)return[];const e=await this.client.listFolders({parentFolderId:t,projectId:this.projectId}),s=[];for(const r of ts(e,t)){const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const u=(await this.client.listFiles({folderId:N(r)})).map(w=>String(w.name??"")),f=u.find(w=>w===Qe)??u.find(w=>w.endsWith(".frag")&&!w.startsWith(Ze)),y=u.includes(se)||u.includes(Q)||!!f;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:N(r),modelName:f,...y?{}:{empty:!0}})}return s}doc(t,e){return new ss(this.client,this,t,e)}async rootFolderId(t=!1){if(l(this,C))return l(this,C);const e=await a(this,mt,ne).call(this);if(e)return e;if(!t)return;const s=await this.client.createFolder(Be,void 0,this.projectId);return _(this,C,N(s)),l(this,C)}}C=new WeakMap,mt=new WeakSet,ne=async function(){if(l(this,C))return l(this,C);const e=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===Be&&!s.parentId);return e&&_(this,C,N(e)),l(this,C)};var q,d,Z,tt,F,re,ut,et,ie,It,dt,Ct,oe,ns;class ss{constructor(t,e,s,r){b(this,d);b(this,q);this.client=t,this.project=e,this.source=s,this.docId=r}async timeline(){const t=await a(this,d,It).call(this);return Se((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 a(this,d,et).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async folderId(){return await a(this,d,F).call(this,!1)}async descriptor(){return await l(this,d,Z).descriptor(await a(this,d,F).call(this,!1))}async view(t){const e=await a(this,d,F).call(this,!1),s=await l(this,d,Z).descriptor(e);if(s){for(const i of t){const o=s.views.find(c=>c.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await a(this,d,et).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await a(this,d,F).call(this,!0);if(await l(this,d,Z).descriptor(e)){await l(this,d,Z).addView(e,t);return}const r=await a(this,d,et).call(this);await l(this,d,Z).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??l(this,d,tt),views:[t]})}async ownership(){const t=await a(this,d,ut).call(this,fn);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),s=await Promise.all(e.map(async o=>{try{const c=N(o),u=await this.client.downloadHiddenFile(c),f=JSON.parse(await u.text());return!f||typeof f!="object"||!("revitflowlock"in f)||!Array.isArray(f.keys)?null:{owner:String(f.user??""),keys:f.keys.filter(y=>typeof y=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of s)if(o)for(const c of o.keys){if(!c||r.has(c))continue;r.add(c);const u=i.get(o.owner)??[];u.push(c),i.set(o.owner,u)}return[...i.entries()].map(([o,c])=>({owner:o,elements:c}))}async sync(t){var c;const e=await a(this,d,F).call(this,!0);let s=await a(this,d,It).call(this)??{model:this.docId,commits:[]};const r=Fe(s.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new ee(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Bt(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...(c=t.appliedOps)!=null&&c.length?{appliedOps:t.appliedOps}:{},changes:t.changes,counts:pn(t.changes)};if(t.model&&(await a(this,d,ns).call(this,e,t.model),i.full=!0),t.delta){const u=await a(this,d,et).call(this);if(!u)throw new Error("A delta needs the model file to hang from: sync a full model first.");const f=await this.client.createHiddenFile(t.delta,u.id);i.deltaId=String(f._id??f.id)}const o=await a(this,d,It).call(this);if(o){s=o;const u=Fe(s.commits);if(t.expectedLatestGuid!==void 0&&(u==null?void 0:u.guid)!==t.expectedLatestGuid)throw new ee(t.expectedLatestGuid,u==null?void 0:u.guid);u&&!i.parents&&(i.parents=[u.guid])}return s.commits.push(i),await a(this,d,Ct).call(this,e,se,s),i}async suggestions(){const t=await a(this,d,dt).call(this);return(t==null?void 0:t.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(t=>t.state==="pending")}async suggest(t){const e=await a(this,d,F).call(this,!0),s=await a(this,d,dt).call(this)??{schema:Le,ops:[]},r=await a(this,d,ut).call(this,Q),i={opId:t.opId??Bt(),to:t.to??this.source,title:t.title,verb:t.verb,author:t.author,createdAt:new Date().toISOString(),state:"pending",...t.targets!==void 0?{targets:t.targets}:{},...t.batchId?{batchId:t.batchId}:{},...t.userId?{userId:t.userId}:{},...t.baseCommitGuid?{baseCommitGuid:t.baseCommitGuid}:{}};if(t.payload){const c=r??await a(this,d,oe).call(this,e,Q,s),u=await this.client.createHiddenFile(t.payload,c.id);i.fragId=String(u._id??u.id)}const o=await a(this,d,dt).call(this)??s;return o.schema??(o.schema=Le),o.ops.push(i),await a(this,d,Ct).call(this,e,Q,o),i}async suggestionPayload(t){if(!t.fragId)throw new Error(`Suggestion ${t.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(t.fragId)).blob()}async resolveSuggestion(t,e){const s=await a(this,d,F).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await a(this,d,dt).call(this),i=r==null?void 0:r.ops.find(o=>o.opId===t);if(!r||!i)throw new Error(`No suggestion ${t} in this document's queue.`);return Object.assign(i,e),await a(this,d,Ct).call(this,s,Q,r),i}}q=new WeakMap,d=new WeakSet,Z=function(){return new Te(this.client,this.project.projectId)},tt=function(){return`${this.source}-${this.docId}`},F=async function(t){if(l(this,q))return l(this,q);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=await this.client.listFolders({parentFolderId:e,projectId:this.project.projectId}),r=ts(s,e).find(o=>String(o.name??"")===l(this,d,tt));if(r)return _(this,q,N(r)),l(this,q);if(!t)throw new Error(`Document ${l(this,d,tt)} does not exist in this project.`);const i=await this.client.createFolder(l(this,d,tt),e,this.project.projectId);return _(this,q,N(i)),l(this,q)},re=async function(){const t=await a(this,d,F).call(this,!1);return(await this.client.listFiles({folderId:t})).map(s=>({id:N(s),name:String(s.name??"")}))},ut=async function(t){try{return(await a(this,d,re).call(this)).find(e=>e.name===t)}catch{return}},et=async function(){try{const t=await a(this,d,re).call(this);return t.find(e=>e.name===Qe)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Ze))}catch{return}},ie=async function(t){const e=await a(this,d,ut).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},It=function(){return a(this,d,ie).call(this,se)},dt=function(){return a(this,d,ie).call(this,Q)},Ct=async function(t,e,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,d,ut).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:St()}),i):await a(this,d,oe).call(this,t,e,s)},oe=async function(t,e,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:St(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:N(o??i),name:e}},ns=async function(t,e){const s=await a(this,d,et).call(this);if(s)return await this.client.updateFile(s.id,{file:e,versionTag:St()}),s;const r=`${l(this,d,tt)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:St(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:N(o??i),name:r}};function pn(n){const t={added:0,modified:0,removed:0};for(const e of n)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function Se(n){var u;if(n.length<=1)return n.forEach((f,y)=>f.ordinal=y),[...n];const t=new Map(n.map(f=>[f.guid,f])),e=new Map,s=[];for(const f of n){const y=(u=f.parents)==null?void 0:u[0];if(y&&t.has(y)){const w=e.get(y)??[];w.push(f),e.set(y,w)}else s.push(f)}const r=(f,y)=>String(f.timestamp).localeCompare(String(y.timestamp));s.sort(r);const i=[],o=[...s].reverse(),c=new Set;for(;o.length;){const f=o.pop();if(c.has(f.guid))continue;c.add(f.guid),i.push(f);const y=(e.get(f.guid)??[]).sort(r);for(let w=y.length-1;w>=0;w--)o.push(y[w])}for(const f of n)c.has(f.guid)||i.push(f);return i.forEach((f,y)=>f.ordinal=y),i}function Fe(n){const t=Se(n);return t[t.length-1]}function Bt(){const n=globalThis.crypto;return n!=null&&n.randomUUID?n.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)})}var H,gt,ae;class rs{constructor(t){b(this,gt);b(this,H,new Map);this.client=t}register(t){if(l(this,H).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);l(this,H).set(t.name,t)}list(t){return[...l(this,H).values()].filter(s=>(!(t!=null&&t.to)||s.to===t.to)&&(!(t!=null&&t.input)||s.inputs.includes(t.input)))}get(t){return l(this,H).get(t)}async plan(t,e){const{base:s,opId:r,result:i}=await a(this,gt,ae).call(this,t,e);return{opId:r,projectId:e.projectId,target:e.target,...s!=null&&s.guid?{baseCommitGuid:s.guid}:{},result:i}}async queue(t,e){return{suggestion:await this.client.history(t.projectId).doc(t.target.source,t.target.docId).suggest({opId:t.opId,title:t.result.title,verb:t.result.verb,author:e.author,payload:t.result.payload,targets:t.result.targets,userId:e.userId,baseCommitGuid:t.baseCommitGuid}),result:t.result}}async run(t,e){const{targetDoc:s,base:r,opId:i,result:o}=await a(this,gt,ae).call(this,t,e);return{suggestion:await s.suggest({opId:i,title:o.title,verb:o.verb,author:e.author,payload:o.payload,targets:o.targets,userId:e.userId,baseCommitGuid:r==null?void 0:r.guid}),result:o}}}H=new WeakMap,gt=new WeakSet,ae=async function(t,e){const s=l(this,H).get(t);if(!s)throw new Error(`No recipe named "${t}" is registered.`);if(s.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${s.to}, but the target document belongs to ${e.target.source}.`);const r=this.client.history(e.projectId).doc(e.target.source,e.target.docId),i=await r.latest(),o=Bt(),c=await s.run({client:this.client,projectId:e.projectId,targetDoc:r,opId:o,input:e.input,settings:e.settings??{}});return{recipe:s,targetDoc:r,base:i,opId:o,result:c}};const ce=100;function yn(n){try{const t=JSON.parse(n);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 mn(n){if(!n||typeof n!="object")return;const t=n.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Dt extends Error{constructor(e,s,r,i){const o=yn(r);super(o.message??`${s||"Request failed"} (${e})`);T(this,"status");T(this,"code");T(this,"details");T(this,"body");T(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??mn(o.details)}}const R="item/folder",m="item",j="processor",gn="npm-registry",L="hidden",Gt="FILE",Vt="TOOL",Jt="APP",wn=500,qe=3e4,bn=.25,_n=n=>new Promise(t=>setTimeout(t,n));function En(n){var r,i;const t=(i=(r=n.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function vn(n){return n instanceof Dt?n.status===429||n.status>=500:!0}function Tn(n,t){const e=Math.min(wn*2**t,qe),s=e*bn*Math.random(),r=n instanceof Dt&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,qe)+s:e+s}var h,he,p,M,wt,ft,xt,$t,le,ue,is;const Oe=class Oe{constructor(t,e,s){b(this,h);T(this,"apiUrl");T(this,"accessToken");T(this,"wsUrl");T(this,"retries");T(this,"useBearer");T(this,"builtInGlobals",null);T(this,"localServerUrl",null);T(this,"context");b(this,wt);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=s||{};let c=e;if(c.charAt(c.length-1)==="/"&&(c=c.slice(0,-1)),this.apiUrl=`${c}/api`,this.accessToken=t,this.wsUrl=c,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let u=o;u.charAt(u.length-1)==="/"&&(u=u.slice(0,-1)),this.localServerUrl=u}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new Oe(e.accessToken,e.apiUrl,{...t,useBearer:!0});return s.context=e,s}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,s){return a(this,h,p).call(this,t,e,s)}async listFiles(t){const{folderId:e,archived:s,projectId:r}=t||{};return e?await a(this,h,p).call(this,"GET",`${R}/${e}/items`,{query:{itemType:Gt,archived:s}}):await a(this,h,p).call(this,"GET",`${m}`,{query:{itemType:Gt,archived:s,...r&&{projectId:r}}})}async getFile(t,e){return await a(this,h,ue).call(this,t,e)}async createFile(t){return await a(this,h,$t).call(this,t,Gt)}async updateFile(t,e){return await a(this,h,le).call(this,t,e)}async archiveFile(t){return await a(this,h,p).call(this,"DELETE",`${m}/${t}`)}async recoverFile(t){return await a(this,h,p).call(this,"PUT",`${m}/${t}/recover`)}async downloadFile(t,e){return await a(this,h,xt).call(this,t,e)}async getFileVersionMetadata(t,e,s){const{withDraft:r}=s||{};return await a(this,h,p).call(this,"GET",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,s){return await a(this,h,p).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await a(this,h,p).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:s}=e||{};return await a(this,h,ft).call(this,t,async r=>(await a(this,h,p).call(this,"POST",`${m}/batch/version-metadata`,{body:JSON.stringify({entries:r,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:s,projectId:r}=t||{};return await a(this,h,p).call(this,"GET",R,{query:{parentFolderId:s,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await a(this,h,p).call(this,"GET",`${R}/${t}`)}async getFoldersBatch(t){return await a(this,h,ft).call(this,t,async e=>(await a(this,h,p).call(this,"POST",`${m}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,s){return await a(this,h,p).call(this,"POST",R,{body:JSON.stringify({name:t,...e&&{parentId:e},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(t,e){const{name:s}=e;return await a(this,h,p).call(this,"PUT",`${R}/${t}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(t){return await a(this,h,p).call(this,"DELETE",`${R}/${t}`)}async recoverFolder(t){return await a(this,h,p).call(this,"PUT",`${R}/${t}/recover`)}async downloadFolder(t){return await a(this,h,M).call(this,`${R}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:s,projectId:r}=t||{};return e?await a(this,h,p).call(this,"GET",`${R}/${e}/items`,{query:{itemType:Vt,...s&&{ShowVersions:s}}}):await a(this,h,p).call(this,"GET",`${m}`,{query:{itemType:Vt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(t,e){return await a(this,h,ue).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await a(this,h,$t).call(this,t,Vt,e)}async updateComponent(t,e){const{componentProps:s}=e;return await a(this,h,le).call(this,t,e,s)}async downloadComponent(t,e){return await a(this,h,xt).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,h,M).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(t){return await a(this,h,p).call(this,"DELETE",`${m}/${t}`)}async recoverComponent(t){return await a(this,h,p).call(this,"PUT",`${m}/${t}/recover`)}async getBuiltInComponent(t){return await(await a(this,h,M).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,s){const r=await this.getBuiltInComponent(t.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),c=o.map(w=>i[w]),f=new Function(...o,`${r}
2
+ return main;`)(...c),y=(f==null?void 0:f.componentDefinition)??f;e.get(y)}async initBuiltInComponents(t,...e){await Promise.all(e.map(s=>this.initBuiltInComponent(s,t)))}async setup(t,...e){var o,c;const s=t.OBC,r=t.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(c=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||c.call(o),{components:i}}throwError(t,e){var s,r;(r=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||r.call(s,t,e)}async listApps(t){const{folderId:e,ShowVersions:s,projectId:r}=t||{};return e?await a(this,h,p).call(this,"GET",`${R}/${e}/items`,{query:{itemType:Jt,...s&&{ShowVersions:s}}}):await a(this,h,p).call(this,"GET",`${m}`,{query:{itemType:Jt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await a(this,h,$t).call(this,t,Jt,e)}async downloadApp(t,e){return await a(this,h,xt).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,h,M).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(t){return await a(this,h,p).call(this,"DELETE",`${m}/${t}`)}async getNpmCredentials(){return await a(this,h,p).call(this,"GET",`${gn}/credentials`)}async executeComponent(t,e,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${j}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,h,p).call(this,"POST",`${j}/${t}/execute`,{body:JSON.stringify(e),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${j}/progress/${t}/abort`,s=await fetch(e,{method:"POST"});if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,h,p).call(this,"POST",`${j}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const s=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${j}/${t}/progress${s}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,h,p).call(this,"GET",`${j}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${j}/progress/${t}`,s=await fetch(e);if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,h,p).call(this,"GET",`${j}/progress/${t}`)}async onExecutionProgress(t,e){const s=this.localServerUrl??this.wsUrl,r=await pt(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new Te(this,t)}history(t){return new es(this,t)}get recipes(){return l(this,wt)??_(this,wt,new rs(this)),l(this,wt)}async createHiddenFile(t,e,s){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),s!=null&&r.append("tag",s),await a(this,h,p).call(this,"POST",`${m}/${L}`,{body:r})}async createHiddenFilesBatch(t,e,s){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),s!=null&&r.append("tag",s),await a(this,h,p).call(this,"POST",`${m}/${L}/batch`,{body:r})}async deleteHiddenFile(t){return await a(this,h,p).call(this,"DELETE",`${m}/${L}/${t}`)}async getHiddenFile(t){return await a(this,h,p).call(this,"GET",`${m}/${L}/${t}`)}async downloadHiddenFile(t){return await a(this,h,M).call(this,`${m}/${L}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await a(this,h,p).call(this,"GET",`${m}/${L}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await a(this,h,ft).call(this,t,async s=>(await a(this,h,p).call(this,"POST",`${m}/${L}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await a(this,h,p).call(this,"GET",`${m}/${t}/${L}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await a(this,h,p).call(this,"DELETE",`${m}/${t}/${L}`)}async uploadItemIcon(t,e){const s=new FormData;return s.append("icon",e),await a(this,h,p).call(this,"PUT",`${m}/${t}/icon`,{body:s})}async getItemIcon(t){return await a(this,h,M).call(this,`${m}/${t}/icon`)}async removeItemIcon(t){return await a(this,h,p).call(this,"DELETE",`${m}/${t}/icon`)}async updateItem(t,e){return await a(this,h,p).call(this,"PUT",`${m}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,s,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",s),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await a(this,h,p).call(this,"POST",`${m}/${t}/version`,{body:o})}async listVersions(t,e={}){return await a(this,h,p).call(this,"GET",`${m}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:s}=e;return await a(this,h,ft).call(this,t,async r=>(await a(this,h,p).call(this,"POST",`${m}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await a(this,h,p).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await a(this,h,p).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await a(this,h,p).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};h=new WeakSet,he=function(t){return`${this.apiUrl}/${t}`},p=async function(t,e,s){const{body:r,query:i,contentType:o,retries:c,responseType:u,retryAttempt:f}=s||{},y=a(this,h,he).call(this,e),w=a(this,h,is).call(this,i),$=await this.resolveAccessToken(),ps={...w,...this.useBearer?{}:{accessToken:$}};try{const I=await fetch(y+"?"+new URLSearchParams(ps).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${$}`}},...r&&{body:r}});if(!I.ok){const X=await I.text().then(Et=>Et).catch(()=>"");throw new Dt(I.status,I.statusText,X,En(I))}return u==="blob"?await I.blob():I.json().then(X=>X).catch(()=>{})}catch(I){const X=c??this.retries;if(X>0&&vn(I)){const Et=f??0;return await _n(Tn(I,Et)),await a(this,h,p).call(this,t,e,{...s,retries:X-1,retryAttempt:Et+1})}throw I}},M=async function(t,e){const{query:s}=e||{},r=a(this,h,he).call(this,t),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},wt=new WeakMap,ft=async function(t,e){if(!t.length)return[];const s=[];for(let i=0;i<t.length;i+=ce)s.push(t.slice(i,i+ce));return(await Promise.all(s.map(e))).flat()},xt=async function(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,h,M).call(this,`${m}/${t}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},$t=async function(t,e,s){const{name:r,versionTag:i,parentFolderId:o,projectId:c,file:u,metadata:f}=t,y=new FormData;return y.append("file",u),y.append("name",r),y.append("versionTag",i),y.append("itemType",e),o&&y.append("folderId",o),c&&y.append("projectId",c),s&&y.append("extraProps",JSON.stringify(s)),f&&y.append("metadata",JSON.stringify(f)),await a(this,h,p).call(this,"POST",m,{body:y})},le=async function(t,e,s){const{name:r,versionTag:i,parentFolderId:o,file:c,metadata:u}=e;let f,y;if(c){const w=new FormData;w.append("file",c),i&&w.append("versionTag",i),s&&w.append("extraProps",JSON.stringify(s)),u&&w.append("metadata",JSON.stringify(u)),y=await a(this,h,p).call(this,"POST",`${m}/${t}/version`,{body:w})}if(r||o){const w={...r&&{name:r},...o&&{folderId:o}},$=JSON.stringify(w);f=await a(this,h,p).call(this,"PUT",`${m}/${t}`,{body:$,contentType:"application/json"})}return{item:f,version:y}},ue=async function(t,e){const{showVersions:s=!1}=e||{};return await a(this,h,p).call(this,"GET",`${m}/${t}`,{query:{showVersions:s}})},is=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[s,r])=>(e[s]=r,e),{})};let Lt=Oe;function os(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const t=e=>{e.source===window.parent&&n(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const de="channel:",Sn=1e4;function Rt(n){try{n()}catch(t){console.error("[channel] a listener threw:",t)}}var D,k,O,nt,rt,it,S,fe,pe,st;class ke{constructor(t,e){b(this,S);b(this,D,!1);b(this,k,[]);b(this,O,[]);b(this,nt,new Set);b(this,rt,new Set);b(this,it,new Set);this.transport=t,this.controls=e}get joined(){return l(this,D)}get peers(){return l(this,k)}join(){return l(this,D)?Promise.resolve():a(this,S,fe).call(this,"joined",this.controls.join)}leave(){return!l(this,D)&&!l(this,O).some(t=>t.want==="joined")?Promise.resolve():a(this,S,fe).call(this,"left",this.controls.leave)}onChange(t){return l(this,nt).add(t),()=>void l(this,nt).delete(t)}onPeerJoined(t){return l(this,rt).add(t),()=>void l(this,rt).delete(t)}onPeerLeft(t){return l(this,it).add(t),()=>void l(this,it).delete(t)}applyJoined(){_(this,D,!0),a(this,S,pe).call(this,"joined"),a(this,S,st).call(this)}applyLeft(){_(this,D,!1),_(this,k,[]),a(this,S,pe).call(this,"left"),a(this,S,st).call(this)}applyPeers(t){_(this,k,t),a(this,S,st).call(this)}applyPeerJoined(t){!l(this,D)||l(this,k).some(e=>e.from===t.from)||(_(this,k,[...l(this,k),t]),l(this,rt).forEach(e=>Rt(()=>e(t))),a(this,S,st).call(this))}applyPeerLeft(t){const e=l(this,k).find(s=>s.from===t);e&&(_(this,k,l(this,k).filter(s=>s.from!==t)),l(this,it).forEach(s=>Rt(()=>s(e))),a(this,S,st).call(this))}failPending(t){const e=l(this,O);return _(this,O,[]),e.forEach(s=>{clearTimeout(s.timer),s.reject(t)}),e.length>0}post(t){this.transport.post(t)}}D=new WeakMap,k=new WeakMap,O=new WeakMap,nt=new WeakMap,rt=new WeakMap,it=new WeakMap,S=new WeakSet,fe=function(t,e){return new Promise((s,r)=>{const i={want:t,resolve:s,reject:r,timer:setTimeout(()=>{_(this,O,l(this,O).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},Sn)};l(this,O).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},pe=function(t){const e=l(this,O).filter(s=>s.want===t);_(this,O,l(this,O).filter(s=>s.want!==t)),e.forEach(s=>{clearTimeout(s.timer),s.resolve()})},st=function(){l(this,nt).forEach(t=>Rt(t))};var ot;class as extends ke{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});b(this,ot,new Map)}on(e,s){const r=l(this,ot).get(e)??new Set;return r.add(s),l(this,ot).set(e,r),()=>void r.delete(s)}send(e,s){if(e.startsWith(de))throw new Error(`Message types starting with '${de}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:s}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const s=l(this,ot).get(e.type);if(!(s!=null&&s.size))return{handled:!1};const r=hs(e);return s.forEach(i=>Rt(()=>i(e.payload,r))),{handled:!0}}}ot=new WeakMap;var G;class cs extends ke{constructor(e,s){super(e,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});b(this,G,new Map);this.kind=s}on(e,s){if(l(this,G).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return l(this,G).set(e,s),()=>void l(this,G).delete(e)}accepts(e,s){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===s}get hasHandlers(){return l(this,G).size>0}async handle(e){const s=l(this,G).get(e.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(e.payload,hs(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}G=new WeakMap;function hs(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function kn(n){const t=n;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 K,bt,U,V,J,v,ye,Nt,us,ds,fs,me;class ls{constructor(t){b(this,v);b(this,K);b(this,bt);b(this,U);b(this,V,new Map);b(this,J,new Set);_(this,K,t),_(this,bt,t.listen(e=>void a(this,v,us).call(this,e)))}collab(){return l(this,U)??_(this,U,new as(l(this,K))),l(this,U)}external(t){const e=t??"";let s=l(this,V).get(e);return s||(s=new cs(l(this,K),t),l(this,V).set(e,s)),s}dispose(){l(this,bt).call(this)}}K=new WeakMap,bt=new WeakMap,U=new WeakMap,V=new WeakMap,J=new WeakMap,v=new WeakSet,ye=function(){return[...l(this,U)?[l(this,U)]:[],...l(this,V).values()]},Nt=function(t,e){if(t==="collab")return l(this,U);if(t==="external")return l(this,V).get(typeof e=="string"?e:"")},us=async function(t){const e=kn(t);if(e){if(e.type.startsWith(de)){a(this,v,ds).call(this,e);return}await a(this,v,fs).call(this,e)}},ds=function(t){var s,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(s=a(this,v,Nt).call(this,e.scope,e.kind))==null||s.applyJoined();break;case"channel:left":(r=a(this,v,Nt).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=a(this,v,Nt).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[l(this,U)]:[...l(this,V).values()].filter(c=>c.accepts("external",e.kind));for(const c of o)t.type==="channel:peer-joined"?c==null||c.applyPeerJoined({from:e.from,kind:e.kind}):c==null||c.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));a(this,v,ye).call(this).map(u=>u.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},fs=async function(t){const e=a(this,v,ye).call(this).filter(i=>i.accepts(t.scope,t.kind));let s=!1;for(const i of e){const o=await i.handle(t);o.handled&&(s=!0,t.requestId&&a(this,v,me).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!s&&a(this,v,me).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},me=function(t,e){l(this,J).has(t)||(l(this,J).add(t),l(this,J).size>500&&l(this,J).delete(l(this,J).values().next().value),l(this,K).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 W="project",z="notifications";var at,_t;const Ae=class Ae extends Lt{constructor(e,s,r){super(typeof e=="string"?e:"",s,{...r,useBearer:!0});b(this,at);b(this,_t);typeof e=="function"&&_(this,at,e)}async resolveAccessToken(){return l(this,at)?await l(this,at).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Ae(s.accessToken,s.apiUrl,e);return r.context=s,r}get channel(){return l(this,_t)??_(this,_t,new ls(os())),l(this,_t)}async listProjects(){return await this.request("GET",W)}async getProject(e){return await this.request("GET",`${W}/${e}`)}async getProjectData(e){return await this.request("GET",`${W}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${W}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${W}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",z,{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",`${z}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${z}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${z}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${z}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${z}/subscriptions/${e}`)}async subscribeToAutomation(e,s,r){return await this.request("POST",`${W}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,s,r){return await this.request("PATCH",`${W}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const s=await this.resolveAccessToken(),r=pt(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};at=new WeakMap,_t=new WeakMap;let ge=Ae;const On={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},An={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},In={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Cn={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},xn={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},$n={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Rn={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Nn={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Pn={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Bn={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=An;exports.ChannelClient=ls;exports.ChannelRoom=ke;exports.ClashesManager=In;exports.CollabRoom=as;exports.DOCUMENT_FILE=Zt;exports.DOCUMENT_SCHEMA=Pt;exports.EngineServicesClient=Lt;exports.ExternalRoom=cs;exports.FileList=Cn;exports.FlowDoc=ss;exports.GISManager=xn;exports.GitHistoryManager=$n;exports.HelloWorld=Rn;exports.METADATA_LIMITS=On;exports.PlatformClient=ge;exports.ProjectDocuments=Te;exports.ProjectHistory=es;exports.ProjectManager=Nn;exports.Recipes=rs;exports.RequestError=Dt;exports.STORAGE_BATCH_MAX=ce;exports.StaleHistoryError=ee;exports.TopicsManager=Pn;exports.UIManager=Bn;exports.mintGuid=Bt;exports.orderByGraph=Se;exports.windowTransport=os;
3
3
  //# sourceMappingURL=index.cjs.js.map