hypha-rpc 0.20.79 → 0.20.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hypha-rpc-websocket.js +266 -1
- package/dist/hypha-rpc-websocket.js.map +1 -1
- package/dist/hypha-rpc-websocket.min.js +1 -1
- package/dist/hypha-rpc-websocket.min.js.map +1 -1
- package/dist/hypha-rpc-websocket.min.mjs +1 -1
- package/dist/hypha-rpc-websocket.min.mjs.map +1 -1
- package/dist/hypha-rpc-websocket.mjs +266 -1
- package/dist/hypha-rpc-websocket.mjs.map +1 -1
- package/package.json +1 -1
- package/src/rpc.js +266 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hypha-rpc-websocket.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;;;;;;ACVA;AACA;AACA;AACA;AAa0B;AACyB;;AAEqB;;AAEjE;AACP;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,IAAI;AACJ,aAAa;AACb,IAAI;AACJ,aAAa;AACb,IAAI;AACJ,aAAa;AACb,IAAI;AACJ,aAAa;AACb,IAAI;AACJ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,wCAAwC,IAAI,wBAAwB,KAAK;AACzE;AACA;;AAEA;AACA;AACA;AACA,2CAA2C,IAAI,wBAAwB,KAAK;AAC5E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,KAAK,GAAG,EAAE;AACnC;AACA;AACA,UAAU;AACV;AACA,4BAA4B,gEAAc;AAC1C;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA,8CAA8C,EAAE,aAAa,QAAQ;AACrE;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,oDAAoD,KAAK;AACzD;AACA;AACA,yBAAyB,KAAK,GAAG,EAAE;AACnC;AACA;AACA,UAAU;AACV;AACA,4BAA4B,gEAAc;AAC1C;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA,sDAAsD,GAAG,WAAW,QAAQ;AAC5E;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0CAA0C;AAC1C;;AAEA;AACA,sCAAsC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,wCAAwC,YAAY;AACpD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACO,kBAAkB,2DAAc;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,IAAI,uDAAM;AACV,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC;AAClC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,mCAAmC,2CAA2C;AAC9E,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA,uCAAuC,sBAAsB,GAAG,gBAAgB;AAChF;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;;AAEA,MAAM,uDAAM;AACZ,MAAM,uDAAM;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD,wBAAwB;AAC9E;AACA,gBAAgB;AAChB;AACA;AACA,gDAAgD,wBAAwB,IAAI,aAAa;AACzF;AACA;AACA;;AAEA;AACA;AACA,+CAA+C,iBAAiB;AAChE;AACA,cAAc;AACd;AACA,mCAAmC,iBAAiB,SAAS,eAAe,6CAA6C,0BAA0B;AACnJ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA,yEAAyE,aAAa;AACtF;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,IAAI,uDAAM;AACV;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,sCAAsC,IAAI;AAC1C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA,2CAA2C,KAAK,SAAS,sBAAsB;AAC/E,mBAAmB,6DAAW;AAC9B,YAAY,cAAc;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,KAAK,SAAS,sBAAsB;AAClE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,qBAAqB,6DAAW;AAChC,cAAc,cAAc;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,0BAA0B,sBAAsB;AAChD;AACA;AACA,eAAe,4BAA4B;AAC3C,YAAY,uCAAuC;AACnD;AACA;AACA,QAAQ;AACR;AACA;AACA,oDAAoD,YAAY,GAAG,WAAW,KAAK,UAAU;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,4BAA4B;;AAE5B,0BAA0B,sBAAsB;AAChD;AACA;AACA;AACA,+CAA+C,WAAW,cAAc,YAAY,GAAG,WAAW;AAClG;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA,eAAe,4BAA4B;AAC3C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,0DAA0D,WAAW,MAAM,UAAU;AACrF;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV,IAAI,uDAAM;;AAEV;AACA,IAAI,uDAAM;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0DAA0D,WAAW,wBAAwB,IAAI,KAAK,cAAc;AACpH;AACA;AACA;AACA,UAAU,6CAA6C;AACvD;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,uDAAM;AACd;AACA,6BAA6B,QAAQ,KAAK,aAAa;AACvD;AACA;AACA,IAAI,uDAAM,mCAAmC,YAAY;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,sBAAsB,wDAAO;AAC7B;AACA;AACA;AACA;AACA,kBAAkB,SAAS,GAAG,WAAW;AACzC;AACA,cAAc,6DAAY;AAC1B;AACA;AACA;AACA;AACA,UAAU,4DAAW;AACrB;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC,YAAY;AACZ;AACA,yCAAyC,4BAA4B,uBAAuB,iBAAiB,KAAK,UAAU;AAC5H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA,+BAA+B,IAAI;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,uDAAM;;AAEV;AACA;AACA;AACA;AACA;AACA,mGAAmG,WAAW;AAC9G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gFAAgF,aAAa;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA,qCAAqC,OAAO,uCAAuC,OAAO;AAC1F;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,iBAAiB,GAAG,gBAAgB,GAAG,cAAc;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,UAAU,gCAAgC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,QAAQ;AACR,sDAAsD,SAAS,WAAW,EAAE;AAC5E;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,QAAQ;AACR,+DAA+D,EAAE;AACjE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,IAAI,uDAAM;AACV;AACA,6BAA6B,WAAW;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,WAAW;AACvD;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;;AAEA;AACA,mBAAmB,kEAAiB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,WAAW,GAAG,KAAK;AAC1C;AACA;AACA;AACA,aAAa,gBAAgB,GAAG,gBAAgB;AAChD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,+BAA+B,UAAU,IAAI,YAAY,KAAK,MAAM;AACpE;AACA,QAAQ;AACR;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,UAAU;AACtD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iCAAiC,YAAY;AAC7C;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,YAAY;AAC7C;AACA;AACA,UAAU;AACV;AACA,4DAA4D,WAAW;AACvE;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,YAAY,2BAA2B,cAAc;AACpF;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN,uDAAuD,WAAW;AAClE;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,YAAY;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,gDAAgD,WAAW;AAC3D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,qDAAqD,WAAW;AAChE;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,sBAAsB,uBAAuB;AAC7C;AACA;AACA;AACA,4BAA4B,YAAY,qBAAqB,MAAM;AACnE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,WAAW;;AAEvD;AACA;AACA;AACA,MAAM;AACN;AACA,iDAAiD,WAAW;AAC5D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,YAAY;AAC3D;;AAEA;AACA,wBAAwB,WAAW;AACnC;AACA,sCAAsC;AACtC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,MAAM,IAAI,0CAA0C;AACvG;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,uCAAuC,eAAe;AACtD;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,WAAW;AACrD;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,YAAY;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA;;AAEA;AACA;AACA;AACA,SAAS,UAAU;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qCAAqC,uDAAM;AAC3C;AACA,mCAAmC;AACnC;AACA;AACA;AACA,4BAA4B,sDAAS;;AAErC;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gCAAgC,QAAQ,GAAG,WAAW,SAAS,YAAY;AAC3E;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,UAAU;AACV;AACA,6DAA6D,aAAa;AAC1E;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,QAAQ,GAAG,WAAW,SAAS,YAAY;AACzE;AACA;AACA;AACA;AACA;AACA,oCAAoC,YAAY,iBAAiB,aAAa;AAC9E;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,wDAAa;AACvC;AACA,oBAAoB,wDAAa;AACjC;AACA;AACA;AACA;AACA,kDAAkD,WAAW;AAC7D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,UAAU,UAAU,qBAAqB;AAC5E;;AAEA;AACA;AACA,+BAA+B,uDAAM;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,kBAAkB,YAAY,YAAY;AACtG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,sCAAsC,UAAU,GAAG,UAAU,aAAa,iBAAiB;AAC3F;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,UAAU,GAAG,UAAU;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,kBAAkB;AACxD;AACA;AACA;;AAEA;AACA;AACA;AACA,uCAAuC,YAAY,aAAa,YAAY;AAC5E;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;AACA,YAAY;AACZ,yDAAyD,aAAa;AACtE;AACA;AACA;AACA,8BAA8B,wDAAa;AAC3C;AACA,wBAAwB,wDAAa;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,mFAAmF,UAAU,GAAG,UAAU,YAAY,IAAI;AAC1H;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,mFAAmF,UAAU,GAAG,UAAU,YAAY,IAAI;AAC1H;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,OAAO;AACP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gDAAgD,UAAU;AAC1D;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM,uDAAM;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,UAAU,uDAAM;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,8BAA8B,gBAAgB,sDAAsD,YAAY;AAChH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,YAAY,oBAAoB,gBAAgB,sCAAsC,YAAY;AAC3H;AACA;AACA;AACA,+DAA+D,YAAY;AAC3E;AACA;AACA,YAAY;AACZ;AACA,yBAAyB,YAAY,uBAAuB,eAAe,uBAAuB,YAAY;AAC9G;AACA;AACA;AACA,qDAAqD,YAAY;AACjE;AACA;AACA;AACA;;AAEA;AACA,mCAAmC,aAAa,KAAK,gBAAgB;AACrE;AACA;AACA,+BAA+B,aAAa,KAAK,gBAAgB;AACjE;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,MAAM,uDAAM;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ,uDAAM;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,uBAAuB;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA,sEAAsE,YAAY,aAAa,eAAe,UAAU,YAAY;AACpI;AACA;AACA,4CAA4C,aAAa,GAAG,YAAY;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa,OAAO;AACpB;AACA,eAAe,OAAO;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,iEAAiE,QAAQ,oBAAoB,sBAAsB;AACnH;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,QAAQ,4DAAW,aAAa,iEAAgB;AAChD;AACA,MAAM,uDAAM;AACZ;AACA;AACA;AACA,wBAAwB,uDAAM;;AAE9B;AACA;AACA,MAAM,uDAAM;AACZ;AACA,0CAA0C,YAAY;AACtD;;AAEA;AACA,sBAAsB,iEAAgB;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,qBAAqB,WAAW,GAAG,UAAU;AAC7C;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,QAAQ,uDAAM;AACd;AACA;AACA,yBAAyB,uDAAM,GAAG,GAAG,iBAAiB;AACtD,UAAU;AACV,sBAAsB,uDAAM;AAC5B;AACA;AACA;AACA;AACA;AACA,uBAAuB,WAAW,GAAG,UAAU;AAC/C;AACA;AACA;AACA;AACA,QAAQ,uDAAM;AACd;AACA,4CAA4C,YAAY;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,aAAa;AAC5C;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kEAAiB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,oBAAoB,kEAAiB;AACrC;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,iDAAiD,QAAQ;AACzD;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,4BAA4B,8DAAiB;AAC7C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,QAAQ;AACR,0BAA0B,8DAAiB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,WAAW;AACX,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,YAAY;AAC7D,OAAO;AACP;AACA;AACA;AACA;AACA,+CAA+C,YAAY;AAC3D,OAAO;AACP;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D,OAAO;AACP;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AChjFO;AACP;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;;AAEO;AACP;AACA,gBAAgB;AAChB;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,yCAAyC,IAAI;AAC7C;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB,sCAAsC;AACtC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,qCAAqC;AACrC;AACA;AACA,QAAQ;AACR,2CAA2C;AAC3C;AACA;AACA;;AAEA;AACA;;AAEO;AACP;AACA,gBAAgB;AAChB;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4CAA4C;AAC5C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,4CAA4C;AAC5C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,WAAW;AACX;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,yBAAyB;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA,YAAY;AACZ;AACA,YAAY;AACZ;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yBAAyB;AAC/C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;;AAEO;AACP;AACA;AACA,wDAAwD,aAAa;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,GAAG;AACH;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;;AAEO;AACP;AACA;AACA;AACA;;AAEA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,SAAS;AACtB;AACO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,KAAK;AAChB,aAAa,SAAS;AACtB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;AC5hBoC;;AAEpC;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH,mBAAmB,kCAAkC;AACrD,mBAAmB,kCAAkC;AACrD,oBAAoB,mCAAmC;AACvD,oBAAoB,mCAAmC;AACvD,uBAAuB,wCAAwC;;AAE/D;AACA,2BAA2B,4BAA4B;AACvD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,wBAAwB;AAClE;AACA;AACA,CAAC;;AAEM;AACP;AACA,IAAI,0EAA0E;AAC9E;AACA;AACA;AACA;AACA,EAAE,iDAAM;;AAER;AACA;AACA,EAAE,iDAAM;;AAER;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAE,iDAAM;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;ACjF+B;AACmB;AACC;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,6BAA6B;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA,MAAM;AACN,mDAAmD,IAAI;AACvD;AACA;AACA;;AAEA;AACA;AACA;AACA,0DAA0D,OAAO;AACjE;AACA;;AAEA;AACA,EAAE,uDAAM;AACR,EAAE,uDAAM;AACR;AACA,uCAAuC,uDAAM;AAC7C;AACA;AACA;AACA;AACA,kBAAkB,wCAAG;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,QAAQ,wCAAwC;AAChD;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAqC,uDAAM;;AAE3C;AACA;AACA,QAAQ,wCAAwC;AAChD;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,UAAU;;AAEf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;;AAEA,2DAA2D,eAAe;AAC1E;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,uDAAM;AACtB;AACA;AACA;AACA,gBAAgB,uDAAM;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,gEAAc;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA,qBAAqB;AACrB,mBAAmB;AACnB;AACA,iBAAiB;AACjB,eAAe;AACf,8BAA8B,gEAAc;AAC5C;AACA;AACA,8BAA8B,gCAAgC;AAC9D,eAAe;AACf,iCAAiC,gEAAc;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,gBAAgB;AAChD,gCAAgC;AAChC,mCAAmC,kBAAkB;AACrD,mCAAmC,kBAAkB;AACrD,uBAAuB;AACvB,qBAAqB;AACrB,mBAAmB;AACnB,iBAAiB;AACjB,eAAe;AACf;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,SAAS;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kDAAkD,MAAM;AACxD;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAE6C;;;;;;;;;;;;;;;;ACtXG;AAChD;AACA;AACA;AACA;AACA,uCAAuC;AACvC,0CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,uBAAuB;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,uBAAuB;AACjF;AACA;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,6DAAY;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAC2B;AAC5B;;;;;;;;;;;;;;AC/DA,iBAAiB,SAAI,IAAI,SAAI;AAC7B;AACA;AACA,eAAe,gBAAgB,sCAAsC,kBAAkB;AACvF,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,CAAC;AACsB;AACvB;;;;;;;;;;;;;;;;;;;;;;AChCA,iBAAiB,SAAI,IAAI,SAAI;AAC7B,4BAA4B,+DAA+D,iBAAiB;AAC5G;AACA,oCAAoC,MAAM,+BAA+B,YAAY;AACrF,mCAAmC,MAAM,mCAAmC,YAAY;AACxF,gCAAgC;AAChC;AACA,KAAK;AACL;AACA,mBAAmB,SAAI,IAAI,SAAI;AAC/B,cAAc,6BAA6B,0BAA0B,cAAc,qBAAqB;AACxG,iBAAiB,oDAAoD,qEAAqE,cAAc;AACxJ,uBAAuB,sBAAsB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC;AACxC,mCAAmC,SAAS;AAC5C,mCAAmC,WAAW,UAAU;AACxD,0CAA0C,cAAc;AACxD;AACA,8GAA8G,OAAO;AACrH,iFAAiF,iBAAiB;AAClG,yDAAyD,gBAAgB,QAAQ;AACjF,+CAA+C,gBAAgB,gBAAgB;AAC/E;AACA,kCAAkC;AAClC;AACA;AACA,UAAU,YAAY,aAAa,SAAS,UAAU;AACtD,oCAAoC,SAAS;AAC7C;AACA;AACA,qBAAqB,SAAI,IAAI,SAAI;AACjC;AACA;AACA,2GAA2G,uFAAuF,cAAc;AAChN,uBAAuB,8BAA8B,gDAAgD,wDAAwD;AAC7J,6CAA6C,sCAAsC,UAAU,mBAAmB,IAAI;AACpH;AACA,eAAe,SAAI,IAAI,SAAI,4BAA4B;AACvD,wBAAwB,SAAI,IAAI,SAAI;AACpC;AACA;AACA,iBAAiB,uFAAuF,cAAc;AACtH,uBAAuB,gCAAgC,qCAAqC,2CAA2C;AACvI,4BAA4B,MAAM,iBAAiB,YAAY;AAC/D,uBAAuB;AACvB,8BAA8B;AAC9B,6BAA6B;AAC7B,4BAA4B;AAC5B;AACoD;AACE;AACY;AACoB;AACX;AACjB;AACV;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA,iCAAiC,mEAAgB;AACjD;AACA;AACA,yCAAyC,iBAAiB,+DAAc;AACxE,kCAAkC;AAClC,uCAAuC,eAAe,sDAAU;AAChE,uCAAuC,eAAe,sDAAU;AAChE,yCAAyC,iBAAiB,sDAAU;AACpE,uCAAuC,eAAe,sDAAU;AAChE,uCAAuC,eAAe,sDAAU;AAChE,qCAAqC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,wEAAgB;AACrC,oBAAoB,sEAAc;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,wEAAgB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oFAAoF,iEAAU;AAC9F;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,KAAK,EAAE,EAAwB;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,yDAAW,mCAAmC,iEAAU;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,yDAAW;AAC7C;AACA;AACA,kCAAkC,yDAAW;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,yDAAW,yCAAyC,iEAAU;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB;AACnB,SAAS;AACT;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,mEAAsB;AACpD,qBAAqB,6DAAY;AACjC;AACA;AACA,qBAAqB,6DAAY;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,yDAAS;AAC7B;AACA;AACA;AACA;AACA,oBAAoB,wDAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACkB;AACnB;;;;;;;;;;;;;;;;;;;;AC7tBiG;AAC3C;AACA;AACK;AACpD;AACA;AACP;AACA;AACA,yCAAyC,iBAAiB,+DAAc;AACxE,kCAAkC;AAClC,mCAAmC;AACnC,4CAA4C;AAC5C,mCAAmC;AACnC,uCAAuC;AACvC,0CAA0C;AAC1C,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,qBAAqB,0FAA0F,qBAAqB;AACzK;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,mEAAsB;AAC9C,6BAA6B,0DAAS;AACtC;AACA;AACA,YAAY,6DAAY;AACxB;AACA;AACA;AACA,6BAA6B,0DAAS;AACtC;AACA;AACA,YAAY,6DAAY;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,wEAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,oBAAoB;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,oBAAoB;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,yDAAS;AACjB;AACA;AACA;AACA;AACA,QAAQ,wDAAQ;AAChB;AACA;AACA;AACA,CAAC;AACkB;AACnB;;;;;;;;;;;;;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACkB;AACnB;;;;;;;;;;;;;;;;ACXA;AACwC;AACa;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,8DAAkB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,iCAAiC;AACzD;AACA;AACA;AACA;AACA;AACA,+BAA+B,iDAAO;AACtC;AACA;AACA;AACA;AACA,wBAAwB,0BAA0B;AAClD;AACA;AACA;AACA;AACA;AACA,+BAA+B,iDAAO;AACtC;AACA;AACA;AACA,8BAA8B,iDAAO;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,iDAAO;AAC9B;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B;;;;;;;;;;;;;;;;;ACtEwC;AACjC;AACP;AACA;AACA;AACA;AACA,kDAAkD,oBAAoB,GAAG,qBAAqB,MAAM,0BAA0B;AAC9H;AACA,YAAY,kBAAkB;AAC9B,YAAY,mBAAmB;AAC/B;AACO;AACP,8BAA8B;AAC9B,sBAAsB,iDAAO;AAC7B;AACA;AACA;AACA;AACA,6BAA6B,0BAA0B;AACvD;AACA,YAAY,kBAAkB;AAC9B,YAAY,mBAAmB;AAC/B;AACO;AACP,8BAA8B;AAC9B,sBAAsB,iDAAO;AAC7B;AACA;AACA;;;;;;;;;;;;;;;AC5BwC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,8BAA8B;AAC9B,sBAAsB,iDAAO;AAC7B;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;ACbA;AACgD;AACK;AAC9C;AACP,2CAA2C;AAC3C,2CAA2C;AACpC;AACP;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B;AACA;AACA;AACA,QAAQ,wDAAQ;AAChB;AACA;AACA;AACO;AACP;AACA;AACA;AACA,oBAAoB,YAAY;AAChC;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA,qBAAqB;AACrB;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA,gCAAgC;AAChC,sBAAsB,wDAAQ;AAC9B;AACA,qBAAqB;AACrB;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACO;AACP;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;AChGA;AACO;AACP;AACA;AACO;AACP;AACA,qBAAqB;AACrB;AACA;AACA;AACO;AACP;AACA,qBAAqB;AACrB;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;AC1BO;AACP;AACA;AACA;;;;;;;;;;;;;;;ACHO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;ACtBA;AACA;AACuC;AACvC;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,MAAM,gDAAU;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,MAAM,gDAAU;AAChB;AACA;AACA;AACO;AACP;AACA;AACA;AACA;;;;;;UC/JA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;;;;WCtBA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;ACN4C;AAOlB;AACyB;AACoB;;AAE3B;AAChB;AACiB;;AAE7C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC,sCAAsC;AACtC;AACA,wDAAwD;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B,0CAA0C;AAC1C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,wDAAwD,MAAM;AAC9D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA,yCAAyC,oCAAoC;AAC7E;AACA,yCAAyC,oCAAoC;AAC7E;AACA,qCAAqC,gCAAgC;AACrE;AACA;AACA,8BAA8B,6CAA6C;AAC3E;;AAEA;AACA;AACA,wCAAwC,2BAA2B;;AAEnE;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uDAAM;AAClB;AACA,mDAAmD,+BAA+B,cAAc,gBAAgB;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,4BAA4B,oDAAoD,kDAAkD;AACzL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,+BAA+B,gBAAgB,gBAAgB;AAC/H;AACA;AACA,2BAA2B,kCAAkC;AAC7D;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,YAAY,wDAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,8CAA8C,uBAAuB;AACrE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,uEAAuE,WAAW,KAAK,cAAc;AACrG;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,gCAAgC;AAChC,gCAAgC;AAChC,+BAA+B;;AAE/B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iCAAiC,gCAAgC,YAAY,MAAM;AACnF;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,kBAAkB;AACtE;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,mBAAmB,EAAE;AACrB;AACA;AACA,cAAc,YAAY,EAAE;AAC5B;AACA,mBAAmB,EAAE;AACrB;AACA;AACA;;AAEA;AACA;AACA,kEAAkE,UAAU;AAC5E,cAAc;AACd;AACA;AACA;AACA;AACA,2DAA2D,UAAU;AACrE;AACA,cAAc;AACd;AACA,yDAAyD,UAAU;AACnE;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB,+BAA+B;AACxD;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAgB;AAChB;AACA,+CAA+C,WAAW;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC;AACjC;AACA,iCAAiC;AACjC,MAAM;AACN,mDAAmD,IAAI;AACvD;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,OAAO;AAC9D;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,IAAI,uDAAM,0CAA0C,WAAW;AAC/D;AACA;AACA,kCAAkC,uCAAuC;AACzE,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN,2DAA2D,kBAAkB;AAC7E;AACA,0CAA0C,kCAAkC;AAC5E,IAAI;AACJ;AACA,IAAI;AACJ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,uDAAM;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2BAA2B,gEAAa;AACxC;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,uDAAM;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,uDAAM;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,8BAA8B;AAC9B,+BAA+B;AAC/B;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN,oDAAoD,sBAAsB;AAC1E;AACA;AACA;AACA;AACA,2CAA2C,0BAA0B,cAAc,iBAAiB;AACpG;AACA;;AAEA;AACA,kBAAkB,wCAAG;AACrB;AACA;AACA,uBAAuB,8BAA8B;AACrD;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA,sCAAsC,iBAAiB;AACvD;;AAEA;AACA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA,kCAAkC,SAAS;AAC3C;;AAEA;AACA;AACA,IAAI,uDAAM;AACV,IAAI,uDAAM;AACV,oBAAoB;AACpB;AACA;;AAEA;AACA;AACA;AACA,cAAc,gEAAc;AAC5B;AACA;AACA;AACA,oBAAoB,OAAO,oDAAoD;AAC/E;AACA;AACA,KAAK;AACL,GAAG;AACH,cAAc,gEAAc;AAC5B;AACA;AACA;AACA;AACA,oBAAoB,2DAA2D;AAC/E,OAAO;AACP;AACA,KAAK;AACL,GAAG;AACH,gBAAgB,gEAAc;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA,KAAK;AACL,GAAG;AACH,kBAAkB,gEAAc;AAChC;AACA;AACA,kBAAkB,8BAA8B,gBAAgB;AAChE,GAAG;AACH,qBAAqB,gEAAc;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC,oBAAoB;AACpB,uBAAuB,kBAAkB;AACzC,uBAAuB,kBAAkB;AACzC,WAAW;AACX,SAAS;AACT,OAAO;AACP,KAAK;AACL,GAAG;;AAEH,YAAY,gEAAc;AAC1B;AACA;AACA;AACA,oBAAoB,QAAQ,mDAAmD;AAC/E;AACA;AACA,KAAK;AACL,GAAG;;AAEH,UAAU,gEAAc;AACxB;AACA;AACA;AACA;AACA,iBAAiB,uDAAuD;AACxE,mBAAmB,uDAAuD;AAC1E,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,WAAW,gEAAc;AACzB;AACA;AACA;AACA;AACA,iBAAiB,oDAAoD;AACrE,mBAAmB,uDAAuD;AAC1E,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,YAAY,gEAAc;AAC1B;AACA;AACA;AACA;AACA,iBAAiB,uDAAuD;AACxE,mBAAmB,uDAAuD;AAC1E,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,wBAAwB,gEAAc;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,uBAAuB,gEAAc;AACrC;AACA;AACA;AACA;AACA,mBAAmB,wDAAwD;AAC3E;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;AACH,yBAAyB,gEAAc;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,UAAU,qEAAkB,QAAQ,SAAS;AAC7C;AACA,gCAAgC;AAChC;AACA;AACA;AACA,oBAAoB,gEAAc;AAClC,0CAA0C,UAAU,GAAG,SAAS;AAChE;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA,uBAAuB,gEAAc,CAAC,4DAAa;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA,OAAO;AACP,KAAK;AACL,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,kDAAkD,WAAW,GAAG,UAAU;AAC1E,8CAA8C,iBAAiB;AAC/D;;AAEA,sBAAsB,gEAAc;AACpC;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,aAAa,wEAAwE;AAChI;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;;AAEO,uDAAuD;AAC9D,UAAU,mDAAmD;AAC7D,IAAI,gEAAe;AACnB,2BAA2B,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,MAAM;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAgB,iBAAiB;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,YAAY;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;;AAEV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,mBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP;AACA;AACA;AACA,kCAAkC,0BAA0B;AAC5D,MAAM;AACN,yBAAyB,0BAA0B;AACnD;AACA,GAAG;AACH","sources":["webpack://hyphaWebsocketClient/webpack/universalModuleDefinition","webpack://hyphaWebsocketClient/./src/rpc.js","webpack://hyphaWebsocketClient/./src/utils/index.js","webpack://hyphaWebsocketClient/./src/utils/schema.js","webpack://hyphaWebsocketClient/./src/webrtc-client.js","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs","webpack://hyphaWebsocketClient/webpack/bootstrap","webpack://hyphaWebsocketClient/webpack/runtime/define property getters","webpack://hyphaWebsocketClient/webpack/runtime/hasOwnProperty shorthand","webpack://hyphaWebsocketClient/webpack/runtime/make namespace object","webpack://hyphaWebsocketClient/./src/websocket-client.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"hyphaWebsocketClient\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"hyphaWebsocketClient\"] = factory();\n\telse\n\t\troot[\"hyphaWebsocketClient\"] = factory();\n})(this, () => {\nreturn ","/**\n * Contains the RPC object used both by the application\n * site, and by each plugin\n */\nimport {\n randId,\n typedArrayToDtype,\n dtypeToTypedArray,\n MessageEmitter,\n assert,\n waitFor,\n convertCase,\n expandKwargs,\n Semaphore,\n isAsyncGenerator,\n isGenerator,\n} from \"./utils/index.js\";\nimport { schemaFunction } from \"./utils/schema.js\";\n\nimport { encode as msgpack_packb, decodeMulti } from \"@msgpack/msgpack\";\n\nexport const API_VERSION = 3;\nconst CHUNK_SIZE = 1024 * 256;\nconst CONCURRENCY_LIMIT = 30;\n\nconst ArrayBufferView = Object.getPrototypeOf(\n Object.getPrototypeOf(new Uint8Array()),\n).constructor;\n\nfunction _appendBuffer(buffer1, buffer2) {\n const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);\n tmp.set(new Uint8Array(buffer1), 0);\n tmp.set(new Uint8Array(buffer2), buffer1.byteLength);\n return tmp.buffer;\n}\n\nfunction indexObject(obj, is) {\n if (!is) throw new Error(\"undefined index\");\n if (typeof is === \"string\") return indexObject(obj, is.split(\".\"));\n else if (is.length === 0) return obj;\n else return indexObject(obj[is[0]], is.slice(1));\n}\n\n// Simple fallback schema generation - no docstring parsing for JS\n\nfunction _get_schema(obj, name = null, skipContext = false) {\n if (Array.isArray(obj)) {\n return obj.map((v, i) => _get_schema(v, null, skipContext));\n } else if (typeof obj === \"object\" && obj !== null) {\n let schema = {};\n for (let k in obj) {\n schema[k] = _get_schema(obj[k], k, skipContext);\n }\n return schema;\n } else if (typeof obj === \"function\") {\n if (obj.__schema__) {\n const schema = JSON.parse(JSON.stringify(obj.__schema__));\n if (name) {\n schema.name = name;\n obj.__schema__.name = name;\n }\n if (skipContext) {\n if (schema.parameters && schema.parameters.properties) {\n delete schema.parameters.properties[\"context\"];\n }\n if (schema.parameters && schema.parameters.required) {\n const contextIndex = schema.parameters.required.indexOf(\"context\");\n if (contextIndex > -1) {\n schema.parameters.required.splice(contextIndex, 1);\n }\n }\n }\n return { type: \"function\", function: schema };\n } else {\n // Simple fallback for JavaScript - just return basic function schema with name\n const funcName = name || obj.name || \"function\";\n return {\n type: \"function\",\n function: {\n name: funcName,\n },\n };\n }\n } else if (typeof obj === \"number\") {\n return { type: \"number\" };\n } else if (typeof obj === \"string\") {\n return { type: \"string\" };\n } else if (typeof obj === \"boolean\") {\n return { type: \"boolean\" };\n } else if (obj === null) {\n return { type: \"null\" };\n } else {\n return {};\n }\n}\n\nfunction _annotate_service(service, serviceTypeInfo) {\n function validateKeys(serviceDict, schemaDict, path = \"root\") {\n // Validate that all keys in schemaDict exist in serviceDict\n for (let key in schemaDict) {\n if (!serviceDict.hasOwnProperty(key)) {\n throw new Error(`Missing key '${key}' in service at path '${path}'`);\n }\n }\n\n // Check for any unexpected keys in serviceDict\n for (let key in serviceDict) {\n if (key !== \"type\" && !schemaDict.hasOwnProperty(key)) {\n throw new Error(`Unexpected key '${key}' in service at path '${path}'`);\n }\n }\n }\n\n function annotateRecursive(newService, schemaInfo, path = \"root\") {\n if (typeof newService === \"object\" && !Array.isArray(newService)) {\n validateKeys(newService, schemaInfo, path);\n for (let k in newService) {\n let v = newService[k];\n let newPath = `${path}.${k}`;\n if (typeof v === \"object\" && !Array.isArray(v)) {\n annotateRecursive(v, schemaInfo[k], newPath);\n } else if (typeof v === \"function\") {\n if (schemaInfo.hasOwnProperty(k)) {\n newService[k] = schemaFunction(v, {\n name: schemaInfo[k][\"name\"],\n description: schemaInfo[k].description || \"\",\n parameters: schemaInfo[k][\"parameters\"],\n });\n } else {\n throw new Error(\n `Missing schema for function '${k}' at path '${newPath}'`,\n );\n }\n }\n }\n } else if (Array.isArray(newService)) {\n if (newService.length !== schemaInfo.length) {\n throw new Error(`Length mismatch at path '${path}'`);\n }\n newService.forEach((v, i) => {\n let newPath = `${path}[${i}]`;\n if (typeof v === \"object\" && !Array.isArray(v)) {\n annotateRecursive(v, schemaInfo[i], newPath);\n } else if (typeof v === \"function\") {\n if (schemaInfo.hasOwnProperty(i)) {\n newService[i] = schemaFunction(v, {\n name: schemaInfo[i][\"name\"],\n description: schemaInfo[i].description || \"\",\n parameters: schemaInfo[i][\"parameters\"],\n });\n } else {\n throw new Error(\n `Missing schema for function at index ${i} in path '${newPath}'`,\n );\n }\n }\n });\n }\n }\n\n validateKeys(service, serviceTypeInfo[\"definition\"]);\n annotateRecursive(service, serviceTypeInfo[\"definition\"]);\n return service;\n}\n\nfunction getFunctionInfo(func) {\n const funcString = func.toString();\n\n // Extract function name\n const nameMatch = funcString.match(/function\\s*(\\w*)/);\n const name = (nameMatch && nameMatch[1]) || \"\";\n\n // Extract function parameters, excluding comments\n const paramsMatch = funcString.match(/\\(([^)]*)\\)/);\n let params = \"\";\n if (paramsMatch) {\n params = paramsMatch[1]\n .split(\",\")\n .map((p) =>\n p\n .replace(/\\/\\*.*?\\*\\//g, \"\") // Remove block comments\n .replace(/\\/\\/.*$/g, \"\"),\n ) // Remove line comments\n .filter((p) => p.trim().length > 0) // Remove empty strings after removing comments\n .map((p) => p.trim()) // Trim remaining whitespace\n .join(\", \");\n }\n\n // Extract function docstring (block comment)\n let docMatch = funcString.match(/\\)\\s*\\{\\s*\\/\\*([\\s\\S]*?)\\*\\//);\n const docstringBlock = (docMatch && docMatch[1].trim()) || \"\";\n\n // Extract function docstring (line comment)\n docMatch = funcString.match(/\\)\\s*\\{\\s*(\\/\\/[\\s\\S]*?)\\n\\s*[^\\s\\/]/);\n const docstringLine =\n (docMatch &&\n docMatch[1]\n .split(\"\\n\")\n .map((s) => s.replace(/^\\/\\/\\s*/, \"\").trim())\n .join(\"\\n\")) ||\n \"\";\n\n const docstring = docstringBlock || docstringLine;\n return (\n name &&\n params.length > 0 && {\n name: name,\n sig: params,\n doc: docstring,\n }\n );\n}\n\nfunction concatArrayBuffers(buffers) {\n var buffersLengths = buffers.map(function (b) {\n return b.byteLength;\n }),\n totalBufferlength = buffersLengths.reduce(function (p, c) {\n return p + c;\n }, 0),\n unit8Arr = new Uint8Array(totalBufferlength);\n buffersLengths.reduce(function (p, c, i) {\n unit8Arr.set(new Uint8Array(buffers[i]), p);\n return p + c;\n }, 0);\n return unit8Arr.buffer;\n}\n\nclass Timer {\n constructor(timeout, callback, args, label) {\n this._timeout = timeout;\n this._callback = callback;\n this._args = args;\n this._label = label || \"timer\";\n this._task = null;\n this.started = false;\n }\n\n start() {\n if (this.started) {\n this.reset();\n } else {\n this._task = setTimeout(() => {\n this._callback.apply(this, this._args);\n }, this._timeout * 1000);\n this.started = true;\n }\n }\n\n clear() {\n if (this._task && this.started) {\n clearTimeout(this._task);\n this._task = null;\n this.started = false;\n } else {\n console.warn(`Clearing a timer (${this._label}) which is not started`);\n }\n }\n\n reset() {\n if (this._task) {\n clearTimeout(this._task);\n }\n this._task = setTimeout(() => {\n this._callback.apply(this, this._args);\n }, this._timeout * 1000);\n this.started = true;\n }\n}\n\nclass RemoteService extends Object {}\n\n/**\n * RPC object represents a single site in the\n * communication protocol between the application and the plugin\n *\n * @param {Object} connection a special object allowing to send\n * and receive messages from the opposite site (basically it\n * should only provide send() and onMessage() methods)\n */\nexport class RPC extends MessageEmitter {\n constructor(\n connection,\n {\n client_id = null,\n default_context = null,\n name = null,\n codecs = null,\n method_timeout = null,\n max_message_buffer_size = 0,\n debug = false,\n workspace = null,\n silent = false,\n app_id = null,\n server_base_url = null,\n long_message_chunk_size = null,\n },\n ) {\n super(debug);\n this._codecs = codecs || {};\n assert(client_id && typeof client_id === \"string\");\n assert(client_id, \"client_id is required\");\n this._client_id = client_id;\n this._name = name;\n this._app_id = app_id || \"*\";\n this._local_workspace = workspace;\n this._silent = silent;\n this.default_context = default_context || {};\n this._method_annotations = new WeakMap();\n this._max_message_buffer_size = max_message_buffer_size;\n this._chunk_store = {};\n this._method_timeout = method_timeout || 30;\n this._server_base_url = server_base_url;\n this._long_message_chunk_size = long_message_chunk_size || CHUNK_SIZE;\n\n // make sure there is an execute function\n this._services = {};\n this._object_store = {\n services: this._services,\n };\n\n // Set up global unhandled promise rejection handler for RPC-related errors\n const handleUnhandledRejection = (event) => {\n const reason = event.reason;\n if (reason && typeof reason === \"object\") {\n // Check if this is a \"Method not found\" or \"Session not found\" error that we can ignore\n const reasonStr = reason.toString();\n if (\n reasonStr.includes(\"Method not found\") ||\n reasonStr.includes(\"Session not found\") ||\n reasonStr.includes(\"Method expired\") ||\n reasonStr.includes(\"Session not found\")\n ) {\n console.debug(\n \"Ignoring expected method/session not found error:\",\n reason,\n );\n event.preventDefault(); // Prevent the default unhandled rejection behavior\n return;\n }\n }\n console.warn(\"Unhandled RPC promise rejection:\", reason);\n };\n\n // Only set the handler if we haven't already set one for this RPC instance\n if (typeof window !== \"undefined\" && !window._hypha_rejection_handler_set) {\n window.addEventListener(\"unhandledrejection\", handleUnhandledRejection);\n window._hypha_rejection_handler_set = true;\n } else if (\n typeof process !== \"undefined\" &&\n !process._hypha_rejection_handler_set\n ) {\n process.on(\"unhandledRejection\", (reason, promise) => {\n handleUnhandledRejection({ reason, promise, preventDefault: () => {} });\n });\n process._hypha_rejection_handler_set = true;\n }\n\n if (connection) {\n this.add_service({\n id: \"built-in\",\n type: \"built-in\",\n name: `Built-in services for ${this._local_workspace}/${this._client_id}`,\n config: {\n require_context: true,\n visibility: \"public\",\n api_version: API_VERSION,\n },\n ping: this._ping.bind(this),\n get_service: this.get_local_service.bind(this),\n message_cache: {\n create: this._create_message.bind(this),\n append: this._append_message.bind(this),\n set: this._set_message.bind(this),\n process: this._process_message.bind(this),\n remove: this._remove_message.bind(this),\n },\n });\n this.on(\"method\", this._handle_method.bind(this));\n this.on(\"error\", console.error);\n\n assert(connection.emit_message && connection.on_message);\n assert(\n connection.manager_id !== undefined,\n \"Connection must have manager_id\",\n );\n this._emit_message = connection.emit_message.bind(connection);\n connection.on_message(this._on_message.bind(this));\n this._connection = connection;\n const onConnected = async (connectionInfo) => {\n if (!this._silent && this._connection.manager_id) {\n console.debug(\"Connection established, reporting services...\");\n try {\n // Retry getting manager service with exponential backoff\n const manager = await this._get_manager_with_retry();\n const services = Object.values(this._services);\n const servicesCount = services.length;\n let registeredCount = 0;\n const failedServices = [];\n\n for (let service of services) {\n try {\n const serviceInfo = this._extract_service_info(service);\n await manager.registerService(serviceInfo);\n registeredCount++;\n console.debug(\n `Successfully registered service: ${service.id || \"unknown\"}`,\n );\n } catch (serviceError) {\n failedServices.push(service.id || \"unknown\");\n console.error(\n `Failed to register service ${service.id || \"unknown\"}: ${serviceError}`,\n );\n }\n }\n\n if (registeredCount === servicesCount) {\n console.info(\n `Successfully registered all ${registeredCount} services with the server`,\n );\n } else {\n console.warn(\n `Only registered ${registeredCount} out of ${servicesCount} services with the server. Failed services: ${failedServices.join(\", \")}`,\n );\n }\n\n // Fire event with registration status\n this._fire(\"services_registered\", {\n total: servicesCount,\n registered: registeredCount,\n failed: failedServices,\n });\n } catch (managerError) {\n console.error(\n `Failed to get manager service for registering services: ${managerError}`,\n );\n // Fire event with error status\n this._fire(\"services_registration_failed\", {\n error: managerError.toString(),\n total_services: Object.keys(this._services).length,\n });\n }\n } else {\n // console.debug(\"Connection established\", connectionInfo);\n }\n if (connectionInfo) {\n if (connectionInfo.public_base_url) {\n this._server_base_url = connectionInfo.public_base_url;\n }\n this._fire(\"connected\", connectionInfo);\n }\n };\n connection.on_connected(onConnected);\n onConnected();\n } else {\n this._emit_message = function () {\n console.log(\"No connection to emit message\");\n };\n }\n }\n\n register_codec(config) {\n if (!config[\"name\"] || (!config[\"encoder\"] && !config[\"decoder\"])) {\n throw new Error(\n \"Invalid codec format, please make sure you provide a name, type, encoder and decoder.\",\n );\n } else {\n if (config.type) {\n for (let k of Object.keys(this._codecs)) {\n if (this._codecs[k].type === config.type || k === config.name) {\n delete this._codecs[k];\n console.warn(\"Remove duplicated codec: \" + k);\n }\n }\n }\n this._codecs[config[\"name\"]] = config;\n }\n }\n\n async _ping(msg, context) {\n assert(msg == \"ping\");\n return \"pong\";\n }\n\n async ping(client_id, timeout) {\n let method = this._generate_remote_method({\n _rserver: this._server_base_url,\n _rtarget: client_id,\n _rmethod: \"services.built-in.ping\",\n _rpromise: true,\n _rdoc: \"Ping a remote client\",\n });\n assert((await method(\"ping\", timeout)) == \"pong\");\n }\n\n _create_message(key, heartbeat, overwrite, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n\n if (!this._object_store[\"message_cache\"]) {\n this._object_store[\"message_cache\"] = {};\n }\n if (!overwrite && this._object_store[\"message_cache\"][key]) {\n throw new Error(\n `Message with the same key (${key}) already exists in the cache store, please use overwrite=true or remove it first.`,\n );\n }\n this._object_store[\"message_cache\"][key] = [];\n }\n\n _append_message(key, data, heartbeat, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n const cache = this._object_store[\"message_cache\"];\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n assert(data instanceof ArrayBufferView);\n cache[key].push(data);\n }\n\n _set_message(key, index, data, heartbeat, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n const cache = this._object_store[\"message_cache\"];\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n assert(data instanceof ArrayBufferView);\n cache[key][index] = data;\n }\n\n _remove_message(key, context) {\n const cache = this._object_store[\"message_cache\"];\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n delete cache[key];\n }\n\n _process_message(key, heartbeat, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n const cache = this._object_store[\"message_cache\"];\n assert(!!context, \"Context is required\");\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n cache[key] = concatArrayBuffers(cache[key]);\n // console.debug(`Processing message ${key} (bytes=${cache[key].byteLength})`);\n let unpacker = decodeMulti(cache[key]);\n const { done, value } = unpacker.next();\n const main = value;\n // Make sure the fields are from trusted source\n Object.assign(main, {\n from: context.from,\n to: context.to,\n ws: context.ws,\n user: context.user,\n });\n main[\"ctx\"] = JSON.parse(JSON.stringify(main));\n Object.assign(main[\"ctx\"], this.default_context);\n if (!done) {\n let extra = unpacker.next();\n Object.assign(main, extra.value);\n }\n this._fire(main[\"type\"], main);\n // console.debug(\n // this._client_id,\n // `Processed message ${key} (bytes=${cache[key].byteLength})`,\n // );\n delete cache[key];\n }\n\n _on_message(message) {\n if (typeof message === \"string\") {\n const main = JSON.parse(message);\n // Add trusted context to the method call\n main[\"ctx\"] = JSON.parse(JSON.stringify(main));\n Object.assign(main[\"ctx\"], this.default_context);\n this._fire(main[\"type\"], main);\n } else if (message instanceof ArrayBuffer) {\n let unpacker = decodeMulti(message);\n const { done, value } = unpacker.next();\n const main = value;\n // Add trusted context to the method call\n main[\"ctx\"] = JSON.parse(JSON.stringify(main));\n Object.assign(main[\"ctx\"], this.default_context);\n if (!done) {\n let extra = unpacker.next();\n Object.assign(main, extra.value);\n }\n this._fire(main[\"type\"], main);\n } else if (typeof message === \"object\") {\n // Add trusted context to the method call\n message[\"ctx\"] = JSON.parse(JSON.stringify(message));\n Object.assign(message[\"ctx\"], this.default_context);\n this._fire(message[\"type\"], message);\n } else {\n throw new Error(\"Invalid message format\");\n }\n }\n\n reset() {\n this._event_handlers = {};\n this._services = {};\n }\n\n close() {\n // Clear all heartbeat intervals\n for (const session_id in this._object_store) {\n if (this._object_store.hasOwnProperty(session_id)) {\n const session = this._object_store[session_id];\n if (session && session.heartbeat_task) {\n clearInterval(session.heartbeat_task);\n }\n if (session && session.timer) {\n session.timer.clear();\n }\n }\n }\n this._fire(\"disconnected\");\n }\n\n async disconnect() {\n this.close();\n await this._connection.disconnect();\n }\n\n async _get_manager_with_retry(maxRetries = 20) {\n const baseDelay = 500;\n const maxDelay = 10000;\n let lastError = null;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n const svc = await this.get_remote_service(\n `*/${this._connection.manager_id}:default`,\n { timeout: 20, case_conversion: \"camel\" },\n );\n return svc;\n } catch (e) {\n lastError = e;\n console.warn(\n `Failed to get manager service (attempt ${attempt + 1}/${maxRetries}): ${e.message}`,\n );\n if (attempt < maxRetries - 1) {\n // Exponential backoff with maximum delay\n const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n // If we get here, all retries failed\n throw lastError;\n }\n\n async get_manager_service(config) {\n config = config || {};\n\n // Add retry logic\n const maxRetries = 20;\n const retryDelay = 500; // 500ms\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n if (!this._connection.manager_id) {\n if (attempt < maxRetries - 1) {\n console.warn(\n `Manager ID not set, retrying in ${retryDelay}ms (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n continue;\n } else {\n throw new Error(\"Manager ID not set after maximum retries\");\n }\n }\n\n try {\n const svc = await this.get_remote_service(\n `*/${this._connection.manager_id}:default`,\n config,\n );\n return svc;\n } catch (e) {\n if (attempt < maxRetries - 1) {\n console.warn(\n `Failed to get manager service, retrying in ${retryDelay}ms: ${e.message}`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n } else {\n throw e;\n }\n }\n }\n }\n\n get_all_local_services() {\n return this._services;\n }\n get_local_service(service_id, context) {\n assert(service_id);\n assert(context, \"Context is required\");\n\n const [ws, client_id] = context[\"to\"].split(\"/\");\n assert(\n client_id === this._client_id,\n \"Services can only be accessed locally\",\n );\n\n const service = this._services[service_id];\n if (!service) {\n throw new Error(\"Service not found: \" + service_id);\n }\n\n service.config[\"workspace\"] = context[\"ws\"];\n // allow access for the same workspace\n if (\n service.config.visibility == \"public\" ||\n service.config.visibility == \"unlisted\"\n ) {\n return service;\n }\n\n // allow access for the same workspace\n if (context[\"ws\"] === ws) {\n return service;\n }\n\n // Check if user is from an authorized workspace\n const authorized_workspaces = service.config.authorized_workspaces;\n if (\n authorized_workspaces &&\n authorized_workspaces.includes(context[\"ws\"])\n ) {\n return service;\n }\n\n throw new Error(\n `Permission denied for getting protected service: ${service_id}, workspace mismatch: ${ws} != ${context[\"ws\"]}`,\n );\n }\n async get_remote_service(service_uri, config) {\n let { timeout, case_conversion, kwargs_expansion } = config || {};\n timeout = timeout === undefined ? this._method_timeout : timeout;\n if (!service_uri && this._connection.manager_id) {\n service_uri = \"*/\" + this._connection.manager_id;\n } else if (!service_uri.includes(\":\")) {\n service_uri = this._client_id + \":\" + service_uri;\n }\n const provider = service_uri.split(\":\")[0];\n let service_id = service_uri.split(\":\")[1];\n if (service_id.includes(\"@\")) {\n service_id = service_id.split(\"@\")[0];\n const app_id = service_uri.split(\"@\")[1];\n if (this._app_id && this._app_id !== \"*\")\n assert(\n app_id === this._app_id,\n `Invalid app id: ${app_id} != ${this._app_id}`,\n );\n }\n assert(provider, `Invalid service uri: ${service_uri}`);\n\n try {\n const method = this._generate_remote_method({\n _rserver: this._server_base_url,\n _rtarget: provider,\n _rmethod: \"services.built-in.get_service\",\n _rpromise: true,\n _rdoc: \"Get a remote service\",\n });\n let svc = await waitFor(\n method(service_id),\n timeout,\n \"Timeout Error: Failed to get remote service: \" + service_uri,\n );\n svc.id = `${provider}:${service_id}`;\n if (kwargs_expansion) {\n svc = expandKwargs(svc);\n }\n if (case_conversion)\n return Object.assign(\n new RemoteService(),\n convertCase(svc, case_conversion),\n );\n else return Object.assign(new RemoteService(), svc);\n } catch (e) {\n console.warn(\"Failed to get remote service: \" + service_uri, e);\n throw e;\n }\n }\n _annotate_service_methods(\n aObject,\n object_id,\n require_context,\n run_in_executor,\n visibility,\n authorized_workspaces,\n ) {\n if (typeof aObject === \"function\") {\n // mark the method as a remote method that requires context\n let method_name = object_id.split(\".\")[1];\n this._method_annotations.set(aObject, {\n require_context: Array.isArray(require_context)\n ? require_context.includes(method_name)\n : !!require_context,\n run_in_executor: run_in_executor,\n method_id: \"services.\" + object_id,\n visibility: visibility,\n authorized_workspaces: authorized_workspaces,\n });\n } else if (aObject instanceof Array || aObject instanceof Object) {\n for (let key of Object.keys(aObject)) {\n let val = aObject[key];\n if (typeof val === \"function\" && val.__rpc_object__) {\n let client_id = val.__rpc_object__._rtarget;\n if (client_id.includes(\"/\")) {\n client_id = client_id.split(\"/\")[1];\n }\n if (this._client_id === client_id) {\n if (aObject instanceof Array) {\n aObject = aObject.slice();\n }\n // recover local method\n aObject[key] = indexObject(\n this._object_store,\n val.__rpc_object__._rmethod,\n );\n val = aObject[key]; // make sure it's annotated later\n } else {\n throw new Error(\n `Local method not found: ${val.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${client_id}`,\n );\n }\n }\n this._annotate_service_methods(\n val,\n object_id + \".\" + key,\n require_context,\n run_in_executor,\n visibility,\n authorized_workspaces,\n );\n }\n }\n }\n add_service(api, overwrite) {\n if (!api || Array.isArray(api)) throw new Error(\"Invalid service object\");\n if (api.constructor === Object) {\n api = Object.assign({}, api);\n } else {\n const normApi = {};\n const props = Object.getOwnPropertyNames(api).concat(\n Object.getOwnPropertyNames(Object.getPrototypeOf(api)),\n );\n for (let k of props) {\n if (k !== \"constructor\") {\n if (typeof api[k] === \"function\") normApi[k] = api[k].bind(api);\n else normApi[k] = api[k];\n }\n }\n // For class instance, we need set a default id\n api.id = api.id || \"default\";\n api = normApi;\n }\n assert(\n api.id && typeof api.id === \"string\",\n `Service id not found: ${api}`,\n );\n if (!api.name) {\n api.name = api.id;\n }\n if (!api.config) {\n api.config = {};\n }\n if (!api.type) {\n api.type = \"generic\";\n }\n // require_context only applies to the top-level functions\n let require_context = false,\n run_in_executor = false;\n if (api.config.require_context)\n require_context = api.config.require_context;\n if (api.config.run_in_executor) run_in_executor = true;\n const visibility = api.config.visibility || \"protected\";\n assert([\"protected\", \"public\", \"unlisted\"].includes(visibility));\n\n // Validate authorized_workspaces\n const authorized_workspaces = api.config.authorized_workspaces;\n if (authorized_workspaces !== undefined) {\n if (visibility !== \"protected\") {\n throw new Error(\n `authorized_workspaces can only be set when visibility is 'protected', got visibility='${visibility}'`,\n );\n }\n if (!Array.isArray(authorized_workspaces)) {\n throw new Error(\n \"authorized_workspaces must be an array of workspace ids\",\n );\n }\n for (const ws_id of authorized_workspaces) {\n if (typeof ws_id !== \"string\") {\n throw new Error(\n `Each workspace id in authorized_workspaces must be a string, got ${typeof ws_id}`,\n );\n }\n }\n }\n this._annotate_service_methods(\n api,\n api[\"id\"],\n require_context,\n run_in_executor,\n visibility,\n authorized_workspaces,\n );\n\n if (this._services[api.id]) {\n if (overwrite) {\n delete this._services[api.id];\n } else {\n throw new Error(\n `Service already exists: ${api.id}, please specify a different id (not ${api.id}) or overwrite=true`,\n );\n }\n }\n this._services[api.id] = api;\n return api;\n }\n\n _extract_service_info(service) {\n const config = service.config || {};\n config.workspace =\n config.workspace || this._local_workspace || this._connection.workspace;\n const skipContext = config.require_context;\n const excludeKeys = [\n \"id\",\n \"config\",\n \"name\",\n \"description\",\n \"type\",\n \"docs\",\n \"app_id\",\n \"service_schema\",\n ];\n const filteredService = {};\n for (const key of Object.keys(service)) {\n if (!excludeKeys.includes(key)) {\n filteredService[key] = service[key];\n }\n }\n const serviceSchema = _get_schema(filteredService, null, skipContext);\n const serviceInfo = {\n config: config,\n id: `${config.workspace}/${this._client_id}:${service[\"id\"]}`,\n name: service.name || service[\"id\"],\n description: service.description || \"\",\n type: service.type || \"generic\",\n docs: service.docs || null,\n app_id: this._app_id,\n service_schema: serviceSchema,\n };\n return serviceInfo;\n }\n\n async get_service_schema(service) {\n const skipContext = service.config.require_context;\n return _get_schema(service, null, skipContext);\n }\n\n async register_service(api, config) {\n let { check_type, notify, overwrite } = config || {};\n notify = notify === undefined ? true : notify;\n let manager;\n if (check_type && api.type) {\n try {\n manager = await this.get_manager_service({\n timeout: 10,\n case_conversion: \"camel\",\n });\n const type_info = await manager.get_service_type(api.type);\n api = _annotate_service(api, type_info);\n } catch (e) {\n throw new Error(`Failed to get service type ${api.type}, error: ${e}`);\n }\n }\n\n const service = this.add_service(api, overwrite);\n const serviceInfo = this._extract_service_info(service);\n if (notify) {\n try {\n manager =\n manager ||\n (await this.get_manager_service({\n timeout: 10,\n case_conversion: \"camel\",\n }));\n await manager.registerService(serviceInfo);\n } catch (e) {\n throw new Error(`Failed to notify workspace manager: ${e}`);\n }\n }\n return serviceInfo;\n }\n\n async unregister_service(service, notify) {\n notify = notify === undefined ? true : notify;\n let service_id;\n if (typeof service === \"string\") {\n service_id = service;\n } else {\n service_id = service.id;\n }\n assert(\n service_id && typeof service_id === \"string\",\n `Invalid service id: ${service_id}`,\n );\n if (service_id.includes(\":\")) {\n service_id = service_id.split(\":\")[1];\n }\n if (service_id.includes(\"@\")) {\n service_id = service_id.split(\"@\")[0];\n }\n if (!this._services[service_id]) {\n throw new Error(`Service not found: ${service_id}`);\n }\n if (notify) {\n const manager = await this.get_manager_service({\n timeout: 10,\n case_conversion: \"camel\",\n });\n await manager.unregisterService(service_id);\n }\n delete this._services[service_id];\n }\n\n _ndarray(typedArray, shape, dtype) {\n const _dtype = typedArrayToDtype(typedArray);\n if (dtype && dtype !== _dtype) {\n throw (\n \"dtype doesn't match the type of the array: \" + _dtype + \" != \" + dtype\n );\n }\n shape = shape || [typedArray.length];\n return {\n _rtype: \"ndarray\",\n _rvalue: typedArray.buffer,\n _rshape: shape,\n _rdtype: _dtype,\n };\n }\n\n _encode_callback(\n name,\n callback,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n description,\n ) {\n let method_id = `${session_id}.${name}`;\n let encoded = {\n _rtype: \"method\",\n _rtarget: local_workspace\n ? `${local_workspace}/${this._client_id}`\n : this._client_id,\n _rmethod: method_id,\n _rpromise: false,\n };\n\n const self = this;\n let wrapped_callback = function () {\n try {\n callback.apply(null, Array.prototype.slice.call(arguments));\n } catch (error) {\n console.error(\n `Error in callback(${method_id}, ${description}): ${error}`,\n );\n } finally {\n // Clear the timer first if it exists\n if (timer && timer.started) {\n timer.clear();\n }\n\n // Clean up the entire session when resolve/reject is called\n if (clear_after_called && self._object_store[session_id]) {\n // For promise callbacks (resolve/reject), clean up the entire session\n if (name === \"resolve\" || name === \"reject\") {\n delete self._object_store[session_id];\n } else {\n // For other callbacks, just clean up this specific callback\n self._cleanup_session_if_needed(session_id, name);\n }\n }\n }\n };\n wrapped_callback.__name__ = `callback(${method_id})`;\n return [encoded, wrapped_callback];\n }\n\n _cleanup_session_if_needed(session_id, callback_name) {\n /**\n * Clean session management - all logic in one place.\n */\n if (!session_id) {\n console.debug(\"Cannot cleanup session: session_id is empty\");\n return;\n }\n\n try {\n const store = this._get_session_store(session_id, false);\n if (!store) {\n console.debug(`Session ${session_id} not found for cleanup`);\n return;\n }\n\n let should_cleanup = false;\n\n // Promise sessions: let the promise manager decide cleanup\n if (store._promise_manager) {\n try {\n const promise_manager = store._promise_manager;\n if (\n promise_manager.should_cleanup_on_callback &&\n promise_manager.should_cleanup_on_callback(callback_name)\n ) {\n if (promise_manager.settle) {\n promise_manager.settle();\n }\n should_cleanup = true;\n console.debug(\n `Promise session ${session_id} settled and marked for cleanup`,\n );\n }\n } catch (e) {\n console.warn(\n `Error in promise manager cleanup for session ${session_id}:`,\n e,\n );\n }\n } else {\n // Regular sessions: only cleanup temporary method call sessions\n // Don't cleanup service registration sessions or persistent sessions\n // Only cleanup sessions that are clearly temporary promises for method calls\n if (\n (callback_name === \"resolve\" || callback_name === \"reject\") &&\n store._callbacks &&\n Object.keys(store._callbacks).includes(callback_name)\n ) {\n should_cleanup = true;\n console.debug(\n `Regular session ${session_id} marked for cleanup after ${callback_name}`,\n );\n }\n }\n\n if (should_cleanup) {\n this._cleanup_session_completely(session_id);\n }\n } catch (error) {\n console.warn(`Error during session cleanup for ${session_id}:`, error);\n }\n }\n\n _cleanup_session_completely(session_id) {\n /**\n * Complete session cleanup with resource management.\n */\n try {\n const store = this._get_session_store(session_id, false);\n if (!store) {\n console.debug(`Session ${session_id} already cleaned up`);\n return;\n }\n\n // Clean up resources before removing session\n if (store.timer && typeof store.timer.clear === \"function\") {\n try {\n store.timer.clear();\n } catch (error) {\n console.warn(\n `Error clearing timer for session ${session_id}:`,\n error,\n );\n }\n }\n\n if (\n store.heartbeat_task &&\n typeof store.heartbeat_task.cancel === \"function\"\n ) {\n try {\n store.heartbeat_task.cancel();\n } catch (error) {\n console.warn(\n `Error canceling heartbeat for session ${session_id}:`,\n error,\n );\n }\n }\n\n // Navigate and clean session path\n const levels = session_id.split(\".\");\n let current_store = this._object_store;\n\n // Navigate to parent of target level\n for (let i = 0; i < levels.length - 1; i++) {\n const level = levels[i];\n if (!current_store[level]) {\n console.debug(\n `Session path ${session_id} not found at level ${level}`,\n );\n return;\n }\n current_store = current_store[level];\n }\n\n // Delete the final level\n const final_key = levels[levels.length - 1];\n if (current_store[final_key]) {\n delete current_store[final_key];\n console.debug(`Cleaned up session ${session_id}`);\n\n // Clean up empty parent containers\n this._cleanup_empty_containers(levels.slice(0, -1));\n }\n } catch (error) {\n console.warn(\n `Error in complete session cleanup for ${session_id}:`,\n error,\n );\n }\n }\n\n _cleanup_empty_containers(path_levels) {\n /**\n * Clean up empty parent containers to prevent memory leaks.\n */\n try {\n // Work backwards from the deepest level\n for (let depth = path_levels.length - 1; depth >= 0; depth--) {\n let current_store = this._object_store;\n\n // Navigate to parent of current depth\n for (let i = 0; i < depth; i++) {\n current_store = current_store[path_levels[i]];\n if (!current_store) return; // Path doesn't exist\n }\n\n // Check if container at current depth is empty\n const container_key = path_levels[depth];\n const container = current_store[container_key];\n\n if (\n container &&\n typeof container === \"object\" &&\n Object.keys(container).length === 0\n ) {\n delete current_store[container_key];\n console.debug(\n `Cleaned up empty container at depth ${depth}: ${path_levels.slice(0, depth + 1).join(\".\")}`,\n );\n } else {\n // Container is not empty, stop cleanup\n break;\n }\n }\n } catch (error) {\n console.warn(\"Error cleaning up empty containers:\", error);\n }\n }\n\n get_session_stats() {\n /**\n * Get detailed session statistics.\n */\n const stats = {\n total_sessions: 0,\n promise_sessions: 0,\n regular_sessions: 0,\n sessions_with_timers: 0,\n sessions_with_heartbeat: 0,\n system_stores: {},\n session_ids: [],\n memory_usage: 0,\n };\n\n if (!this._object_store) {\n return stats;\n }\n\n for (const key in this._object_store) {\n const value = this._object_store[key];\n\n if ([\"services\", \"message_cache\"].includes(key)) {\n // System stores - don't count these as sessions\n stats.system_stores[key] = {\n size:\n typeof value === \"object\" && value ? Object.keys(value).length : 0,\n };\n continue;\n }\n\n // Count all non-system non-empty objects as sessions\n if (value && typeof value === \"object\") {\n const sessionKeys = Object.keys(value);\n\n // Only skip completely empty objects\n if (sessionKeys.length > 0) {\n stats.total_sessions++;\n stats.session_ids.push(key);\n\n if (value._promise_manager) {\n stats.promise_sessions++;\n } else {\n stats.regular_sessions++;\n }\n\n if (value._timer || value.timer) stats.sessions_with_timers++;\n if (value._heartbeat || value.heartbeat)\n stats.sessions_with_heartbeat++;\n\n // Estimate memory usage\n stats.memory_usage += JSON.stringify(value).length;\n }\n }\n }\n\n return stats;\n }\n\n _force_cleanup_all_sessions() {\n /**\n * Force cleanup all sessions (for testing purposes).\n */\n if (!this._object_store) {\n console.debug(\"Force cleaning up 0 sessions\");\n return;\n }\n\n let cleaned_count = 0;\n const keys_to_delete = [];\n\n for (const key in this._object_store) {\n // Don't delete system stores\n if (![\"services\", \"message_cache\"].includes(key)) {\n const value = this._object_store[key];\n if (\n value &&\n typeof value === \"object\" &&\n Object.keys(value).length > 0\n ) {\n keys_to_delete.push(key);\n cleaned_count++;\n }\n }\n }\n\n // Delete the sessions\n for (const key of keys_to_delete) {\n delete this._object_store[key];\n }\n\n console.debug(`Force cleaning up ${cleaned_count} sessions`);\n }\n\n // Clean helper to identify promise method calls by session type\n _is_promise_method_call(method_path) {\n const session_id = method_path.split(\".\")[0];\n const session = this._get_session_store(session_id, false);\n return session && session._promise_manager;\n }\n\n // Simplified Promise Manager - enhanced version\n _create_promise_manager() {\n /**\n * Create a promise manager to track promise state and decide cleanup.\n */\n return {\n should_cleanup_on_callback: (callback_name) => {\n return [\"resolve\", \"reject\"].includes(callback_name);\n },\n settle: () => {\n // Promise is settled (resolved or rejected)\n console.debug(\"Promise settled\");\n },\n };\n }\n\n async _encode_promise(\n resolve,\n reject,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n description,\n ) {\n let store = this._get_session_store(session_id, true);\n if (!store) {\n console.warn(\n `Failed to create session store ${session_id}, session management may be impaired`,\n );\n store = {};\n }\n\n // Clean promise lifecycle management - TYPE-BASED, not string-based\n store._promise_manager = this._create_promise_manager();\n\n let encoded = {};\n\n if (timer && reject && this._method_timeout) {\n [encoded.heartbeat, store.heartbeat] = this._encode_callback(\n \"heartbeat\",\n timer.reset.bind(timer),\n session_id,\n false,\n null,\n local_workspace,\n );\n store.timer = timer;\n encoded.interval = this._method_timeout / 2;\n } else {\n timer = null;\n }\n\n [encoded.resolve, store.resolve] = this._encode_callback(\n \"resolve\",\n resolve,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n `resolve (${description})`,\n );\n [encoded.reject, store.reject] = this._encode_callback(\n \"reject\",\n reject,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n `reject (${description})`,\n );\n return encoded;\n }\n\n async _send_chunks(data, target_id, session_id) {\n // 1) Get the remote service\n const remote_services = await this.get_remote_service(\n `${target_id}:built-in`,\n );\n if (!remote_services.message_cache) {\n throw new Error(\n \"Remote client does not support message caching for large messages.\",\n );\n }\n\n const message_cache = remote_services.message_cache;\n const message_id = session_id || randId();\n const total_size = data.length;\n const start_time = Date.now(); // measure time\n const chunk_num = Math.ceil(total_size / this._long_message_chunk_size);\n if (remote_services.config.api_version >= 3) {\n await message_cache.create(message_id, !!session_id);\n const semaphore = new Semaphore(CONCURRENCY_LIMIT);\n\n const tasks = [];\n for (let idx = 0; idx < chunk_num; idx++) {\n const startByte = idx * this._long_message_chunk_size;\n const chunk = data.slice(\n startByte,\n startByte + this._long_message_chunk_size,\n );\n\n const taskFn = async () => {\n await message_cache.set(message_id, idx, chunk, !!session_id);\n // console.debug(\n // `Sending chunk ${idx + 1}/${chunk_num} (total=${total_size} bytes)`,\n // );\n };\n\n // Push into an array, each one runs under the semaphore\n tasks.push(semaphore.run(taskFn));\n }\n\n // Wait for all chunk uploads to finish\n try {\n await Promise.all(tasks);\n } catch (error) {\n // If any chunk fails, clean up the message cache\n try {\n await message_cache.remove(message_id);\n } catch (cleanupError) {\n console.error(\n `Failed to clean up message cache after error: ${cleanupError}`,\n );\n }\n throw error;\n }\n } else {\n // 3) Legacy version (sequential appends):\n await message_cache.create(message_id, !!session_id);\n for (let idx = 0; idx < chunk_num; idx++) {\n const startByte = idx * this._long_message_chunk_size;\n const chunk = data.slice(\n startByte,\n startByte + this._long_message_chunk_size,\n );\n await message_cache.append(message_id, chunk, !!session_id);\n // console.debug(\n // `Sending chunk ${idx + 1}/${chunk_num} (total=${total_size} bytes)`,\n // );\n }\n }\n await message_cache.process(message_id, !!session_id);\n const durationSec = ((Date.now() - start_time) / 1000).toFixed(2);\n // console.debug(`All chunks (${total_size} bytes) sent in ${durationSec} s`);\n }\n\n emit(main_message, extra_data) {\n assert(\n typeof main_message === \"object\" && main_message.type,\n \"Invalid message, must be an object with a `type` fields.\",\n );\n if (!main_message.to) {\n this._fire(main_message.type, main_message);\n return;\n }\n let message_package = msgpack_packb(main_message);\n if (extra_data) {\n const extra = msgpack_packb(extra_data);\n message_package = new Uint8Array([...message_package, ...extra]);\n }\n const total_size = message_package.length;\n if (total_size > this._long_message_chunk_size + 1024) {\n console.warn(`Sending large message (size=${total_size})`);\n }\n return this._emit_message(message_package);\n }\n\n _generate_remote_method(\n encoded_method,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ) {\n let target_id = encoded_method._rtarget;\n if (remote_workspace && !target_id.includes(\"/\")) {\n if (remote_workspace !== target_id) {\n target_id = remote_workspace + \"/\" + target_id;\n }\n // Fix the target id to be an absolute id\n encoded_method._rtarget = target_id;\n }\n let method_id = encoded_method._rmethod;\n let with_promise = encoded_method._rpromise || false;\n const description = `method: ${method_id}, docs: ${encoded_method._rdoc}`;\n const self = this;\n\n function remote_method() {\n return new Promise(async (resolve, reject) => {\n let local_session_id = randId();\n if (local_parent) {\n // Store the children session under the parent\n local_session_id = local_parent + \".\" + local_session_id;\n }\n let store = self._get_session_store(local_session_id, true);\n if (!store) {\n reject(\n new Error(\n `Runtime Error: Failed to get session store ${local_session_id} (context: ${description})`,\n ),\n );\n return;\n }\n store[\"target_id\"] = target_id;\n const args = await self._encode(\n Array.prototype.slice.call(arguments),\n local_session_id,\n local_workspace,\n );\n const argLength = args.length;\n // if the last argument is an object, mark it as kwargs\n const withKwargs =\n argLength > 0 &&\n typeof args[argLength - 1] === \"object\" &&\n args[argLength - 1] !== null &&\n args[argLength - 1]._rkwargs;\n if (withKwargs) delete args[argLength - 1]._rkwargs;\n\n let from_client;\n if (!self._local_workspace) {\n from_client = self._client_id;\n } else {\n from_client = self._local_workspace + \"/\" + self._client_id;\n }\n\n let main_message = {\n type: \"method\",\n from: from_client,\n to: target_id,\n method: method_id,\n };\n let extra_data = {};\n if (args) {\n extra_data[\"args\"] = args;\n }\n if (withKwargs) {\n extra_data[\"with_kwargs\"] = withKwargs;\n }\n\n // console.log(\n // `Calling remote method ${target_id}:${method_id}, session: ${local_session_id}`\n // );\n if (remote_parent) {\n // Set the parent session\n // Note: It's a session id for the remote, not the current client\n main_message[\"parent\"] = remote_parent;\n }\n\n let timer = null;\n if (with_promise) {\n // Only pass the current session id to the remote\n // if we want to received the result\n // I.e. the session id won't be passed for promises themselves\n main_message[\"session\"] = local_session_id;\n let method_name = `${target_id}:${method_id}`;\n\n // Create a timer that gets reset by heartbeat\n // Methods can run indefinitely as long as heartbeat keeps resetting the timer\n // IMPORTANT: When timeout occurs, we must clean up the session to prevent memory leaks\n const timeoutCallback = function (error_msg) {\n // First reject the promise\n reject(error_msg);\n // Then clean up the entire session to stop all callbacks\n if (self._object_store[local_session_id]) {\n delete self._object_store[local_session_id];\n console.debug(\n `Cleaned up session ${local_session_id} after timeout`,\n );\n }\n };\n\n timer = new Timer(\n self._method_timeout,\n timeoutCallback,\n [`Method call timed out: ${method_name}, context: ${description}`],\n method_name,\n );\n // By default, hypha will clear the session after the method is called\n // However, if the args contains _rintf === true, we will not clear the session\n\n // Helper function to recursively check for _rintf objects\n function hasInterfaceObject(obj) {\n if (!obj || typeof obj !== \"object\") return false;\n if (obj._rintf === true) return true;\n if (Array.isArray(obj)) {\n return obj.some((item) => hasInterfaceObject(item));\n }\n if (obj.constructor === Object) {\n return Object.values(obj).some((value) =>\n hasInterfaceObject(value),\n );\n }\n return false;\n }\n\n let clear_after_called = !hasInterfaceObject(args);\n\n const promiseData = await self._encode_promise(\n resolve,\n reject,\n local_session_id,\n clear_after_called,\n timer,\n local_workspace,\n description,\n );\n\n if (with_promise === true) {\n extra_data[\"promise\"] = promiseData;\n } else if (with_promise === \"*\") {\n extra_data[\"promise\"] = \"*\";\n extra_data[\"t\"] = self._method_timeout / 2;\n } else {\n throw new Error(`Unsupported promise type: ${with_promise}`);\n }\n }\n // The message consists of two segments, the main message and extra data\n let message_package = msgpack_packb(main_message);\n if (extra_data) {\n const extra = msgpack_packb(extra_data);\n message_package = new Uint8Array([...message_package, ...extra]);\n }\n const total_size = message_package.length;\n if (\n total_size <= self._long_message_chunk_size + 1024 ||\n remote_method.__no_chunk__\n ) {\n self\n ._emit_message(message_package)\n .then(function () {\n if (timer) {\n // Start the timer after message is sent successfully\n timer.start();\n }\n })\n .catch(function (err) {\n const error_msg = `Failed to send the request when calling method (${target_id}:${method_id}), error: ${err}`;\n if (reject) {\n reject(new Error(error_msg));\n } else {\n // No reject callback available, log the error to prevent unhandled promise rejections\n console.warn(\"Unhandled RPC method call error:\", error_msg);\n }\n if (timer) {\n timer.clear();\n }\n });\n } else {\n // send chunk by chunk\n self\n ._send_chunks(message_package, target_id, remote_parent)\n .then(function () {\n if (timer) {\n // Start the timer after message is sent successfully\n timer.start();\n }\n })\n .catch(function (err) {\n const error_msg = `Failed to send the request when calling method (${target_id}:${method_id}), error: ${err}`;\n if (reject) {\n reject(new Error(error_msg));\n } else {\n // No reject callback available, log the error to prevent unhandled promise rejections\n console.warn(\"Unhandled RPC method call error:\", error_msg);\n }\n if (timer) {\n timer.clear();\n }\n });\n }\n });\n }\n\n // Generate debugging information for the method\n remote_method.__rpc_object__ = encoded_method;\n const parts = method_id.split(\".\");\n\n remote_method.__name__ = encoded_method._rname || parts[parts.length - 1];\n if (remote_method.__name__.includes(\"#\")) {\n remote_method.__name__ = remote_method.__name__.split(\"#\")[1];\n }\n remote_method.__doc__ =\n encoded_method._rdoc || `Remote method: ${method_id}`;\n remote_method.__schema__ = encoded_method._rschema;\n // Prevent circular chunk sending\n remote_method.__no_chunk__ =\n encoded_method._rmethod === \"services.built-in.message_cache.append\";\n return remote_method;\n }\n\n get_client_info() {\n const services = [];\n for (let service of Object.values(this._services)) {\n services.push(this._extract_service_info(service));\n }\n\n return {\n id: this._client_id,\n services: services,\n };\n }\n\n async _handle_method(data) {\n let reject = null;\n let heartbeat_task = null;\n try {\n assert(data.method && data.ctx && data.from);\n const method_name = data.from + \":\" + data.method;\n const remote_workspace = data.from.split(\"/\")[0];\n const remote_client_id = data.from.split(\"/\")[1];\n // Make sure the target id is an absolute id\n data[\"to\"] = data[\"to\"].includes(\"/\")\n ? data[\"to\"]\n : remote_workspace + \"/\" + data[\"to\"];\n data[\"ctx\"][\"to\"] = data[\"to\"];\n let local_workspace;\n if (!this._local_workspace) {\n local_workspace = data[\"to\"].split(\"/\")[0];\n } else {\n if (this._local_workspace && this._local_workspace !== \"*\") {\n assert(\n data[\"to\"].split(\"/\")[0] === this._local_workspace,\n \"Workspace mismatch: \" +\n data[\"to\"].split(\"/\")[0] +\n \" != \" +\n this._local_workspace,\n );\n }\n local_workspace = this._local_workspace;\n }\n const local_parent = data.parent;\n\n let resolve, reject;\n if (data.promise) {\n // Decode the promise with the remote session id\n // Such that the session id will be passed to the remote as a parent session id\n const promise = await this._decode(\n data.promise === \"*\" ? this._expand_promise(data) : data.promise,\n data.session,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n resolve = promise.resolve;\n reject = promise.reject;\n if (promise.heartbeat && promise.interval) {\n async function heartbeat() {\n try {\n // console.debug(\"Reset heartbeat timer: \" + data.method);\n await promise.heartbeat();\n } catch (err) {\n console.error(err);\n }\n }\n heartbeat_task = setInterval(heartbeat, promise.interval * 1000);\n // Store the heartbeat task in the session store for cleanup\n if (data.session) {\n const session_store = this._get_session_store(data.session, false);\n if (session_store) {\n session_store.heartbeat_task = heartbeat_task;\n }\n }\n }\n }\n\n let method;\n\n try {\n method = indexObject(this._object_store, data[\"method\"]);\n } catch (e) {\n // Clean promise method detection - TYPE-BASED, not string-based\n if (this._is_promise_method_call(data[\"method\"])) {\n console.debug(\n `Promise method ${data[\"method\"]} not available (detected by session type), ignoring: ${method_name}`,\n );\n return;\n }\n\n // Check if this is a session-based method call that might have expired\n const method_parts = data[\"method\"].split(\".\");\n if (method_parts.length > 1) {\n const session_id = method_parts[0];\n // Check if the session exists but the specific method doesn't\n if (session_id in this._object_store) {\n console.debug(\n `Session ${session_id} exists but method ${data[\"method\"]} not found, likely expired callback: ${method_name}`,\n );\n // For expired callbacks, don't throw an exception, just log and return\n if (typeof reject === \"function\") {\n reject(new Error(`Method expired or not found: ${method_name}`));\n }\n return;\n } else {\n console.debug(\n `Session ${session_id} not found for method ${data[\"method\"]}, likely cleaned up: ${method_name}`,\n );\n // For cleaned up sessions, just log and return without throwing\n if (typeof reject === \"function\") {\n reject(new Error(`Session not found: ${method_name}`));\n }\n return;\n }\n }\n\n console.debug(\n `Failed to find method ${method_name} at ${this._client_id}`,\n );\n const error = new Error(\n `Method not found: ${method_name} at ${this._client_id}`,\n );\n if (typeof reject === \"function\") {\n reject(error);\n } else {\n // Log the error instead of throwing to prevent unhandled exceptions\n console.warn(\n \"Method not found and no reject callback:\",\n error.message,\n );\n }\n return;\n }\n\n assert(\n method && typeof method === \"function\",\n \"Invalid method: \" + method_name,\n );\n\n // Check permission\n if (this._method_annotations.has(method)) {\n // For services, it should not be protected\n if (this._method_annotations.get(method).visibility === \"protected\") {\n // Allow access from same workspace\n if (local_workspace === remote_workspace) {\n // Access granted\n }\n // Check if remote workspace is in authorized_workspaces list\n else if (\n this._method_annotations.get(method).authorized_workspaces &&\n this._method_annotations\n .get(method)\n .authorized_workspaces.includes(remote_workspace)\n ) {\n // Access granted\n }\n // Allow manager access\n else if (\n remote_workspace === \"*\" &&\n remote_client_id === this._connection.manager_id\n ) {\n // Access granted\n } else {\n throw new Error(\n \"Permission denied for invoking protected method \" +\n method_name +\n \", workspace mismatch: \" +\n local_workspace +\n \" != \" +\n remote_workspace,\n );\n }\n }\n } else {\n // For sessions, the target_id should match exactly\n let session_target_id =\n this._object_store[data.method.split(\".\")[0]].target_id;\n if (\n local_workspace === remote_workspace &&\n session_target_id &&\n session_target_id.indexOf(\"/\") === -1\n ) {\n session_target_id = local_workspace + \"/\" + session_target_id;\n }\n if (session_target_id !== data.from) {\n throw new Error(\n \"Access denied for method call (\" +\n method_name +\n \") from \" +\n data.from +\n \" to target \" +\n session_target_id,\n );\n }\n }\n\n // Make sure the parent session is still open\n if (local_parent) {\n // The parent session should be a session that generate the current method call\n assert(\n this._get_session_store(local_parent, true) !== null,\n \"Parent session was closed: \" + local_parent,\n );\n }\n let args;\n if (data.args) {\n args = await this._decode(\n data.args,\n data.session,\n null,\n remote_workspace,\n null,\n );\n } else {\n args = [];\n }\n if (\n this._method_annotations.has(method) &&\n this._method_annotations.get(method).require_context\n ) {\n // if args.length + 1 is less than the required number of arguments we will pad with undefined\n // so we make sure the last argument is the context\n if (args.length + 1 < method.length) {\n for (let i = args.length; i < method.length - 1; i++) {\n args.push(undefined);\n }\n }\n args.push(data.ctx);\n // assert(\n // args.length === method.length,\n // `Runtime Error: Invalid number of arguments for method ${method_name}, expected ${method.length} but got ${args.length}`,\n // );\n }\n // console.debug(`Executing method: ${method_name} (${data.method})`);\n if (data.promise) {\n const result = method.apply(null, args);\n if (result instanceof Promise) {\n result\n .then((result) => {\n resolve(result);\n clearInterval(heartbeat_task);\n })\n .catch((err) => {\n reject(err);\n clearInterval(heartbeat_task);\n });\n } else {\n resolve(result);\n clearInterval(heartbeat_task);\n }\n } else {\n method.apply(null, args);\n clearInterval(heartbeat_task);\n }\n } catch (err) {\n if (reject) {\n reject(err);\n // console.debug(\"Error during calling method: \", err);\n } else {\n console.error(\"Error during calling method: \", err);\n }\n // make sure we clear the heartbeat timer\n clearInterval(heartbeat_task);\n }\n }\n\n encode(aObject, session_id) {\n return this._encode(aObject, session_id);\n }\n\n _get_session_store(session_id, create) {\n if (!session_id) {\n return null;\n }\n let store = this._object_store;\n const levels = session_id.split(\".\");\n if (create) {\n const last_index = levels.length - 1;\n for (let level of levels.slice(0, last_index)) {\n if (!store[level]) {\n // Instead of returning null, create intermediate sessions as needed\n store[level] = {};\n }\n store = store[level];\n }\n // Create the last level\n if (!store[levels[last_index]]) {\n store[levels[last_index]] = {};\n }\n return store[levels[last_index]];\n } else {\n for (let level of levels) {\n if (!store[level]) {\n return null;\n }\n store = store[level];\n }\n return store;\n }\n }\n\n /**\n * Prepares the provided set of remote method arguments for\n * sending to the remote site, replaces all the callbacks with\n * identifiers\n *\n * @param {Array} args to wrap\n *\n * @returns {Array} wrapped arguments\n */\n async _encode(aObject, session_id, local_workspace) {\n const aType = typeof aObject;\n if (\n aType === \"number\" ||\n aType === \"string\" ||\n aType === \"boolean\" ||\n aObject === null ||\n aObject === undefined ||\n aObject instanceof Uint8Array\n ) {\n return aObject;\n }\n if (aObject instanceof ArrayBuffer) {\n return {\n _rtype: \"memoryview\",\n _rvalue: new Uint8Array(aObject),\n };\n }\n // Reuse the remote object\n if (aObject.__rpc_object__) {\n const _server = aObject.__rpc_object__._rserver || this._server_base_url;\n if (_server === this._server_base_url) {\n return aObject.__rpc_object__;\n } // else {\n // console.debug(\n // `Encoding remote function from a different server ${_server}, current server: ${this._server_base_url}`,\n // );\n // }\n }\n\n let bObject;\n\n // skip if already encoded\n if (aObject.constructor instanceof Object && aObject._rtype) {\n // make sure the interface functions are encoded\n const temp = aObject._rtype;\n delete aObject._rtype;\n bObject = await this._encode(aObject, session_id, local_workspace);\n bObject._rtype = temp;\n return bObject;\n }\n\n if (isGenerator(aObject) || isAsyncGenerator(aObject)) {\n // Handle generator functions and generator objects\n assert(\n session_id && typeof session_id === \"string\",\n \"Session ID is required for generator encoding\",\n );\n const object_id = randId();\n\n // Get the session store\n const store = this._get_session_store(session_id, true);\n assert(\n store !== null,\n `Failed to create session store ${session_id} due to invalid parent`,\n );\n\n // Check if it's an async generator\n const isAsync = isAsyncGenerator(aObject);\n\n // Define method to get next item from the generator\n const nextItemMethod = async () => {\n if (isAsync) {\n const iterator = aObject;\n const result = await iterator.next();\n if (result.done) {\n delete store[object_id];\n return { _rtype: \"stop_iteration\" };\n }\n return result.value;\n } else {\n const iterator = aObject;\n const result = iterator.next();\n if (result.done) {\n delete store[object_id];\n return { _rtype: \"stop_iteration\" };\n }\n return result.value;\n }\n };\n\n // Store the next_item method in the session\n store[object_id] = nextItemMethod;\n\n // Create a method that will be used to fetch the next item from the generator\n bObject = {\n _rtype: \"generator\",\n _rserver: this._server_base_url,\n _rtarget: this._client_id,\n _rmethod: `${session_id}.${object_id}`,\n _rpromise: \"*\",\n _rdoc: \"Remote generator\",\n };\n return bObject;\n } else if (typeof aObject === \"function\") {\n if (this._method_annotations.has(aObject)) {\n let annotation = this._method_annotations.get(aObject);\n bObject = {\n _rtype: \"method\",\n _rserver: this._server_base_url,\n _rtarget: this._client_id,\n _rmethod: annotation.method_id,\n _rpromise: \"*\",\n _rname: aObject.name,\n };\n } else {\n assert(typeof session_id === \"string\");\n let object_id;\n if (aObject.__name__) {\n object_id = `${randId()}#${aObject.__name__}`;\n } else {\n object_id = randId();\n }\n bObject = {\n _rtype: \"method\",\n _rserver: this._server_base_url,\n _rtarget: this._client_id,\n _rmethod: `${session_id}.${object_id}`,\n _rpromise: \"*\",\n _rname: aObject.name,\n };\n let store = this._get_session_store(session_id, true);\n assert(\n store !== null,\n `Failed to create session store ${session_id} due to invalid parent`,\n );\n store[object_id] = aObject;\n }\n bObject._rdoc = aObject.__doc__;\n if (!bObject._rdoc) {\n try {\n const funcInfo = getFunctionInfo(aObject);\n if (funcInfo && !bObject._rdoc) {\n bObject._rdoc = `${funcInfo.doc}`;\n }\n } catch (e) {\n console.error(\"Failed to extract function docstring:\", aObject);\n }\n }\n bObject._rschema = aObject.__schema__;\n return bObject;\n }\n const isarray = Array.isArray(aObject);\n\n for (let tp of Object.keys(this._codecs)) {\n const codec = this._codecs[tp];\n if (codec.encoder && aObject instanceof codec.type) {\n // TODO: what if multiple encoders found\n let encodedObj = await Promise.resolve(codec.encoder(aObject));\n if (encodedObj && !encodedObj._rtype) encodedObj._rtype = codec.name;\n // encode the functions in the interface object\n if (typeof encodedObj === \"object\") {\n const temp = encodedObj._rtype;\n delete encodedObj._rtype;\n encodedObj = await this._encode(\n encodedObj,\n session_id,\n local_workspace,\n );\n encodedObj._rtype = temp;\n }\n bObject = encodedObj;\n return bObject;\n }\n }\n\n if (\n /*global tf*/\n typeof tf !== \"undefined\" &&\n tf.Tensor &&\n aObject instanceof tf.Tensor\n ) {\n const v_buffer = aObject.dataSync();\n bObject = {\n _rtype: \"ndarray\",\n _rvalue: new Uint8Array(v_buffer.buffer),\n _rshape: aObject.shape,\n _rdtype: aObject.dtype,\n };\n } else if (\n /*global nj*/\n typeof nj !== \"undefined\" &&\n nj.NdArray &&\n aObject instanceof nj.NdArray\n ) {\n if (!aObject.selection || !aObject.selection.data) {\n throw new Error(\"Invalid NumJS array: missing selection or data\");\n }\n const dtype = typedArrayToDtype(aObject.selection.data);\n bObject = {\n _rtype: \"ndarray\",\n _rvalue: new Uint8Array(aObject.selection.data.buffer),\n _rshape: aObject.shape,\n _rdtype: dtype,\n };\n } else if (aObject instanceof Error) {\n console.error(aObject);\n bObject = {\n _rtype: \"error\",\n _rvalue: aObject.toString(),\n _rtrace: aObject.stack,\n };\n }\n // send objects supported by structure clone algorithm\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n else if (\n aObject !== Object(aObject) ||\n aObject instanceof Boolean ||\n aObject instanceof String ||\n aObject instanceof Date ||\n aObject instanceof RegExp ||\n (typeof ImageData !== \"undefined\" && aObject instanceof ImageData) ||\n (typeof FileList !== \"undefined\" && aObject instanceof FileList) ||\n (typeof FileSystemDirectoryHandle !== \"undefined\" &&\n aObject instanceof FileSystemDirectoryHandle) ||\n (typeof FileSystemFileHandle !== \"undefined\" &&\n aObject instanceof FileSystemFileHandle) ||\n (typeof FileSystemHandle !== \"undefined\" &&\n aObject instanceof FileSystemHandle) ||\n (typeof FileSystemWritableFileStream !== \"undefined\" &&\n aObject instanceof FileSystemWritableFileStream)\n ) {\n bObject = aObject;\n // TODO: avoid object such as DynamicPlugin instance.\n } else if (aObject instanceof Blob) {\n let _current_pos = 0;\n async function read(length) {\n let blob;\n if (length) {\n blob = aObject.slice(_current_pos, _current_pos + length);\n } else {\n blob = aObject.slice(_current_pos);\n }\n const ret = new Uint8Array(await blob.arrayBuffer());\n _current_pos = _current_pos + ret.byteLength;\n return ret;\n }\n function seek(pos) {\n _current_pos = pos;\n }\n bObject = {\n _rtype: \"iostream\",\n _rnative: \"js:blob\",\n type: aObject.type,\n name: aObject.name,\n size: aObject.size,\n path: aObject._path || aObject.webkitRelativePath,\n read: await this._encode(read, session_id, local_workspace),\n seek: await this._encode(seek, session_id, local_workspace),\n };\n } else if (aObject instanceof ArrayBufferView) {\n const dtype = typedArrayToDtype(aObject);\n bObject = {\n _rtype: \"typedarray\",\n _rvalue: new Uint8Array(aObject.buffer),\n _rdtype: dtype,\n };\n } else if (aObject instanceof DataView) {\n bObject = {\n _rtype: \"memoryview\",\n _rvalue: new Uint8Array(aObject.buffer),\n };\n } else if (aObject instanceof Set) {\n bObject = {\n _rtype: \"set\",\n _rvalue: await this._encode(\n Array.from(aObject),\n session_id,\n local_workspace,\n ),\n };\n } else if (aObject instanceof Map) {\n bObject = {\n _rtype: \"orderedmap\",\n _rvalue: await this._encode(\n Array.from(aObject),\n session_id,\n local_workspace,\n ),\n };\n } else if (aObject.constructor === Object || Array.isArray(aObject)) {\n bObject = isarray ? [] : {};\n const keys = Object.keys(aObject);\n for (let k of keys) {\n bObject[k] = await this._encode(\n aObject[k],\n session_id,\n local_workspace,\n );\n }\n } else {\n throw `hypha-rpc: Unsupported data type: ${aObject}, you can register a custom codec to encode/decode the object.`;\n }\n\n if (!bObject) {\n throw new Error(\"Failed to encode object\");\n }\n return bObject;\n }\n\n async decode(aObject) {\n return await this._decode(aObject);\n }\n\n async _decode(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ) {\n if (!aObject) {\n return aObject;\n }\n let bObject;\n if (aObject._rtype) {\n if (\n this._codecs[aObject._rtype] &&\n this._codecs[aObject._rtype].decoder\n ) {\n const temp = aObject._rtype;\n delete aObject._rtype;\n aObject = await this._decode(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n aObject._rtype = temp;\n\n bObject = await Promise.resolve(\n this._codecs[aObject._rtype].decoder(aObject),\n );\n } else if (aObject._rtype === \"method\") {\n bObject = this._generate_remote_method(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n } else if (aObject._rtype === \"generator\") {\n // Create a method to fetch next items from the remote generator\n const gen_method = this._generate_remote_method(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n\n // Create an async generator proxy\n async function* asyncGeneratorProxy() {\n while (true) {\n try {\n const next_item = await gen_method();\n // Check for StopIteration signal\n if (next_item && next_item._rtype === \"stop_iteration\") {\n break;\n }\n yield next_item;\n } catch (error) {\n console.error(\"Error in generator:\", error);\n throw error;\n }\n }\n }\n bObject = asyncGeneratorProxy();\n } else if (aObject._rtype === \"ndarray\") {\n /*global nj tf*/\n //create build array/tensor if used in the plugin\n if (typeof nj !== \"undefined\" && nj.array) {\n if (Array.isArray(aObject._rvalue)) {\n aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);\n }\n bObject = nj\n .array(new Uint8(aObject._rvalue), aObject._rdtype)\n .reshape(aObject._rshape);\n } else if (typeof tf !== \"undefined\" && tf.Tensor) {\n if (Array.isArray(aObject._rvalue)) {\n aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);\n }\n const arraytype = dtypeToTypedArray[aObject._rdtype];\n bObject = tf.tensor(\n new arraytype(aObject._rvalue),\n aObject._rshape,\n aObject._rdtype,\n );\n } else {\n //keep it as regular if transfered to the main app\n bObject = aObject;\n }\n } else if (aObject._rtype === \"error\") {\n bObject = new Error(\n \"RemoteError: \" + aObject._rvalue + \"\\n\" + (aObject._rtrace || \"\"),\n );\n } else if (aObject._rtype === \"typedarray\") {\n const arraytype = dtypeToTypedArray[aObject._rdtype];\n if (!arraytype)\n throw new Error(\"unsupported dtype: \" + aObject._rdtype);\n const buffer = aObject._rvalue.buffer.slice(\n aObject._rvalue.byteOffset,\n aObject._rvalue.byteOffset + aObject._rvalue.byteLength,\n );\n bObject = new arraytype(buffer);\n } else if (aObject._rtype === \"memoryview\") {\n bObject = aObject._rvalue.buffer.slice(\n aObject._rvalue.byteOffset,\n aObject._rvalue.byteOffset + aObject._rvalue.byteLength,\n ); // ArrayBuffer\n } else if (aObject._rtype === \"iostream\") {\n if (aObject._rnative === \"js:blob\") {\n const read = await this._generate_remote_method(\n aObject.read,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n const bytes = await read();\n bObject = new Blob([bytes], {\n type: aObject.type,\n name: aObject.name,\n });\n } else {\n bObject = {};\n for (let k of Object.keys(aObject)) {\n if (!k.startsWith(\"_\")) {\n bObject[k] = await this._decode(\n aObject[k],\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n }\n }\n }\n bObject[\"__rpc_object__\"] = aObject;\n } else if (aObject._rtype === \"orderedmap\") {\n bObject = new Map(\n await this._decode(\n aObject._rvalue,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ),\n );\n } else if (aObject._rtype === \"set\") {\n bObject = new Set(\n await this._decode(\n aObject._rvalue,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ),\n );\n } else {\n const temp = aObject._rtype;\n delete aObject._rtype;\n bObject = await this._decode(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n bObject._rtype = temp;\n }\n } else if (aObject.constructor === Object || Array.isArray(aObject)) {\n const isarray = Array.isArray(aObject);\n bObject = isarray ? [] : {};\n for (let k of Object.keys(aObject)) {\n if (isarray || aObject.hasOwnProperty(k)) {\n const v = aObject[k];\n bObject[k] = await this._decode(\n v,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n }\n }\n } else {\n bObject = aObject;\n }\n if (bObject === undefined) {\n throw new Error(\"Failed to decode object\");\n }\n return bObject;\n }\n\n _expand_promise(data) {\n return {\n heartbeat: {\n _rtype: \"method\",\n _rtarget: data.from.split(\"/\")[1],\n _rmethod: data.session + \".heartbeat\",\n _rdoc: `heartbeat callback for method: ${data.method}`,\n },\n resolve: {\n _rtype: \"method\",\n _rtarget: data.from.split(\"/\")[1],\n _rmethod: data.session + \".resolve\",\n _rdoc: `resolve callback for method: ${data.method}`,\n },\n reject: {\n _rtype: \"method\",\n _rtarget: data.from.split(\"/\")[1],\n _rmethod: data.session + \".reject\",\n _rdoc: `reject callback for method: ${data.method}`,\n },\n interval: data.t,\n };\n }\n}\n","export function randId() {\n return Math.random().toString(36).substr(2, 10) + new Date().getTime();\n}\n\nexport function toCamelCase(str) {\n // Check if the string is already in camelCase\n if (!str.includes(\"_\")) {\n return str;\n }\n // Convert from snake_case to camelCase\n return str.replace(/_./g, (match) => match[1].toUpperCase());\n}\n\nexport function toSnakeCase(str) {\n // Convert from camelCase to snake_case\n return str.replace(/([A-Z])/g, \"_$1\").toLowerCase();\n}\n\nexport function expandKwargs(obj) {\n if (typeof obj !== \"object\" || obj === null) {\n return obj; // Return the value if obj is not an object\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n const value = obj[key];\n\n if (typeof value === \"function\") {\n newObj[key] = (...args) => {\n if (args.length === 0) {\n throw new Error(`Function \"${key}\" expects at least one argument.`);\n }\n\n // Check if the last argument is an object\n const lastArg = args[args.length - 1];\n let kwargs = {};\n\n if (\n typeof lastArg === \"object\" &&\n lastArg !== null &&\n !Array.isArray(lastArg)\n ) {\n // Extract kwargs from the last argument\n kwargs = { ...lastArg, _rkwarg: true };\n args = args.slice(0, -1); // Remove the last argument from args\n }\n\n // Call the original function with positional args followed by kwargs\n return value(...args, kwargs);\n };\n\n // Preserve metadata like __name__ and __schema__\n newObj[key].__name__ = key;\n if (value.__schema__) {\n newObj[key].__schema__ = { ...value.__schema__ };\n newObj[key].__schema__.name = key;\n }\n } else {\n newObj[key] = expandKwargs(value); // Recursively process nested objects\n }\n }\n }\n\n return newObj;\n}\n\nexport function convertCase(obj, caseType) {\n if (typeof obj !== \"object\" || obj === null || !caseType) {\n return obj; // Return the value if obj is not an object\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n const value = obj[key];\n const camelKey = toCamelCase(key);\n const snakeKey = toSnakeCase(key);\n\n if (caseType === \"camel\") {\n newObj[camelKey] = convertCase(value, caseType);\n if (typeof value === \"function\") {\n newObj[camelKey].__name__ = camelKey;\n if (value.__schema__) {\n newObj[camelKey].__schema__ = { ...value.__schema__ };\n newObj[camelKey].__schema__.name = camelKey;\n }\n }\n } else if (caseType === \"snake\") {\n newObj[snakeKey] = convertCase(value, caseType);\n if (typeof value === \"function\") {\n newObj[snakeKey].__name__ = snakeKey;\n if (value.__schema__) {\n newObj[snakeKey].__schema__ = { ...value.__schema__ };\n newObj[snakeKey].__schema__.name = snakeKey;\n }\n }\n } else {\n // TODO handle schema for camel + snake\n if (caseType.includes(\"camel\")) {\n newObj[camelKey] = convertCase(value, \"camel\");\n }\n if (caseType.includes(\"snake\")) {\n newObj[snakeKey] = convertCase(value, \"snake\");\n }\n }\n }\n }\n\n return newObj;\n}\n\nexport function parseServiceUrl(url) {\n // Ensure no trailing slash\n url = url.replace(/\\/$/, \"\");\n\n // Regex pattern to match the URL structure\n const pattern = new RegExp(\n \"^(https?:\\\\/\\\\/[^/]+)\" + // server_url (http or https followed by domain)\n \"\\\\/([a-z0-9_-]+)\" + // workspace (lowercase letters, numbers, - or _)\n \"\\\\/services\\\\/\" + // static part of the URL\n \"(?:(?<clientId>[a-zA-Z0-9_-]+):)?\" + // optional client_id\n \"(?<serviceId>[a-zA-Z0-9_-]+)\" + // service_id\n \"(?:@(?<appId>[a-zA-Z0-9_-]+))?\", // optional app_id\n );\n\n const match = url.match(pattern);\n if (!match) {\n throw new Error(\"URL does not match the expected pattern\");\n }\n\n const serverUrl = match[1];\n const workspace = match[2];\n const clientId = match.groups?.clientId || \"*\";\n const serviceId = match.groups?.serviceId;\n const appId = match.groups?.appId || \"*\";\n\n return { serverUrl, workspace, clientId, serviceId, appId };\n}\n\nexport const dtypeToTypedArray = {\n int8: Int8Array,\n int16: Int16Array,\n int32: Int32Array,\n uint8: Uint8Array,\n uint16: Uint16Array,\n uint32: Uint32Array,\n float32: Float32Array,\n float64: Float64Array,\n array: Array,\n};\n\nexport async function loadRequirementsInWindow(requirements) {\n function _importScript(url) {\n //url is URL of external file, implementationCode is the code\n //to be called from the file, location is the location to\n //insert the <script> element\n return new Promise((resolve, reject) => {\n var scriptTag = document.createElement(\"script\");\n scriptTag.src = url;\n scriptTag.type = \"text/javascript\";\n scriptTag.onload = resolve;\n scriptTag.onreadystatechange = function () {\n if (this.readyState === \"loaded\" || this.readyState === \"complete\") {\n resolve();\n }\n };\n scriptTag.onerror = reject;\n document.head.appendChild(scriptTag);\n });\n }\n\n // support importScripts outside web worker\n async function importScripts() {\n var args = Array.prototype.slice.call(arguments),\n len = args.length,\n i = 0;\n for (; i < len; i++) {\n await _importScript(args[i]);\n }\n }\n\n if (\n requirements &&\n (Array.isArray(requirements) || typeof requirements === \"string\")\n ) {\n try {\n var link_node;\n requirements =\n typeof requirements === \"string\" ? [requirements] : requirements;\n if (Array.isArray(requirements)) {\n for (var i = 0; i < requirements.length; i++) {\n if (\n requirements[i].toLowerCase().endsWith(\".css\") ||\n requirements[i].startsWith(\"css:\")\n ) {\n if (requirements[i].startsWith(\"css:\")) {\n requirements[i] = requirements[i].slice(4);\n }\n link_node = document.createElement(\"link\");\n link_node.rel = \"stylesheet\";\n link_node.href = requirements[i];\n document.head.appendChild(link_node);\n } else if (\n requirements[i].toLowerCase().endsWith(\".mjs\") ||\n requirements[i].startsWith(\"mjs:\")\n ) {\n // import esmodule\n if (requirements[i].startsWith(\"mjs:\")) {\n requirements[i] = requirements[i].slice(4);\n }\n await import(/* webpackIgnore: true */ requirements[i]);\n } else if (\n requirements[i].toLowerCase().endsWith(\".js\") ||\n requirements[i].startsWith(\"js:\")\n ) {\n if (requirements[i].startsWith(\"js:\")) {\n requirements[i] = requirements[i].slice(3);\n }\n await importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"http\")) {\n await importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"cache:\")) {\n //ignore cache\n } else {\n console.log(\"Unprocessed requirements url: \" + requirements[i]);\n }\n }\n } else {\n throw \"unsupported requirements definition\";\n }\n } catch (e) {\n throw \"failed to import required scripts: \" + requirements.toString();\n }\n }\n}\n\nexport async function loadRequirementsInWebworker(requirements) {\n if (\n requirements &&\n (Array.isArray(requirements) || typeof requirements === \"string\")\n ) {\n try {\n if (!Array.isArray(requirements)) {\n requirements = [requirements];\n }\n for (var i = 0; i < requirements.length; i++) {\n if (\n requirements[i].toLowerCase().endsWith(\".css\") ||\n requirements[i].startsWith(\"css:\")\n ) {\n throw \"unable to import css in a webworker\";\n } else if (\n requirements[i].toLowerCase().endsWith(\".js\") ||\n requirements[i].startsWith(\"js:\")\n ) {\n if (requirements[i].startsWith(\"js:\")) {\n requirements[i] = requirements[i].slice(3);\n }\n importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"http\")) {\n importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"cache:\")) {\n //ignore cache\n } else {\n console.log(\"Unprocessed requirements url: \" + requirements[i]);\n }\n }\n } catch (e) {\n throw \"failed to import required scripts: \" + requirements.toString();\n }\n }\n}\n\nexport function loadRequirements(requirements) {\n if (\n typeof WorkerGlobalScope !== \"undefined\" &&\n self instanceof WorkerGlobalScope\n ) {\n return loadRequirementsInWebworker(requirements);\n } else {\n return loadRequirementsInWindow(requirements);\n }\n}\n\nexport function normalizeConfig(config) {\n config.version = config.version || \"0.1.0\";\n config.description =\n config.description || `[TODO: add description for ${config.name} ]`;\n config.type = config.type || \"rpc-window\";\n config.id = config.id || randId();\n config.target_origin = config.target_origin || \"*\";\n config.allow_execution = config.allow_execution || false;\n // remove functions\n config = Object.keys(config).reduce((p, c) => {\n if (typeof config[c] !== \"function\") p[c] = config[c];\n return p;\n }, {});\n return config;\n}\nexport const typedArrayToDtypeMapping = {\n Int8Array: \"int8\",\n Int16Array: \"int16\",\n Int32Array: \"int32\",\n Uint8Array: \"uint8\",\n Uint16Array: \"uint16\",\n Uint32Array: \"uint32\",\n Float32Array: \"float32\",\n Float64Array: \"float64\",\n Array: \"array\",\n};\n\nconst typedArrayToDtypeKeys = [];\nfor (const arrType of Object.keys(typedArrayToDtypeMapping)) {\n typedArrayToDtypeKeys.push(eval(arrType));\n}\n\nexport function typedArrayToDtype(obj) {\n let dtype = typedArrayToDtypeMapping[obj.constructor.name];\n if (!dtype) {\n const pt = Object.getPrototypeOf(obj);\n for (const arrType of typedArrayToDtypeKeys) {\n if (pt instanceof arrType) {\n dtype = typedArrayToDtypeMapping[arrType.name];\n break;\n }\n }\n }\n return dtype;\n}\n\nfunction cacheUrlInServiceWorker(url) {\n return new Promise(function (resolve, reject) {\n const message = {\n command: \"add\",\n url: url,\n };\n if (!navigator.serviceWorker || !navigator.serviceWorker.register) {\n reject(\"Service worker is not supported.\");\n return;\n }\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = function (event) {\n if (event.data && event.data.error) {\n reject(event.data.error);\n } else {\n resolve(event.data && event.data.result);\n }\n };\n\n if (navigator.serviceWorker && navigator.serviceWorker.controller) {\n navigator.serviceWorker.controller.postMessage(message, [\n messageChannel.port2,\n ]);\n } else {\n reject(\"Service worker controller is not available\");\n }\n });\n}\n\nexport async function cacheRequirements(requirements) {\n requirements = requirements || [];\n if (!Array.isArray(requirements)) {\n requirements = [requirements];\n }\n for (let req of requirements) {\n //remove prefix\n if (req.startsWith(\"js:\")) req = req.slice(3);\n if (req.startsWith(\"css:\")) req = req.slice(4);\n if (req.startsWith(\"cache:\")) req = req.slice(6);\n if (!req.startsWith(\"http\")) continue;\n\n await cacheUrlInServiceWorker(req).catch((e) => {\n console.error(e);\n });\n }\n}\n\nexport function assert(condition, message) {\n if (!condition) {\n throw new Error(message || \"Assertion failed\");\n }\n}\n\n//#Source https://bit.ly/2neWfJ2\nexport function urlJoin(...args) {\n return args\n .join(\"/\")\n .replace(/[\\/]+/g, \"/\")\n .replace(/^(.+):\\//, \"$1://\")\n .replace(/^file:/, \"file:/\")\n .replace(/\\/(\\?|&|#[^!])/g, \"$1\")\n .replace(/\\?/g, \"&\")\n .replace(\"&\", \"?\");\n}\n\nexport function waitFor(prom, time, error) {\n let timer;\n return Promise.race([\n prom,\n new Promise(\n (_r, rej) =>\n (timer = setTimeout(() => {\n rej(error || \"Timeout Error\");\n }, time * 1000)),\n ),\n ]).finally(() => clearTimeout(timer));\n}\n\nexport class MessageEmitter {\n constructor(debug) {\n this._event_handlers = {};\n this._once_handlers = {};\n this._debug = debug;\n }\n emit() {\n throw new Error(\"emit is not implemented\");\n }\n on(event, handler) {\n if (!this._event_handlers[event]) {\n this._event_handlers[event] = [];\n }\n this._event_handlers[event].push(handler);\n }\n once(event, handler) {\n handler.___event_run_once = true;\n this.on(event, handler);\n }\n off(event, handler) {\n if (!event && !handler) {\n // remove all events handlers\n this._event_handlers = {};\n } else if (event && !handler) {\n // remove all hanlders for the event\n if (this._event_handlers[event]) this._event_handlers[event] = [];\n } else {\n // remove a specific handler\n if (this._event_handlers[event]) {\n const idx = this._event_handlers[event].indexOf(handler);\n if (idx >= 0) {\n this._event_handlers[event].splice(idx, 1);\n }\n }\n }\n }\n _fire(event, data) {\n if (this._event_handlers[event]) {\n var i = this._event_handlers[event].length;\n while (i--) {\n const handler = this._event_handlers[event][i];\n try {\n handler(data);\n } catch (e) {\n console.error(e);\n } finally {\n if (handler.___event_run_once) {\n this._event_handlers[event].splice(i, 1);\n }\n }\n }\n } else {\n if (this._debug) {\n console.warn(\"unhandled event\", event, data);\n }\n }\n }\n\n waitFor(event, timeout) {\n return new Promise((resolve, reject) => {\n const handler = (data) => {\n clearTimeout(timer);\n resolve(data);\n };\n this.once(event, handler);\n const timer = setTimeout(() => {\n this.off(event, handler);\n reject(new Error(\"Timeout\"));\n }, timeout * 1000);\n });\n }\n}\n\nexport class Semaphore {\n constructor(max) {\n this.max = max;\n this.queue = [];\n this.current = 0;\n }\n async run(task) {\n if (this.current >= this.max) {\n // Wait until a slot is free\n await new Promise((resolve) => this.queue.push(resolve));\n }\n this.current++;\n try {\n return await task();\n } finally {\n this.current--;\n if (this.queue.length > 0) {\n // release one waiter\n this.queue.shift()();\n }\n }\n }\n}\n\n/**\n * Check if the object is a generator\n * @param {Object} obj - Object to check\n * @returns {boolean} - True if the object is a generator\n */\nexport function isGenerator(obj) {\n if (!obj) return false;\n\n return (\n typeof obj === \"object\" &&\n typeof obj.next === \"function\" &&\n typeof obj.throw === \"function\" &&\n typeof obj.return === \"function\"\n );\n}\n\n/**\n * Check if an object is an async generator object\n * @param {any} obj - Object to check\n * @returns {boolean} True if object is an async generator object\n */\nexport function isAsyncGenerator(obj) {\n if (!obj) return false;\n // Check if it's an async generator object\n return (\n typeof obj === \"object\" &&\n typeof obj.next === \"function\" &&\n typeof obj.throw === \"function\" &&\n typeof obj.return === \"function\" &&\n Symbol.asyncIterator in Object(obj) &&\n obj[Symbol.toStringTag] === \"AsyncGenerator\"\n );\n}\n","import { assert } from \"./index.js\";\n\n// Schema builder utility inspired by Zod for consistent API with Python\nexport const z = {\n object: (properties) => ({\n type: \"object\",\n properties,\n required: Object.keys(properties).filter(\n (key) => !properties[key]._optional,\n ),\n }),\n\n string: () => ({ type: \"string\", _optional: false }),\n number: () => ({ type: \"number\", _optional: false }),\n integer: () => ({ type: \"integer\", _optional: false }),\n boolean: () => ({ type: \"boolean\", _optional: false }),\n array: (items) => ({ type: \"array\", items, _optional: false }),\n\n // Make field optional\n optional: (schema) => ({ ...schema, _optional: true }),\n};\n\n// Add description method to schema types\n[\"string\", \"number\", \"integer\", \"boolean\", \"array\"].forEach((type) => {\n z[type] = () => {\n const schema = {\n type: type === \"integer\" ? \"integer\" : type,\n _optional: false,\n };\n schema.describe = (description) => ({ ...schema, description });\n return schema;\n };\n});\n\nexport function schemaFunction(\n func,\n { schema_type = \"auto\", name = null, description = null, parameters = null },\n) {\n if (!func || typeof func !== \"function\") {\n throw Error(\"func should be a function\");\n }\n assert(schema_type === \"auto\", \"schema_type should be auto\");\n\n // If no name provided, try to get it from function\n const funcName = name || func.name;\n assert(funcName, \"name should not be null\");\n\n // If parameters is a z.object result, convert it properly\n let processedParameters = parameters;\n if (\n parameters &&\n typeof parameters === \"object\" &&\n parameters.type === \"object\"\n ) {\n processedParameters = {\n type: \"object\",\n properties: parameters.properties || {},\n required: parameters.required || [],\n };\n\n // Clean up internal _optional flags\n for (const [key, schema] of Object.entries(\n processedParameters.properties,\n )) {\n if (schema._optional !== undefined) {\n delete schema._optional;\n }\n }\n }\n\n assert(\n processedParameters && processedParameters.type === \"object\",\n \"parameters should be an object schema\",\n );\n\n func.__schema__ = {\n name: funcName,\n description: description || \"\",\n parameters: processedParameters,\n };\n return func;\n}\n","import { RPC } from \"./rpc.js\";\nimport { assert, randId } from \"./utils/index.js\";\nimport { schemaFunction } from \"./utils/schema.js\";\n\nclass WebRTCConnection {\n constructor(channel) {\n this._data_channel = channel;\n this._handle_message = null;\n this._reconnection_token = null;\n this._handle_disconnected = null;\n this._handle_connected = () => {};\n this.manager_id = null;\n this._last_message = null;\n this._data_channel.onopen = async () => {\n if (this._last_message) {\n console.info(\"Resending last message after connection established\");\n this._data_channel.send(this._last_message);\n this._last_message = null;\n }\n this._handle_connected &&\n this._handle_connected({ channel: this._data_channel });\n };\n this._data_channel.onmessage = async (event) => {\n let data = event.data;\n if (data instanceof Blob) {\n data = await data.arrayBuffer();\n }\n this._handle_message(data);\n };\n const self = this;\n this._data_channel.onclose = function () {\n if (this._handle_disconnected) this._handle_disconnected(\"closed\");\n console.log(\"websocket closed\");\n self._data_channel = null;\n };\n }\n\n on_disconnected(handler) {\n this._handle_disconnected = handler;\n }\n\n on_connected(handler) {\n this._handle_connected = handler;\n }\n\n on_message(handler) {\n assert(handler, \"handler is required\");\n this._handle_message = handler;\n }\n\n async emit_message(data) {\n assert(this._handle_message, \"No handler for message\");\n try {\n this._last_message = data;\n this._data_channel.send(data);\n this._last_message = null;\n } catch (exp) {\n console.error(`Failed to send data, error: ${exp}`);\n throw exp;\n }\n }\n\n async disconnect(reason) {\n this._last_message = null;\n this._data_channel = null;\n console.info(`data channel connection disconnected (${reason})`);\n }\n}\n\nasync function _setupRPC(config) {\n assert(config.channel, \"No channel provided\");\n assert(config.workspace, \"No workspace provided\");\n const channel = config.channel;\n const clientId = config.client_id || randId();\n const connection = new WebRTCConnection(channel);\n config.context = config.context || {};\n config.context.connection_type = \"webrtc\";\n config.context.ws = config.workspace;\n const rpc = new RPC(connection, {\n client_id: clientId,\n default_context: config.context,\n name: config.name,\n method_timeout: config.method_timeout || 10.0,\n workspace: config.workspace,\n app_id: config.app_id,\n long_message_chunk_size: config.long_message_chunk_size,\n });\n return rpc;\n}\n\nasync function _createOffer(params, server, config, onInit, context) {\n config = config || {};\n let offer = new RTCSessionDescription({\n sdp: params.sdp,\n type: params.type,\n });\n\n let pc = new RTCPeerConnection({\n iceServers: config.ice_servers || [\n { urls: [\"stun:stun.l.google.com:19302\"] },\n ],\n sdpSemantics: \"unified-plan\",\n });\n\n if (server) {\n pc.addEventListener(\"datachannel\", async (event) => {\n const channel = event.channel;\n let ctx = null;\n if (context && context.user) ctx = { user: context.user, ws: context.ws };\n const rpc = await _setupRPC({\n channel: channel,\n client_id: channel.label,\n workspace: server.config.workspace,\n context: ctx,\n });\n // Map all the local services to the webrtc client\n rpc._services = server.rpc._services;\n });\n }\n\n if (onInit) {\n await onInit(pc);\n }\n\n await pc.setRemoteDescription(offer);\n\n let answer = await pc.createAnswer();\n await pc.setLocalDescription(answer);\n\n // Wait for ICE candidates to be gathered (important for Firefox)\n await new Promise((resolveIce) => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n } else {\n pc.addEventListener(\"icegatheringstatechange\", () => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n }\n });\n // Don't wait forever for ICE gathering\n setTimeout(resolveIce, 5000);\n }\n });\n\n return {\n sdp: pc.localDescription.sdp,\n type: pc.localDescription.type,\n workspace: server.config.workspace,\n };\n}\n\nasync function getRTCService(server, service_id, config) {\n config = config || {};\n config.peer_id = config.peer_id || randId();\n\n const pc = new RTCPeerConnection({\n iceServers: config.ice_servers || [\n { urls: [\"stun:stun.l.google.com:19302\"] },\n ],\n sdpSemantics: \"unified-plan\",\n });\n\n return new Promise(async (resolve, reject) => {\n let resolved = false;\n const timeout = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n pc.close();\n reject(new Error(\"WebRTC Connection timeout\"));\n }\n }, 30000); // Increase timeout to 30 seconds\n\n try {\n pc.addEventListener(\n \"connectionstatechange\",\n () => {\n console.log(\"WebRTC Connection state: \", pc.connectionState);\n if (pc.connectionState === \"failed\") {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n pc.close();\n reject(new Error(\"WebRTC Connection failed\"));\n }\n } else if (pc.connectionState === \"closed\") {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(new Error(\"WebRTC Connection closed\"));\n }\n } else if (pc.connectionState === \"connected\") {\n console.log(\"WebRTC Connection established successfully\");\n }\n },\n false,\n );\n\n // Add ICE connection state change handler for better debugging\n pc.addEventListener(\"iceconnectionstatechange\", () => {\n console.log(\"ICE Connection state: \", pc.iceConnectionState);\n if (pc.iceConnectionState === \"failed\") {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n pc.close();\n reject(new Error(\"ICE Connection failed\"));\n }\n }\n });\n\n if (config.on_init) {\n await config.on_init(pc);\n delete config.on_init;\n }\n\n let channel = pc.createDataChannel(config.peer_id, { ordered: true });\n channel.binaryType = \"arraybuffer\";\n\n // Wait for ICE gathering to complete before creating offer\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n\n // Wait for ICE candidates to be gathered (important for Firefox)\n await new Promise((resolveIce) => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n } else {\n pc.addEventListener(\"icegatheringstatechange\", () => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n }\n });\n // Don't wait forever for ICE gathering\n setTimeout(resolveIce, 5000);\n }\n });\n\n const svc = await server.getService(service_id);\n const answer = await svc.offer({\n sdp: pc.localDescription.sdp,\n type: pc.localDescription.type,\n });\n\n channel.onopen = () => {\n config.channel = channel;\n config.workspace = answer.workspace;\n // Increase timeout for Firefox compatibility\n setTimeout(async () => {\n if (!resolved) {\n try {\n const rpc = await _setupRPC(config);\n pc.rpc = rpc;\n async function get_service(name, ...args) {\n assert(\n !name.includes(\":\"),\n \"WebRTC service name should not contain ':'\",\n );\n assert(\n !name.includes(\"/\"),\n \"WebRTC service name should not contain '/'\",\n );\n return await rpc.get_remote_service(\n config.workspace + \"/\" + config.peer_id + \":\" + name,\n ...args,\n );\n }\n async function disconnect() {\n await rpc.disconnect();\n pc.close();\n }\n pc.getService = schemaFunction(get_service, {\n name: \"getService\",\n description: \"Get a remote service via webrtc\",\n parameters: {\n type: \"object\",\n properties: {\n service_id: {\n type: \"string\",\n description:\n \"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'\",\n },\n config: {\n type: \"object\",\n description: \"Options for the service\",\n },\n },\n required: [\"id\"],\n },\n });\n pc.disconnect = schemaFunction(disconnect, {\n name: \"disconnect\",\n description: \"Disconnect from the webrtc connection via webrtc\",\n parameters: { type: \"object\", properties: {} },\n });\n pc.registerCodec = schemaFunction(rpc.register_codec, {\n name: \"registerCodec\",\n description: \"Register a codec for the webrtc connection\",\n parameters: {\n type: \"object\",\n properties: {\n codec: {\n type: \"object\",\n description: \"Codec to register\",\n properties: {\n name: { type: \"string\" },\n type: {},\n encoder: { type: \"function\" },\n decoder: { type: \"function\" },\n },\n },\n },\n },\n });\n resolved = true;\n clearTimeout(timeout);\n resolve(pc);\n } catch (e) {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(e);\n }\n }\n }\n }, 1000); // Increase timeout to 1 second for Firefox\n };\n\n channel.onclose = () => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(new Error(\"Data channel closed\"));\n }\n };\n\n channel.onerror = (error) => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(new Error(`Data channel error: ${error}`));\n }\n };\n\n await pc.setRemoteDescription(\n new RTCSessionDescription({\n sdp: answer.sdp,\n type: answer.type,\n }),\n );\n } catch (e) {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(e);\n }\n }\n });\n}\n\nasync function registerRTCService(server, service_id, config) {\n config = config || {\n visibility: \"protected\",\n require_context: true,\n };\n const onInit = config.on_init;\n delete config.on_init;\n return await server.registerService({\n id: service_id,\n config,\n offer: (params, context) =>\n _createOffer(params, server, config, onInit, context),\n });\n}\n\nexport { getRTCService, registerRTCService };\n","import { utf8DecodeJs } from \"./utils/utf8.mjs\";\nvar DEFAULT_MAX_KEY_LENGTH = 16;\nvar DEFAULT_MAX_LENGTH_PER_KEY = 16;\nvar CachedKeyDecoder = /** @class */ (function () {\n function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {\n if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }\n if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }\n this.maxKeyLength = maxKeyLength;\n this.maxLengthPerKey = maxLengthPerKey;\n this.hit = 0;\n this.miss = 0;\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (var i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n CachedKeyDecoder.prototype.canBeCached = function (byteLength) {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n };\n CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {\n var records = this.caches[byteLength - 1];\n FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {\n var record = records_1[_i];\n var recordBytes = record.bytes;\n for (var j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n };\n CachedKeyDecoder.prototype.store = function (bytes, value) {\n var records = this.caches[bytes.length - 1];\n var record = { bytes: bytes, str: value };\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n }\n else {\n records.push(record);\n }\n };\n CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {\n var cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n var str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n };\n return CachedKeyDecoder;\n}());\nexport { CachedKeyDecoder };\n//# sourceMappingURL=CachedKeyDecoder.mjs.map","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar DecodeError = /** @class */ (function (_super) {\n __extends(DecodeError, _super);\n function DecodeError(message) {\n var _this = _super.call(this, message) || this;\n // fix the prototype chain in a cross-platform way\n var proto = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(_this, proto);\n Object.defineProperty(_this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n return _this;\n }\n return DecodeError;\n}(Error));\nexport { DecodeError };\n//# sourceMappingURL=DecodeError.mjs.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nimport { prettyByte } from \"./utils/prettyByte.mjs\";\nimport { ExtensionCodec } from \"./ExtensionCodec.mjs\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int.mjs\";\nimport { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from \"./utils/utf8.mjs\";\nimport { createDataView, ensureUint8Array } from \"./utils/typedArrays.mjs\";\nimport { CachedKeyDecoder } from \"./CachedKeyDecoder.mjs\";\nimport { DecodeError } from \"./DecodeError.mjs\";\nvar isValidMapKeyType = function (key) {\n var keyType = typeof key;\n return keyType === \"string\" || keyType === \"number\";\n};\nvar HEAD_BYTE_REQUIRED = -1;\nvar EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nvar EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\n// IE11: Hack to support IE11.\n// IE11: Drop this hack and just use RangeError when IE11 is obsolete.\nexport var DataViewIndexOutOfBoundsError = (function () {\n try {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n }\n catch (e) {\n return e.constructor;\n }\n throw new Error(\"never reached\");\n})();\nvar MORE_DATA = new DataViewIndexOutOfBoundsError(\"Insufficient data\");\nvar sharedCachedKeyDecoder = new CachedKeyDecoder();\nvar Decoder = /** @class */ (function () {\n function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {\n if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }\n if (context === void 0) { context = undefined; }\n if (maxStrLength === void 0) { maxStrLength = UINT32_MAX; }\n if (maxBinLength === void 0) { maxBinLength = UINT32_MAX; }\n if (maxArrayLength === void 0) { maxArrayLength = UINT32_MAX; }\n if (maxMapLength === void 0) { maxMapLength = UINT32_MAX; }\n if (maxExtLength === void 0) { maxExtLength = UINT32_MAX; }\n if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }\n this.extensionCodec = extensionCodec;\n this.context = context;\n this.maxStrLength = maxStrLength;\n this.maxBinLength = maxBinLength;\n this.maxArrayLength = maxArrayLength;\n this.maxMapLength = maxMapLength;\n this.maxExtLength = maxExtLength;\n this.keyDecoder = keyDecoder;\n this.totalPos = 0;\n this.pos = 0;\n this.view = EMPTY_VIEW;\n this.bytes = EMPTY_BYTES;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack = [];\n }\n Decoder.prototype.reinitializeState = function () {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.length = 0;\n // view, bytes, and pos will be re-initialized in setBuffer()\n };\n Decoder.prototype.setBuffer = function (buffer) {\n this.bytes = ensureUint8Array(buffer);\n this.view = createDataView(this.bytes);\n this.pos = 0;\n };\n Decoder.prototype.appendBuffer = function (buffer) {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n }\n else {\n var remainingData = this.bytes.subarray(this.pos);\n var newData = ensureUint8Array(buffer);\n // concat remainingData + newData\n var newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n };\n Decoder.prototype.hasRemaining = function (size) {\n return this.view.byteLength - this.pos >= size;\n };\n Decoder.prototype.createExtraByteError = function (posToShow) {\n var _a = this, view = _a.view, pos = _a.pos;\n return new RangeError(\"Extra \".concat(view.byteLength - pos, \" of \").concat(view.byteLength, \" byte(s) found at buffer[\").concat(posToShow, \"]\"));\n };\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n Decoder.prototype.decode = function (buffer) {\n this.reinitializeState();\n this.setBuffer(buffer);\n var object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n };\n Decoder.prototype.decodeMulti = function (buffer) {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.reinitializeState();\n this.setBuffer(buffer);\n _a.label = 1;\n case 1:\n if (!this.hasRemaining(1)) return [3 /*break*/, 3];\n return [4 /*yield*/, this.doDecodeSync()];\n case 2:\n _a.sent();\n return [3 /*break*/, 1];\n case 3: return [2 /*return*/];\n }\n });\n };\n Decoder.prototype.decodeAsync = function (stream) {\n var stream_1, stream_1_1;\n var e_1, _a;\n return __awaiter(this, void 0, void 0, function () {\n var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n decoded = false;\n _c.label = 1;\n case 1:\n _c.trys.push([1, 6, 7, 12]);\n stream_1 = __asyncValues(stream);\n _c.label = 2;\n case 2: return [4 /*yield*/, stream_1.next()];\n case 3:\n if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];\n buffer = stream_1_1.value;\n if (decoded) {\n throw this.createExtraByteError(this.totalPos);\n }\n this.appendBuffer(buffer);\n try {\n object = this.doDecodeSync();\n decoded = true;\n }\n catch (e) {\n if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n _c.label = 4;\n case 4: return [3 /*break*/, 2];\n case 5: return [3 /*break*/, 12];\n case 6:\n e_1_1 = _c.sent();\n e_1 = { error: e_1_1 };\n return [3 /*break*/, 12];\n case 7:\n _c.trys.push([7, , 10, 11]);\n if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];\n return [4 /*yield*/, _a.call(stream_1)];\n case 8:\n _c.sent();\n _c.label = 9;\n case 9: return [3 /*break*/, 11];\n case 10:\n if (e_1) throw e_1.error;\n return [7 /*endfinally*/];\n case 11: return [7 /*endfinally*/];\n case 12:\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return [2 /*return*/, object];\n }\n _b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;\n throw new RangeError(\"Insufficient data in parsing \".concat(prettyByte(headByte), \" at \").concat(totalPos, \" (\").concat(pos, \" in the current buffer)\"));\n }\n });\n });\n };\n Decoder.prototype.decodeArrayStream = function (stream) {\n return this.decodeMultiAsync(stream, true);\n };\n Decoder.prototype.decodeStream = function (stream) {\n return this.decodeMultiAsync(stream, false);\n };\n Decoder.prototype.decodeMultiAsync = function (stream, isArray) {\n return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {\n var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;\n var e_3, _a;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n isArrayHeaderRequired = isArray;\n arrayItemsLeft = -1;\n _b.label = 1;\n case 1:\n _b.trys.push([1, 13, 14, 19]);\n stream_2 = __asyncValues(stream);\n _b.label = 2;\n case 2: return [4 /*yield*/, __await(stream_2.next())];\n case 3:\n if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];\n buffer = stream_2_1.value;\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n this.appendBuffer(buffer);\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n _b.label = 4;\n case 4:\n _b.trys.push([4, 9, , 10]);\n _b.label = 5;\n case 5:\n if (!true) return [3 /*break*/, 8];\n return [4 /*yield*/, __await(this.doDecodeSync())];\n case 6: return [4 /*yield*/, _b.sent()];\n case 7:\n _b.sent();\n if (--arrayItemsLeft === 0) {\n return [3 /*break*/, 8];\n }\n return [3 /*break*/, 5];\n case 8: return [3 /*break*/, 10];\n case 9:\n e_2 = _b.sent();\n if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {\n throw e_2; // rethrow\n }\n return [3 /*break*/, 10];\n case 10:\n this.totalPos += this.pos;\n _b.label = 11;\n case 11: return [3 /*break*/, 2];\n case 12: return [3 /*break*/, 19];\n case 13:\n e_3_1 = _b.sent();\n e_3 = { error: e_3_1 };\n return [3 /*break*/, 19];\n case 14:\n _b.trys.push([14, , 17, 18]);\n if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];\n return [4 /*yield*/, __await(_a.call(stream_2))];\n case 15:\n _b.sent();\n _b.label = 16;\n case 16: return [3 /*break*/, 18];\n case 17:\n if (e_3) throw e_3.error;\n return [7 /*endfinally*/];\n case 18: return [7 /*endfinally*/];\n case 19: return [2 /*return*/];\n }\n });\n });\n };\n Decoder.prototype.doDecodeSync = function () {\n DECODE: while (true) {\n var headByte = this.readHeadByte();\n var object = void 0;\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n }\n else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n }\n else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n var size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n var size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n var byteLength = headByte - 0xa0;\n object = this.decodeUtf8String(byteLength, 0);\n }\n }\n else if (headByte === 0xc0) {\n // nil\n object = null;\n }\n else if (headByte === 0xc2) {\n // false\n object = false;\n }\n else if (headByte === 0xc3) {\n // true\n object = true;\n }\n else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n }\n else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n }\n else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n }\n else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n }\n else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n }\n else if (headByte === 0xcf) {\n // uint 64\n object = this.readU64();\n }\n else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n }\n else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n }\n else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n }\n else if (headByte === 0xd3) {\n // int 64\n object = this.readI64();\n }\n else if (headByte === 0xd9) {\n // str 8\n var byteLength = this.lookU8();\n object = this.decodeUtf8String(byteLength, 1);\n }\n else if (headByte === 0xda) {\n // str 16\n var byteLength = this.lookU16();\n object = this.decodeUtf8String(byteLength, 2);\n }\n else if (headByte === 0xdb) {\n // str 32\n var byteLength = this.lookU32();\n object = this.decodeUtf8String(byteLength, 4);\n }\n else if (headByte === 0xdc) {\n // array 16\n var size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else if (headByte === 0xdd) {\n // array 32\n var size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else if (headByte === 0xde) {\n // map 16\n var size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte === 0xdf) {\n // map 32\n var size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte === 0xc4) {\n // bin 8\n var size = this.lookU8();\n object = this.decodeBinary(size, 1);\n }\n else if (headByte === 0xc5) {\n // bin 16\n var size = this.lookU16();\n object = this.decodeBinary(size, 2);\n }\n else if (headByte === 0xc6) {\n // bin 32\n var size = this.lookU32();\n object = this.decodeBinary(size, 4);\n }\n else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n }\n else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n }\n else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n }\n else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n }\n else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n }\n else if (headByte === 0xc7) {\n // ext 8\n var size = this.lookU8();\n object = this.decodeExtension(size, 1);\n }\n else if (headByte === 0xc8) {\n // ext 16\n var size = this.lookU16();\n object = this.decodeExtension(size, 2);\n }\n else if (headByte === 0xc9) {\n // ext 32\n var size = this.lookU32();\n object = this.decodeExtension(size, 4);\n }\n else {\n throw new DecodeError(\"Unrecognized type byte: \".concat(prettyByte(headByte)));\n }\n this.complete();\n var stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n var state = stack[stack.length - 1];\n if (state.type === 0 /* State.ARRAY */) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n stack.pop();\n object = state.array;\n }\n else {\n continue DECODE;\n }\n }\n else if (state.type === 1 /* State.MAP_KEY */) {\n if (!isValidMapKeyType(object)) {\n throw new DecodeError(\"The type of key must be string or number but \" + typeof object);\n }\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n state.key = object;\n state.type = 2 /* State.MAP_VALUE */;\n continue DECODE;\n }\n else {\n // it must be `state.type === State.MAP_VALUE` here\n state.map[state.key] = object;\n state.readCount++;\n if (state.readCount === state.size) {\n stack.pop();\n object = state.map;\n }\n else {\n state.key = null;\n state.type = 1 /* State.MAP_KEY */;\n continue DECODE;\n }\n }\n }\n return object;\n }\n };\n Decoder.prototype.readHeadByte = function () {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n return this.headByte;\n };\n Decoder.prototype.complete = function () {\n this.headByte = HEAD_BYTE_REQUIRED;\n };\n Decoder.prototype.readArraySize = function () {\n var headByte = this.readHeadByte();\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n }\n else {\n throw new DecodeError(\"Unrecognized array type byte: \".concat(prettyByte(headByte)));\n }\n }\n }\n };\n Decoder.prototype.pushMapState = function (size) {\n if (size > this.maxMapLength) {\n throw new DecodeError(\"Max length exceeded: map length (\".concat(size, \") > maxMapLengthLength (\").concat(this.maxMapLength, \")\"));\n }\n this.stack.push({\n type: 1 /* State.MAP_KEY */,\n size: size,\n key: null,\n readCount: 0,\n map: {},\n });\n };\n Decoder.prototype.pushArrayState = function (size) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(\"Max length exceeded: array length (\".concat(size, \") > maxArrayLength (\").concat(this.maxArrayLength, \")\"));\n }\n this.stack.push({\n type: 0 /* State.ARRAY */,\n size: size,\n array: new Array(size),\n position: 0,\n });\n };\n Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {\n var _a;\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\"Max length exceeded: UTF-8 byte length (\".concat(byteLength, \") > maxStrLength (\").concat(this.maxStrLength, \")\"));\n }\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n var offset = this.pos + headerOffset;\n var object;\n if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n }\n else if (byteLength > TEXT_DECODER_THRESHOLD) {\n object = utf8DecodeTD(this.bytes, offset, byteLength);\n }\n else {\n object = utf8DecodeJs(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n };\n Decoder.prototype.stateIsMapKey = function () {\n if (this.stack.length > 0) {\n var state = this.stack[this.stack.length - 1];\n return state.type === 1 /* State.MAP_KEY */;\n }\n return false;\n };\n Decoder.prototype.decodeBinary = function (byteLength, headOffset) {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(\"Max length exceeded: bin length (\".concat(byteLength, \") > maxBinLength (\").concat(this.maxBinLength, \")\"));\n }\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n var offset = this.pos + headOffset;\n var object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n };\n Decoder.prototype.decodeExtension = function (size, headOffset) {\n if (size > this.maxExtLength) {\n throw new DecodeError(\"Max length exceeded: ext length (\".concat(size, \") > maxExtLength (\").concat(this.maxExtLength, \")\"));\n }\n var extType = this.view.getInt8(this.pos + headOffset);\n var data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n };\n Decoder.prototype.lookU8 = function () {\n return this.view.getUint8(this.pos);\n };\n Decoder.prototype.lookU16 = function () {\n return this.view.getUint16(this.pos);\n };\n Decoder.prototype.lookU32 = function () {\n return this.view.getUint32(this.pos);\n };\n Decoder.prototype.readU8 = function () {\n var value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n };\n Decoder.prototype.readI8 = function () {\n var value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n };\n Decoder.prototype.readU16 = function () {\n var value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n };\n Decoder.prototype.readI16 = function () {\n var value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n };\n Decoder.prototype.readU32 = function () {\n var value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n };\n Decoder.prototype.readI32 = function () {\n var value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n };\n Decoder.prototype.readU64 = function () {\n var value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n };\n Decoder.prototype.readI64 = function () {\n var value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n };\n Decoder.prototype.readF32 = function () {\n var value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n };\n Decoder.prototype.readF64 = function () {\n var value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n };\n return Decoder;\n}());\nexport { Decoder };\n//# sourceMappingURL=Decoder.mjs.map","import { utf8EncodeJs, utf8Count, TEXT_ENCODER_THRESHOLD, utf8EncodeTE } from \"./utils/utf8.mjs\";\nimport { ExtensionCodec } from \"./ExtensionCodec.mjs\";\nimport { setInt64, setUint64 } from \"./utils/int.mjs\";\nimport { ensureUint8Array } from \"./utils/typedArrays.mjs\";\nexport var DEFAULT_MAX_DEPTH = 100;\nexport var DEFAULT_INITIAL_BUFFER_SIZE = 2048;\nvar Encoder = /** @class */ (function () {\n function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {\n if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }\n if (context === void 0) { context = undefined; }\n if (maxDepth === void 0) { maxDepth = DEFAULT_MAX_DEPTH; }\n if (initialBufferSize === void 0) { initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE; }\n if (sortKeys === void 0) { sortKeys = false; }\n if (forceFloat32 === void 0) { forceFloat32 = false; }\n if (ignoreUndefined === void 0) { ignoreUndefined = false; }\n if (forceIntegerToFloat === void 0) { forceIntegerToFloat = false; }\n this.extensionCodec = extensionCodec;\n this.context = context;\n this.maxDepth = maxDepth;\n this.initialBufferSize = initialBufferSize;\n this.sortKeys = sortKeys;\n this.forceFloat32 = forceFloat32;\n this.ignoreUndefined = ignoreUndefined;\n this.forceIntegerToFloat = forceIntegerToFloat;\n this.pos = 0;\n this.view = new DataView(new ArrayBuffer(this.initialBufferSize));\n this.bytes = new Uint8Array(this.view.buffer);\n }\n Encoder.prototype.reinitializeState = function () {\n this.pos = 0;\n };\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n Encoder.prototype.encodeSharedRef = function (object) {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n };\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n Encoder.prototype.encode = function (object) {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n };\n Encoder.prototype.doEncode = function (object, depth) {\n if (depth > this.maxDepth) {\n throw new Error(\"Too deep objects in depth \".concat(depth));\n }\n if (object == null) {\n this.encodeNil();\n }\n else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n }\n else if (typeof object === \"number\") {\n this.encodeNumber(object);\n }\n else if (typeof object === \"string\") {\n this.encodeString(object);\n }\n else {\n this.encodeObject(object, depth);\n }\n };\n Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) {\n var requiredSize = this.pos + sizeToWrite;\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n };\n Encoder.prototype.resizeBuffer = function (newSize) {\n var newBuffer = new ArrayBuffer(newSize);\n var newBytes = new Uint8Array(newBuffer);\n var newView = new DataView(newBuffer);\n newBytes.set(this.bytes);\n this.view = newView;\n this.bytes = newBytes;\n };\n Encoder.prototype.encodeNil = function () {\n this.writeU8(0xc0);\n };\n Encoder.prototype.encodeBoolean = function (object) {\n if (object === false) {\n this.writeU8(0xc2);\n }\n else {\n this.writeU8(0xc3);\n }\n };\n Encoder.prototype.encodeNumber = function (object) {\n if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n }\n else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n }\n else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n }\n else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n }\n else {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n }\n }\n else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n }\n else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n }\n else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n }\n else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n }\n else {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n }\n }\n }\n else {\n // non-integer numbers\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n }\n else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n };\n Encoder.prototype.writeStringHeader = function (byteLength) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n }\n else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n }\n else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n }\n else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n }\n else {\n throw new Error(\"Too long string: \".concat(byteLength, \" bytes in UTF-8\"));\n }\n };\n Encoder.prototype.encodeString = function (object) {\n var maxHeaderSize = 1 + 4;\n var strLength = object.length;\n if (strLength > TEXT_ENCODER_THRESHOLD) {\n var byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeTE(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n else {\n var byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeJs(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n };\n Encoder.prototype.encodeObject = function (object, depth) {\n // try to encode objects with custom codec first of non-primitives\n var ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n }\n else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n }\n else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n }\n else if (typeof object === \"object\") {\n this.encodeMap(object, depth);\n }\n else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(\"Unrecognized object: \".concat(Object.prototype.toString.apply(object)));\n }\n };\n Encoder.prototype.encodeBinary = function (object) {\n var size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n }\n else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large binary: \".concat(size));\n }\n var bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n };\n Encoder.prototype.encodeArray = function (object, depth) {\n var size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n }\n else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large array: \".concat(size));\n }\n for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {\n var item = object_1[_i];\n this.doEncode(item, depth + 1);\n }\n };\n Encoder.prototype.countWithoutUndefined = function (object, keys) {\n var count = 0;\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var key = keys_1[_i];\n if (object[key] !== undefined) {\n count++;\n }\n }\n return count;\n };\n Encoder.prototype.encodeMap = function (object, depth) {\n var keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n }\n else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large map object: \".concat(size));\n }\n for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {\n var key = keys_2[_i];\n var value = object[key];\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n };\n Encoder.prototype.encodeExtension = function (ext) {\n var size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n }\n else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n }\n else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n }\n else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n }\n else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n }\n else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n }\n else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large extension object: \".concat(size));\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n };\n Encoder.prototype.writeU8 = function (value) {\n this.ensureBufferSizeToWrite(1);\n this.view.setUint8(this.pos, value);\n this.pos++;\n };\n Encoder.prototype.writeU8a = function (values) {\n var size = values.length;\n this.ensureBufferSizeToWrite(size);\n this.bytes.set(values, this.pos);\n this.pos += size;\n };\n Encoder.prototype.writeI8 = function (value) {\n this.ensureBufferSizeToWrite(1);\n this.view.setInt8(this.pos, value);\n this.pos++;\n };\n Encoder.prototype.writeU16 = function (value) {\n this.ensureBufferSizeToWrite(2);\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n };\n Encoder.prototype.writeI16 = function (value) {\n this.ensureBufferSizeToWrite(2);\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n };\n Encoder.prototype.writeU32 = function (value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n };\n Encoder.prototype.writeI32 = function (value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n };\n Encoder.prototype.writeF32 = function (value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n };\n Encoder.prototype.writeF64 = function (value) {\n this.ensureBufferSizeToWrite(8);\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n };\n Encoder.prototype.writeU64 = function (value) {\n this.ensureBufferSizeToWrite(8);\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n };\n Encoder.prototype.writeI64 = function (value) {\n this.ensureBufferSizeToWrite(8);\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n };\n return Encoder;\n}());\nexport { Encoder };\n//# sourceMappingURL=Encoder.mjs.map","/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nvar ExtData = /** @class */ (function () {\n function ExtData(type, data) {\n this.type = type;\n this.data = data;\n }\n return ExtData;\n}());\nexport { ExtData };\n//# sourceMappingURL=ExtData.mjs.map","// ExtensionCodec to handle MessagePack extensions\nimport { ExtData } from \"./ExtData.mjs\";\nimport { timestampExtension } from \"./timestamp.mjs\";\nvar ExtensionCodec = /** @class */ (function () {\n function ExtensionCodec() {\n // built-in extensions\n this.builtInEncoders = [];\n this.builtInDecoders = [];\n // custom extensions\n this.encoders = [];\n this.decoders = [];\n this.register(timestampExtension);\n }\n ExtensionCodec.prototype.register = function (_a) {\n var type = _a.type, encode = _a.encode, decode = _a.decode;\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n }\n else {\n // built-in extensions\n var index = 1 + type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n };\n ExtensionCodec.prototype.tryToEncode = function (object, context) {\n // built-in extensions\n for (var i = 0; i < this.builtInEncoders.length; i++) {\n var encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n var data = encodeExt(object, context);\n if (data != null) {\n var type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n // custom extensions\n for (var i = 0; i < this.encoders.length; i++) {\n var encodeExt = this.encoders[i];\n if (encodeExt != null) {\n var data = encodeExt(object, context);\n if (data != null) {\n var type = i;\n return new ExtData(type, data);\n }\n }\n }\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n };\n ExtensionCodec.prototype.decode = function (data, type, context) {\n var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n }\n else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n };\n ExtensionCodec.defaultCodec = new ExtensionCodec();\n return ExtensionCodec;\n}());\nexport { ExtensionCodec };\n//# sourceMappingURL=ExtensionCodec.mjs.map","import { Decoder } from \"./Decoder.mjs\";\nexport var defaultDecodeOptions = {};\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode(buffer, options) {\n if (options === void 0) { options = defaultDecodeOptions; }\n var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);\n return decoder.decode(buffer);\n}\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti(buffer, options) {\n if (options === void 0) { options = defaultDecodeOptions; }\n var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);\n return decoder.decodeMulti(buffer);\n}\n//# sourceMappingURL=decode.mjs.map","import { Encoder } from \"./Encoder.mjs\";\nvar defaultEncodeOptions = {};\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode(value, options) {\n if (options === void 0) { options = defaultEncodeOptions; }\n var encoder = new Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);\n return encoder.encodeSharedRef(value);\n}\n//# sourceMappingURL=encode.mjs.map","// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError.mjs\";\nimport { getInt64, setInt64 } from \"./utils/int.mjs\";\nexport var EXT_TIMESTAMP = -1;\nvar TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nvar TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\nexport function encodeTimeSpecToTimestamp(_a) {\n var sec = _a.sec, nsec = _a.nsec;\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n var rv = new Uint8Array(4);\n var view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n }\n else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n var secHigh = sec / 0x100000000;\n var secLow = sec & 0xffffffff;\n var rv = new Uint8Array(8);\n var view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n }\n else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n var rv = new Uint8Array(12);\n var view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\nexport function encodeDateToTimeSpec(date) {\n var msec = date.getTime();\n var sec = Math.floor(msec / 1e3);\n var nsec = (msec - sec * 1e3) * 1e6;\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n var nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\nexport function encodeTimestampExtension(object) {\n if (object instanceof Date) {\n var timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n }\n else {\n return null;\n }\n}\nexport function decodeTimestampToTimeSpec(data) {\n var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n var sec = view.getUint32(0);\n var nsec = 0;\n return { sec: sec, nsec: nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n var nsec30AndSecHigh2 = view.getUint32(0);\n var secLow32 = view.getUint32(4);\n var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n var nsec = nsec30AndSecHigh2 >>> 2;\n return { sec: sec, nsec: nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n var sec = getInt64(view, 4);\n var nsec = view.getUint32(0);\n return { sec: sec, nsec: nsec };\n }\n default:\n throw new DecodeError(\"Unrecognized data size for timestamp (expected 4, 8, or 12): \".concat(data.length));\n }\n}\nexport function decodeTimestampExtension(data) {\n var timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\nexport var timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n//# sourceMappingURL=timestamp.mjs.map","// Integer Utility\nexport var UINT32_MAX = 4294967295;\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\nexport function setUint64(view, offset, value) {\n var high = value / 4294967296;\n var low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\nexport function setInt64(view, offset, value) {\n var high = Math.floor(value / 4294967296);\n var low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\nexport function getInt64(view, offset) {\n var high = view.getInt32(offset);\n var low = view.getUint32(offset + 4);\n return high * 4294967296 + low;\n}\nexport function getUint64(view, offset) {\n var high = view.getUint32(offset);\n var low = view.getUint32(offset + 4);\n return high * 4294967296 + low;\n}\n//# sourceMappingURL=int.mjs.map","export function prettyByte(byte) {\n return \"\".concat(byte < 0 ? \"-\" : \"\", \"0x\").concat(Math.abs(byte).toString(16).padStart(2, \"0\"));\n}\n//# sourceMappingURL=prettyByte.mjs.map","export function ensureUint8Array(buffer) {\n if (buffer instanceof Uint8Array) {\n return buffer;\n }\n else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n else if (buffer instanceof ArrayBuffer) {\n return new Uint8Array(buffer);\n }\n else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\nexport function createDataView(buffer) {\n if (buffer instanceof ArrayBuffer) {\n return new DataView(buffer);\n }\n var bufferView = ensureUint8Array(buffer);\n return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n}\n//# sourceMappingURL=typedArrays.mjs.map","var _a, _b, _c;\n/* eslint-disable @typescript-eslint/no-unnecessary-condition */\nimport { UINT32_MAX } from \"./int.mjs\";\nvar TEXT_ENCODING_AVAILABLE = (typeof process === \"undefined\" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[\"TEXT_ENCODING\"]) !== \"never\") &&\n typeof TextEncoder !== \"undefined\" &&\n typeof TextDecoder !== \"undefined\";\nexport function utf8Count(str) {\n var strLength = str.length;\n var byteLength = 0;\n var pos = 0;\n while (pos < strLength) {\n var value = str.charCodeAt(pos++);\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n }\n else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n var extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n }\n else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\nexport function utf8EncodeJs(str, output, outputOffset) {\n var strLength = str.length;\n var offset = outputOffset;\n var pos = 0;\n while (pos < strLength) {\n var value = str.charCodeAt(pos++);\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n }\n else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n var extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\nvar sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;\nexport var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b[\"TEXT_ENCODING\"]) !== \"force\"\n ? 200\n : 0;\nfunction utf8EncodeTEencode(str, output, outputOffset) {\n output.set(sharedTextEncoder.encode(str), outputOffset);\n}\nfunction utf8EncodeTEencodeInto(str, output, outputOffset) {\n sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));\n}\nexport var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;\nvar CHUNK_SIZE = 4096;\nexport function utf8DecodeJs(bytes, inputOffset, byteLength) {\n var offset = inputOffset;\n var end = offset + byteLength;\n var units = [];\n var result = \"\";\n while (offset < end) {\n var byte1 = bytes[offset++];\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n }\n else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n var byte2 = bytes[offset++] & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n }\n else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n var byte2 = bytes[offset++] & 0x3f;\n var byte3 = bytes[offset++] & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n }\n else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n var byte2 = bytes[offset++] & 0x3f;\n var byte3 = bytes[offset++] & 0x3f;\n var byte4 = bytes[offset++] & 0x3f;\n var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n }\n else {\n units.push(byte1);\n }\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode.apply(String, units);\n units.length = 0;\n }\n }\n if (units.length > 0) {\n result += String.fromCharCode.apply(String, units);\n }\n return result;\n}\nvar sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;\nexport var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c[\"TEXT_DECODER\"]) !== \"force\"\n ? 200\n : 0;\nexport function utf8DecodeTD(bytes, inputOffset, byteLength) {\n var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder.decode(stringBytes);\n}\n//# sourceMappingURL=utf8.mjs.map","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { RPC, API_VERSION } from \"./rpc.js\";\nimport {\n assert,\n randId,\n waitFor,\n loadRequirements,\n parseServiceUrl,\n} from \"./utils/index.js\";\nimport { schemaFunction } from \"./utils/schema.js\";\nimport { getRTCService, registerRTCService } from \"./webrtc-client.js\";\n\nexport { RPC, API_VERSION, schemaFunction };\nexport { loadRequirements };\nexport { getRTCService, registerRTCService };\n\nconst MAX_RETRY = 1000000;\n\nclass WebsocketRPCConnection {\n constructor(\n server_url,\n client_id,\n workspace,\n token,\n reconnection_token = null,\n timeout = 60,\n WebSocketClass = null,\n token_refresh_interval = 2 * 60 * 60,\n additional_headers = null,\n ) {\n assert(server_url && client_id, \"server_url and client_id are required\");\n this._server_url = server_url;\n this._client_id = client_id;\n this._workspace = workspace;\n this._token = token;\n this._reconnection_token = reconnection_token;\n this._websocket = null;\n this._handle_message = null;\n this._handle_connected = null; // Connection open event handler\n this._handle_disconnected = null; // Disconnection event handler\n this._timeout = timeout;\n this._WebSocketClass = WebSocketClass || WebSocket; // Allow overriding the WebSocket class\n this._closed = false;\n this._legacy_auth = null;\n this.connection_info = null;\n this._enable_reconnect = false;\n this._token_refresh_interval = token_refresh_interval;\n this.manager_id = null;\n this._refresh_token_task = null;\n this._last_message = null; // Store the last sent message\n this._reconnect_timeouts = new Set(); // Track reconnection timeouts\n this._additional_headers = additional_headers;\n }\n\n /**\n * Centralized cleanup method to clear all timers and prevent resource leaks\n */\n _cleanup() {\n // Clear token refresh interval\n if (this._refresh_token_task) {\n clearInterval(this._refresh_token_task);\n this._refresh_token_task = null;\n }\n\n // Clear all reconnection timeouts\n for (const timeoutId of this._reconnect_timeouts) {\n clearTimeout(timeoutId);\n }\n this._reconnect_timeouts.clear();\n }\n\n on_message(handler) {\n assert(handler, \"handler is required\");\n this._handle_message = handler;\n }\n\n on_connected(handler) {\n this._handle_connected = handler;\n }\n\n on_disconnected(handler) {\n this._handle_disconnected = handler;\n }\n\n async _attempt_connection(server_url, attempt_fallback = true) {\n return new Promise((resolve, reject) => {\n this._legacy_auth = false;\n const websocket = new this._WebSocketClass(server_url);\n websocket.binaryType = \"arraybuffer\";\n\n websocket.onopen = () => {\n console.info(\"WebSocket connection established\");\n resolve(websocket);\n };\n\n websocket.onerror = (event) => {\n console.error(\"WebSocket connection error:\", event);\n reject(new Error(`WebSocket connection error: ${event}`));\n };\n\n websocket.onclose = (event) => {\n if (event.code === 1003 && attempt_fallback) {\n console.info(\n \"Received 1003 error, attempting connection with query parameters.\",\n );\n this._legacy_auth = true;\n this._attempt_connection_with_query_params(server_url)\n .then(resolve)\n .catch(reject);\n } else if (this._handle_disconnected) {\n this._handle_disconnected(event.reason);\n }\n };\n });\n }\n\n async _attempt_connection_with_query_params(server_url) {\n // Initialize an array to hold parts of the query string\n const queryParamsParts = [];\n\n // Conditionally add each parameter if it has a non-empty value\n if (this._client_id)\n queryParamsParts.push(`client_id=${encodeURIComponent(this._client_id)}`);\n if (this._workspace)\n queryParamsParts.push(`workspace=${encodeURIComponent(this._workspace)}`);\n if (this._token)\n queryParamsParts.push(`token=${encodeURIComponent(this._token)}`);\n if (this._reconnection_token)\n queryParamsParts.push(\n `reconnection_token=${encodeURIComponent(this._reconnection_token)}`,\n );\n\n // Join the parts with '&' to form the final query string, prepend '?' if there are any parameters\n const queryString =\n queryParamsParts.length > 0 ? `?${queryParamsParts.join(\"&\")}` : \"\";\n\n // Construct the full URL by appending the query string if it exists\n const full_url = server_url + queryString;\n\n return await this._attempt_connection(full_url, false);\n }\n\n _establish_connection() {\n return new Promise((resolve, reject) => {\n this._websocket.onmessage = (event) => {\n const data = event.data;\n const first_message = JSON.parse(data);\n if (first_message.type == \"connection_info\") {\n this.connection_info = first_message;\n if (this._workspace) {\n assert(\n this.connection_info.workspace === this._workspace,\n `Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`,\n );\n }\n if (this.connection_info.reconnection_token) {\n this._reconnection_token = this.connection_info.reconnection_token;\n }\n if (this.connection_info.reconnection_token_life_time) {\n // make sure the token refresh interval is less than the token life time\n if (\n this.token_refresh_interval >\n this.connection_info.reconnection_token_life_time / 1.5\n ) {\n console.warn(\n `Token refresh interval is too long (${this.token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`,\n );\n this.token_refresh_interval =\n this.connection_info.reconnection_token_life_time / 1.5;\n }\n }\n this.manager_id = this.connection_info.manager_id || null;\n console.log(\n `Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`,\n );\n if (this.connection_info.announcement) {\n console.log(`${this.connection_info.announcement}`);\n }\n resolve(this.connection_info);\n } else if (first_message.type == \"error\") {\n const error = \"ConnectionAbortedError: \" + first_message.message;\n console.error(\"Failed to connect, \" + error);\n reject(new Error(error));\n return;\n } else {\n console.error(\n \"ConnectionAbortedError: Unexpected message received from the server:\",\n data,\n );\n reject(\n new Error(\n \"ConnectionAbortedError: Unexpected message received from the server\",\n ),\n );\n return;\n }\n };\n });\n }\n\n async open() {\n console.log(\n \"Creating a new websocket connection to\",\n this._server_url.split(\"?\")[0],\n );\n try {\n this._websocket = await this._attempt_connection(this._server_url);\n if (this._legacy_auth) {\n throw new Error(\n \"NotImplementedError: Legacy authentication is not supported\",\n );\n }\n // Send authentication info as the first message if connected without query params\n const authInfo = JSON.stringify({\n client_id: this._client_id,\n workspace: this._workspace,\n token: this._token,\n reconnection_token: this._reconnection_token,\n });\n this._websocket.send(authInfo);\n // Wait for the first message from the server\n await waitFor(\n this._establish_connection(),\n this._timeout,\n \"Failed to receive the first message from the server\",\n );\n if (this._token_refresh_interval > 0) {\n setTimeout(() => {\n this._send_refresh_token();\n this._refresh_token_task = setInterval(() => {\n this._send_refresh_token();\n }, this._token_refresh_interval * 1000);\n }, 2000);\n }\n // Listen to messages from the server\n this._enable_reconnect = true;\n this._closed = false;\n this._websocket.onmessage = (event) => {\n if (typeof event.data === \"string\") {\n const parsedData = JSON.parse(event.data);\n // Check if the message is a reconnection token\n if (parsedData.type === \"reconnection_token\") {\n this._reconnection_token = parsedData.reconnection_token;\n // console.log(\"Reconnection token received\");\n } else {\n console.log(\"Received message from the server:\", parsedData);\n }\n } else {\n this._handle_message(event.data);\n }\n };\n\n this._websocket.onerror = (event) => {\n console.error(\"WebSocket connection error:\", event);\n // Clean up timers on error\n this._cleanup();\n };\n\n this._websocket.onclose = this._handle_close.bind(this);\n\n if (this._handle_connected) {\n this._handle_connected(this.connection_info);\n }\n return this.connection_info;\n } catch (error) {\n // Clean up any timers that might have been set up before the error\n this._cleanup();\n console.error(\n \"Failed to connect to\",\n this._server_url.split(\"?\")[0],\n error,\n );\n throw error;\n }\n }\n\n _send_refresh_token() {\n if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {\n const refreshMessage = JSON.stringify({ type: \"refresh_token\" });\n this._websocket.send(refreshMessage);\n // console.log(\"Requested refresh token\");\n }\n }\n\n _handle_close(event) {\n if (\n !this._closed &&\n this._websocket &&\n this._websocket.readyState === WebSocket.CLOSED\n ) {\n // Clean up timers when connection closes\n this._cleanup();\n\n // Even if it's a graceful closure (codes 1000, 1001), if it wasn't user-initiated,\n // we should attempt to reconnect (e.g., server restart, k8s upgrade)\n if (this._enable_reconnect) {\n if ([1000, 1001].includes(event.code)) {\n console.warn(\n `Websocket connection closed gracefully by server (code: ${event.code}): ${event.reason} - attempting reconnect`,\n );\n } else {\n console.warn(\n \"Websocket connection closed unexpectedly (code: %s): %s\",\n event.code,\n event.reason,\n );\n }\n\n let retry = 0;\n const baseDelay = 1000; // Start with 1 second\n const maxDelay = 60000; // Maximum delay of 60 seconds\n const maxJitter = 0.1; // Maximum jitter factor\n\n const reconnect = async () => {\n // Check if we were explicitly closed\n if (this._closed) {\n console.info(\"Connection was closed, stopping reconnection\");\n return;\n }\n\n try {\n console.warn(\n `Reconnecting to ${this._server_url.split(\"?\")[0]} (attempt #${retry})`,\n );\n // Open the connection, this will trigger the on_connected callback\n await this.open();\n\n // Wait a short time for services to be registered\n // This gives time for the on_connected callback to complete\n // which includes re-registering all services to the server\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n // Resend last message if there was one\n if (this._last_message) {\n console.info(\"Resending last message after reconnection\");\n this._websocket.send(this._last_message);\n this._last_message = null;\n }\n console.warn(\n `Successfully reconnected to server ${this._server_url} (services re-registered)`,\n );\n // Emit reconnection success event\n if (this._handle_connected) {\n this._handle_connected(this.connection_info);\n }\n } catch (e) {\n if (`${e}`.includes(\"ConnectionAbortedError:\")) {\n console.warn(\"Failed to reconnect, connection aborted:\", e);\n return;\n } else if (`${e}`.includes(\"NotImplementedError:\")) {\n console.error(\n `${e}\\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`,\n );\n return;\n }\n\n // Log specific error types for better debugging\n if (e.name === \"NetworkError\" || e.message.includes(\"network\")) {\n console.error(`Network error during reconnection: ${e.message}`);\n } else if (\n e.name === \"TimeoutError\" ||\n e.message.includes(\"timeout\")\n ) {\n console.error(\n `Connection timeout during reconnection: ${e.message}`,\n );\n } else {\n console.error(\n `Unexpected error during reconnection: ${e.message}`,\n );\n }\n\n // Calculate exponential backoff with jitter\n const delay = Math.min(baseDelay * Math.pow(2, retry), maxDelay);\n // Add jitter to prevent thundering herd\n const jitter = (Math.random() * 2 - 1) * maxJitter * delay;\n const finalDelay = Math.max(100, delay + jitter);\n\n console.debug(\n `Waiting ${(finalDelay / 1000).toFixed(2)}s before next reconnection attempt`,\n );\n\n // Track the reconnection timeout to prevent leaks\n const timeoutId = setTimeout(async () => {\n this._reconnect_timeouts.delete(timeoutId);\n\n // Check if connection was restored externally\n if (\n this._websocket &&\n this._websocket.readyState === WebSocket.OPEN\n ) {\n console.info(\"Connection restored externally\");\n return;\n }\n\n // Check if we were explicitly closed\n if (this._closed) {\n console.info(\"Connection was closed, stopping reconnection\");\n return;\n }\n\n retry += 1;\n if (retry < MAX_RETRY) {\n await reconnect();\n } else {\n console.error(\n `Failed to reconnect after ${MAX_RETRY} attempts, giving up. Exiting process.`,\n );\n // Notify about max retry exceeded\n if (this._handle_disconnected) {\n this._handle_disconnected(\n \"Max reconnection attempts exceeded\",\n );\n }\n // Exit process to prevent stuck event loop\n if (typeof process !== \"undefined\" && process.exit) {\n console.error(\n \"Forcing process exit due to unrecoverable connection failure\",\n );\n process.exit(1);\n }\n }\n }, finalDelay);\n this._reconnect_timeouts.add(timeoutId);\n }\n };\n reconnect();\n }\n } else {\n // Clean up timers in all cases\n this._cleanup();\n if (this._handle_disconnected) {\n this._handle_disconnected(event.reason);\n }\n }\n }\n\n async emit_message(data) {\n if (this._closed) {\n throw new Error(\"Connection is closed\");\n }\n if (!this._websocket || this._websocket.readyState !== WebSocket.OPEN) {\n await this.open();\n }\n try {\n this._last_message = data; // Store the message before sending\n this._websocket.send(data);\n this._last_message = null; // Clear after successful send\n } catch (exp) {\n console.error(`Failed to send data, error: ${exp}`);\n throw exp;\n }\n }\n\n disconnect(reason) {\n this._closed = true;\n this._last_message = null; // Clear last message on disconnect\n // Ensure websocket is closed if it exists and is not already closed or closing\n if (\n this._websocket &&\n this._websocket.readyState !== WebSocket.CLOSED &&\n this._websocket.readyState !== WebSocket.CLOSING\n ) {\n this._websocket.close(1000, reason);\n }\n // Use centralized cleanup to clear all timers\n this._cleanup();\n console.info(`WebSocket connection disconnected (${reason})`);\n }\n}\n\nfunction normalizeServerUrl(server_url) {\n if (!server_url) throw new Error(\"server_url is required\");\n if (server_url.startsWith(\"http://\")) {\n server_url =\n server_url.replace(\"http://\", \"ws://\").replace(/\\/$/, \"\") + \"/ws\";\n } else if (server_url.startsWith(\"https://\")) {\n server_url =\n server_url.replace(\"https://\", \"wss://\").replace(/\\/$/, \"\") + \"/ws\";\n }\n return server_url;\n}\n\nexport async function login(config) {\n const service_id = config.login_service_id || \"public/hypha-login\";\n const workspace = config.workspace;\n const expires_in = config.expires_in;\n const timeout = config.login_timeout || 60;\n const callback = config.login_callback;\n const profile = config.profile;\n const additional_headers = config.additional_headers;\n\n const server = await connectToServer({\n name: \"initial login client\",\n server_url: config.server_url,\n additional_headers: additional_headers,\n });\n try {\n const svc = await server.getService(service_id);\n assert(svc, `Failed to get the login service: ${service_id}`);\n let context;\n if (workspace) {\n context = await svc.start({ workspace, expires_in, _rkwargs: true });\n } else {\n context = await svc.start();\n }\n if (callback) {\n await callback(context);\n } else {\n console.log(`Please open your browser and login at ${context.login_url}`);\n }\n return await svc.check(context.key, { timeout, profile, _rkwargs: true });\n } catch (error) {\n throw error;\n } finally {\n await server.disconnect();\n }\n}\n\nasync function webrtcGetService(wm, rtc_service_id, query, config) {\n config = config || {};\n const webrtc = config.webrtc;\n const webrtc_config = config.webrtc_config;\n if (config.webrtc !== undefined) delete config.webrtc;\n if (config.webrtc_config !== undefined) delete config.webrtc_config;\n assert(\n [undefined, true, false, \"auto\"].includes(webrtc),\n \"webrtc must be true, false or 'auto'\",\n );\n\n const svc = await wm.getService(query, config);\n if (webrtc === true || webrtc === \"auto\") {\n if (svc.id.includes(\":\") && svc.id.includes(\"/\")) {\n try {\n // Assuming that the client registered a webrtc service with the client_id + \"-rtc\"\n const peer = await getRTCService(wm, rtc_service_id, webrtc_config);\n const rtcSvc = await peer.getService(svc.id.split(\":\")[1], config);\n rtcSvc._webrtc = true;\n rtcSvc._peer = peer;\n rtcSvc._service = svc;\n return rtcSvc;\n } catch (e) {\n console.warn(\n \"Failed to get webrtc service, using websocket connection\",\n e,\n );\n }\n }\n if (webrtc === true) {\n throw new Error(\"Failed to get the service via webrtc\");\n }\n }\n return svc;\n}\n\nexport async function connectToServer(config) {\n if (config.server) {\n config.server_url = config.server_url || config.server.url;\n config.WebSocketClass =\n config.WebSocketClass || config.server.WebSocketClass;\n }\n let clientId = config.client_id;\n if (!clientId) {\n clientId = randId();\n config.client_id = clientId;\n }\n if (Object.keys(config).length === 0) {\n if (typeof process !== \"undefined\" && process.env) {\n // Node.js\n config.server_url = process.env.HYPHA_SERVER_URL;\n config.token = process.env.HYPHA_TOKEN;\n config.client_id = process.env.HYPHA_CLIENT_ID;\n config.workspace = process.env.HYPHA_WORKSPACE;\n } else if (typeof self !== \"undefined\" && self.env) {\n // WebWorker (only if you inject self.env manually)\n config.server_url = self.env.HYPHA_SERVER_URL;\n config.token = self.env.HYPHA_TOKEN;\n config.client_id = self.env.HYPHA_CLIENT_ID;\n config.workspace = self.env.HYPHA_WORKSPACE;\n } else if (typeof globalThis !== \"undefined\" && globalThis.env) {\n // Browser (only if you define globalThis.env beforehand)\n config.server_url = globalThis.env.HYPHA_SERVER_URL;\n config.token = globalThis.env.HYPHA_TOKEN;\n config.client_id = globalThis.env.HYPHA_CLIENT_ID;\n config.workspace = globalThis.env.HYPHA_WORKSPACE;\n }\n }\n\n let server_url = normalizeServerUrl(config.server_url);\n\n let connection = new WebsocketRPCConnection(\n server_url,\n clientId,\n config.workspace,\n config.token,\n config.reconnection_token,\n config.method_timeout || 60,\n config.WebSocketClass,\n config.token_refresh_interval,\n config.additional_headers,\n );\n const connection_info = await connection.open();\n assert(\n connection_info,\n \"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version.\",\n );\n // wait for 0.5 seconds\n await new Promise((resolve) => setTimeout(resolve, 100));\n // Ensure manager_id is set before proceeding\n if (!connection.manager_id) {\n console.warn(\"Manager ID not set immediately, waiting...\");\n\n // Wait for manager_id to be set with timeout\n const maxWaitTime = 5000; // 5 seconds\n const checkInterval = 100; // 100ms\n const startTime = Date.now();\n\n while (!connection.manager_id && Date.now() - startTime < maxWaitTime) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n }\n\n if (!connection.manager_id) {\n console.error(\"Manager ID still not set after waiting\");\n throw new Error(\"Failed to get manager ID from server\");\n } else {\n console.info(`Manager ID set after waiting: ${connection.manager_id}`);\n }\n }\n if (config.workspace && connection_info.workspace !== config.workspace) {\n throw new Error(\n `Connected to the wrong workspace: ${connection_info.workspace}, expected: ${config.workspace}`,\n );\n }\n\n const workspace = connection_info.workspace;\n const rpc = new RPC(connection, {\n client_id: clientId,\n workspace,\n default_context: { connection_type: \"websocket\" },\n name: config.name,\n method_timeout: config.method_timeout,\n app_id: config.app_id,\n server_base_url: connection_info.public_base_url,\n long_message_chunk_size: config.long_message_chunk_size,\n });\n await rpc.waitFor(\"services_registered\", config.method_timeout || 120);\n const wm = await rpc.get_manager_service({\n timeout: config.method_timeout,\n case_conversion: \"camel\",\n kwargs_expansion: config.kwargs_expansion || false,\n });\n wm.rpc = rpc;\n\n async function _export(api) {\n api.id = \"default\";\n api.name = api.name || config.name || api.id;\n api.description = api.description || config.description;\n await rpc.register_service(api, { overwrite: true });\n }\n\n async function getApp(clientId) {\n clientId = clientId || \"*\";\n assert(!clientId.includes(\":\"), \"clientId should not contain ':'\");\n if (!clientId.includes(\"/\")) {\n clientId = connection_info.workspace + \"/\" + clientId;\n }\n assert(\n clientId.split(\"/\").length === 2,\n \"clientId should match pattern workspace/clientId\",\n );\n return await wm.getService(`${clientId}:default`);\n }\n\n async function listApps(ws) {\n ws = ws || workspace;\n assert(!ws.includes(\":\"), \"workspace should not contain ':'\");\n assert(!ws.includes(\"/\"), \"workspace should not contain '/'\");\n const query = { workspace: ws, service_id: \"default\" };\n return await wm.listServices(query);\n }\n\n if (connection_info) {\n wm.config = Object.assign(wm.config, connection_info);\n }\n wm.export = schemaFunction(_export, {\n name: \"export\",\n description: \"Export the api.\",\n parameters: {\n properties: { api: { description: \"The api to export\", type: \"object\" } },\n required: [\"api\"],\n type: \"object\",\n },\n });\n wm.getApp = schemaFunction(getApp, {\n name: \"getApp\",\n description: \"Get the app.\",\n parameters: {\n properties: {\n clientId: { default: \"*\", description: \"The clientId\", type: \"string\" },\n },\n type: \"object\",\n },\n });\n wm.listApps = schemaFunction(listApps, {\n name: \"listApps\",\n description: \"List the apps.\",\n parameters: {\n properties: {\n workspace: {\n default: workspace,\n description: \"The workspace\",\n type: \"string\",\n },\n },\n type: \"object\",\n },\n });\n wm.disconnect = schemaFunction(rpc.disconnect.bind(rpc), {\n name: \"disconnect\",\n description: \"Disconnect from the server.\",\n parameters: { type: \"object\", properties: {}, required: [] },\n });\n wm.registerCodec = schemaFunction(rpc.register_codec.bind(rpc), {\n name: \"registerCodec\",\n description: \"Register a codec for the webrtc connection\",\n parameters: {\n type: \"object\",\n properties: {\n codec: {\n type: \"object\",\n description: \"Codec to register\",\n properties: {\n name: { type: \"string\" },\n type: {},\n encoder: { type: \"function\" },\n decoder: { type: \"function\" },\n },\n },\n },\n },\n });\n\n wm.emit = schemaFunction(rpc.emit.bind(rpc), {\n name: \"emit\",\n description: \"Emit a message.\",\n parameters: {\n properties: { data: { description: \"The data to emit\", type: \"object\" } },\n required: [\"data\"],\n type: \"object\",\n },\n });\n\n wm.on = schemaFunction(rpc.on.bind(rpc), {\n name: \"on\",\n description: \"Register a message handler.\",\n parameters: {\n properties: {\n event: { description: \"The event to listen to\", type: \"string\" },\n handler: { description: \"The handler function\", type: \"function\" },\n },\n required: [\"event\", \"handler\"],\n type: \"object\",\n },\n });\n\n wm.off = schemaFunction(rpc.off.bind(rpc), {\n name: \"off\",\n description: \"Remove a message handler.\",\n parameters: {\n properties: {\n event: { description: \"The event to remove\", type: \"string\" },\n handler: { description: \"The handler function\", type: \"function\" },\n },\n required: [\"event\", \"handler\"],\n type: \"object\",\n },\n });\n\n wm.once = schemaFunction(rpc.once.bind(rpc), {\n name: \"once\",\n description: \"Register a one-time message handler.\",\n parameters: {\n properties: {\n event: { description: \"The event to listen to\", type: \"string\" },\n handler: { description: \"The handler function\", type: \"function\" },\n },\n required: [\"event\", \"handler\"],\n type: \"object\",\n },\n });\n\n wm.getServiceSchema = schemaFunction(rpc.get_service_schema, {\n name: \"getServiceSchema\",\n description: \"Get the service schema.\",\n parameters: {\n properties: {\n service: {\n description: \"The service to extract schema\",\n type: \"object\",\n },\n },\n required: [\"service\"],\n type: \"object\",\n },\n });\n\n wm.registerService = schemaFunction(rpc.register_service.bind(rpc), {\n name: \"registerService\",\n description: \"Register a service.\",\n parameters: {\n properties: {\n service: { description: \"The service to register\", type: \"object\" },\n force: {\n default: false,\n description: \"Force to register the service\",\n type: \"boolean\",\n },\n },\n required: [\"service\"],\n type: \"object\",\n },\n });\n wm.unregisterService = schemaFunction(rpc.unregister_service.bind(rpc), {\n name: \"unregisterService\",\n description: \"Unregister a service.\",\n parameters: {\n properties: {\n service: {\n description: \"The service id to unregister\",\n type: \"string\",\n },\n notify: {\n default: true,\n description: \"Notify the workspace manager\",\n type: \"boolean\",\n },\n },\n required: [\"service\"],\n type: \"object\",\n },\n });\n if (connection.manager_id) {\n rpc.on(\"force-exit\", async (message) => {\n if (message.from === \"*/\" + connection.manager_id) {\n console.log(\"Disconnecting from server, reason:\", message.reason);\n await rpc.disconnect();\n }\n });\n }\n if (config.webrtc) {\n await registerRTCService(wm, `${clientId}-rtc`, config.webrtc_config);\n // make a copy of wm, so webrtc can use the original wm.getService\n const _wm = Object.assign({}, wm);\n const description = _wm.getService.__schema__.description;\n // TODO: Fix the schema for adding options for webrtc\n const parameters = _wm.getService.__schema__.parameters;\n wm.getService = schemaFunction(\n webrtcGetService.bind(null, _wm, `${workspace}/${clientId}-rtc`),\n {\n name: \"getService\",\n description,\n parameters,\n },\n );\n\n wm.getRTCService = schemaFunction(getRTCService.bind(null, wm), {\n name: \"getRTCService\",\n description: \"Get the webrtc connection, returns a peer connection.\",\n parameters: {\n properties: {\n config: {\n description: \"The config for the webrtc service\",\n type: \"object\",\n },\n },\n required: [\"config\"],\n type: \"object\",\n },\n });\n } else {\n const _getService = wm.getService;\n wm.getService = (query, config) => {\n config = config || {};\n return _getService(query, config);\n };\n wm.getService.__schema__ = _getService.__schema__;\n }\n\n async function registerProbes(probes) {\n probes.id = \"probes\";\n probes.name = \"Probes\";\n probes.config = { visibility: \"public\" };\n probes.type = \"probes\";\n probes.description = `Probes Service, visit ${server_url}/${workspace}services/probes for the available probes.`;\n return await wm.registerService(probes, { overwrite: true });\n }\n\n wm.registerProbes = schemaFunction(registerProbes, {\n name: \"registerProbes\",\n description: \"Register probes service\",\n parameters: {\n properties: {\n probes: {\n description:\n \"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}\",\n type: \"object\",\n },\n },\n required: [\"probes\"],\n type: \"object\",\n },\n });\n return wm;\n}\n\nexport async function getRemoteService(serviceUri, config = {}) {\n const { serverUrl, workspace, clientId, serviceId, appId } =\n parseServiceUrl(serviceUri);\n const fullServiceId = `${workspace}/${clientId}:${serviceId}@${appId}`;\n\n if (config.serverUrl) {\n if (config.serverUrl !== serverUrl) {\n throw new Error(\n \"server_url in config does not match the server_url in the url\",\n );\n }\n }\n config.serverUrl = serverUrl;\n const server = await connectToServer(config);\n return await server.getService(fullServiceId);\n}\n\nexport class LocalWebSocket {\n constructor(url, client_id, workspace) {\n this.url = url;\n this.onopen = () => {};\n this.onmessage = () => {};\n this.onclose = () => {};\n this.onerror = () => {};\n this.client_id = client_id;\n this.workspace = workspace;\n const context = typeof window !== \"undefined\" ? window : self;\n const isWindow = typeof window !== \"undefined\";\n this.postMessage = (message) => {\n if (isWindow) {\n window.parent.postMessage(message, \"*\");\n } else {\n self.postMessage(message);\n }\n };\n\n this.readyState = WebSocket.CONNECTING;\n context.addEventListener(\n \"message\",\n (event) => {\n const { type, data, to } = event.data;\n if (to !== this.client_id) {\n // console.debug(\"message not for me\", to, this.client_id);\n return;\n }\n switch (type) {\n case \"message\":\n if (this.readyState === WebSocket.OPEN && this.onmessage) {\n this.onmessage({ data: data });\n }\n break;\n case \"connected\":\n this.readyState = WebSocket.OPEN;\n this.onopen(event);\n break;\n case \"closed\":\n this.readyState = WebSocket.CLOSED;\n this.onclose(event);\n break;\n default:\n break;\n }\n },\n false,\n );\n\n if (!this.client_id) throw new Error(\"client_id is required\");\n if (!this.workspace) throw new Error(\"workspace is required\");\n this.postMessage({\n type: \"connect\",\n url: this.url,\n from: this.client_id,\n workspace: this.workspace,\n });\n }\n\n send(data) {\n if (this.readyState === WebSocket.OPEN) {\n this.postMessage({\n type: \"message\",\n data: data,\n from: this.client_id,\n workspace: this.workspace,\n });\n }\n }\n\n close() {\n this.readyState = WebSocket.CLOSING;\n this.postMessage({\n type: \"close\",\n from: this.client_id,\n workspace: this.workspace,\n });\n this.onclose();\n }\n\n addEventListener(type, listener) {\n if (type === \"message\") {\n this.onmessage = listener;\n }\n if (type === \"open\") {\n this.onopen = listener;\n }\n if (type === \"close\") {\n this.onclose = listener;\n }\n if (type === \"error\") {\n this.onerror = listener;\n }\n }\n}\n\nexport function setupLocalClient({\n enable_execution = false,\n on_ready = null,\n}) {\n return new Promise((resolve, reject) => {\n const context = typeof window !== \"undefined\" ? window : self;\n const isWindow = typeof window !== \"undefined\";\n context.addEventListener(\n \"message\",\n (event) => {\n const {\n type,\n server_url,\n workspace,\n client_id,\n token,\n method_timeout,\n name,\n config,\n } = event.data;\n\n if (type === \"initializeHyphaClient\") {\n if (!server_url || !workspace || !client_id) {\n console.error(\"server_url, workspace, and client_id are required.\");\n return;\n }\n\n if (!server_url.startsWith(\"https://local-hypha-server:\")) {\n console.error(\n \"server_url should start with https://local-hypha-server:\",\n );\n return;\n }\n\n class FixedLocalWebSocket extends LocalWebSocket {\n constructor(url) {\n // Call the parent class's constructor with fixed values\n super(url, client_id, workspace);\n }\n }\n connectToServer({\n server_url,\n workspace,\n client_id,\n token,\n method_timeout,\n name,\n WebSocketClass: FixedLocalWebSocket,\n }).then(async (server) => {\n globalThis.api = server;\n try {\n // for iframe\n if (isWindow && enable_execution) {\n function loadScript(script) {\n return new Promise((resolve, reject) => {\n const scriptElement = document.createElement(\"script\");\n scriptElement.innerHTML = script.content;\n scriptElement.lang = script.lang;\n\n scriptElement.onload = () => resolve();\n scriptElement.onerror = (e) => reject(e);\n\n document.head.appendChild(scriptElement);\n });\n }\n if (config.styles && config.styles.length > 0) {\n for (const style of config.styles) {\n const styleElement = document.createElement(\"style\");\n styleElement.innerHTML = style.content;\n styleElement.lang = style.lang;\n document.head.appendChild(styleElement);\n }\n }\n if (config.links && config.links.length > 0) {\n for (const link of config.links) {\n const linkElement = document.createElement(\"a\");\n linkElement.href = link.url;\n linkElement.innerText = link.text;\n document.body.appendChild(linkElement);\n }\n }\n if (config.windows && config.windows.length > 0) {\n for (const w of config.windows) {\n document.body.innerHTML = w.content;\n break;\n }\n }\n if (config.scripts && config.scripts.length > 0) {\n for (const script of config.scripts) {\n if (script.lang !== \"javascript\")\n throw new Error(\"Only javascript scripts are supported\");\n await loadScript(script); // Await the loading of each script\n }\n }\n }\n // for web worker\n else if (\n !isWindow &&\n enable_execution &&\n config.scripts &&\n config.scripts.length > 0\n ) {\n for (const script of config.scripts) {\n if (script.lang !== \"javascript\")\n throw new Error(\"Only javascript scripts are supported\");\n eval(script.content);\n }\n }\n\n if (on_ready) {\n await on_ready(server, config);\n }\n resolve(server);\n } catch (e) {\n reject(e);\n }\n });\n }\n },\n false,\n );\n if (isWindow) {\n window.parent.postMessage({ type: \"hyphaClientReady\" }, \"*\");\n } else {\n self.postMessage({ type: \"hyphaClientReady\" });\n }\n });\n}\n"],"names":[],"sourceRoot":""}
|
|
1
|
+
{"version":3,"file":"hypha-rpc-websocket.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;;;;;;ACVA;AACA;AACA;AACA;AAa0B;AACyB;;AAEqB;;AAEjE;AACP;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,IAAI;AACJ,aAAa;AACb,IAAI;AACJ,aAAa;AACb,IAAI;AACJ,aAAa;AACb,IAAI;AACJ,aAAa;AACb,IAAI;AACJ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,wCAAwC,IAAI,wBAAwB,KAAK;AACzE;AACA;;AAEA;AACA;AACA;AACA,2CAA2C,IAAI,wBAAwB,KAAK;AAC5E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,KAAK,GAAG,EAAE;AACnC;AACA;AACA,UAAU;AACV;AACA,4BAA4B,gEAAc;AAC1C;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA,8CAA8C,EAAE,aAAa,QAAQ;AACrE;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,oDAAoD,KAAK;AACzD;AACA;AACA,yBAAyB,KAAK,GAAG,EAAE;AACnC;AACA;AACA,UAAU;AACV;AACA,4BAA4B,gEAAc;AAC1C;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA,sDAAsD,GAAG,WAAW,QAAQ;AAC5E;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0CAA0C;AAC1C;;AAEA;AACA,sCAAsC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,wCAAwC,YAAY;AACpD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACO,kBAAkB,2DAAc;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,IAAI,uDAAM;AACV,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC;AAClC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,mCAAmC,2CAA2C;AAC9E,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA,uCAAuC,sBAAsB,GAAG,gBAAgB;AAChF;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;;AAEA,MAAM,uDAAM;AACZ,MAAM,uDAAM;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD,wBAAwB;AAC9E;AACA,gBAAgB;AAChB;AACA;AACA,gDAAgD,wBAAwB,IAAI,aAAa;AACzF;AACA;AACA;;AAEA;AACA;AACA,+CAA+C,iBAAiB;AAChE;AACA,cAAc;AACd;AACA,mCAAmC,iBAAiB,SAAS,eAAe,6CAA6C,0BAA0B;AACnJ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa;;AAEb;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,UAAU,GAAG,SAAS;AAClE;AACA,gCAAgC,cAAc;AAC9C;AACA;AACA,oBAAoB;AACpB;AACA,gCAAgC,UAAU;AAC1C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA,sEAAsE,eAAe;AACrF;AACA;AACA;AACA,YAAY;AACZ;AACA,yEAAyE,aAAa;AACtF;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,IAAI,uDAAM;AACV;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,sCAAsC,IAAI;AAC1C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA;;AAEA;AACA;AACA;AACA,2DAA2D,IAAI;AAC/D;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA,2CAA2C,KAAK,SAAS,sBAAsB;AAC/E,mBAAmB,6DAAW;AAC9B,YAAY,cAAc;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,KAAK,SAAS,sBAAsB;AAClE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,qBAAqB,6DAAW;AAChC,cAAc,cAAc;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,iEAAiE,EAAE;AACnE;AACA,aAAa;AACb;AACA;AACA;AACA,QAAQ;AACR,uEAAuE,EAAE;AACzE;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,8DAA8D,EAAE;AAChE;AACA;AACA;AACA;AACA,MAAM;AACN,2DAA2D,EAAE;AAC7D;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,wDAAwD,EAAE;AAC1D;;AAEA;AACA;;AAEA;AACA;AACA,0DAA0D,SAAS;;AAEnE;AACA;;AAEA;AACA;AACA,wBAAwB,iBAAiB,oCAAoC,SAAS;AACtF;AACA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA,mDAAmD,SAAS,IAAI,EAAE;AAClE;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,6CAA6C,WAAW;AACxD;AACA,6DAA6D,SAAS;AACtE,YAAY;AACZ,oDAAoD,WAAW,IAAI,EAAE;AACrE;AACA;;AAEA;AACA,6CAA6C,YAAY;AACzD;AACA,8DAA8D,SAAS;AACvE,YAAY;AACZ,oDAAoD,WAAW,IAAI,EAAE;AACrE;AACA;;AAEA;AACA;AACA;AACA;AACA,YAAY;AACZ,qDAAqD,WAAW,IAAI,EAAE;AACtE;AACA;;AAEA;AACA;AACA;AACA;AACA,YAAY;AACZ,yDAAyD,WAAW,IAAI,EAAE;AAC1E;AACA;;AAEA;AACA;AACA;AACA,6CAA6C,WAAW;AACxD;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd,uEAAuE,EAAE;AACzE;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd,qDAAqD,EAAE;AACvD;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN,2DAA2D,EAAE;AAC7D;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAQ;AACR,oEAAoE,EAAE;AACtE;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,0BAA0B,sBAAsB;AAChD;AACA;AACA,eAAe,4BAA4B;AAC3C,YAAY,uCAAuC;AACnD;AACA;AACA,QAAQ;AACR;AACA;AACA,oDAAoD,YAAY,GAAG,WAAW,KAAK,UAAU;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,4BAA4B;;AAE5B,0BAA0B,sBAAsB;AAChD;AACA;AACA;AACA,+CAA+C,WAAW,cAAc,YAAY,GAAG,WAAW;AAClG;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA,eAAe,4BAA4B;AAC3C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,0DAA0D,WAAW,MAAM,UAAU;AACrF;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV,IAAI,uDAAM;;AAEV;AACA,IAAI,uDAAM;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0DAA0D,WAAW,wBAAwB,IAAI,KAAK,cAAc;AACpH;AACA;AACA;AACA,UAAU,6CAA6C;AACvD;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,uDAAM;AACd;AACA,6BAA6B,QAAQ,KAAK,aAAa;AACvD;AACA;AACA,IAAI,uDAAM,mCAAmC,YAAY;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,sBAAsB,wDAAO;AAC7B;AACA;AACA;AACA;AACA,kBAAkB,SAAS,GAAG,WAAW;AACzC;AACA,cAAc,6DAAY;AAC1B;AACA;AACA;AACA;AACA,UAAU,4DAAW;AACrB;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC,YAAY;AACZ;AACA,yCAAyC,4BAA4B,uBAAuB,iBAAiB,KAAK,UAAU;AAC5H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA,+BAA+B,IAAI;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,uDAAM;;AAEV;AACA;AACA;AACA;AACA;AACA,mGAAmG,WAAW;AAC9G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gFAAgF,aAAa;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA,qCAAqC,OAAO,uCAAuC,OAAO;AAC1F;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,iBAAiB,GAAG,gBAAgB,GAAG,cAAc;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,UAAU,gCAAgC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,QAAQ;AACR,sDAAsD,SAAS,WAAW,EAAE;AAC5E;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,QAAQ;AACR,+DAA+D,EAAE;AACjE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,IAAI,uDAAM;AACV;AACA,6BAA6B,WAAW;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,WAAW;AACvD;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;;AAEA;AACA,mBAAmB,kEAAiB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,WAAW,GAAG,KAAK;AAC1C;AACA;AACA;AACA,aAAa,gBAAgB,GAAG,gBAAgB;AAChD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,+BAA+B,UAAU,IAAI,YAAY,KAAK,MAAM;AACpE;AACA,QAAQ;AACR;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,UAAU;AACtD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iCAAiC,YAAY;AAC7C;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,YAAY;AAC7C;AACA;AACA,UAAU;AACV;AACA,4DAA4D,WAAW;AACvE;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,YAAY,2BAA2B,cAAc;AACpF;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN,uDAAuD,WAAW;AAClE;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,YAAY;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,gDAAgD,WAAW;AAC3D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,qDAAqD,WAAW;AAChE;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,sBAAsB,uBAAuB;AAC7C;AACA;AACA;AACA,4BAA4B,YAAY,qBAAqB,MAAM;AACnE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,WAAW;;AAEvD;AACA;AACA;AACA,MAAM;AACN;AACA,iDAAiD,WAAW;AAC5D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,YAAY;AAC3D;;AAEA;AACA,wBAAwB,WAAW;AACnC;AACA,sCAAsC;AACtC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,MAAM,IAAI,0CAA0C;AACvG;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,uCAAuC,eAAe;AACtD;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,WAAW;AACrD;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,YAAY;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA;;AAEA;AACA;AACA;AACA,SAAS,UAAU;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qCAAqC,uDAAM;AAC3C;AACA,mCAAmC;AACnC;AACA;AACA;AACA,4BAA4B,sDAAS;;AAErC;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gCAAgC,QAAQ,GAAG,WAAW,SAAS,YAAY;AAC3E;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,UAAU;AACV;AACA,6DAA6D,aAAa;AAC1E;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,QAAQ,GAAG,WAAW,SAAS,YAAY;AACzE;AACA;AACA;AACA;AACA;AACA,oCAAoC,YAAY,iBAAiB,aAAa;AAC9E;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,wDAAa;AACvC;AACA,oBAAoB,wDAAa;AACjC;AACA;AACA;AACA;AACA,kDAAkD,WAAW;AAC7D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,UAAU,UAAU,qBAAqB;AAC5E;;AAEA;AACA;AACA,+BAA+B,uDAAM;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,kBAAkB,YAAY,YAAY;AACtG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,sCAAsC,UAAU,GAAG,UAAU,aAAa,iBAAiB;AAC3F;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,UAAU,GAAG,UAAU;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,kBAAkB;AACxD;AACA;AACA;;AAEA;AACA;AACA;AACA,uCAAuC,YAAY,aAAa,YAAY;AAC5E;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;AACA,YAAY;AACZ,yDAAyD,aAAa;AACtE;AACA;AACA;AACA,8BAA8B,wDAAa;AAC3C;AACA,wBAAwB,wDAAa;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,mFAAmF,UAAU,GAAG,UAAU,YAAY,IAAI;AAC1H;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,mFAAmF,UAAU,GAAG,UAAU,YAAY,IAAI;AAC1H;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,OAAO;AACP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gDAAgD,UAAU;AAC1D;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM,uDAAM;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,UAAU,uDAAM;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,8BAA8B,gBAAgB,sDAAsD,YAAY;AAChH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,YAAY,oBAAoB,gBAAgB,sCAAsC,YAAY;AAC3H;AACA;AACA;AACA,+DAA+D,YAAY;AAC3E;AACA;AACA,YAAY;AACZ;AACA,yBAAyB,YAAY,uBAAuB,eAAe,uBAAuB,YAAY;AAC9G;AACA;AACA;AACA,qDAAqD,YAAY;AACjE;AACA;AACA;AACA;;AAEA;AACA,mCAAmC,aAAa,KAAK,gBAAgB;AACrE;AACA;AACA,+BAA+B,aAAa,KAAK,gBAAgB;AACjE;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,MAAM,uDAAM;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ,uDAAM;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,uBAAuB;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA,sEAAsE,YAAY,aAAa,eAAe,UAAU,YAAY;AACpI;AACA;AACA,4CAA4C,aAAa,GAAG,YAAY;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa,OAAO;AACpB;AACA,eAAe,OAAO;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,iEAAiE,QAAQ,oBAAoB,sBAAsB;AACnH;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,QAAQ,4DAAW,aAAa,iEAAgB;AAChD;AACA,MAAM,uDAAM;AACZ;AACA;AACA;AACA,wBAAwB,uDAAM;;AAE9B;AACA;AACA,MAAM,uDAAM;AACZ;AACA,0CAA0C,YAAY;AACtD;;AAEA;AACA,sBAAsB,iEAAgB;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,qBAAqB,WAAW,GAAG,UAAU;AAC7C;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,QAAQ,uDAAM;AACd;AACA;AACA,yBAAyB,uDAAM,GAAG,GAAG,iBAAiB;AACtD,UAAU;AACV,sBAAsB,uDAAM;AAC5B;AACA;AACA;AACA;AACA;AACA,uBAAuB,WAAW,GAAG,UAAU;AAC/C;AACA;AACA;AACA;AACA,QAAQ,uDAAM;AACd;AACA,4CAA4C,YAAY;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,aAAa;AAC5C;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kEAAiB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,oBAAoB,kEAAiB;AACrC;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,iDAAiD,QAAQ;AACzD;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,4BAA4B,8DAAiB;AAC7C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,QAAQ;AACR,0BAA0B,8DAAiB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,WAAW;AACX,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,YAAY;AAC7D,OAAO;AACP;AACA;AACA;AACA;AACA,+CAA+C,YAAY;AAC3D,OAAO;AACP;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D,OAAO;AACP;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzzFO;AACP;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;;AAEO;AACP;AACA,gBAAgB;AAChB;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,yCAAyC,IAAI;AAC7C;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB,sCAAsC;AACtC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,qCAAqC;AACrC;AACA;AACA,QAAQ;AACR,2CAA2C;AAC3C;AACA;AACA;;AAEA;AACA;;AAEO;AACP;AACA,gBAAgB;AAChB;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4CAA4C;AAC5C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,4CAA4C;AAC5C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,WAAW;AACX;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,yBAAyB;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA,YAAY;AACZ;AACA,YAAY;AACZ;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yBAAyB;AAC/C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;;AAEO;AACP;AACA;AACA,wDAAwD,aAAa;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,GAAG;AACH;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;;AAEO;AACP;AACA;AACA;AACA;;AAEA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,SAAS;AACtB;AACO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,KAAK;AAChB,aAAa,SAAS;AACtB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;AC5hBoC;;AAEpC;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH,mBAAmB,kCAAkC;AACrD,mBAAmB,kCAAkC;AACrD,oBAAoB,mCAAmC;AACvD,oBAAoB,mCAAmC;AACvD,uBAAuB,wCAAwC;;AAE/D;AACA,2BAA2B,4BAA4B;AACvD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,wBAAwB;AAClE;AACA;AACA,CAAC;;AAEM;AACP;AACA,IAAI,0EAA0E;AAC9E;AACA;AACA;AACA;AACA,EAAE,iDAAM;;AAER;AACA;AACA,EAAE,iDAAM;;AAER;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAE,iDAAM;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;ACjF+B;AACmB;AACC;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,6BAA6B;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA,MAAM;AACN,mDAAmD,IAAI;AACvD;AACA;AACA;;AAEA;AACA;AACA;AACA,0DAA0D,OAAO;AACjE;AACA;;AAEA;AACA,EAAE,uDAAM;AACR,EAAE,uDAAM;AACR;AACA,uCAAuC,uDAAM;AAC7C;AACA;AACA;AACA;AACA,kBAAkB,wCAAG;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,QAAQ,wCAAwC;AAChD;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAqC,uDAAM;;AAE3C;AACA;AACA,QAAQ,wCAAwC;AAChD;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,UAAU;;AAEf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;;AAEA,2DAA2D,eAAe;AAC1E;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,uDAAM;AACtB;AACA;AACA;AACA,gBAAgB,uDAAM;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,gEAAc;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA,qBAAqB;AACrB,mBAAmB;AACnB;AACA,iBAAiB;AACjB,eAAe;AACf,8BAA8B,gEAAc;AAC5C;AACA;AACA,8BAA8B,gCAAgC;AAC9D,eAAe;AACf,iCAAiC,gEAAc;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,gBAAgB;AAChD,gCAAgC;AAChC,mCAAmC,kBAAkB;AACrD,mCAAmC,kBAAkB;AACrD,uBAAuB;AACvB,qBAAqB;AACrB,mBAAmB;AACnB,iBAAiB;AACjB,eAAe;AACf;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,SAAS;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kDAAkD,MAAM;AACxD;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAE6C;;;;;;;;;;;;;;;;ACtXG;AAChD;AACA;AACA;AACA;AACA,uCAAuC;AACvC,0CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,uBAAuB;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,uBAAuB;AACjF;AACA;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,6DAAY;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAC2B;AAC5B;;;;;;;;;;;;;;AC/DA,iBAAiB,SAAI,IAAI,SAAI;AAC7B;AACA;AACA,eAAe,gBAAgB,sCAAsC,kBAAkB;AACvF,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,CAAC;AACsB;AACvB;;;;;;;;;;;;;;;;;;;;;;AChCA,iBAAiB,SAAI,IAAI,SAAI;AAC7B,4BAA4B,+DAA+D,iBAAiB;AAC5G;AACA,oCAAoC,MAAM,+BAA+B,YAAY;AACrF,mCAAmC,MAAM,mCAAmC,YAAY;AACxF,gCAAgC;AAChC;AACA,KAAK;AACL;AACA,mBAAmB,SAAI,IAAI,SAAI;AAC/B,cAAc,6BAA6B,0BAA0B,cAAc,qBAAqB;AACxG,iBAAiB,oDAAoD,qEAAqE,cAAc;AACxJ,uBAAuB,sBAAsB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC;AACxC,mCAAmC,SAAS;AAC5C,mCAAmC,WAAW,UAAU;AACxD,0CAA0C,cAAc;AACxD;AACA,8GAA8G,OAAO;AACrH,iFAAiF,iBAAiB;AAClG,yDAAyD,gBAAgB,QAAQ;AACjF,+CAA+C,gBAAgB,gBAAgB;AAC/E;AACA,kCAAkC;AAClC;AACA;AACA,UAAU,YAAY,aAAa,SAAS,UAAU;AACtD,oCAAoC,SAAS;AAC7C;AACA;AACA,qBAAqB,SAAI,IAAI,SAAI;AACjC;AACA;AACA,2GAA2G,uFAAuF,cAAc;AAChN,uBAAuB,8BAA8B,gDAAgD,wDAAwD;AAC7J,6CAA6C,sCAAsC,UAAU,mBAAmB,IAAI;AACpH;AACA,eAAe,SAAI,IAAI,SAAI,4BAA4B;AACvD,wBAAwB,SAAI,IAAI,SAAI;AACpC;AACA;AACA,iBAAiB,uFAAuF,cAAc;AACtH,uBAAuB,gCAAgC,qCAAqC,2CAA2C;AACvI,4BAA4B,MAAM,iBAAiB,YAAY;AAC/D,uBAAuB;AACvB,8BAA8B;AAC9B,6BAA6B;AAC7B,4BAA4B;AAC5B;AACoD;AACE;AACY;AACoB;AACX;AACjB;AACV;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA,iCAAiC,mEAAgB;AACjD;AACA;AACA,yCAAyC,iBAAiB,+DAAc;AACxE,kCAAkC;AAClC,uCAAuC,eAAe,sDAAU;AAChE,uCAAuC,eAAe,sDAAU;AAChE,yCAAyC,iBAAiB,sDAAU;AACpE,uCAAuC,eAAe,sDAAU;AAChE,uCAAuC,eAAe,sDAAU;AAChE,qCAAqC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,wEAAgB;AACrC,oBAAoB,sEAAc;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,wEAAgB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oFAAoF,iEAAU;AAC9F;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,KAAK,EAAE,EAAwB;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,yDAAW,mCAAmC,iEAAU;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,yDAAW;AAC7C;AACA;AACA,kCAAkC,yDAAW;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,yDAAW,yCAAyC,iEAAU;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB;AACnB,SAAS;AACT;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,mEAAsB;AACpD,qBAAqB,6DAAY;AACjC;AACA;AACA,qBAAqB,6DAAY;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,yDAAS;AAC7B;AACA;AACA;AACA;AACA,oBAAoB,wDAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACkB;AACnB;;;;;;;;;;;;;;;;;;;;AC7tBiG;AAC3C;AACA;AACK;AACpD;AACA;AACP;AACA;AACA,yCAAyC,iBAAiB,+DAAc;AACxE,kCAAkC;AAClC,mCAAmC;AACnC,4CAA4C;AAC5C,mCAAmC;AACnC,uCAAuC;AACvC,0CAA0C;AAC1C,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,qBAAqB,0FAA0F,qBAAqB;AACzK;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,mEAAsB;AAC9C,6BAA6B,0DAAS;AACtC;AACA;AACA,YAAY,6DAAY;AACxB;AACA;AACA;AACA,6BAA6B,0DAAS;AACtC;AACA;AACA,YAAY,6DAAY;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,wEAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,oBAAoB;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,oBAAoB;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,yDAAS;AACjB;AACA;AACA;AACA;AACA,QAAQ,wDAAQ;AAChB;AACA;AACA;AACA,CAAC;AACkB;AACnB;;;;;;;;;;;;;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACkB;AACnB;;;;;;;;;;;;;;;;ACXA;AACwC;AACa;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,8DAAkB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,iCAAiC;AACzD;AACA;AACA;AACA;AACA;AACA,+BAA+B,iDAAO;AACtC;AACA;AACA;AACA;AACA,wBAAwB,0BAA0B;AAClD;AACA;AACA;AACA;AACA;AACA,+BAA+B,iDAAO;AACtC;AACA;AACA;AACA,8BAA8B,iDAAO;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,iDAAO;AAC9B;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B;;;;;;;;;;;;;;;;;ACtEwC;AACjC;AACP;AACA;AACA;AACA;AACA,kDAAkD,oBAAoB,GAAG,qBAAqB,MAAM,0BAA0B;AAC9H;AACA,YAAY,kBAAkB;AAC9B,YAAY,mBAAmB;AAC/B;AACO;AACP,8BAA8B;AAC9B,sBAAsB,iDAAO;AAC7B;AACA;AACA;AACA;AACA,6BAA6B,0BAA0B;AACvD;AACA,YAAY,kBAAkB;AAC9B,YAAY,mBAAmB;AAC/B;AACO;AACP,8BAA8B;AAC9B,sBAAsB,iDAAO;AAC7B;AACA;AACA;;;;;;;;;;;;;;;AC5BwC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,8BAA8B;AAC9B,sBAAsB,iDAAO;AAC7B;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;ACbA;AACgD;AACK;AAC9C;AACP,2CAA2C;AAC3C,2CAA2C;AACpC;AACP;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B;AACA;AACA;AACA,QAAQ,wDAAQ;AAChB;AACA;AACA;AACO;AACP;AACA;AACA;AACA,oBAAoB,YAAY;AAChC;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA,qBAAqB;AACrB;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA,gCAAgC;AAChC,sBAAsB,wDAAQ;AAC9B;AACA,qBAAqB;AACrB;AACA;AACA,sBAAsB,yDAAW;AACjC;AACA;AACO;AACP;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;AChGA;AACO;AACP;AACA;AACO;AACP;AACA,qBAAqB;AACrB;AACA;AACA;AACO;AACP;AACA,qBAAqB;AACrB;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;AC1BO;AACP;AACA;AACA;;;;;;;;;;;;;;;ACHO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;ACtBA;AACA;AACuC;AACvC;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,MAAM,gDAAU;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,MAAM,gDAAU;AAChB;AACA;AACA;AACO;AACP;AACA;AACA;AACA;;;;;;UC/JA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;;;;WCtBA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;ACN4C;AAOlB;AACyB;AACoB;;AAE3B;AAChB;AACiB;;AAE7C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC,sCAAsC;AACtC;AACA,wDAAwD;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B,0CAA0C;AAC1C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAI,uDAAM;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,wDAAwD,MAAM;AAC9D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA,yCAAyC,oCAAoC;AAC7E;AACA,yCAAyC,oCAAoC;AAC7E;AACA,qCAAqC,gCAAgC;AACrE;AACA;AACA,8BAA8B,6CAA6C;AAC3E;;AAEA;AACA;AACA,wCAAwC,2BAA2B;;AAEnE;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uDAAM;AAClB;AACA,mDAAmD,+BAA+B,cAAc,gBAAgB;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,4BAA4B,oDAAoD,kDAAkD;AACzL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,+BAA+B,gBAAgB,gBAAgB;AAC/H;AACA;AACA,2BAA2B,kCAAkC;AAC7D;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,YAAY,wDAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,8CAA8C,uBAAuB;AACrE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,uEAAuE,WAAW,KAAK,cAAc;AACrG;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,gCAAgC;AAChC,gCAAgC;AAChC,+BAA+B;;AAE/B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iCAAiC,gCAAgC,YAAY,MAAM;AACnF;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,kBAAkB;AACtE;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,mBAAmB,EAAE;AACrB;AACA;AACA,cAAc,YAAY,EAAE;AAC5B;AACA,mBAAmB,EAAE;AACrB;AACA;AACA;;AAEA;AACA;AACA,kEAAkE,UAAU;AAC5E,cAAc;AACd;AACA;AACA;AACA;AACA,2DAA2D,UAAU;AACrE;AACA,cAAc;AACd;AACA,yDAAyD,UAAU;AACnE;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB,+BAA+B;AACxD;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAgB;AAChB;AACA,+CAA+C,WAAW;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC;AACjC;AACA,iCAAiC;AACjC,MAAM;AACN,mDAAmD,IAAI;AACvD;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,OAAO;AAC9D;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,IAAI,uDAAM,0CAA0C,WAAW;AAC/D;AACA;AACA,kCAAkC,uCAAuC;AACzE,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN,2DAA2D,kBAAkB;AAC7E;AACA,0CAA0C,kCAAkC;AAC5E,IAAI;AACJ;AACA,IAAI;AACJ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,uDAAM;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2BAA2B,gEAAa;AACxC;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,uDAAM;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,uDAAM;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,8BAA8B;AAC9B,+BAA+B;AAC/B;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN,oDAAoD,sBAAsB;AAC1E;AACA;AACA;AACA;AACA,2CAA2C,0BAA0B,cAAc,iBAAiB;AACpG;AACA;;AAEA;AACA,kBAAkB,wCAAG;AACrB;AACA;AACA,uBAAuB,8BAA8B;AACrD;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA,sCAAsC,iBAAiB;AACvD;;AAEA;AACA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA,IAAI,uDAAM;AACV;AACA;AACA;AACA,kCAAkC,SAAS;AAC3C;;AAEA;AACA;AACA,IAAI,uDAAM;AACV,IAAI,uDAAM;AACV,oBAAoB;AACpB;AACA;;AAEA;AACA;AACA;AACA,cAAc,gEAAc;AAC5B;AACA;AACA;AACA,oBAAoB,OAAO,oDAAoD;AAC/E;AACA;AACA,KAAK;AACL,GAAG;AACH,cAAc,gEAAc;AAC5B;AACA;AACA;AACA;AACA,oBAAoB,2DAA2D;AAC/E,OAAO;AACP;AACA,KAAK;AACL,GAAG;AACH,gBAAgB,gEAAc;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA,KAAK;AACL,GAAG;AACH,kBAAkB,gEAAc;AAChC;AACA;AACA,kBAAkB,8BAA8B,gBAAgB;AAChE,GAAG;AACH,qBAAqB,gEAAc;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC,oBAAoB;AACpB,uBAAuB,kBAAkB;AACzC,uBAAuB,kBAAkB;AACzC,WAAW;AACX,SAAS;AACT,OAAO;AACP,KAAK;AACL,GAAG;;AAEH,YAAY,gEAAc;AAC1B;AACA;AACA;AACA,oBAAoB,QAAQ,mDAAmD;AAC/E;AACA;AACA,KAAK;AACL,GAAG;;AAEH,UAAU,gEAAc;AACxB;AACA;AACA;AACA;AACA,iBAAiB,uDAAuD;AACxE,mBAAmB,uDAAuD;AAC1E,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,WAAW,gEAAc;AACzB;AACA;AACA;AACA;AACA,iBAAiB,oDAAoD;AACrE,mBAAmB,uDAAuD;AAC1E,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,YAAY,gEAAc;AAC1B;AACA;AACA;AACA;AACA,iBAAiB,uDAAuD;AACxE,mBAAmB,uDAAuD;AAC1E,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,wBAAwB,gEAAc;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;;AAEH,uBAAuB,gEAAc;AACrC;AACA;AACA;AACA;AACA,mBAAmB,wDAAwD;AAC3E;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;AACH,yBAAyB,gEAAc;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,UAAU,qEAAkB,QAAQ,SAAS;AAC7C;AACA,gCAAgC;AAChC;AACA;AACA;AACA,oBAAoB,gEAAc;AAClC,0CAA0C,UAAU,GAAG,SAAS;AAChE;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA,uBAAuB,gEAAc,CAAC,4DAAa;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA,OAAO;AACP,KAAK;AACL,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,kDAAkD,WAAW,GAAG,UAAU;AAC1E,8CAA8C,iBAAiB;AAC/D;;AAEA,sBAAsB,gEAAc;AACpC;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,aAAa,wEAAwE;AAChI;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;;AAEO,uDAAuD;AAC9D,UAAU,mDAAmD;AAC7D,IAAI,gEAAe;AACnB,2BAA2B,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,MAAM;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAgB,iBAAiB;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,YAAY;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;;AAEV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,mBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP;AACA;AACA;AACA,kCAAkC,0BAA0B;AAC5D,MAAM;AACN,yBAAyB,0BAA0B;AACnD;AACA,GAAG;AACH","sources":["webpack://hyphaWebsocketClient/webpack/universalModuleDefinition","webpack://hyphaWebsocketClient/./src/rpc.js","webpack://hyphaWebsocketClient/./src/utils/index.js","webpack://hyphaWebsocketClient/./src/utils/schema.js","webpack://hyphaWebsocketClient/./src/webrtc-client.js","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs","webpack://hyphaWebsocketClient/./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs","webpack://hyphaWebsocketClient/webpack/bootstrap","webpack://hyphaWebsocketClient/webpack/runtime/define property getters","webpack://hyphaWebsocketClient/webpack/runtime/hasOwnProperty shorthand","webpack://hyphaWebsocketClient/webpack/runtime/make namespace object","webpack://hyphaWebsocketClient/./src/websocket-client.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"hyphaWebsocketClient\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"hyphaWebsocketClient\"] = factory();\n\telse\n\t\troot[\"hyphaWebsocketClient\"] = factory();\n})(this, () => {\nreturn ","/**\n * Contains the RPC object used both by the application\n * site, and by each plugin\n */\nimport {\n randId,\n typedArrayToDtype,\n dtypeToTypedArray,\n MessageEmitter,\n assert,\n waitFor,\n convertCase,\n expandKwargs,\n Semaphore,\n isAsyncGenerator,\n isGenerator,\n} from \"./utils/index.js\";\nimport { schemaFunction } from \"./utils/schema.js\";\n\nimport { encode as msgpack_packb, decodeMulti } from \"@msgpack/msgpack\";\n\nexport const API_VERSION = 3;\nconst CHUNK_SIZE = 1024 * 256;\nconst CONCURRENCY_LIMIT = 30;\n\nconst ArrayBufferView = Object.getPrototypeOf(\n Object.getPrototypeOf(new Uint8Array()),\n).constructor;\n\nfunction _appendBuffer(buffer1, buffer2) {\n const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);\n tmp.set(new Uint8Array(buffer1), 0);\n tmp.set(new Uint8Array(buffer2), buffer1.byteLength);\n return tmp.buffer;\n}\n\nfunction indexObject(obj, is) {\n if (!is) throw new Error(\"undefined index\");\n if (typeof is === \"string\") return indexObject(obj, is.split(\".\"));\n else if (is.length === 0) return obj;\n else return indexObject(obj[is[0]], is.slice(1));\n}\n\n// Simple fallback schema generation - no docstring parsing for JS\n\nfunction _get_schema(obj, name = null, skipContext = false) {\n if (Array.isArray(obj)) {\n return obj.map((v, i) => _get_schema(v, null, skipContext));\n } else if (typeof obj === \"object\" && obj !== null) {\n let schema = {};\n for (let k in obj) {\n schema[k] = _get_schema(obj[k], k, skipContext);\n }\n return schema;\n } else if (typeof obj === \"function\") {\n if (obj.__schema__) {\n const schema = JSON.parse(JSON.stringify(obj.__schema__));\n if (name) {\n schema.name = name;\n obj.__schema__.name = name;\n }\n if (skipContext) {\n if (schema.parameters && schema.parameters.properties) {\n delete schema.parameters.properties[\"context\"];\n }\n if (schema.parameters && schema.parameters.required) {\n const contextIndex = schema.parameters.required.indexOf(\"context\");\n if (contextIndex > -1) {\n schema.parameters.required.splice(contextIndex, 1);\n }\n }\n }\n return { type: \"function\", function: schema };\n } else {\n // Simple fallback for JavaScript - just return basic function schema with name\n const funcName = name || obj.name || \"function\";\n return {\n type: \"function\",\n function: {\n name: funcName,\n },\n };\n }\n } else if (typeof obj === \"number\") {\n return { type: \"number\" };\n } else if (typeof obj === \"string\") {\n return { type: \"string\" };\n } else if (typeof obj === \"boolean\") {\n return { type: \"boolean\" };\n } else if (obj === null) {\n return { type: \"null\" };\n } else {\n return {};\n }\n}\n\nfunction _annotate_service(service, serviceTypeInfo) {\n function validateKeys(serviceDict, schemaDict, path = \"root\") {\n // Validate that all keys in schemaDict exist in serviceDict\n for (let key in schemaDict) {\n if (!serviceDict.hasOwnProperty(key)) {\n throw new Error(`Missing key '${key}' in service at path '${path}'`);\n }\n }\n\n // Check for any unexpected keys in serviceDict\n for (let key in serviceDict) {\n if (key !== \"type\" && !schemaDict.hasOwnProperty(key)) {\n throw new Error(`Unexpected key '${key}' in service at path '${path}'`);\n }\n }\n }\n\n function annotateRecursive(newService, schemaInfo, path = \"root\") {\n if (typeof newService === \"object\" && !Array.isArray(newService)) {\n validateKeys(newService, schemaInfo, path);\n for (let k in newService) {\n let v = newService[k];\n let newPath = `${path}.${k}`;\n if (typeof v === \"object\" && !Array.isArray(v)) {\n annotateRecursive(v, schemaInfo[k], newPath);\n } else if (typeof v === \"function\") {\n if (schemaInfo.hasOwnProperty(k)) {\n newService[k] = schemaFunction(v, {\n name: schemaInfo[k][\"name\"],\n description: schemaInfo[k].description || \"\",\n parameters: schemaInfo[k][\"parameters\"],\n });\n } else {\n throw new Error(\n `Missing schema for function '${k}' at path '${newPath}'`,\n );\n }\n }\n }\n } else if (Array.isArray(newService)) {\n if (newService.length !== schemaInfo.length) {\n throw new Error(`Length mismatch at path '${path}'`);\n }\n newService.forEach((v, i) => {\n let newPath = `${path}[${i}]`;\n if (typeof v === \"object\" && !Array.isArray(v)) {\n annotateRecursive(v, schemaInfo[i], newPath);\n } else if (typeof v === \"function\") {\n if (schemaInfo.hasOwnProperty(i)) {\n newService[i] = schemaFunction(v, {\n name: schemaInfo[i][\"name\"],\n description: schemaInfo[i].description || \"\",\n parameters: schemaInfo[i][\"parameters\"],\n });\n } else {\n throw new Error(\n `Missing schema for function at index ${i} in path '${newPath}'`,\n );\n }\n }\n });\n }\n }\n\n validateKeys(service, serviceTypeInfo[\"definition\"]);\n annotateRecursive(service, serviceTypeInfo[\"definition\"]);\n return service;\n}\n\nfunction getFunctionInfo(func) {\n const funcString = func.toString();\n\n // Extract function name\n const nameMatch = funcString.match(/function\\s*(\\w*)/);\n const name = (nameMatch && nameMatch[1]) || \"\";\n\n // Extract function parameters, excluding comments\n const paramsMatch = funcString.match(/\\(([^)]*)\\)/);\n let params = \"\";\n if (paramsMatch) {\n params = paramsMatch[1]\n .split(\",\")\n .map((p) =>\n p\n .replace(/\\/\\*.*?\\*\\//g, \"\") // Remove block comments\n .replace(/\\/\\/.*$/g, \"\"),\n ) // Remove line comments\n .filter((p) => p.trim().length > 0) // Remove empty strings after removing comments\n .map((p) => p.trim()) // Trim remaining whitespace\n .join(\", \");\n }\n\n // Extract function docstring (block comment)\n let docMatch = funcString.match(/\\)\\s*\\{\\s*\\/\\*([\\s\\S]*?)\\*\\//);\n const docstringBlock = (docMatch && docMatch[1].trim()) || \"\";\n\n // Extract function docstring (line comment)\n docMatch = funcString.match(/\\)\\s*\\{\\s*(\\/\\/[\\s\\S]*?)\\n\\s*[^\\s\\/]/);\n const docstringLine =\n (docMatch &&\n docMatch[1]\n .split(\"\\n\")\n .map((s) => s.replace(/^\\/\\/\\s*/, \"\").trim())\n .join(\"\\n\")) ||\n \"\";\n\n const docstring = docstringBlock || docstringLine;\n return (\n name &&\n params.length > 0 && {\n name: name,\n sig: params,\n doc: docstring,\n }\n );\n}\n\nfunction concatArrayBuffers(buffers) {\n var buffersLengths = buffers.map(function (b) {\n return b.byteLength;\n }),\n totalBufferlength = buffersLengths.reduce(function (p, c) {\n return p + c;\n }, 0),\n unit8Arr = new Uint8Array(totalBufferlength);\n buffersLengths.reduce(function (p, c, i) {\n unit8Arr.set(new Uint8Array(buffers[i]), p);\n return p + c;\n }, 0);\n return unit8Arr.buffer;\n}\n\nclass Timer {\n constructor(timeout, callback, args, label) {\n this._timeout = timeout;\n this._callback = callback;\n this._args = args;\n this._label = label || \"timer\";\n this._task = null;\n this.started = false;\n }\n\n start() {\n if (this.started) {\n this.reset();\n } else {\n this._task = setTimeout(() => {\n this._callback.apply(this, this._args);\n }, this._timeout * 1000);\n this.started = true;\n }\n }\n\n clear() {\n if (this._task && this.started) {\n clearTimeout(this._task);\n this._task = null;\n this.started = false;\n } else {\n console.warn(`Clearing a timer (${this._label}) which is not started`);\n }\n }\n\n reset() {\n if (this._task) {\n clearTimeout(this._task);\n }\n this._task = setTimeout(() => {\n this._callback.apply(this, this._args);\n }, this._timeout * 1000);\n this.started = true;\n }\n}\n\nclass RemoteService extends Object {}\n\n/**\n * RPC object represents a single site in the\n * communication protocol between the application and the plugin\n *\n * @param {Object} connection a special object allowing to send\n * and receive messages from the opposite site (basically it\n * should only provide send() and onMessage() methods)\n */\nexport class RPC extends MessageEmitter {\n constructor(\n connection,\n {\n client_id = null,\n default_context = null,\n name = null,\n codecs = null,\n method_timeout = null,\n max_message_buffer_size = 0,\n debug = false,\n workspace = null,\n silent = false,\n app_id = null,\n server_base_url = null,\n long_message_chunk_size = null,\n },\n ) {\n super(debug);\n this._codecs = codecs || {};\n assert(client_id && typeof client_id === \"string\");\n assert(client_id, \"client_id is required\");\n this._client_id = client_id;\n this._name = name;\n this._app_id = app_id || \"*\";\n this._local_workspace = workspace;\n this._silent = silent;\n this.default_context = default_context || {};\n this._method_annotations = new WeakMap();\n this._max_message_buffer_size = max_message_buffer_size;\n this._chunk_store = {};\n this._method_timeout = method_timeout || 30;\n this._server_base_url = server_base_url;\n this._long_message_chunk_size = long_message_chunk_size || CHUNK_SIZE;\n\n // make sure there is an execute function\n this._services = {};\n this._object_store = {\n services: this._services,\n };\n\n // Track background tasks for proper cleanup\n this._background_tasks = new Set();\n\n // Set up global unhandled promise rejection handler for RPC-related errors\n const handleUnhandledRejection = (event) => {\n const reason = event.reason;\n if (reason && typeof reason === \"object\") {\n // Check if this is a \"Method not found\" or \"Session not found\" error that we can ignore\n const reasonStr = reason.toString();\n if (\n reasonStr.includes(\"Method not found\") ||\n reasonStr.includes(\"Session not found\") ||\n reasonStr.includes(\"Method expired\") ||\n reasonStr.includes(\"Session not found\")\n ) {\n console.debug(\n \"Ignoring expected method/session not found error:\",\n reason,\n );\n event.preventDefault(); // Prevent the default unhandled rejection behavior\n return;\n }\n }\n console.warn(\"Unhandled RPC promise rejection:\", reason);\n };\n\n // Only set the handler if we haven't already set one for this RPC instance\n if (typeof window !== \"undefined\" && !window._hypha_rejection_handler_set) {\n window.addEventListener(\"unhandledrejection\", handleUnhandledRejection);\n window._hypha_rejection_handler_set = true;\n } else if (\n typeof process !== \"undefined\" &&\n !process._hypha_rejection_handler_set\n ) {\n process.on(\"unhandledRejection\", (reason, promise) => {\n handleUnhandledRejection({ reason, promise, preventDefault: () => {} });\n });\n process._hypha_rejection_handler_set = true;\n }\n\n if (connection) {\n this.add_service({\n id: \"built-in\",\n type: \"built-in\",\n name: `Built-in services for ${this._local_workspace}/${this._client_id}`,\n config: {\n require_context: true,\n visibility: \"public\",\n api_version: API_VERSION,\n },\n ping: this._ping.bind(this),\n get_service: this.get_local_service.bind(this),\n message_cache: {\n create: this._create_message.bind(this),\n append: this._append_message.bind(this),\n set: this._set_message.bind(this),\n process: this._process_message.bind(this),\n remove: this._remove_message.bind(this),\n },\n });\n this.on(\"method\", this._handle_method.bind(this));\n this.on(\"error\", console.error);\n\n assert(connection.emit_message && connection.on_message);\n assert(\n connection.manager_id !== undefined,\n \"Connection must have manager_id\",\n );\n this._emit_message = connection.emit_message.bind(connection);\n connection.on_message(this._on_message.bind(this));\n this._connection = connection;\n const onConnected = async (connectionInfo) => {\n if (!this._silent && this._connection.manager_id) {\n console.debug(\"Connection established, reporting services...\");\n try {\n // Retry getting manager service with exponential backoff\n const manager = await this._get_manager_with_retry();\n const services = Object.values(this._services);\n const servicesCount = services.length;\n let registeredCount = 0;\n const failedServices = [];\n\n for (let service of services) {\n try {\n const serviceInfo = this._extract_service_info(service);\n await manager.registerService(serviceInfo);\n registeredCount++;\n console.debug(\n `Successfully registered service: ${service.id || \"unknown\"}`,\n );\n } catch (serviceError) {\n failedServices.push(service.id || \"unknown\");\n console.error(\n `Failed to register service ${service.id || \"unknown\"}: ${serviceError}`,\n );\n }\n }\n\n if (registeredCount === servicesCount) {\n console.info(\n `Successfully registered all ${registeredCount} services with the server`,\n );\n } else {\n console.warn(\n `Only registered ${registeredCount} out of ${servicesCount} services with the server. Failed services: ${failedServices.join(\", \")}`,\n );\n }\n\n // Fire event with registration status\n this._fire(\"services_registered\", {\n total: servicesCount,\n registered: registeredCount,\n failed: failedServices,\n });\n\n // Subscribe to client_disconnected events if the manager supports it\n try {\n if (\n manager.subscribe &&\n typeof manager.subscribe === \"function\"\n ) {\n console.debug(\"Subscribing to client_disconnected events\");\n\n const handleClientDisconnected = async (event) => {\n // The client ID is in event.data.id based on the event structure\n const clientId = event.data?.id || event.client;\n const workspace = event.data?.workspace;\n if (clientId && workspace) {\n // Construct the full client path with workspace prefix\n const fullClientId = `${workspace}/${clientId}`;\n console.debug(\n `Client ${fullClientId} disconnected, cleaning up sessions`,\n );\n await this._handleClientDisconnected(fullClientId);\n } else if (clientId) {\n console.debug(\n `Client ${clientId} disconnected, cleaning up sessions`,\n );\n await this._handleClientDisconnected(clientId);\n }\n };\n\n // Subscribe to the event topic first\n this._clientDisconnectedSubscription = await manager.subscribe([\n \"client_disconnected\",\n ]);\n\n // Then register the local event handler\n this.on(\"client_disconnected\", handleClientDisconnected);\n\n console.debug(\n \"Successfully subscribed to client_disconnected events\",\n );\n } else {\n console.debug(\n \"Manager does not support subscribe method, skipping client_disconnected handling\",\n );\n this._clientDisconnectedSubscription = null;\n }\n } catch (subscribeError) {\n console.warn(\n `Failed to subscribe to client_disconnected events: ${subscribeError}`,\n );\n this._clientDisconnectedSubscription = null;\n }\n } catch (managerError) {\n console.error(\n `Failed to get manager service for registering services: ${managerError}`,\n );\n // Fire event with error status\n this._fire(\"services_registration_failed\", {\n error: managerError.toString(),\n total_services: Object.keys(this._services).length,\n });\n }\n } else {\n // console.debug(\"Connection established\", connectionInfo);\n }\n if (connectionInfo) {\n if (connectionInfo.public_base_url) {\n this._server_base_url = connectionInfo.public_base_url;\n }\n this._fire(\"connected\", connectionInfo);\n }\n };\n connection.on_connected(onConnected);\n onConnected();\n } else {\n this._emit_message = function () {\n console.log(\"No connection to emit message\");\n };\n }\n }\n\n register_codec(config) {\n if (!config[\"name\"] || (!config[\"encoder\"] && !config[\"decoder\"])) {\n throw new Error(\n \"Invalid codec format, please make sure you provide a name, type, encoder and decoder.\",\n );\n } else {\n if (config.type) {\n for (let k of Object.keys(this._codecs)) {\n if (this._codecs[k].type === config.type || k === config.name) {\n delete this._codecs[k];\n console.warn(\"Remove duplicated codec: \" + k);\n }\n }\n }\n this._codecs[config[\"name\"]] = config;\n }\n }\n\n async _ping(msg, context) {\n assert(msg == \"ping\");\n return \"pong\";\n }\n\n async ping(client_id, timeout) {\n let method = this._generate_remote_method({\n _rserver: this._server_base_url,\n _rtarget: client_id,\n _rmethod: \"services.built-in.ping\",\n _rpromise: true,\n _rdoc: \"Ping a remote client\",\n });\n assert((await method(\"ping\", timeout)) == \"pong\");\n }\n\n _create_message(key, heartbeat, overwrite, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n\n if (!this._object_store[\"message_cache\"]) {\n this._object_store[\"message_cache\"] = {};\n }\n if (!overwrite && this._object_store[\"message_cache\"][key]) {\n throw new Error(\n `Message with the same key (${key}) already exists in the cache store, please use overwrite=true or remove it first.`,\n );\n }\n this._object_store[\"message_cache\"][key] = [];\n }\n\n _append_message(key, data, heartbeat, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n const cache = this._object_store[\"message_cache\"];\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n assert(data instanceof ArrayBufferView);\n cache[key].push(data);\n }\n\n _set_message(key, index, data, heartbeat, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n const cache = this._object_store[\"message_cache\"];\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n assert(data instanceof ArrayBufferView);\n cache[key][index] = data;\n }\n\n _remove_message(key, context) {\n const cache = this._object_store[\"message_cache\"];\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n delete cache[key];\n }\n\n _process_message(key, heartbeat, context) {\n if (heartbeat) {\n if (!this._object_store[key]) {\n throw new Error(`session does not exist anymore: ${key}`);\n }\n this._object_store[key][\"timer\"].reset();\n }\n const cache = this._object_store[\"message_cache\"];\n assert(!!context, \"Context is required\");\n if (!cache[key]) {\n throw new Error(`Message with key ${key} does not exists.`);\n }\n cache[key] = concatArrayBuffers(cache[key]);\n // console.debug(`Processing message ${key} (bytes=${cache[key].byteLength})`);\n let unpacker = decodeMulti(cache[key]);\n const { done, value } = unpacker.next();\n const main = value;\n // Make sure the fields are from trusted source\n Object.assign(main, {\n from: context.from,\n to: context.to,\n ws: context.ws,\n user: context.user,\n });\n main[\"ctx\"] = JSON.parse(JSON.stringify(main));\n Object.assign(main[\"ctx\"], this.default_context);\n if (!done) {\n let extra = unpacker.next();\n Object.assign(main, extra.value);\n }\n this._fire(main[\"type\"], main);\n // console.debug(\n // this._client_id,\n // `Processed message ${key} (bytes=${cache[key].byteLength})`,\n // );\n delete cache[key];\n }\n\n _on_message(message) {\n if (typeof message === \"string\") {\n const main = JSON.parse(message);\n // Add trusted context to the method call\n main[\"ctx\"] = JSON.parse(JSON.stringify(main));\n Object.assign(main[\"ctx\"], this.default_context);\n this._fire(main[\"type\"], main);\n } else if (message instanceof ArrayBuffer) {\n let unpacker = decodeMulti(message);\n const { done, value } = unpacker.next();\n const main = value;\n // Add trusted context to the method call\n main[\"ctx\"] = JSON.parse(JSON.stringify(main));\n Object.assign(main[\"ctx\"], this.default_context);\n if (!done) {\n let extra = unpacker.next();\n Object.assign(main, extra.value);\n }\n this._fire(main[\"type\"], main);\n } else if (typeof message === \"object\") {\n // Add trusted context to the method call\n message[\"ctx\"] = JSON.parse(JSON.stringify(message));\n Object.assign(message[\"ctx\"], this.default_context);\n this._fire(message[\"type\"], message);\n } else {\n throw new Error(\"Invalid message format\");\n }\n }\n\n reset() {\n this._event_handlers = {};\n this._services = {};\n }\n\n close() {\n // Clean up all pending sessions before closing\n this._cleanupOnDisconnect();\n\n // Clear all heartbeat intervals\n for (const session_id in this._object_store) {\n if (this._object_store.hasOwnProperty(session_id)) {\n const session = this._object_store[session_id];\n if (session && session.heartbeat_task) {\n clearInterval(session.heartbeat_task);\n }\n if (session && session.timer) {\n session.timer.clear();\n }\n }\n }\n\n // Unsubscribe from client_disconnected events if subscribed\n if (this._clientDisconnectedSubscription) {\n try {\n // Get the manager service to unsubscribe (non-blocking)\n if (this._connection && this._connection.manager_id) {\n this.get_remote_service(\"*/\" + this._connection.manager_id)\n .then((manager) => {\n if (\n manager.unsubscribe &&\n typeof manager.unsubscribe === \"function\"\n ) {\n return manager.unsubscribe(\"client_disconnected\");\n }\n })\n .catch((e) => {\n console.debug(\n `Error unsubscribing from client_disconnected: ${e}`,\n );\n });\n }\n // Remove the local event handler\n this.off(\"client_disconnected\");\n } catch (e) {\n console.debug(`Error unsubscribing from client_disconnected: ${e}`);\n }\n }\n\n // Clean up background tasks\n try {\n // Cancel all background tasks\n for (const task of this._background_tasks) {\n if (task && typeof task.cancel === \"function\") {\n try {\n task.cancel();\n } catch (e) {\n console.debug(`Error canceling background task: ${e}`);\n }\n }\n }\n this._background_tasks.clear();\n } catch (e) {\n console.debug(`Error cleaning up background tasks: ${e}`);\n }\n\n // Clean up connection references to prevent circular references\n try {\n // Clear connection reference to break circular references\n this._connection = null;\n\n // Replace emit_message with a no-op to prevent further calls\n this._emit_message = function () {\n console.debug(\"RPC connection closed, ignoring message\");\n return Promise.reject(new Error(\"Connection is closed\"));\n };\n } catch (e) {\n console.debug(`Error during connection cleanup: ${e}`);\n }\n\n this._fire(\"disconnected\");\n }\n\n async _handleClientDisconnected(clientId) {\n try {\n console.debug(`Handling disconnection for client: ${clientId}`);\n\n // Clean up all sessions for the disconnected client\n const sessionsCleaned = this._cleanupSessionsForClient(clientId);\n\n if (sessionsCleaned > 0) {\n console.debug(\n `Cleaned up ${sessionsCleaned} sessions for disconnected client: ${clientId}`,\n );\n }\n\n // Fire an event to notify about the client disconnection\n this._fire(\"remote_client_disconnected\", {\n client_id: clientId,\n sessions_cleaned: sessionsCleaned,\n });\n } catch (e) {\n console.error(\n `Error handling client disconnection for ${clientId}: ${e}`,\n );\n }\n }\n\n _cleanupSessionsForClient(clientId) {\n let sessionsCleaned = 0;\n\n // Iterate through all top-level session keys\n for (const sessionKey of Object.keys(this._object_store)) {\n if (sessionKey === \"services\" || sessionKey === \"message_cache\") {\n continue;\n }\n\n const session = this._object_store[sessionKey];\n if (!session || typeof session !== \"object\") {\n continue;\n }\n\n // Check if this session belongs to the disconnected client\n // Sessions have a target_id property that identifies which client they're calling\n if (session.target_id === clientId) {\n // Reject any pending promises in this session\n if (session.reject && typeof session.reject === \"function\") {\n console.debug(`Rejecting session ${sessionKey}`);\n try {\n session.reject(new Error(`Client disconnected: ${clientId}`));\n } catch (e) {\n console.warn(`Error rejecting session ${sessionKey}: ${e}`);\n }\n }\n\n if (session.resolve && typeof session.resolve === \"function\") {\n console.debug(`Resolving session ${sessionKey} with error`);\n try {\n session.resolve(new Error(`Client disconnected: ${clientId}`));\n } catch (e) {\n console.warn(`Error resolving session ${sessionKey}: ${e}`);\n }\n }\n\n // Clear any timers\n if (session.timer && typeof session.timer.clear === \"function\") {\n try {\n session.timer.clear();\n } catch (e) {\n console.warn(`Error clearing timer for ${sessionKey}: ${e}`);\n }\n }\n\n // Clear heartbeat tasks\n if (session.heartbeat_task) {\n try {\n clearInterval(session.heartbeat_task);\n } catch (e) {\n console.warn(`Error clearing heartbeat for ${sessionKey}: ${e}`);\n }\n }\n\n // Remove the entire session\n delete this._object_store[sessionKey];\n sessionsCleaned++;\n console.debug(`Cleaned up session: ${sessionKey}`);\n }\n }\n\n return sessionsCleaned;\n }\n\n _cleanupOnDisconnect() {\n try {\n console.debug(\"Cleaning up all sessions due to local RPC disconnection\");\n\n // Get all keys to delete after cleanup\n const keysToDelete = [];\n\n for (const key of Object.keys(this._object_store)) {\n if (key === \"services\") {\n continue;\n }\n\n const value = this._object_store[key];\n\n if (typeof value === \"object\" && value !== null) {\n // Reject any pending promises\n if (value.reject && typeof value.reject === \"function\") {\n try {\n value.reject(new Error(\"RPC connection closed\"));\n } catch (e) {\n console.debug(`Error rejecting promise during cleanup: ${e}`);\n }\n }\n\n // Clean up timers and tasks\n if (value.heartbeat_task) {\n clearInterval(value.heartbeat_task);\n }\n if (value.timer && typeof value.timer.clear === \"function\") {\n try {\n value.timer.clear();\n } catch (e) {\n console.debug(`Error clearing timer: ${e}`);\n }\n }\n }\n\n // Mark ALL keys for deletion except services\n keysToDelete.push(key);\n }\n\n // Delete all marked sessions\n for (const key of keysToDelete) {\n delete this._object_store[key];\n }\n } catch (e) {\n console.error(`Error during cleanup on disconnect: ${e}`);\n }\n }\n\n async disconnect() {\n // Store connection reference before closing\n const connection = this._connection;\n this.close();\n\n // Disconnect the underlying connection if it exists\n if (connection) {\n try {\n await connection.disconnect();\n } catch (e) {\n console.debug(`Error disconnecting underlying connection: ${e}`);\n }\n }\n }\n\n async _get_manager_with_retry(maxRetries = 20) {\n const baseDelay = 500;\n const maxDelay = 10000;\n let lastError = null;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n const svc = await this.get_remote_service(\n `*/${this._connection.manager_id}:default`,\n { timeout: 20, case_conversion: \"camel\" },\n );\n return svc;\n } catch (e) {\n lastError = e;\n console.warn(\n `Failed to get manager service (attempt ${attempt + 1}/${maxRetries}): ${e.message}`,\n );\n if (attempt < maxRetries - 1) {\n // Exponential backoff with maximum delay\n const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n // If we get here, all retries failed\n throw lastError;\n }\n\n async get_manager_service(config) {\n config = config || {};\n\n // Add retry logic\n const maxRetries = 20;\n const retryDelay = 500; // 500ms\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n if (!this._connection.manager_id) {\n if (attempt < maxRetries - 1) {\n console.warn(\n `Manager ID not set, retrying in ${retryDelay}ms (attempt ${attempt + 1}/${maxRetries})`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n continue;\n } else {\n throw new Error(\"Manager ID not set after maximum retries\");\n }\n }\n\n try {\n const svc = await this.get_remote_service(\n `*/${this._connection.manager_id}:default`,\n config,\n );\n return svc;\n } catch (e) {\n if (attempt < maxRetries - 1) {\n console.warn(\n `Failed to get manager service, retrying in ${retryDelay}ms: ${e.message}`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n } else {\n throw e;\n }\n }\n }\n }\n\n get_all_local_services() {\n return this._services;\n }\n get_local_service(service_id, context) {\n assert(service_id);\n assert(context, \"Context is required\");\n\n const [ws, client_id] = context[\"to\"].split(\"/\");\n assert(\n client_id === this._client_id,\n \"Services can only be accessed locally\",\n );\n\n const service = this._services[service_id];\n if (!service) {\n throw new Error(\"Service not found: \" + service_id);\n }\n\n service.config[\"workspace\"] = context[\"ws\"];\n // allow access for the same workspace\n if (\n service.config.visibility == \"public\" ||\n service.config.visibility == \"unlisted\"\n ) {\n return service;\n }\n\n // allow access for the same workspace\n if (context[\"ws\"] === ws) {\n return service;\n }\n\n // Check if user is from an authorized workspace\n const authorized_workspaces = service.config.authorized_workspaces;\n if (\n authorized_workspaces &&\n authorized_workspaces.includes(context[\"ws\"])\n ) {\n return service;\n }\n\n throw new Error(\n `Permission denied for getting protected service: ${service_id}, workspace mismatch: ${ws} != ${context[\"ws\"]}`,\n );\n }\n async get_remote_service(service_uri, config) {\n let { timeout, case_conversion, kwargs_expansion } = config || {};\n timeout = timeout === undefined ? this._method_timeout : timeout;\n if (!service_uri && this._connection.manager_id) {\n service_uri = \"*/\" + this._connection.manager_id;\n } else if (!service_uri.includes(\":\")) {\n service_uri = this._client_id + \":\" + service_uri;\n }\n const provider = service_uri.split(\":\")[0];\n let service_id = service_uri.split(\":\")[1];\n if (service_id.includes(\"@\")) {\n service_id = service_id.split(\"@\")[0];\n const app_id = service_uri.split(\"@\")[1];\n if (this._app_id && this._app_id !== \"*\")\n assert(\n app_id === this._app_id,\n `Invalid app id: ${app_id} != ${this._app_id}`,\n );\n }\n assert(provider, `Invalid service uri: ${service_uri}`);\n\n try {\n const method = this._generate_remote_method({\n _rserver: this._server_base_url,\n _rtarget: provider,\n _rmethod: \"services.built-in.get_service\",\n _rpromise: true,\n _rdoc: \"Get a remote service\",\n });\n let svc = await waitFor(\n method(service_id),\n timeout,\n \"Timeout Error: Failed to get remote service: \" + service_uri,\n );\n svc.id = `${provider}:${service_id}`;\n if (kwargs_expansion) {\n svc = expandKwargs(svc);\n }\n if (case_conversion)\n return Object.assign(\n new RemoteService(),\n convertCase(svc, case_conversion),\n );\n else return Object.assign(new RemoteService(), svc);\n } catch (e) {\n console.warn(\"Failed to get remote service: \" + service_uri, e);\n throw e;\n }\n }\n _annotate_service_methods(\n aObject,\n object_id,\n require_context,\n run_in_executor,\n visibility,\n authorized_workspaces,\n ) {\n if (typeof aObject === \"function\") {\n // mark the method as a remote method that requires context\n let method_name = object_id.split(\".\")[1];\n this._method_annotations.set(aObject, {\n require_context: Array.isArray(require_context)\n ? require_context.includes(method_name)\n : !!require_context,\n run_in_executor: run_in_executor,\n method_id: \"services.\" + object_id,\n visibility: visibility,\n authorized_workspaces: authorized_workspaces,\n });\n } else if (aObject instanceof Array || aObject instanceof Object) {\n for (let key of Object.keys(aObject)) {\n let val = aObject[key];\n if (typeof val === \"function\" && val.__rpc_object__) {\n let client_id = val.__rpc_object__._rtarget;\n if (client_id.includes(\"/\")) {\n client_id = client_id.split(\"/\")[1];\n }\n if (this._client_id === client_id) {\n if (aObject instanceof Array) {\n aObject = aObject.slice();\n }\n // recover local method\n aObject[key] = indexObject(\n this._object_store,\n val.__rpc_object__._rmethod,\n );\n val = aObject[key]; // make sure it's annotated later\n } else {\n throw new Error(\n `Local method not found: ${val.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${client_id}`,\n );\n }\n }\n this._annotate_service_methods(\n val,\n object_id + \".\" + key,\n require_context,\n run_in_executor,\n visibility,\n authorized_workspaces,\n );\n }\n }\n }\n add_service(api, overwrite) {\n if (!api || Array.isArray(api)) throw new Error(\"Invalid service object\");\n if (api.constructor === Object) {\n api = Object.assign({}, api);\n } else {\n const normApi = {};\n const props = Object.getOwnPropertyNames(api).concat(\n Object.getOwnPropertyNames(Object.getPrototypeOf(api)),\n );\n for (let k of props) {\n if (k !== \"constructor\") {\n if (typeof api[k] === \"function\") normApi[k] = api[k].bind(api);\n else normApi[k] = api[k];\n }\n }\n // For class instance, we need set a default id\n api.id = api.id || \"default\";\n api = normApi;\n }\n assert(\n api.id && typeof api.id === \"string\",\n `Service id not found: ${api}`,\n );\n if (!api.name) {\n api.name = api.id;\n }\n if (!api.config) {\n api.config = {};\n }\n if (!api.type) {\n api.type = \"generic\";\n }\n // require_context only applies to the top-level functions\n let require_context = false,\n run_in_executor = false;\n if (api.config.require_context)\n require_context = api.config.require_context;\n if (api.config.run_in_executor) run_in_executor = true;\n const visibility = api.config.visibility || \"protected\";\n assert([\"protected\", \"public\", \"unlisted\"].includes(visibility));\n\n // Validate authorized_workspaces\n const authorized_workspaces = api.config.authorized_workspaces;\n if (authorized_workspaces !== undefined) {\n if (visibility !== \"protected\") {\n throw new Error(\n `authorized_workspaces can only be set when visibility is 'protected', got visibility='${visibility}'`,\n );\n }\n if (!Array.isArray(authorized_workspaces)) {\n throw new Error(\n \"authorized_workspaces must be an array of workspace ids\",\n );\n }\n for (const ws_id of authorized_workspaces) {\n if (typeof ws_id !== \"string\") {\n throw new Error(\n `Each workspace id in authorized_workspaces must be a string, got ${typeof ws_id}`,\n );\n }\n }\n }\n this._annotate_service_methods(\n api,\n api[\"id\"],\n require_context,\n run_in_executor,\n visibility,\n authorized_workspaces,\n );\n\n if (this._services[api.id]) {\n if (overwrite) {\n delete this._services[api.id];\n } else {\n throw new Error(\n `Service already exists: ${api.id}, please specify a different id (not ${api.id}) or overwrite=true`,\n );\n }\n }\n this._services[api.id] = api;\n return api;\n }\n\n _extract_service_info(service) {\n const config = service.config || {};\n config.workspace =\n config.workspace || this._local_workspace || this._connection.workspace;\n const skipContext = config.require_context;\n const excludeKeys = [\n \"id\",\n \"config\",\n \"name\",\n \"description\",\n \"type\",\n \"docs\",\n \"app_id\",\n \"service_schema\",\n ];\n const filteredService = {};\n for (const key of Object.keys(service)) {\n if (!excludeKeys.includes(key)) {\n filteredService[key] = service[key];\n }\n }\n const serviceSchema = _get_schema(filteredService, null, skipContext);\n const serviceInfo = {\n config: config,\n id: `${config.workspace}/${this._client_id}:${service[\"id\"]}`,\n name: service.name || service[\"id\"],\n description: service.description || \"\",\n type: service.type || \"generic\",\n docs: service.docs || null,\n app_id: this._app_id,\n service_schema: serviceSchema,\n };\n return serviceInfo;\n }\n\n async get_service_schema(service) {\n const skipContext = service.config.require_context;\n return _get_schema(service, null, skipContext);\n }\n\n async register_service(api, config) {\n let { check_type, notify, overwrite } = config || {};\n notify = notify === undefined ? true : notify;\n let manager;\n if (check_type && api.type) {\n try {\n manager = await this.get_manager_service({\n timeout: 10,\n case_conversion: \"camel\",\n });\n const type_info = await manager.get_service_type(api.type);\n api = _annotate_service(api, type_info);\n } catch (e) {\n throw new Error(`Failed to get service type ${api.type}, error: ${e}`);\n }\n }\n\n const service = this.add_service(api, overwrite);\n const serviceInfo = this._extract_service_info(service);\n if (notify) {\n try {\n manager =\n manager ||\n (await this.get_manager_service({\n timeout: 10,\n case_conversion: \"camel\",\n }));\n await manager.registerService(serviceInfo);\n } catch (e) {\n throw new Error(`Failed to notify workspace manager: ${e}`);\n }\n }\n return serviceInfo;\n }\n\n async unregister_service(service, notify) {\n notify = notify === undefined ? true : notify;\n let service_id;\n if (typeof service === \"string\") {\n service_id = service;\n } else {\n service_id = service.id;\n }\n assert(\n service_id && typeof service_id === \"string\",\n `Invalid service id: ${service_id}`,\n );\n if (service_id.includes(\":\")) {\n service_id = service_id.split(\":\")[1];\n }\n if (service_id.includes(\"@\")) {\n service_id = service_id.split(\"@\")[0];\n }\n if (!this._services[service_id]) {\n throw new Error(`Service not found: ${service_id}`);\n }\n if (notify) {\n const manager = await this.get_manager_service({\n timeout: 10,\n case_conversion: \"camel\",\n });\n await manager.unregisterService(service_id);\n }\n delete this._services[service_id];\n }\n\n _ndarray(typedArray, shape, dtype) {\n const _dtype = typedArrayToDtype(typedArray);\n if (dtype && dtype !== _dtype) {\n throw (\n \"dtype doesn't match the type of the array: \" + _dtype + \" != \" + dtype\n );\n }\n shape = shape || [typedArray.length];\n return {\n _rtype: \"ndarray\",\n _rvalue: typedArray.buffer,\n _rshape: shape,\n _rdtype: _dtype,\n };\n }\n\n _encode_callback(\n name,\n callback,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n description,\n ) {\n let method_id = `${session_id}.${name}`;\n let encoded = {\n _rtype: \"method\",\n _rtarget: local_workspace\n ? `${local_workspace}/${this._client_id}`\n : this._client_id,\n _rmethod: method_id,\n _rpromise: false,\n };\n\n const self = this;\n let wrapped_callback = function () {\n try {\n callback.apply(null, Array.prototype.slice.call(arguments));\n } catch (error) {\n console.error(\n `Error in callback(${method_id}, ${description}): ${error}`,\n );\n } finally {\n // Clear the timer first if it exists\n if (timer && timer.started) {\n timer.clear();\n }\n\n // Clean up the entire session when resolve/reject is called\n if (clear_after_called && self._object_store[session_id]) {\n // For promise callbacks (resolve/reject), clean up the entire session\n if (name === \"resolve\" || name === \"reject\") {\n delete self._object_store[session_id];\n } else {\n // For other callbacks, just clean up this specific callback\n self._cleanup_session_if_needed(session_id, name);\n }\n }\n }\n };\n wrapped_callback.__name__ = `callback(${method_id})`;\n return [encoded, wrapped_callback];\n }\n\n _cleanup_session_if_needed(session_id, callback_name) {\n /**\n * Clean session management - all logic in one place.\n */\n if (!session_id) {\n console.debug(\"Cannot cleanup session: session_id is empty\");\n return;\n }\n\n try {\n const store = this._get_session_store(session_id, false);\n if (!store) {\n console.debug(`Session ${session_id} not found for cleanup`);\n return;\n }\n\n let should_cleanup = false;\n\n // Promise sessions: let the promise manager decide cleanup\n if (store._promise_manager) {\n try {\n const promise_manager = store._promise_manager;\n if (\n promise_manager.should_cleanup_on_callback &&\n promise_manager.should_cleanup_on_callback(callback_name)\n ) {\n if (promise_manager.settle) {\n promise_manager.settle();\n }\n should_cleanup = true;\n console.debug(\n `Promise session ${session_id} settled and marked for cleanup`,\n );\n }\n } catch (e) {\n console.warn(\n `Error in promise manager cleanup for session ${session_id}:`,\n e,\n );\n }\n } else {\n // Regular sessions: only cleanup temporary method call sessions\n // Don't cleanup service registration sessions or persistent sessions\n // Only cleanup sessions that are clearly temporary promises for method calls\n if (\n (callback_name === \"resolve\" || callback_name === \"reject\") &&\n store._callbacks &&\n Object.keys(store._callbacks).includes(callback_name)\n ) {\n should_cleanup = true;\n console.debug(\n `Regular session ${session_id} marked for cleanup after ${callback_name}`,\n );\n }\n }\n\n if (should_cleanup) {\n this._cleanup_session_completely(session_id);\n }\n } catch (error) {\n console.warn(`Error during session cleanup for ${session_id}:`, error);\n }\n }\n\n _cleanup_session_completely(session_id) {\n /**\n * Complete session cleanup with resource management.\n */\n try {\n const store = this._get_session_store(session_id, false);\n if (!store) {\n console.debug(`Session ${session_id} already cleaned up`);\n return;\n }\n\n // Clean up resources before removing session\n if (store.timer && typeof store.timer.clear === \"function\") {\n try {\n store.timer.clear();\n } catch (error) {\n console.warn(\n `Error clearing timer for session ${session_id}:`,\n error,\n );\n }\n }\n\n if (\n store.heartbeat_task &&\n typeof store.heartbeat_task.cancel === \"function\"\n ) {\n try {\n store.heartbeat_task.cancel();\n } catch (error) {\n console.warn(\n `Error canceling heartbeat for session ${session_id}:`,\n error,\n );\n }\n }\n\n // Navigate and clean session path\n const levels = session_id.split(\".\");\n let current_store = this._object_store;\n\n // Navigate to parent of target level\n for (let i = 0; i < levels.length - 1; i++) {\n const level = levels[i];\n if (!current_store[level]) {\n console.debug(\n `Session path ${session_id} not found at level ${level}`,\n );\n return;\n }\n current_store = current_store[level];\n }\n\n // Delete the final level\n const final_key = levels[levels.length - 1];\n if (current_store[final_key]) {\n delete current_store[final_key];\n console.debug(`Cleaned up session ${session_id}`);\n\n // Clean up empty parent containers\n this._cleanup_empty_containers(levels.slice(0, -1));\n }\n } catch (error) {\n console.warn(\n `Error in complete session cleanup for ${session_id}:`,\n error,\n );\n }\n }\n\n _cleanup_empty_containers(path_levels) {\n /**\n * Clean up empty parent containers to prevent memory leaks.\n */\n try {\n // Work backwards from the deepest level\n for (let depth = path_levels.length - 1; depth >= 0; depth--) {\n let current_store = this._object_store;\n\n // Navigate to parent of current depth\n for (let i = 0; i < depth; i++) {\n current_store = current_store[path_levels[i]];\n if (!current_store) return; // Path doesn't exist\n }\n\n // Check if container at current depth is empty\n const container_key = path_levels[depth];\n const container = current_store[container_key];\n\n if (\n container &&\n typeof container === \"object\" &&\n Object.keys(container).length === 0\n ) {\n delete current_store[container_key];\n console.debug(\n `Cleaned up empty container at depth ${depth}: ${path_levels.slice(0, depth + 1).join(\".\")}`,\n );\n } else {\n // Container is not empty, stop cleanup\n break;\n }\n }\n } catch (error) {\n console.warn(\"Error cleaning up empty containers:\", error);\n }\n }\n\n get_session_stats() {\n /**\n * Get detailed session statistics.\n */\n const stats = {\n total_sessions: 0,\n promise_sessions: 0,\n regular_sessions: 0,\n sessions_with_timers: 0,\n sessions_with_heartbeat: 0,\n system_stores: {},\n session_ids: [],\n memory_usage: 0,\n };\n\n if (!this._object_store) {\n return stats;\n }\n\n for (const key in this._object_store) {\n const value = this._object_store[key];\n\n if ([\"services\", \"message_cache\"].includes(key)) {\n // System stores - don't count these as sessions\n stats.system_stores[key] = {\n size:\n typeof value === \"object\" && value ? Object.keys(value).length : 0,\n };\n continue;\n }\n\n // Count all non-system non-empty objects as sessions\n if (value && typeof value === \"object\") {\n const sessionKeys = Object.keys(value);\n\n // Only skip completely empty objects\n if (sessionKeys.length > 0) {\n stats.total_sessions++;\n stats.session_ids.push(key);\n\n if (value._promise_manager) {\n stats.promise_sessions++;\n } else {\n stats.regular_sessions++;\n }\n\n if (value._timer || value.timer) stats.sessions_with_timers++;\n if (value._heartbeat || value.heartbeat)\n stats.sessions_with_heartbeat++;\n\n // Estimate memory usage\n stats.memory_usage += JSON.stringify(value).length;\n }\n }\n }\n\n return stats;\n }\n\n _force_cleanup_all_sessions() {\n /**\n * Force cleanup all sessions (for testing purposes).\n */\n if (!this._object_store) {\n console.debug(\"Force cleaning up 0 sessions\");\n return;\n }\n\n let cleaned_count = 0;\n const keys_to_delete = [];\n\n for (const key in this._object_store) {\n // Don't delete system stores\n if (![\"services\", \"message_cache\"].includes(key)) {\n const value = this._object_store[key];\n if (\n value &&\n typeof value === \"object\" &&\n Object.keys(value).length > 0\n ) {\n keys_to_delete.push(key);\n cleaned_count++;\n }\n }\n }\n\n // Delete the sessions\n for (const key of keys_to_delete) {\n delete this._object_store[key];\n }\n\n console.debug(`Force cleaning up ${cleaned_count} sessions`);\n }\n\n // Clean helper to identify promise method calls by session type\n _is_promise_method_call(method_path) {\n const session_id = method_path.split(\".\")[0];\n const session = this._get_session_store(session_id, false);\n return session && session._promise_manager;\n }\n\n // Simplified Promise Manager - enhanced version\n _create_promise_manager() {\n /**\n * Create a promise manager to track promise state and decide cleanup.\n */\n return {\n should_cleanup_on_callback: (callback_name) => {\n return [\"resolve\", \"reject\"].includes(callback_name);\n },\n settle: () => {\n // Promise is settled (resolved or rejected)\n console.debug(\"Promise settled\");\n },\n };\n }\n\n async _encode_promise(\n resolve,\n reject,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n description,\n ) {\n let store = this._get_session_store(session_id, true);\n if (!store) {\n console.warn(\n `Failed to create session store ${session_id}, session management may be impaired`,\n );\n store = {};\n }\n\n // Clean promise lifecycle management - TYPE-BASED, not string-based\n store._promise_manager = this._create_promise_manager();\n\n let encoded = {};\n\n if (timer && reject && this._method_timeout) {\n [encoded.heartbeat, store.heartbeat] = this._encode_callback(\n \"heartbeat\",\n timer.reset.bind(timer),\n session_id,\n false,\n null,\n local_workspace,\n );\n store.timer = timer;\n encoded.interval = this._method_timeout / 2;\n } else {\n timer = null;\n }\n\n [encoded.resolve, store.resolve] = this._encode_callback(\n \"resolve\",\n resolve,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n `resolve (${description})`,\n );\n [encoded.reject, store.reject] = this._encode_callback(\n \"reject\",\n reject,\n session_id,\n clear_after_called,\n timer,\n local_workspace,\n `reject (${description})`,\n );\n return encoded;\n }\n\n async _send_chunks(data, target_id, session_id) {\n // 1) Get the remote service\n const remote_services = await this.get_remote_service(\n `${target_id}:built-in`,\n );\n if (!remote_services.message_cache) {\n throw new Error(\n \"Remote client does not support message caching for large messages.\",\n );\n }\n\n const message_cache = remote_services.message_cache;\n const message_id = session_id || randId();\n const total_size = data.length;\n const start_time = Date.now(); // measure time\n const chunk_num = Math.ceil(total_size / this._long_message_chunk_size);\n if (remote_services.config.api_version >= 3) {\n await message_cache.create(message_id, !!session_id);\n const semaphore = new Semaphore(CONCURRENCY_LIMIT);\n\n const tasks = [];\n for (let idx = 0; idx < chunk_num; idx++) {\n const startByte = idx * this._long_message_chunk_size;\n const chunk = data.slice(\n startByte,\n startByte + this._long_message_chunk_size,\n );\n\n const taskFn = async () => {\n await message_cache.set(message_id, idx, chunk, !!session_id);\n // console.debug(\n // `Sending chunk ${idx + 1}/${chunk_num} (total=${total_size} bytes)`,\n // );\n };\n\n // Push into an array, each one runs under the semaphore\n tasks.push(semaphore.run(taskFn));\n }\n\n // Wait for all chunk uploads to finish\n try {\n await Promise.all(tasks);\n } catch (error) {\n // If any chunk fails, clean up the message cache\n try {\n await message_cache.remove(message_id);\n } catch (cleanupError) {\n console.error(\n `Failed to clean up message cache after error: ${cleanupError}`,\n );\n }\n throw error;\n }\n } else {\n // 3) Legacy version (sequential appends):\n await message_cache.create(message_id, !!session_id);\n for (let idx = 0; idx < chunk_num; idx++) {\n const startByte = idx * this._long_message_chunk_size;\n const chunk = data.slice(\n startByte,\n startByte + this._long_message_chunk_size,\n );\n await message_cache.append(message_id, chunk, !!session_id);\n // console.debug(\n // `Sending chunk ${idx + 1}/${chunk_num} (total=${total_size} bytes)`,\n // );\n }\n }\n await message_cache.process(message_id, !!session_id);\n const durationSec = ((Date.now() - start_time) / 1000).toFixed(2);\n // console.debug(`All chunks (${total_size} bytes) sent in ${durationSec} s`);\n }\n\n emit(main_message, extra_data) {\n assert(\n typeof main_message === \"object\" && main_message.type,\n \"Invalid message, must be an object with a `type` fields.\",\n );\n if (!main_message.to) {\n this._fire(main_message.type, main_message);\n return;\n }\n let message_package = msgpack_packb(main_message);\n if (extra_data) {\n const extra = msgpack_packb(extra_data);\n message_package = new Uint8Array([...message_package, ...extra]);\n }\n const total_size = message_package.length;\n if (total_size > this._long_message_chunk_size + 1024) {\n console.warn(`Sending large message (size=${total_size})`);\n }\n return this._emit_message(message_package);\n }\n\n _generate_remote_method(\n encoded_method,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ) {\n let target_id = encoded_method._rtarget;\n if (remote_workspace && !target_id.includes(\"/\")) {\n if (remote_workspace !== target_id) {\n target_id = remote_workspace + \"/\" + target_id;\n }\n // Fix the target id to be an absolute id\n encoded_method._rtarget = target_id;\n }\n let method_id = encoded_method._rmethod;\n let with_promise = encoded_method._rpromise || false;\n const description = `method: ${method_id}, docs: ${encoded_method._rdoc}`;\n const self = this;\n\n function remote_method() {\n return new Promise(async (resolve, reject) => {\n let local_session_id = randId();\n if (local_parent) {\n // Store the children session under the parent\n local_session_id = local_parent + \".\" + local_session_id;\n }\n let store = self._get_session_store(local_session_id, true);\n if (!store) {\n reject(\n new Error(\n `Runtime Error: Failed to get session store ${local_session_id} (context: ${description})`,\n ),\n );\n return;\n }\n store[\"target_id\"] = target_id;\n const args = await self._encode(\n Array.prototype.slice.call(arguments),\n local_session_id,\n local_workspace,\n );\n const argLength = args.length;\n // if the last argument is an object, mark it as kwargs\n const withKwargs =\n argLength > 0 &&\n typeof args[argLength - 1] === \"object\" &&\n args[argLength - 1] !== null &&\n args[argLength - 1]._rkwargs;\n if (withKwargs) delete args[argLength - 1]._rkwargs;\n\n let from_client;\n if (!self._local_workspace) {\n from_client = self._client_id;\n } else {\n from_client = self._local_workspace + \"/\" + self._client_id;\n }\n\n let main_message = {\n type: \"method\",\n from: from_client,\n to: target_id,\n method: method_id,\n };\n let extra_data = {};\n if (args) {\n extra_data[\"args\"] = args;\n }\n if (withKwargs) {\n extra_data[\"with_kwargs\"] = withKwargs;\n }\n\n // console.log(\n // `Calling remote method ${target_id}:${method_id}, session: ${local_session_id}`\n // );\n if (remote_parent) {\n // Set the parent session\n // Note: It's a session id for the remote, not the current client\n main_message[\"parent\"] = remote_parent;\n }\n\n let timer = null;\n if (with_promise) {\n // Only pass the current session id to the remote\n // if we want to received the result\n // I.e. the session id won't be passed for promises themselves\n main_message[\"session\"] = local_session_id;\n let method_name = `${target_id}:${method_id}`;\n\n // Create a timer that gets reset by heartbeat\n // Methods can run indefinitely as long as heartbeat keeps resetting the timer\n // IMPORTANT: When timeout occurs, we must clean up the session to prevent memory leaks\n const timeoutCallback = function (error_msg) {\n // First reject the promise\n reject(error_msg);\n // Then clean up the entire session to stop all callbacks\n if (self._object_store[local_session_id]) {\n delete self._object_store[local_session_id];\n console.debug(\n `Cleaned up session ${local_session_id} after timeout`,\n );\n }\n };\n\n timer = new Timer(\n self._method_timeout,\n timeoutCallback,\n [`Method call timed out: ${method_name}, context: ${description}`],\n method_name,\n );\n // By default, hypha will clear the session after the method is called\n // However, if the args contains _rintf === true, we will not clear the session\n\n // Helper function to recursively check for _rintf objects\n function hasInterfaceObject(obj) {\n if (!obj || typeof obj !== \"object\") return false;\n if (obj._rintf === true) return true;\n if (Array.isArray(obj)) {\n return obj.some((item) => hasInterfaceObject(item));\n }\n if (obj.constructor === Object) {\n return Object.values(obj).some((value) =>\n hasInterfaceObject(value),\n );\n }\n return false;\n }\n\n let clear_after_called = !hasInterfaceObject(args);\n\n const promiseData = await self._encode_promise(\n resolve,\n reject,\n local_session_id,\n clear_after_called,\n timer,\n local_workspace,\n description,\n );\n\n if (with_promise === true) {\n extra_data[\"promise\"] = promiseData;\n } else if (with_promise === \"*\") {\n extra_data[\"promise\"] = \"*\";\n extra_data[\"t\"] = self._method_timeout / 2;\n } else {\n throw new Error(`Unsupported promise type: ${with_promise}`);\n }\n }\n // The message consists of two segments, the main message and extra data\n let message_package = msgpack_packb(main_message);\n if (extra_data) {\n const extra = msgpack_packb(extra_data);\n message_package = new Uint8Array([...message_package, ...extra]);\n }\n const total_size = message_package.length;\n if (\n total_size <= self._long_message_chunk_size + 1024 ||\n remote_method.__no_chunk__\n ) {\n self\n ._emit_message(message_package)\n .then(function () {\n if (timer) {\n // Start the timer after message is sent successfully\n timer.start();\n }\n })\n .catch(function (err) {\n const error_msg = `Failed to send the request when calling method (${target_id}:${method_id}), error: ${err}`;\n if (reject) {\n reject(new Error(error_msg));\n } else {\n // No reject callback available, log the error to prevent unhandled promise rejections\n console.warn(\"Unhandled RPC method call error:\", error_msg);\n }\n if (timer) {\n timer.clear();\n }\n });\n } else {\n // send chunk by chunk\n self\n ._send_chunks(message_package, target_id, remote_parent)\n .then(function () {\n if (timer) {\n // Start the timer after message is sent successfully\n timer.start();\n }\n })\n .catch(function (err) {\n const error_msg = `Failed to send the request when calling method (${target_id}:${method_id}), error: ${err}`;\n if (reject) {\n reject(new Error(error_msg));\n } else {\n // No reject callback available, log the error to prevent unhandled promise rejections\n console.warn(\"Unhandled RPC method call error:\", error_msg);\n }\n if (timer) {\n timer.clear();\n }\n });\n }\n });\n }\n\n // Generate debugging information for the method\n remote_method.__rpc_object__ = encoded_method;\n const parts = method_id.split(\".\");\n\n remote_method.__name__ = encoded_method._rname || parts[parts.length - 1];\n if (remote_method.__name__.includes(\"#\")) {\n remote_method.__name__ = remote_method.__name__.split(\"#\")[1];\n }\n remote_method.__doc__ =\n encoded_method._rdoc || `Remote method: ${method_id}`;\n remote_method.__schema__ = encoded_method._rschema;\n // Prevent circular chunk sending\n remote_method.__no_chunk__ =\n encoded_method._rmethod === \"services.built-in.message_cache.append\";\n return remote_method;\n }\n\n get_client_info() {\n const services = [];\n for (let service of Object.values(this._services)) {\n services.push(this._extract_service_info(service));\n }\n\n return {\n id: this._client_id,\n services: services,\n };\n }\n\n async _handle_method(data) {\n let reject = null;\n let heartbeat_task = null;\n try {\n assert(data.method && data.ctx && data.from);\n const method_name = data.from + \":\" + data.method;\n const remote_workspace = data.from.split(\"/\")[0];\n const remote_client_id = data.from.split(\"/\")[1];\n // Make sure the target id is an absolute id\n data[\"to\"] = data[\"to\"].includes(\"/\")\n ? data[\"to\"]\n : remote_workspace + \"/\" + data[\"to\"];\n data[\"ctx\"][\"to\"] = data[\"to\"];\n let local_workspace;\n if (!this._local_workspace) {\n local_workspace = data[\"to\"].split(\"/\")[0];\n } else {\n if (this._local_workspace && this._local_workspace !== \"*\") {\n assert(\n data[\"to\"].split(\"/\")[0] === this._local_workspace,\n \"Workspace mismatch: \" +\n data[\"to\"].split(\"/\")[0] +\n \" != \" +\n this._local_workspace,\n );\n }\n local_workspace = this._local_workspace;\n }\n const local_parent = data.parent;\n\n let resolve, reject;\n if (data.promise) {\n // Decode the promise with the remote session id\n // Such that the session id will be passed to the remote as a parent session id\n const promise = await this._decode(\n data.promise === \"*\" ? this._expand_promise(data) : data.promise,\n data.session,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n resolve = promise.resolve;\n reject = promise.reject;\n if (promise.heartbeat && promise.interval) {\n async function heartbeat() {\n try {\n // console.debug(\"Reset heartbeat timer: \" + data.method);\n await promise.heartbeat();\n } catch (err) {\n console.error(err);\n }\n }\n heartbeat_task = setInterval(heartbeat, promise.interval * 1000);\n // Store the heartbeat task in the session store for cleanup\n if (data.session) {\n const session_store = this._get_session_store(data.session, false);\n if (session_store) {\n session_store.heartbeat_task = heartbeat_task;\n }\n }\n }\n }\n\n let method;\n\n try {\n method = indexObject(this._object_store, data[\"method\"]);\n } catch (e) {\n // Clean promise method detection - TYPE-BASED, not string-based\n if (this._is_promise_method_call(data[\"method\"])) {\n console.debug(\n `Promise method ${data[\"method\"]} not available (detected by session type), ignoring: ${method_name}`,\n );\n return;\n }\n\n // Check if this is a session-based method call that might have expired\n const method_parts = data[\"method\"].split(\".\");\n if (method_parts.length > 1) {\n const session_id = method_parts[0];\n // Check if the session exists but the specific method doesn't\n if (session_id in this._object_store) {\n console.debug(\n `Session ${session_id} exists but method ${data[\"method\"]} not found, likely expired callback: ${method_name}`,\n );\n // For expired callbacks, don't throw an exception, just log and return\n if (typeof reject === \"function\") {\n reject(new Error(`Method expired or not found: ${method_name}`));\n }\n return;\n } else {\n console.debug(\n `Session ${session_id} not found for method ${data[\"method\"]}, likely cleaned up: ${method_name}`,\n );\n // For cleaned up sessions, just log and return without throwing\n if (typeof reject === \"function\") {\n reject(new Error(`Session not found: ${method_name}`));\n }\n return;\n }\n }\n\n console.debug(\n `Failed to find method ${method_name} at ${this._client_id}`,\n );\n const error = new Error(\n `Method not found: ${method_name} at ${this._client_id}`,\n );\n if (typeof reject === \"function\") {\n reject(error);\n } else {\n // Log the error instead of throwing to prevent unhandled exceptions\n console.warn(\n \"Method not found and no reject callback:\",\n error.message,\n );\n }\n return;\n }\n\n assert(\n method && typeof method === \"function\",\n \"Invalid method: \" + method_name,\n );\n\n // Check permission\n if (this._method_annotations.has(method)) {\n // For services, it should not be protected\n if (this._method_annotations.get(method).visibility === \"protected\") {\n // Allow access from same workspace\n if (local_workspace === remote_workspace) {\n // Access granted\n }\n // Check if remote workspace is in authorized_workspaces list\n else if (\n this._method_annotations.get(method).authorized_workspaces &&\n this._method_annotations\n .get(method)\n .authorized_workspaces.includes(remote_workspace)\n ) {\n // Access granted\n }\n // Allow manager access\n else if (\n remote_workspace === \"*\" &&\n remote_client_id === this._connection.manager_id\n ) {\n // Access granted\n } else {\n throw new Error(\n \"Permission denied for invoking protected method \" +\n method_name +\n \", workspace mismatch: \" +\n local_workspace +\n \" != \" +\n remote_workspace,\n );\n }\n }\n } else {\n // For sessions, the target_id should match exactly\n let session_target_id =\n this._object_store[data.method.split(\".\")[0]].target_id;\n if (\n local_workspace === remote_workspace &&\n session_target_id &&\n session_target_id.indexOf(\"/\") === -1\n ) {\n session_target_id = local_workspace + \"/\" + session_target_id;\n }\n if (session_target_id !== data.from) {\n throw new Error(\n \"Access denied for method call (\" +\n method_name +\n \") from \" +\n data.from +\n \" to target \" +\n session_target_id,\n );\n }\n }\n\n // Make sure the parent session is still open\n if (local_parent) {\n // The parent session should be a session that generate the current method call\n assert(\n this._get_session_store(local_parent, true) !== null,\n \"Parent session was closed: \" + local_parent,\n );\n }\n let args;\n if (data.args) {\n args = await this._decode(\n data.args,\n data.session,\n null,\n remote_workspace,\n null,\n );\n } else {\n args = [];\n }\n if (\n this._method_annotations.has(method) &&\n this._method_annotations.get(method).require_context\n ) {\n // if args.length + 1 is less than the required number of arguments we will pad with undefined\n // so we make sure the last argument is the context\n if (args.length + 1 < method.length) {\n for (let i = args.length; i < method.length - 1; i++) {\n args.push(undefined);\n }\n }\n args.push(data.ctx);\n // assert(\n // args.length === method.length,\n // `Runtime Error: Invalid number of arguments for method ${method_name}, expected ${method.length} but got ${args.length}`,\n // );\n }\n // console.debug(`Executing method: ${method_name} (${data.method})`);\n if (data.promise) {\n const result = method.apply(null, args);\n if (result instanceof Promise) {\n result\n .then((result) => {\n resolve(result);\n clearInterval(heartbeat_task);\n })\n .catch((err) => {\n reject(err);\n clearInterval(heartbeat_task);\n });\n } else {\n resolve(result);\n clearInterval(heartbeat_task);\n }\n } else {\n method.apply(null, args);\n clearInterval(heartbeat_task);\n }\n } catch (err) {\n if (reject) {\n reject(err);\n // console.debug(\"Error during calling method: \", err);\n } else {\n console.error(\"Error during calling method: \", err);\n }\n // make sure we clear the heartbeat timer\n clearInterval(heartbeat_task);\n }\n }\n\n encode(aObject, session_id) {\n return this._encode(aObject, session_id);\n }\n\n _get_session_store(session_id, create) {\n if (!session_id) {\n return null;\n }\n let store = this._object_store;\n const levels = session_id.split(\".\");\n if (create) {\n const last_index = levels.length - 1;\n for (let level of levels.slice(0, last_index)) {\n if (!store[level]) {\n // Instead of returning null, create intermediate sessions as needed\n store[level] = {};\n }\n store = store[level];\n }\n // Create the last level\n if (!store[levels[last_index]]) {\n store[levels[last_index]] = {};\n }\n return store[levels[last_index]];\n } else {\n for (let level of levels) {\n if (!store[level]) {\n return null;\n }\n store = store[level];\n }\n return store;\n }\n }\n\n /**\n * Prepares the provided set of remote method arguments for\n * sending to the remote site, replaces all the callbacks with\n * identifiers\n *\n * @param {Array} args to wrap\n *\n * @returns {Array} wrapped arguments\n */\n async _encode(aObject, session_id, local_workspace) {\n const aType = typeof aObject;\n if (\n aType === \"number\" ||\n aType === \"string\" ||\n aType === \"boolean\" ||\n aObject === null ||\n aObject === undefined ||\n aObject instanceof Uint8Array\n ) {\n return aObject;\n }\n if (aObject instanceof ArrayBuffer) {\n return {\n _rtype: \"memoryview\",\n _rvalue: new Uint8Array(aObject),\n };\n }\n // Reuse the remote object\n if (aObject.__rpc_object__) {\n const _server = aObject.__rpc_object__._rserver || this._server_base_url;\n if (_server === this._server_base_url) {\n return aObject.__rpc_object__;\n } // else {\n // console.debug(\n // `Encoding remote function from a different server ${_server}, current server: ${this._server_base_url}`,\n // );\n // }\n }\n\n let bObject;\n\n // skip if already encoded\n if (aObject.constructor instanceof Object && aObject._rtype) {\n // make sure the interface functions are encoded\n const temp = aObject._rtype;\n delete aObject._rtype;\n bObject = await this._encode(aObject, session_id, local_workspace);\n bObject._rtype = temp;\n return bObject;\n }\n\n if (isGenerator(aObject) || isAsyncGenerator(aObject)) {\n // Handle generator functions and generator objects\n assert(\n session_id && typeof session_id === \"string\",\n \"Session ID is required for generator encoding\",\n );\n const object_id = randId();\n\n // Get the session store\n const store = this._get_session_store(session_id, true);\n assert(\n store !== null,\n `Failed to create session store ${session_id} due to invalid parent`,\n );\n\n // Check if it's an async generator\n const isAsync = isAsyncGenerator(aObject);\n\n // Define method to get next item from the generator\n const nextItemMethod = async () => {\n if (isAsync) {\n const iterator = aObject;\n const result = await iterator.next();\n if (result.done) {\n delete store[object_id];\n return { _rtype: \"stop_iteration\" };\n }\n return result.value;\n } else {\n const iterator = aObject;\n const result = iterator.next();\n if (result.done) {\n delete store[object_id];\n return { _rtype: \"stop_iteration\" };\n }\n return result.value;\n }\n };\n\n // Store the next_item method in the session\n store[object_id] = nextItemMethod;\n\n // Create a method that will be used to fetch the next item from the generator\n bObject = {\n _rtype: \"generator\",\n _rserver: this._server_base_url,\n _rtarget: this._client_id,\n _rmethod: `${session_id}.${object_id}`,\n _rpromise: \"*\",\n _rdoc: \"Remote generator\",\n };\n return bObject;\n } else if (typeof aObject === \"function\") {\n if (this._method_annotations.has(aObject)) {\n let annotation = this._method_annotations.get(aObject);\n bObject = {\n _rtype: \"method\",\n _rserver: this._server_base_url,\n _rtarget: this._client_id,\n _rmethod: annotation.method_id,\n _rpromise: \"*\",\n _rname: aObject.name,\n };\n } else {\n assert(typeof session_id === \"string\");\n let object_id;\n if (aObject.__name__) {\n object_id = `${randId()}#${aObject.__name__}`;\n } else {\n object_id = randId();\n }\n bObject = {\n _rtype: \"method\",\n _rserver: this._server_base_url,\n _rtarget: this._client_id,\n _rmethod: `${session_id}.${object_id}`,\n _rpromise: \"*\",\n _rname: aObject.name,\n };\n let store = this._get_session_store(session_id, true);\n assert(\n store !== null,\n `Failed to create session store ${session_id} due to invalid parent`,\n );\n store[object_id] = aObject;\n }\n bObject._rdoc = aObject.__doc__;\n if (!bObject._rdoc) {\n try {\n const funcInfo = getFunctionInfo(aObject);\n if (funcInfo && !bObject._rdoc) {\n bObject._rdoc = `${funcInfo.doc}`;\n }\n } catch (e) {\n console.error(\"Failed to extract function docstring:\", aObject);\n }\n }\n bObject._rschema = aObject.__schema__;\n return bObject;\n }\n const isarray = Array.isArray(aObject);\n\n for (let tp of Object.keys(this._codecs)) {\n const codec = this._codecs[tp];\n if (codec.encoder && aObject instanceof codec.type) {\n // TODO: what if multiple encoders found\n let encodedObj = await Promise.resolve(codec.encoder(aObject));\n if (encodedObj && !encodedObj._rtype) encodedObj._rtype = codec.name;\n // encode the functions in the interface object\n if (typeof encodedObj === \"object\") {\n const temp = encodedObj._rtype;\n delete encodedObj._rtype;\n encodedObj = await this._encode(\n encodedObj,\n session_id,\n local_workspace,\n );\n encodedObj._rtype = temp;\n }\n bObject = encodedObj;\n return bObject;\n }\n }\n\n if (\n /*global tf*/\n typeof tf !== \"undefined\" &&\n tf.Tensor &&\n aObject instanceof tf.Tensor\n ) {\n const v_buffer = aObject.dataSync();\n bObject = {\n _rtype: \"ndarray\",\n _rvalue: new Uint8Array(v_buffer.buffer),\n _rshape: aObject.shape,\n _rdtype: aObject.dtype,\n };\n } else if (\n /*global nj*/\n typeof nj !== \"undefined\" &&\n nj.NdArray &&\n aObject instanceof nj.NdArray\n ) {\n if (!aObject.selection || !aObject.selection.data) {\n throw new Error(\"Invalid NumJS array: missing selection or data\");\n }\n const dtype = typedArrayToDtype(aObject.selection.data);\n bObject = {\n _rtype: \"ndarray\",\n _rvalue: new Uint8Array(aObject.selection.data.buffer),\n _rshape: aObject.shape,\n _rdtype: dtype,\n };\n } else if (aObject instanceof Error) {\n console.error(aObject);\n bObject = {\n _rtype: \"error\",\n _rvalue: aObject.toString(),\n _rtrace: aObject.stack,\n };\n }\n // send objects supported by structure clone algorithm\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n else if (\n aObject !== Object(aObject) ||\n aObject instanceof Boolean ||\n aObject instanceof String ||\n aObject instanceof Date ||\n aObject instanceof RegExp ||\n (typeof ImageData !== \"undefined\" && aObject instanceof ImageData) ||\n (typeof FileList !== \"undefined\" && aObject instanceof FileList) ||\n (typeof FileSystemDirectoryHandle !== \"undefined\" &&\n aObject instanceof FileSystemDirectoryHandle) ||\n (typeof FileSystemFileHandle !== \"undefined\" &&\n aObject instanceof FileSystemFileHandle) ||\n (typeof FileSystemHandle !== \"undefined\" &&\n aObject instanceof FileSystemHandle) ||\n (typeof FileSystemWritableFileStream !== \"undefined\" &&\n aObject instanceof FileSystemWritableFileStream)\n ) {\n bObject = aObject;\n // TODO: avoid object such as DynamicPlugin instance.\n } else if (aObject instanceof Blob) {\n let _current_pos = 0;\n async function read(length) {\n let blob;\n if (length) {\n blob = aObject.slice(_current_pos, _current_pos + length);\n } else {\n blob = aObject.slice(_current_pos);\n }\n const ret = new Uint8Array(await blob.arrayBuffer());\n _current_pos = _current_pos + ret.byteLength;\n return ret;\n }\n function seek(pos) {\n _current_pos = pos;\n }\n bObject = {\n _rtype: \"iostream\",\n _rnative: \"js:blob\",\n type: aObject.type,\n name: aObject.name,\n size: aObject.size,\n path: aObject._path || aObject.webkitRelativePath,\n read: await this._encode(read, session_id, local_workspace),\n seek: await this._encode(seek, session_id, local_workspace),\n };\n } else if (aObject instanceof ArrayBufferView) {\n const dtype = typedArrayToDtype(aObject);\n bObject = {\n _rtype: \"typedarray\",\n _rvalue: new Uint8Array(aObject.buffer),\n _rdtype: dtype,\n };\n } else if (aObject instanceof DataView) {\n bObject = {\n _rtype: \"memoryview\",\n _rvalue: new Uint8Array(aObject.buffer),\n };\n } else if (aObject instanceof Set) {\n bObject = {\n _rtype: \"set\",\n _rvalue: await this._encode(\n Array.from(aObject),\n session_id,\n local_workspace,\n ),\n };\n } else if (aObject instanceof Map) {\n bObject = {\n _rtype: \"orderedmap\",\n _rvalue: await this._encode(\n Array.from(aObject),\n session_id,\n local_workspace,\n ),\n };\n } else if (aObject.constructor === Object || Array.isArray(aObject)) {\n bObject = isarray ? [] : {};\n const keys = Object.keys(aObject);\n for (let k of keys) {\n bObject[k] = await this._encode(\n aObject[k],\n session_id,\n local_workspace,\n );\n }\n } else {\n throw `hypha-rpc: Unsupported data type: ${aObject}, you can register a custom codec to encode/decode the object.`;\n }\n\n if (!bObject) {\n throw new Error(\"Failed to encode object\");\n }\n return bObject;\n }\n\n async decode(aObject) {\n return await this._decode(aObject);\n }\n\n async _decode(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ) {\n if (!aObject) {\n return aObject;\n }\n let bObject;\n if (aObject._rtype) {\n if (\n this._codecs[aObject._rtype] &&\n this._codecs[aObject._rtype].decoder\n ) {\n const temp = aObject._rtype;\n delete aObject._rtype;\n aObject = await this._decode(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n aObject._rtype = temp;\n\n bObject = await Promise.resolve(\n this._codecs[aObject._rtype].decoder(aObject),\n );\n } else if (aObject._rtype === \"method\") {\n bObject = this._generate_remote_method(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n } else if (aObject._rtype === \"generator\") {\n // Create a method to fetch next items from the remote generator\n const gen_method = this._generate_remote_method(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n\n // Create an async generator proxy\n async function* asyncGeneratorProxy() {\n while (true) {\n try {\n const next_item = await gen_method();\n // Check for StopIteration signal\n if (next_item && next_item._rtype === \"stop_iteration\") {\n break;\n }\n yield next_item;\n } catch (error) {\n console.error(\"Error in generator:\", error);\n throw error;\n }\n }\n }\n bObject = asyncGeneratorProxy();\n } else if (aObject._rtype === \"ndarray\") {\n /*global nj tf*/\n //create build array/tensor if used in the plugin\n if (typeof nj !== \"undefined\" && nj.array) {\n if (Array.isArray(aObject._rvalue)) {\n aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);\n }\n bObject = nj\n .array(new Uint8(aObject._rvalue), aObject._rdtype)\n .reshape(aObject._rshape);\n } else if (typeof tf !== \"undefined\" && tf.Tensor) {\n if (Array.isArray(aObject._rvalue)) {\n aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);\n }\n const arraytype = dtypeToTypedArray[aObject._rdtype];\n bObject = tf.tensor(\n new arraytype(aObject._rvalue),\n aObject._rshape,\n aObject._rdtype,\n );\n } else {\n //keep it as regular if transfered to the main app\n bObject = aObject;\n }\n } else if (aObject._rtype === \"error\") {\n bObject = new Error(\n \"RemoteError: \" + aObject._rvalue + \"\\n\" + (aObject._rtrace || \"\"),\n );\n } else if (aObject._rtype === \"typedarray\") {\n const arraytype = dtypeToTypedArray[aObject._rdtype];\n if (!arraytype)\n throw new Error(\"unsupported dtype: \" + aObject._rdtype);\n const buffer = aObject._rvalue.buffer.slice(\n aObject._rvalue.byteOffset,\n aObject._rvalue.byteOffset + aObject._rvalue.byteLength,\n );\n bObject = new arraytype(buffer);\n } else if (aObject._rtype === \"memoryview\") {\n bObject = aObject._rvalue.buffer.slice(\n aObject._rvalue.byteOffset,\n aObject._rvalue.byteOffset + aObject._rvalue.byteLength,\n ); // ArrayBuffer\n } else if (aObject._rtype === \"iostream\") {\n if (aObject._rnative === \"js:blob\") {\n const read = await this._generate_remote_method(\n aObject.read,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n const bytes = await read();\n bObject = new Blob([bytes], {\n type: aObject.type,\n name: aObject.name,\n });\n } else {\n bObject = {};\n for (let k of Object.keys(aObject)) {\n if (!k.startsWith(\"_\")) {\n bObject[k] = await this._decode(\n aObject[k],\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n }\n }\n }\n bObject[\"__rpc_object__\"] = aObject;\n } else if (aObject._rtype === \"orderedmap\") {\n bObject = new Map(\n await this._decode(\n aObject._rvalue,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ),\n );\n } else if (aObject._rtype === \"set\") {\n bObject = new Set(\n await this._decode(\n aObject._rvalue,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n ),\n );\n } else {\n const temp = aObject._rtype;\n delete aObject._rtype;\n bObject = await this._decode(\n aObject,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n bObject._rtype = temp;\n }\n } else if (aObject.constructor === Object || Array.isArray(aObject)) {\n const isarray = Array.isArray(aObject);\n bObject = isarray ? [] : {};\n for (let k of Object.keys(aObject)) {\n if (isarray || aObject.hasOwnProperty(k)) {\n const v = aObject[k];\n bObject[k] = await this._decode(\n v,\n remote_parent,\n local_parent,\n remote_workspace,\n local_workspace,\n );\n }\n }\n } else {\n bObject = aObject;\n }\n if (bObject === undefined) {\n throw new Error(\"Failed to decode object\");\n }\n return bObject;\n }\n\n _expand_promise(data) {\n return {\n heartbeat: {\n _rtype: \"method\",\n _rtarget: data.from.split(\"/\")[1],\n _rmethod: data.session + \".heartbeat\",\n _rdoc: `heartbeat callback for method: ${data.method}`,\n },\n resolve: {\n _rtype: \"method\",\n _rtarget: data.from.split(\"/\")[1],\n _rmethod: data.session + \".resolve\",\n _rdoc: `resolve callback for method: ${data.method}`,\n },\n reject: {\n _rtype: \"method\",\n _rtarget: data.from.split(\"/\")[1],\n _rmethod: data.session + \".reject\",\n _rdoc: `reject callback for method: ${data.method}`,\n },\n interval: data.t,\n };\n }\n}\n","export function randId() {\n return Math.random().toString(36).substr(2, 10) + new Date().getTime();\n}\n\nexport function toCamelCase(str) {\n // Check if the string is already in camelCase\n if (!str.includes(\"_\")) {\n return str;\n }\n // Convert from snake_case to camelCase\n return str.replace(/_./g, (match) => match[1].toUpperCase());\n}\n\nexport function toSnakeCase(str) {\n // Convert from camelCase to snake_case\n return str.replace(/([A-Z])/g, \"_$1\").toLowerCase();\n}\n\nexport function expandKwargs(obj) {\n if (typeof obj !== \"object\" || obj === null) {\n return obj; // Return the value if obj is not an object\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n const value = obj[key];\n\n if (typeof value === \"function\") {\n newObj[key] = (...args) => {\n if (args.length === 0) {\n throw new Error(`Function \"${key}\" expects at least one argument.`);\n }\n\n // Check if the last argument is an object\n const lastArg = args[args.length - 1];\n let kwargs = {};\n\n if (\n typeof lastArg === \"object\" &&\n lastArg !== null &&\n !Array.isArray(lastArg)\n ) {\n // Extract kwargs from the last argument\n kwargs = { ...lastArg, _rkwarg: true };\n args = args.slice(0, -1); // Remove the last argument from args\n }\n\n // Call the original function with positional args followed by kwargs\n return value(...args, kwargs);\n };\n\n // Preserve metadata like __name__ and __schema__\n newObj[key].__name__ = key;\n if (value.__schema__) {\n newObj[key].__schema__ = { ...value.__schema__ };\n newObj[key].__schema__.name = key;\n }\n } else {\n newObj[key] = expandKwargs(value); // Recursively process nested objects\n }\n }\n }\n\n return newObj;\n}\n\nexport function convertCase(obj, caseType) {\n if (typeof obj !== \"object\" || obj === null || !caseType) {\n return obj; // Return the value if obj is not an object\n }\n\n const newObj = Array.isArray(obj) ? [] : {};\n\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n const value = obj[key];\n const camelKey = toCamelCase(key);\n const snakeKey = toSnakeCase(key);\n\n if (caseType === \"camel\") {\n newObj[camelKey] = convertCase(value, caseType);\n if (typeof value === \"function\") {\n newObj[camelKey].__name__ = camelKey;\n if (value.__schema__) {\n newObj[camelKey].__schema__ = { ...value.__schema__ };\n newObj[camelKey].__schema__.name = camelKey;\n }\n }\n } else if (caseType === \"snake\") {\n newObj[snakeKey] = convertCase(value, caseType);\n if (typeof value === \"function\") {\n newObj[snakeKey].__name__ = snakeKey;\n if (value.__schema__) {\n newObj[snakeKey].__schema__ = { ...value.__schema__ };\n newObj[snakeKey].__schema__.name = snakeKey;\n }\n }\n } else {\n // TODO handle schema for camel + snake\n if (caseType.includes(\"camel\")) {\n newObj[camelKey] = convertCase(value, \"camel\");\n }\n if (caseType.includes(\"snake\")) {\n newObj[snakeKey] = convertCase(value, \"snake\");\n }\n }\n }\n }\n\n return newObj;\n}\n\nexport function parseServiceUrl(url) {\n // Ensure no trailing slash\n url = url.replace(/\\/$/, \"\");\n\n // Regex pattern to match the URL structure\n const pattern = new RegExp(\n \"^(https?:\\\\/\\\\/[^/]+)\" + // server_url (http or https followed by domain)\n \"\\\\/([a-z0-9_-]+)\" + // workspace (lowercase letters, numbers, - or _)\n \"\\\\/services\\\\/\" + // static part of the URL\n \"(?:(?<clientId>[a-zA-Z0-9_-]+):)?\" + // optional client_id\n \"(?<serviceId>[a-zA-Z0-9_-]+)\" + // service_id\n \"(?:@(?<appId>[a-zA-Z0-9_-]+))?\", // optional app_id\n );\n\n const match = url.match(pattern);\n if (!match) {\n throw new Error(\"URL does not match the expected pattern\");\n }\n\n const serverUrl = match[1];\n const workspace = match[2];\n const clientId = match.groups?.clientId || \"*\";\n const serviceId = match.groups?.serviceId;\n const appId = match.groups?.appId || \"*\";\n\n return { serverUrl, workspace, clientId, serviceId, appId };\n}\n\nexport const dtypeToTypedArray = {\n int8: Int8Array,\n int16: Int16Array,\n int32: Int32Array,\n uint8: Uint8Array,\n uint16: Uint16Array,\n uint32: Uint32Array,\n float32: Float32Array,\n float64: Float64Array,\n array: Array,\n};\n\nexport async function loadRequirementsInWindow(requirements) {\n function _importScript(url) {\n //url is URL of external file, implementationCode is the code\n //to be called from the file, location is the location to\n //insert the <script> element\n return new Promise((resolve, reject) => {\n var scriptTag = document.createElement(\"script\");\n scriptTag.src = url;\n scriptTag.type = \"text/javascript\";\n scriptTag.onload = resolve;\n scriptTag.onreadystatechange = function () {\n if (this.readyState === \"loaded\" || this.readyState === \"complete\") {\n resolve();\n }\n };\n scriptTag.onerror = reject;\n document.head.appendChild(scriptTag);\n });\n }\n\n // support importScripts outside web worker\n async function importScripts() {\n var args = Array.prototype.slice.call(arguments),\n len = args.length,\n i = 0;\n for (; i < len; i++) {\n await _importScript(args[i]);\n }\n }\n\n if (\n requirements &&\n (Array.isArray(requirements) || typeof requirements === \"string\")\n ) {\n try {\n var link_node;\n requirements =\n typeof requirements === \"string\" ? [requirements] : requirements;\n if (Array.isArray(requirements)) {\n for (var i = 0; i < requirements.length; i++) {\n if (\n requirements[i].toLowerCase().endsWith(\".css\") ||\n requirements[i].startsWith(\"css:\")\n ) {\n if (requirements[i].startsWith(\"css:\")) {\n requirements[i] = requirements[i].slice(4);\n }\n link_node = document.createElement(\"link\");\n link_node.rel = \"stylesheet\";\n link_node.href = requirements[i];\n document.head.appendChild(link_node);\n } else if (\n requirements[i].toLowerCase().endsWith(\".mjs\") ||\n requirements[i].startsWith(\"mjs:\")\n ) {\n // import esmodule\n if (requirements[i].startsWith(\"mjs:\")) {\n requirements[i] = requirements[i].slice(4);\n }\n await import(/* webpackIgnore: true */ requirements[i]);\n } else if (\n requirements[i].toLowerCase().endsWith(\".js\") ||\n requirements[i].startsWith(\"js:\")\n ) {\n if (requirements[i].startsWith(\"js:\")) {\n requirements[i] = requirements[i].slice(3);\n }\n await importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"http\")) {\n await importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"cache:\")) {\n //ignore cache\n } else {\n console.log(\"Unprocessed requirements url: \" + requirements[i]);\n }\n }\n } else {\n throw \"unsupported requirements definition\";\n }\n } catch (e) {\n throw \"failed to import required scripts: \" + requirements.toString();\n }\n }\n}\n\nexport async function loadRequirementsInWebworker(requirements) {\n if (\n requirements &&\n (Array.isArray(requirements) || typeof requirements === \"string\")\n ) {\n try {\n if (!Array.isArray(requirements)) {\n requirements = [requirements];\n }\n for (var i = 0; i < requirements.length; i++) {\n if (\n requirements[i].toLowerCase().endsWith(\".css\") ||\n requirements[i].startsWith(\"css:\")\n ) {\n throw \"unable to import css in a webworker\";\n } else if (\n requirements[i].toLowerCase().endsWith(\".js\") ||\n requirements[i].startsWith(\"js:\")\n ) {\n if (requirements[i].startsWith(\"js:\")) {\n requirements[i] = requirements[i].slice(3);\n }\n importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"http\")) {\n importScripts(requirements[i]);\n } else if (requirements[i].startsWith(\"cache:\")) {\n //ignore cache\n } else {\n console.log(\"Unprocessed requirements url: \" + requirements[i]);\n }\n }\n } catch (e) {\n throw \"failed to import required scripts: \" + requirements.toString();\n }\n }\n}\n\nexport function loadRequirements(requirements) {\n if (\n typeof WorkerGlobalScope !== \"undefined\" &&\n self instanceof WorkerGlobalScope\n ) {\n return loadRequirementsInWebworker(requirements);\n } else {\n return loadRequirementsInWindow(requirements);\n }\n}\n\nexport function normalizeConfig(config) {\n config.version = config.version || \"0.1.0\";\n config.description =\n config.description || `[TODO: add description for ${config.name} ]`;\n config.type = config.type || \"rpc-window\";\n config.id = config.id || randId();\n config.target_origin = config.target_origin || \"*\";\n config.allow_execution = config.allow_execution || false;\n // remove functions\n config = Object.keys(config).reduce((p, c) => {\n if (typeof config[c] !== \"function\") p[c] = config[c];\n return p;\n }, {});\n return config;\n}\nexport const typedArrayToDtypeMapping = {\n Int8Array: \"int8\",\n Int16Array: \"int16\",\n Int32Array: \"int32\",\n Uint8Array: \"uint8\",\n Uint16Array: \"uint16\",\n Uint32Array: \"uint32\",\n Float32Array: \"float32\",\n Float64Array: \"float64\",\n Array: \"array\",\n};\n\nconst typedArrayToDtypeKeys = [];\nfor (const arrType of Object.keys(typedArrayToDtypeMapping)) {\n typedArrayToDtypeKeys.push(eval(arrType));\n}\n\nexport function typedArrayToDtype(obj) {\n let dtype = typedArrayToDtypeMapping[obj.constructor.name];\n if (!dtype) {\n const pt = Object.getPrototypeOf(obj);\n for (const arrType of typedArrayToDtypeKeys) {\n if (pt instanceof arrType) {\n dtype = typedArrayToDtypeMapping[arrType.name];\n break;\n }\n }\n }\n return dtype;\n}\n\nfunction cacheUrlInServiceWorker(url) {\n return new Promise(function (resolve, reject) {\n const message = {\n command: \"add\",\n url: url,\n };\n if (!navigator.serviceWorker || !navigator.serviceWorker.register) {\n reject(\"Service worker is not supported.\");\n return;\n }\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = function (event) {\n if (event.data && event.data.error) {\n reject(event.data.error);\n } else {\n resolve(event.data && event.data.result);\n }\n };\n\n if (navigator.serviceWorker && navigator.serviceWorker.controller) {\n navigator.serviceWorker.controller.postMessage(message, [\n messageChannel.port2,\n ]);\n } else {\n reject(\"Service worker controller is not available\");\n }\n });\n}\n\nexport async function cacheRequirements(requirements) {\n requirements = requirements || [];\n if (!Array.isArray(requirements)) {\n requirements = [requirements];\n }\n for (let req of requirements) {\n //remove prefix\n if (req.startsWith(\"js:\")) req = req.slice(3);\n if (req.startsWith(\"css:\")) req = req.slice(4);\n if (req.startsWith(\"cache:\")) req = req.slice(6);\n if (!req.startsWith(\"http\")) continue;\n\n await cacheUrlInServiceWorker(req).catch((e) => {\n console.error(e);\n });\n }\n}\n\nexport function assert(condition, message) {\n if (!condition) {\n throw new Error(message || \"Assertion failed\");\n }\n}\n\n//#Source https://bit.ly/2neWfJ2\nexport function urlJoin(...args) {\n return args\n .join(\"/\")\n .replace(/[\\/]+/g, \"/\")\n .replace(/^(.+):\\//, \"$1://\")\n .replace(/^file:/, \"file:/\")\n .replace(/\\/(\\?|&|#[^!])/g, \"$1\")\n .replace(/\\?/g, \"&\")\n .replace(\"&\", \"?\");\n}\n\nexport function waitFor(prom, time, error) {\n let timer;\n return Promise.race([\n prom,\n new Promise(\n (_r, rej) =>\n (timer = setTimeout(() => {\n rej(error || \"Timeout Error\");\n }, time * 1000)),\n ),\n ]).finally(() => clearTimeout(timer));\n}\n\nexport class MessageEmitter {\n constructor(debug) {\n this._event_handlers = {};\n this._once_handlers = {};\n this._debug = debug;\n }\n emit() {\n throw new Error(\"emit is not implemented\");\n }\n on(event, handler) {\n if (!this._event_handlers[event]) {\n this._event_handlers[event] = [];\n }\n this._event_handlers[event].push(handler);\n }\n once(event, handler) {\n handler.___event_run_once = true;\n this.on(event, handler);\n }\n off(event, handler) {\n if (!event && !handler) {\n // remove all events handlers\n this._event_handlers = {};\n } else if (event && !handler) {\n // remove all hanlders for the event\n if (this._event_handlers[event]) this._event_handlers[event] = [];\n } else {\n // remove a specific handler\n if (this._event_handlers[event]) {\n const idx = this._event_handlers[event].indexOf(handler);\n if (idx >= 0) {\n this._event_handlers[event].splice(idx, 1);\n }\n }\n }\n }\n _fire(event, data) {\n if (this._event_handlers[event]) {\n var i = this._event_handlers[event].length;\n while (i--) {\n const handler = this._event_handlers[event][i];\n try {\n handler(data);\n } catch (e) {\n console.error(e);\n } finally {\n if (handler.___event_run_once) {\n this._event_handlers[event].splice(i, 1);\n }\n }\n }\n } else {\n if (this._debug) {\n console.warn(\"unhandled event\", event, data);\n }\n }\n }\n\n waitFor(event, timeout) {\n return new Promise((resolve, reject) => {\n const handler = (data) => {\n clearTimeout(timer);\n resolve(data);\n };\n this.once(event, handler);\n const timer = setTimeout(() => {\n this.off(event, handler);\n reject(new Error(\"Timeout\"));\n }, timeout * 1000);\n });\n }\n}\n\nexport class Semaphore {\n constructor(max) {\n this.max = max;\n this.queue = [];\n this.current = 0;\n }\n async run(task) {\n if (this.current >= this.max) {\n // Wait until a slot is free\n await new Promise((resolve) => this.queue.push(resolve));\n }\n this.current++;\n try {\n return await task();\n } finally {\n this.current--;\n if (this.queue.length > 0) {\n // release one waiter\n this.queue.shift()();\n }\n }\n }\n}\n\n/**\n * Check if the object is a generator\n * @param {Object} obj - Object to check\n * @returns {boolean} - True if the object is a generator\n */\nexport function isGenerator(obj) {\n if (!obj) return false;\n\n return (\n typeof obj === \"object\" &&\n typeof obj.next === \"function\" &&\n typeof obj.throw === \"function\" &&\n typeof obj.return === \"function\"\n );\n}\n\n/**\n * Check if an object is an async generator object\n * @param {any} obj - Object to check\n * @returns {boolean} True if object is an async generator object\n */\nexport function isAsyncGenerator(obj) {\n if (!obj) return false;\n // Check if it's an async generator object\n return (\n typeof obj === \"object\" &&\n typeof obj.next === \"function\" &&\n typeof obj.throw === \"function\" &&\n typeof obj.return === \"function\" &&\n Symbol.asyncIterator in Object(obj) &&\n obj[Symbol.toStringTag] === \"AsyncGenerator\"\n );\n}\n","import { assert } from \"./index.js\";\n\n// Schema builder utility inspired by Zod for consistent API with Python\nexport const z = {\n object: (properties) => ({\n type: \"object\",\n properties,\n required: Object.keys(properties).filter(\n (key) => !properties[key]._optional,\n ),\n }),\n\n string: () => ({ type: \"string\", _optional: false }),\n number: () => ({ type: \"number\", _optional: false }),\n integer: () => ({ type: \"integer\", _optional: false }),\n boolean: () => ({ type: \"boolean\", _optional: false }),\n array: (items) => ({ type: \"array\", items, _optional: false }),\n\n // Make field optional\n optional: (schema) => ({ ...schema, _optional: true }),\n};\n\n// Add description method to schema types\n[\"string\", \"number\", \"integer\", \"boolean\", \"array\"].forEach((type) => {\n z[type] = () => {\n const schema = {\n type: type === \"integer\" ? \"integer\" : type,\n _optional: false,\n };\n schema.describe = (description) => ({ ...schema, description });\n return schema;\n };\n});\n\nexport function schemaFunction(\n func,\n { schema_type = \"auto\", name = null, description = null, parameters = null },\n) {\n if (!func || typeof func !== \"function\") {\n throw Error(\"func should be a function\");\n }\n assert(schema_type === \"auto\", \"schema_type should be auto\");\n\n // If no name provided, try to get it from function\n const funcName = name || func.name;\n assert(funcName, \"name should not be null\");\n\n // If parameters is a z.object result, convert it properly\n let processedParameters = parameters;\n if (\n parameters &&\n typeof parameters === \"object\" &&\n parameters.type === \"object\"\n ) {\n processedParameters = {\n type: \"object\",\n properties: parameters.properties || {},\n required: parameters.required || [],\n };\n\n // Clean up internal _optional flags\n for (const [key, schema] of Object.entries(\n processedParameters.properties,\n )) {\n if (schema._optional !== undefined) {\n delete schema._optional;\n }\n }\n }\n\n assert(\n processedParameters && processedParameters.type === \"object\",\n \"parameters should be an object schema\",\n );\n\n func.__schema__ = {\n name: funcName,\n description: description || \"\",\n parameters: processedParameters,\n };\n return func;\n}\n","import { RPC } from \"./rpc.js\";\nimport { assert, randId } from \"./utils/index.js\";\nimport { schemaFunction } from \"./utils/schema.js\";\n\nclass WebRTCConnection {\n constructor(channel) {\n this._data_channel = channel;\n this._handle_message = null;\n this._reconnection_token = null;\n this._handle_disconnected = null;\n this._handle_connected = () => {};\n this.manager_id = null;\n this._last_message = null;\n this._data_channel.onopen = async () => {\n if (this._last_message) {\n console.info(\"Resending last message after connection established\");\n this._data_channel.send(this._last_message);\n this._last_message = null;\n }\n this._handle_connected &&\n this._handle_connected({ channel: this._data_channel });\n };\n this._data_channel.onmessage = async (event) => {\n let data = event.data;\n if (data instanceof Blob) {\n data = await data.arrayBuffer();\n }\n this._handle_message(data);\n };\n const self = this;\n this._data_channel.onclose = function () {\n if (this._handle_disconnected) this._handle_disconnected(\"closed\");\n console.log(\"websocket closed\");\n self._data_channel = null;\n };\n }\n\n on_disconnected(handler) {\n this._handle_disconnected = handler;\n }\n\n on_connected(handler) {\n this._handle_connected = handler;\n }\n\n on_message(handler) {\n assert(handler, \"handler is required\");\n this._handle_message = handler;\n }\n\n async emit_message(data) {\n assert(this._handle_message, \"No handler for message\");\n try {\n this._last_message = data;\n this._data_channel.send(data);\n this._last_message = null;\n } catch (exp) {\n console.error(`Failed to send data, error: ${exp}`);\n throw exp;\n }\n }\n\n async disconnect(reason) {\n this._last_message = null;\n this._data_channel = null;\n console.info(`data channel connection disconnected (${reason})`);\n }\n}\n\nasync function _setupRPC(config) {\n assert(config.channel, \"No channel provided\");\n assert(config.workspace, \"No workspace provided\");\n const channel = config.channel;\n const clientId = config.client_id || randId();\n const connection = new WebRTCConnection(channel);\n config.context = config.context || {};\n config.context.connection_type = \"webrtc\";\n config.context.ws = config.workspace;\n const rpc = new RPC(connection, {\n client_id: clientId,\n default_context: config.context,\n name: config.name,\n method_timeout: config.method_timeout || 10.0,\n workspace: config.workspace,\n app_id: config.app_id,\n long_message_chunk_size: config.long_message_chunk_size,\n });\n return rpc;\n}\n\nasync function _createOffer(params, server, config, onInit, context) {\n config = config || {};\n let offer = new RTCSessionDescription({\n sdp: params.sdp,\n type: params.type,\n });\n\n let pc = new RTCPeerConnection({\n iceServers: config.ice_servers || [\n { urls: [\"stun:stun.l.google.com:19302\"] },\n ],\n sdpSemantics: \"unified-plan\",\n });\n\n if (server) {\n pc.addEventListener(\"datachannel\", async (event) => {\n const channel = event.channel;\n let ctx = null;\n if (context && context.user) ctx = { user: context.user, ws: context.ws };\n const rpc = await _setupRPC({\n channel: channel,\n client_id: channel.label,\n workspace: server.config.workspace,\n context: ctx,\n });\n // Map all the local services to the webrtc client\n rpc._services = server.rpc._services;\n });\n }\n\n if (onInit) {\n await onInit(pc);\n }\n\n await pc.setRemoteDescription(offer);\n\n let answer = await pc.createAnswer();\n await pc.setLocalDescription(answer);\n\n // Wait for ICE candidates to be gathered (important for Firefox)\n await new Promise((resolveIce) => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n } else {\n pc.addEventListener(\"icegatheringstatechange\", () => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n }\n });\n // Don't wait forever for ICE gathering\n setTimeout(resolveIce, 5000);\n }\n });\n\n return {\n sdp: pc.localDescription.sdp,\n type: pc.localDescription.type,\n workspace: server.config.workspace,\n };\n}\n\nasync function getRTCService(server, service_id, config) {\n config = config || {};\n config.peer_id = config.peer_id || randId();\n\n const pc = new RTCPeerConnection({\n iceServers: config.ice_servers || [\n { urls: [\"stun:stun.l.google.com:19302\"] },\n ],\n sdpSemantics: \"unified-plan\",\n });\n\n return new Promise(async (resolve, reject) => {\n let resolved = false;\n const timeout = setTimeout(() => {\n if (!resolved) {\n resolved = true;\n pc.close();\n reject(new Error(\"WebRTC Connection timeout\"));\n }\n }, 30000); // Increase timeout to 30 seconds\n\n try {\n pc.addEventListener(\n \"connectionstatechange\",\n () => {\n console.log(\"WebRTC Connection state: \", pc.connectionState);\n if (pc.connectionState === \"failed\") {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n pc.close();\n reject(new Error(\"WebRTC Connection failed\"));\n }\n } else if (pc.connectionState === \"closed\") {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(new Error(\"WebRTC Connection closed\"));\n }\n } else if (pc.connectionState === \"connected\") {\n console.log(\"WebRTC Connection established successfully\");\n }\n },\n false,\n );\n\n // Add ICE connection state change handler for better debugging\n pc.addEventListener(\"iceconnectionstatechange\", () => {\n console.log(\"ICE Connection state: \", pc.iceConnectionState);\n if (pc.iceConnectionState === \"failed\") {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n pc.close();\n reject(new Error(\"ICE Connection failed\"));\n }\n }\n });\n\n if (config.on_init) {\n await config.on_init(pc);\n delete config.on_init;\n }\n\n let channel = pc.createDataChannel(config.peer_id, { ordered: true });\n channel.binaryType = \"arraybuffer\";\n\n // Wait for ICE gathering to complete before creating offer\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n\n // Wait for ICE candidates to be gathered (important for Firefox)\n await new Promise((resolveIce) => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n } else {\n pc.addEventListener(\"icegatheringstatechange\", () => {\n if (pc.iceGatheringState === \"complete\") {\n resolveIce();\n }\n });\n // Don't wait forever for ICE gathering\n setTimeout(resolveIce, 5000);\n }\n });\n\n const svc = await server.getService(service_id);\n const answer = await svc.offer({\n sdp: pc.localDescription.sdp,\n type: pc.localDescription.type,\n });\n\n channel.onopen = () => {\n config.channel = channel;\n config.workspace = answer.workspace;\n // Increase timeout for Firefox compatibility\n setTimeout(async () => {\n if (!resolved) {\n try {\n const rpc = await _setupRPC(config);\n pc.rpc = rpc;\n async function get_service(name, ...args) {\n assert(\n !name.includes(\":\"),\n \"WebRTC service name should not contain ':'\",\n );\n assert(\n !name.includes(\"/\"),\n \"WebRTC service name should not contain '/'\",\n );\n return await rpc.get_remote_service(\n config.workspace + \"/\" + config.peer_id + \":\" + name,\n ...args,\n );\n }\n async function disconnect() {\n await rpc.disconnect();\n pc.close();\n }\n pc.getService = schemaFunction(get_service, {\n name: \"getService\",\n description: \"Get a remote service via webrtc\",\n parameters: {\n type: \"object\",\n properties: {\n service_id: {\n type: \"string\",\n description:\n \"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'\",\n },\n config: {\n type: \"object\",\n description: \"Options for the service\",\n },\n },\n required: [\"id\"],\n },\n });\n pc.disconnect = schemaFunction(disconnect, {\n name: \"disconnect\",\n description: \"Disconnect from the webrtc connection via webrtc\",\n parameters: { type: \"object\", properties: {} },\n });\n pc.registerCodec = schemaFunction(rpc.register_codec, {\n name: \"registerCodec\",\n description: \"Register a codec for the webrtc connection\",\n parameters: {\n type: \"object\",\n properties: {\n codec: {\n type: \"object\",\n description: \"Codec to register\",\n properties: {\n name: { type: \"string\" },\n type: {},\n encoder: { type: \"function\" },\n decoder: { type: \"function\" },\n },\n },\n },\n },\n });\n resolved = true;\n clearTimeout(timeout);\n resolve(pc);\n } catch (e) {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(e);\n }\n }\n }\n }, 1000); // Increase timeout to 1 second for Firefox\n };\n\n channel.onclose = () => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(new Error(\"Data channel closed\"));\n }\n };\n\n channel.onerror = (error) => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(new Error(`Data channel error: ${error}`));\n }\n };\n\n await pc.setRemoteDescription(\n new RTCSessionDescription({\n sdp: answer.sdp,\n type: answer.type,\n }),\n );\n } catch (e) {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n reject(e);\n }\n }\n });\n}\n\nasync function registerRTCService(server, service_id, config) {\n config = config || {\n visibility: \"protected\",\n require_context: true,\n };\n const onInit = config.on_init;\n delete config.on_init;\n return await server.registerService({\n id: service_id,\n config,\n offer: (params, context) =>\n _createOffer(params, server, config, onInit, context),\n });\n}\n\nexport { getRTCService, registerRTCService };\n","import { utf8DecodeJs } from \"./utils/utf8.mjs\";\nvar DEFAULT_MAX_KEY_LENGTH = 16;\nvar DEFAULT_MAX_LENGTH_PER_KEY = 16;\nvar CachedKeyDecoder = /** @class */ (function () {\n function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {\n if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }\n if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }\n this.maxKeyLength = maxKeyLength;\n this.maxLengthPerKey = maxLengthPerKey;\n this.hit = 0;\n this.miss = 0;\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (var i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n CachedKeyDecoder.prototype.canBeCached = function (byteLength) {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n };\n CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {\n var records = this.caches[byteLength - 1];\n FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {\n var record = records_1[_i];\n var recordBytes = record.bytes;\n for (var j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n };\n CachedKeyDecoder.prototype.store = function (bytes, value) {\n var records = this.caches[bytes.length - 1];\n var record = { bytes: bytes, str: value };\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n }\n else {\n records.push(record);\n }\n };\n CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {\n var cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n var str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n };\n return CachedKeyDecoder;\n}());\nexport { CachedKeyDecoder };\n//# sourceMappingURL=CachedKeyDecoder.mjs.map","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar DecodeError = /** @class */ (function (_super) {\n __extends(DecodeError, _super);\n function DecodeError(message) {\n var _this = _super.call(this, message) || this;\n // fix the prototype chain in a cross-platform way\n var proto = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(_this, proto);\n Object.defineProperty(_this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n return _this;\n }\n return DecodeError;\n}(Error));\nexport { DecodeError };\n//# sourceMappingURL=DecodeError.mjs.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n};\nvar __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\nvar __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n};\nimport { prettyByte } from \"./utils/prettyByte.mjs\";\nimport { ExtensionCodec } from \"./ExtensionCodec.mjs\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int.mjs\";\nimport { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from \"./utils/utf8.mjs\";\nimport { createDataView, ensureUint8Array } from \"./utils/typedArrays.mjs\";\nimport { CachedKeyDecoder } from \"./CachedKeyDecoder.mjs\";\nimport { DecodeError } from \"./DecodeError.mjs\";\nvar isValidMapKeyType = function (key) {\n var keyType = typeof key;\n return keyType === \"string\" || keyType === \"number\";\n};\nvar HEAD_BYTE_REQUIRED = -1;\nvar EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nvar EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\n// IE11: Hack to support IE11.\n// IE11: Drop this hack and just use RangeError when IE11 is obsolete.\nexport var DataViewIndexOutOfBoundsError = (function () {\n try {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n }\n catch (e) {\n return e.constructor;\n }\n throw new Error(\"never reached\");\n})();\nvar MORE_DATA = new DataViewIndexOutOfBoundsError(\"Insufficient data\");\nvar sharedCachedKeyDecoder = new CachedKeyDecoder();\nvar Decoder = /** @class */ (function () {\n function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {\n if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }\n if (context === void 0) { context = undefined; }\n if (maxStrLength === void 0) { maxStrLength = UINT32_MAX; }\n if (maxBinLength === void 0) { maxBinLength = UINT32_MAX; }\n if (maxArrayLength === void 0) { maxArrayLength = UINT32_MAX; }\n if (maxMapLength === void 0) { maxMapLength = UINT32_MAX; }\n if (maxExtLength === void 0) { maxExtLength = UINT32_MAX; }\n if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }\n this.extensionCodec = extensionCodec;\n this.context = context;\n this.maxStrLength = maxStrLength;\n this.maxBinLength = maxBinLength;\n this.maxArrayLength = maxArrayLength;\n this.maxMapLength = maxMapLength;\n this.maxExtLength = maxExtLength;\n this.keyDecoder = keyDecoder;\n this.totalPos = 0;\n this.pos = 0;\n this.view = EMPTY_VIEW;\n this.bytes = EMPTY_BYTES;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack = [];\n }\n Decoder.prototype.reinitializeState = function () {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.length = 0;\n // view, bytes, and pos will be re-initialized in setBuffer()\n };\n Decoder.prototype.setBuffer = function (buffer) {\n this.bytes = ensureUint8Array(buffer);\n this.view = createDataView(this.bytes);\n this.pos = 0;\n };\n Decoder.prototype.appendBuffer = function (buffer) {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n }\n else {\n var remainingData = this.bytes.subarray(this.pos);\n var newData = ensureUint8Array(buffer);\n // concat remainingData + newData\n var newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n };\n Decoder.prototype.hasRemaining = function (size) {\n return this.view.byteLength - this.pos >= size;\n };\n Decoder.prototype.createExtraByteError = function (posToShow) {\n var _a = this, view = _a.view, pos = _a.pos;\n return new RangeError(\"Extra \".concat(view.byteLength - pos, \" of \").concat(view.byteLength, \" byte(s) found at buffer[\").concat(posToShow, \"]\"));\n };\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n Decoder.prototype.decode = function (buffer) {\n this.reinitializeState();\n this.setBuffer(buffer);\n var object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n };\n Decoder.prototype.decodeMulti = function (buffer) {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.reinitializeState();\n this.setBuffer(buffer);\n _a.label = 1;\n case 1:\n if (!this.hasRemaining(1)) return [3 /*break*/, 3];\n return [4 /*yield*/, this.doDecodeSync()];\n case 2:\n _a.sent();\n return [3 /*break*/, 1];\n case 3: return [2 /*return*/];\n }\n });\n };\n Decoder.prototype.decodeAsync = function (stream) {\n var stream_1, stream_1_1;\n var e_1, _a;\n return __awaiter(this, void 0, void 0, function () {\n var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n decoded = false;\n _c.label = 1;\n case 1:\n _c.trys.push([1, 6, 7, 12]);\n stream_1 = __asyncValues(stream);\n _c.label = 2;\n case 2: return [4 /*yield*/, stream_1.next()];\n case 3:\n if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];\n buffer = stream_1_1.value;\n if (decoded) {\n throw this.createExtraByteError(this.totalPos);\n }\n this.appendBuffer(buffer);\n try {\n object = this.doDecodeSync();\n decoded = true;\n }\n catch (e) {\n if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n _c.label = 4;\n case 4: return [3 /*break*/, 2];\n case 5: return [3 /*break*/, 12];\n case 6:\n e_1_1 = _c.sent();\n e_1 = { error: e_1_1 };\n return [3 /*break*/, 12];\n case 7:\n _c.trys.push([7, , 10, 11]);\n if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];\n return [4 /*yield*/, _a.call(stream_1)];\n case 8:\n _c.sent();\n _c.label = 9;\n case 9: return [3 /*break*/, 11];\n case 10:\n if (e_1) throw e_1.error;\n return [7 /*endfinally*/];\n case 11: return [7 /*endfinally*/];\n case 12:\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return [2 /*return*/, object];\n }\n _b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;\n throw new RangeError(\"Insufficient data in parsing \".concat(prettyByte(headByte), \" at \").concat(totalPos, \" (\").concat(pos, \" in the current buffer)\"));\n }\n });\n });\n };\n Decoder.prototype.decodeArrayStream = function (stream) {\n return this.decodeMultiAsync(stream, true);\n };\n Decoder.prototype.decodeStream = function (stream) {\n return this.decodeMultiAsync(stream, false);\n };\n Decoder.prototype.decodeMultiAsync = function (stream, isArray) {\n return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {\n var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;\n var e_3, _a;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n isArrayHeaderRequired = isArray;\n arrayItemsLeft = -1;\n _b.label = 1;\n case 1:\n _b.trys.push([1, 13, 14, 19]);\n stream_2 = __asyncValues(stream);\n _b.label = 2;\n case 2: return [4 /*yield*/, __await(stream_2.next())];\n case 3:\n if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];\n buffer = stream_2_1.value;\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n this.appendBuffer(buffer);\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n _b.label = 4;\n case 4:\n _b.trys.push([4, 9, , 10]);\n _b.label = 5;\n case 5:\n if (!true) return [3 /*break*/, 8];\n return [4 /*yield*/, __await(this.doDecodeSync())];\n case 6: return [4 /*yield*/, _b.sent()];\n case 7:\n _b.sent();\n if (--arrayItemsLeft === 0) {\n return [3 /*break*/, 8];\n }\n return [3 /*break*/, 5];\n case 8: return [3 /*break*/, 10];\n case 9:\n e_2 = _b.sent();\n if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {\n throw e_2; // rethrow\n }\n return [3 /*break*/, 10];\n case 10:\n this.totalPos += this.pos;\n _b.label = 11;\n case 11: return [3 /*break*/, 2];\n case 12: return [3 /*break*/, 19];\n case 13:\n e_3_1 = _b.sent();\n e_3 = { error: e_3_1 };\n return [3 /*break*/, 19];\n case 14:\n _b.trys.push([14, , 17, 18]);\n if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];\n return [4 /*yield*/, __await(_a.call(stream_2))];\n case 15:\n _b.sent();\n _b.label = 16;\n case 16: return [3 /*break*/, 18];\n case 17:\n if (e_3) throw e_3.error;\n return [7 /*endfinally*/];\n case 18: return [7 /*endfinally*/];\n case 19: return [2 /*return*/];\n }\n });\n });\n };\n Decoder.prototype.doDecodeSync = function () {\n DECODE: while (true) {\n var headByte = this.readHeadByte();\n var object = void 0;\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n }\n else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n }\n else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n var size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n var size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n var byteLength = headByte - 0xa0;\n object = this.decodeUtf8String(byteLength, 0);\n }\n }\n else if (headByte === 0xc0) {\n // nil\n object = null;\n }\n else if (headByte === 0xc2) {\n // false\n object = false;\n }\n else if (headByte === 0xc3) {\n // true\n object = true;\n }\n else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n }\n else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n }\n else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n }\n else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n }\n else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n }\n else if (headByte === 0xcf) {\n // uint 64\n object = this.readU64();\n }\n else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n }\n else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n }\n else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n }\n else if (headByte === 0xd3) {\n // int 64\n object = this.readI64();\n }\n else if (headByte === 0xd9) {\n // str 8\n var byteLength = this.lookU8();\n object = this.decodeUtf8String(byteLength, 1);\n }\n else if (headByte === 0xda) {\n // str 16\n var byteLength = this.lookU16();\n object = this.decodeUtf8String(byteLength, 2);\n }\n else if (headByte === 0xdb) {\n // str 32\n var byteLength = this.lookU32();\n object = this.decodeUtf8String(byteLength, 4);\n }\n else if (headByte === 0xdc) {\n // array 16\n var size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else if (headByte === 0xdd) {\n // array 32\n var size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = [];\n }\n }\n else if (headByte === 0xde) {\n // map 16\n var size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte === 0xdf) {\n // map 32\n var size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n }\n else {\n object = {};\n }\n }\n else if (headByte === 0xc4) {\n // bin 8\n var size = this.lookU8();\n object = this.decodeBinary(size, 1);\n }\n else if (headByte === 0xc5) {\n // bin 16\n var size = this.lookU16();\n object = this.decodeBinary(size, 2);\n }\n else if (headByte === 0xc6) {\n // bin 32\n var size = this.lookU32();\n object = this.decodeBinary(size, 4);\n }\n else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n }\n else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n }\n else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n }\n else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n }\n else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n }\n else if (headByte === 0xc7) {\n // ext 8\n var size = this.lookU8();\n object = this.decodeExtension(size, 1);\n }\n else if (headByte === 0xc8) {\n // ext 16\n var size = this.lookU16();\n object = this.decodeExtension(size, 2);\n }\n else if (headByte === 0xc9) {\n // ext 32\n var size = this.lookU32();\n object = this.decodeExtension(size, 4);\n }\n else {\n throw new DecodeError(\"Unrecognized type byte: \".concat(prettyByte(headByte)));\n }\n this.complete();\n var stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n var state = stack[stack.length - 1];\n if (state.type === 0 /* State.ARRAY */) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n stack.pop();\n object = state.array;\n }\n else {\n continue DECODE;\n }\n }\n else if (state.type === 1 /* State.MAP_KEY */) {\n if (!isValidMapKeyType(object)) {\n throw new DecodeError(\"The type of key must be string or number but \" + typeof object);\n }\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n state.key = object;\n state.type = 2 /* State.MAP_VALUE */;\n continue DECODE;\n }\n else {\n // it must be `state.type === State.MAP_VALUE` here\n state.map[state.key] = object;\n state.readCount++;\n if (state.readCount === state.size) {\n stack.pop();\n object = state.map;\n }\n else {\n state.key = null;\n state.type = 1 /* State.MAP_KEY */;\n continue DECODE;\n }\n }\n }\n return object;\n }\n };\n Decoder.prototype.readHeadByte = function () {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n return this.headByte;\n };\n Decoder.prototype.complete = function () {\n this.headByte = HEAD_BYTE_REQUIRED;\n };\n Decoder.prototype.readArraySize = function () {\n var headByte = this.readHeadByte();\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n }\n else {\n throw new DecodeError(\"Unrecognized array type byte: \".concat(prettyByte(headByte)));\n }\n }\n }\n };\n Decoder.prototype.pushMapState = function (size) {\n if (size > this.maxMapLength) {\n throw new DecodeError(\"Max length exceeded: map length (\".concat(size, \") > maxMapLengthLength (\").concat(this.maxMapLength, \")\"));\n }\n this.stack.push({\n type: 1 /* State.MAP_KEY */,\n size: size,\n key: null,\n readCount: 0,\n map: {},\n });\n };\n Decoder.prototype.pushArrayState = function (size) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(\"Max length exceeded: array length (\".concat(size, \") > maxArrayLength (\").concat(this.maxArrayLength, \")\"));\n }\n this.stack.push({\n type: 0 /* State.ARRAY */,\n size: size,\n array: new Array(size),\n position: 0,\n });\n };\n Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {\n var _a;\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\"Max length exceeded: UTF-8 byte length (\".concat(byteLength, \") > maxStrLength (\").concat(this.maxStrLength, \")\"));\n }\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n var offset = this.pos + headerOffset;\n var object;\n if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n }\n else if (byteLength > TEXT_DECODER_THRESHOLD) {\n object = utf8DecodeTD(this.bytes, offset, byteLength);\n }\n else {\n object = utf8DecodeJs(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n };\n Decoder.prototype.stateIsMapKey = function () {\n if (this.stack.length > 0) {\n var state = this.stack[this.stack.length - 1];\n return state.type === 1 /* State.MAP_KEY */;\n }\n return false;\n };\n Decoder.prototype.decodeBinary = function (byteLength, headOffset) {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(\"Max length exceeded: bin length (\".concat(byteLength, \") > maxBinLength (\").concat(this.maxBinLength, \")\"));\n }\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n var offset = this.pos + headOffset;\n var object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n };\n Decoder.prototype.decodeExtension = function (size, headOffset) {\n if (size > this.maxExtLength) {\n throw new DecodeError(\"Max length exceeded: ext length (\".concat(size, \") > maxExtLength (\").concat(this.maxExtLength, \")\"));\n }\n var extType = this.view.getInt8(this.pos + headOffset);\n var data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n };\n Decoder.prototype.lookU8 = function () {\n return this.view.getUint8(this.pos);\n };\n Decoder.prototype.lookU16 = function () {\n return this.view.getUint16(this.pos);\n };\n Decoder.prototype.lookU32 = function () {\n return this.view.getUint32(this.pos);\n };\n Decoder.prototype.readU8 = function () {\n var value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n };\n Decoder.prototype.readI8 = function () {\n var value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n };\n Decoder.prototype.readU16 = function () {\n var value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n };\n Decoder.prototype.readI16 = function () {\n var value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n };\n Decoder.prototype.readU32 = function () {\n var value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n };\n Decoder.prototype.readI32 = function () {\n var value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n };\n Decoder.prototype.readU64 = function () {\n var value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n };\n Decoder.prototype.readI64 = function () {\n var value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n };\n Decoder.prototype.readF32 = function () {\n var value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n };\n Decoder.prototype.readF64 = function () {\n var value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n };\n return Decoder;\n}());\nexport { Decoder };\n//# sourceMappingURL=Decoder.mjs.map","import { utf8EncodeJs, utf8Count, TEXT_ENCODER_THRESHOLD, utf8EncodeTE } from \"./utils/utf8.mjs\";\nimport { ExtensionCodec } from \"./ExtensionCodec.mjs\";\nimport { setInt64, setUint64 } from \"./utils/int.mjs\";\nimport { ensureUint8Array } from \"./utils/typedArrays.mjs\";\nexport var DEFAULT_MAX_DEPTH = 100;\nexport var DEFAULT_INITIAL_BUFFER_SIZE = 2048;\nvar Encoder = /** @class */ (function () {\n function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {\n if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }\n if (context === void 0) { context = undefined; }\n if (maxDepth === void 0) { maxDepth = DEFAULT_MAX_DEPTH; }\n if (initialBufferSize === void 0) { initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE; }\n if (sortKeys === void 0) { sortKeys = false; }\n if (forceFloat32 === void 0) { forceFloat32 = false; }\n if (ignoreUndefined === void 0) { ignoreUndefined = false; }\n if (forceIntegerToFloat === void 0) { forceIntegerToFloat = false; }\n this.extensionCodec = extensionCodec;\n this.context = context;\n this.maxDepth = maxDepth;\n this.initialBufferSize = initialBufferSize;\n this.sortKeys = sortKeys;\n this.forceFloat32 = forceFloat32;\n this.ignoreUndefined = ignoreUndefined;\n this.forceIntegerToFloat = forceIntegerToFloat;\n this.pos = 0;\n this.view = new DataView(new ArrayBuffer(this.initialBufferSize));\n this.bytes = new Uint8Array(this.view.buffer);\n }\n Encoder.prototype.reinitializeState = function () {\n this.pos = 0;\n };\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n Encoder.prototype.encodeSharedRef = function (object) {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n };\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n Encoder.prototype.encode = function (object) {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n };\n Encoder.prototype.doEncode = function (object, depth) {\n if (depth > this.maxDepth) {\n throw new Error(\"Too deep objects in depth \".concat(depth));\n }\n if (object == null) {\n this.encodeNil();\n }\n else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n }\n else if (typeof object === \"number\") {\n this.encodeNumber(object);\n }\n else if (typeof object === \"string\") {\n this.encodeString(object);\n }\n else {\n this.encodeObject(object, depth);\n }\n };\n Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) {\n var requiredSize = this.pos + sizeToWrite;\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n };\n Encoder.prototype.resizeBuffer = function (newSize) {\n var newBuffer = new ArrayBuffer(newSize);\n var newBytes = new Uint8Array(newBuffer);\n var newView = new DataView(newBuffer);\n newBytes.set(this.bytes);\n this.view = newView;\n this.bytes = newBytes;\n };\n Encoder.prototype.encodeNil = function () {\n this.writeU8(0xc0);\n };\n Encoder.prototype.encodeBoolean = function (object) {\n if (object === false) {\n this.writeU8(0xc2);\n }\n else {\n this.writeU8(0xc3);\n }\n };\n Encoder.prototype.encodeNumber = function (object) {\n if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n }\n else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n }\n else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n }\n else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n }\n else {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n }\n }\n else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n }\n else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n }\n else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n }\n else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n }\n else {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n }\n }\n }\n else {\n // non-integer numbers\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n }\n else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n };\n Encoder.prototype.writeStringHeader = function (byteLength) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n }\n else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n }\n else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n }\n else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n }\n else {\n throw new Error(\"Too long string: \".concat(byteLength, \" bytes in UTF-8\"));\n }\n };\n Encoder.prototype.encodeString = function (object) {\n var maxHeaderSize = 1 + 4;\n var strLength = object.length;\n if (strLength > TEXT_ENCODER_THRESHOLD) {\n var byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeTE(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n else {\n var byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeJs(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n };\n Encoder.prototype.encodeObject = function (object, depth) {\n // try to encode objects with custom codec first of non-primitives\n var ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n }\n else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n }\n else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n }\n else if (typeof object === \"object\") {\n this.encodeMap(object, depth);\n }\n else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(\"Unrecognized object: \".concat(Object.prototype.toString.apply(object)));\n }\n };\n Encoder.prototype.encodeBinary = function (object) {\n var size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n }\n else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large binary: \".concat(size));\n }\n var bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n };\n Encoder.prototype.encodeArray = function (object, depth) {\n var size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n }\n else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large array: \".concat(size));\n }\n for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {\n var item = object_1[_i];\n this.doEncode(item, depth + 1);\n }\n };\n Encoder.prototype.countWithoutUndefined = function (object, keys) {\n var count = 0;\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var key = keys_1[_i];\n if (object[key] !== undefined) {\n count++;\n }\n }\n return count;\n };\n Encoder.prototype.encodeMap = function (object, depth) {\n var keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n }\n else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large map object: \".concat(size));\n }\n for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {\n var key = keys_2[_i];\n var value = object[key];\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n };\n Encoder.prototype.encodeExtension = function (ext) {\n var size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n }\n else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n }\n else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n }\n else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n }\n else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n }\n else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n }\n else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n }\n else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n }\n else {\n throw new Error(\"Too large extension object: \".concat(size));\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n };\n Encoder.prototype.writeU8 = function (value) {\n this.ensureBufferSizeToWrite(1);\n this.view.setUint8(this.pos, value);\n this.pos++;\n };\n Encoder.prototype.writeU8a = function (values) {\n var size = values.length;\n this.ensureBufferSizeToWrite(size);\n this.bytes.set(values, this.pos);\n this.pos += size;\n };\n Encoder.prototype.writeI8 = function (value) {\n this.ensureBufferSizeToWrite(1);\n this.view.setInt8(this.pos, value);\n this.pos++;\n };\n Encoder.prototype.writeU16 = function (value) {\n this.ensureBufferSizeToWrite(2);\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n };\n Encoder.prototype.writeI16 = function (value) {\n this.ensureBufferSizeToWrite(2);\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n };\n Encoder.prototype.writeU32 = function (value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n };\n Encoder.prototype.writeI32 = function (value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n };\n Encoder.prototype.writeF32 = function (value) {\n this.ensureBufferSizeToWrite(4);\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n };\n Encoder.prototype.writeF64 = function (value) {\n this.ensureBufferSizeToWrite(8);\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n };\n Encoder.prototype.writeU64 = function (value) {\n this.ensureBufferSizeToWrite(8);\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n };\n Encoder.prototype.writeI64 = function (value) {\n this.ensureBufferSizeToWrite(8);\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n };\n return Encoder;\n}());\nexport { Encoder };\n//# sourceMappingURL=Encoder.mjs.map","/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nvar ExtData = /** @class */ (function () {\n function ExtData(type, data) {\n this.type = type;\n this.data = data;\n }\n return ExtData;\n}());\nexport { ExtData };\n//# sourceMappingURL=ExtData.mjs.map","// ExtensionCodec to handle MessagePack extensions\nimport { ExtData } from \"./ExtData.mjs\";\nimport { timestampExtension } from \"./timestamp.mjs\";\nvar ExtensionCodec = /** @class */ (function () {\n function ExtensionCodec() {\n // built-in extensions\n this.builtInEncoders = [];\n this.builtInDecoders = [];\n // custom extensions\n this.encoders = [];\n this.decoders = [];\n this.register(timestampExtension);\n }\n ExtensionCodec.prototype.register = function (_a) {\n var type = _a.type, encode = _a.encode, decode = _a.decode;\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n }\n else {\n // built-in extensions\n var index = 1 + type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n };\n ExtensionCodec.prototype.tryToEncode = function (object, context) {\n // built-in extensions\n for (var i = 0; i < this.builtInEncoders.length; i++) {\n var encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n var data = encodeExt(object, context);\n if (data != null) {\n var type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n // custom extensions\n for (var i = 0; i < this.encoders.length; i++) {\n var encodeExt = this.encoders[i];\n if (encodeExt != null) {\n var data = encodeExt(object, context);\n if (data != null) {\n var type = i;\n return new ExtData(type, data);\n }\n }\n }\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n };\n ExtensionCodec.prototype.decode = function (data, type, context) {\n var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n }\n else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n };\n ExtensionCodec.defaultCodec = new ExtensionCodec();\n return ExtensionCodec;\n}());\nexport { ExtensionCodec };\n//# sourceMappingURL=ExtensionCodec.mjs.map","import { Decoder } from \"./Decoder.mjs\";\nexport var defaultDecodeOptions = {};\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode(buffer, options) {\n if (options === void 0) { options = defaultDecodeOptions; }\n var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);\n return decoder.decode(buffer);\n}\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti(buffer, options) {\n if (options === void 0) { options = defaultDecodeOptions; }\n var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);\n return decoder.decodeMulti(buffer);\n}\n//# sourceMappingURL=decode.mjs.map","import { Encoder } from \"./Encoder.mjs\";\nvar defaultEncodeOptions = {};\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode(value, options) {\n if (options === void 0) { options = defaultEncodeOptions; }\n var encoder = new Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);\n return encoder.encodeSharedRef(value);\n}\n//# sourceMappingURL=encode.mjs.map","// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError.mjs\";\nimport { getInt64, setInt64 } from \"./utils/int.mjs\";\nexport var EXT_TIMESTAMP = -1;\nvar TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nvar TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\nexport function encodeTimeSpecToTimestamp(_a) {\n var sec = _a.sec, nsec = _a.nsec;\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n var rv = new Uint8Array(4);\n var view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n }\n else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n var secHigh = sec / 0x100000000;\n var secLow = sec & 0xffffffff;\n var rv = new Uint8Array(8);\n var view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n }\n else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n var rv = new Uint8Array(12);\n var view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\nexport function encodeDateToTimeSpec(date) {\n var msec = date.getTime();\n var sec = Math.floor(msec / 1e3);\n var nsec = (msec - sec * 1e3) * 1e6;\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n var nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\nexport function encodeTimestampExtension(object) {\n if (object instanceof Date) {\n var timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n }\n else {\n return null;\n }\n}\nexport function decodeTimestampToTimeSpec(data) {\n var view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n var sec = view.getUint32(0);\n var nsec = 0;\n return { sec: sec, nsec: nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n var nsec30AndSecHigh2 = view.getUint32(0);\n var secLow32 = view.getUint32(4);\n var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n var nsec = nsec30AndSecHigh2 >>> 2;\n return { sec: sec, nsec: nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n var sec = getInt64(view, 4);\n var nsec = view.getUint32(0);\n return { sec: sec, nsec: nsec };\n }\n default:\n throw new DecodeError(\"Unrecognized data size for timestamp (expected 4, 8, or 12): \".concat(data.length));\n }\n}\nexport function decodeTimestampExtension(data) {\n var timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\nexport var timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n//# sourceMappingURL=timestamp.mjs.map","// Integer Utility\nexport var UINT32_MAX = 4294967295;\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\nexport function setUint64(view, offset, value) {\n var high = value / 4294967296;\n var low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\nexport function setInt64(view, offset, value) {\n var high = Math.floor(value / 4294967296);\n var low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\nexport function getInt64(view, offset) {\n var high = view.getInt32(offset);\n var low = view.getUint32(offset + 4);\n return high * 4294967296 + low;\n}\nexport function getUint64(view, offset) {\n var high = view.getUint32(offset);\n var low = view.getUint32(offset + 4);\n return high * 4294967296 + low;\n}\n//# sourceMappingURL=int.mjs.map","export function prettyByte(byte) {\n return \"\".concat(byte < 0 ? \"-\" : \"\", \"0x\").concat(Math.abs(byte).toString(16).padStart(2, \"0\"));\n}\n//# sourceMappingURL=prettyByte.mjs.map","export function ensureUint8Array(buffer) {\n if (buffer instanceof Uint8Array) {\n return buffer;\n }\n else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n }\n else if (buffer instanceof ArrayBuffer) {\n return new Uint8Array(buffer);\n }\n else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\nexport function createDataView(buffer) {\n if (buffer instanceof ArrayBuffer) {\n return new DataView(buffer);\n }\n var bufferView = ensureUint8Array(buffer);\n return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n}\n//# sourceMappingURL=typedArrays.mjs.map","var _a, _b, _c;\n/* eslint-disable @typescript-eslint/no-unnecessary-condition */\nimport { UINT32_MAX } from \"./int.mjs\";\nvar TEXT_ENCODING_AVAILABLE = (typeof process === \"undefined\" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[\"TEXT_ENCODING\"]) !== \"never\") &&\n typeof TextEncoder !== \"undefined\" &&\n typeof TextDecoder !== \"undefined\";\nexport function utf8Count(str) {\n var strLength = str.length;\n var byteLength = 0;\n var pos = 0;\n while (pos < strLength) {\n var value = str.charCodeAt(pos++);\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n }\n else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n var extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n }\n else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\nexport function utf8EncodeJs(str, output, outputOffset) {\n var strLength = str.length;\n var offset = outputOffset;\n var pos = 0;\n while (pos < strLength) {\n var value = str.charCodeAt(pos++);\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n }\n else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n var extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\nvar sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;\nexport var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b[\"TEXT_ENCODING\"]) !== \"force\"\n ? 200\n : 0;\nfunction utf8EncodeTEencode(str, output, outputOffset) {\n output.set(sharedTextEncoder.encode(str), outputOffset);\n}\nfunction utf8EncodeTEencodeInto(str, output, outputOffset) {\n sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));\n}\nexport var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;\nvar CHUNK_SIZE = 4096;\nexport function utf8DecodeJs(bytes, inputOffset, byteLength) {\n var offset = inputOffset;\n var end = offset + byteLength;\n var units = [];\n var result = \"\";\n while (offset < end) {\n var byte1 = bytes[offset++];\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n }\n else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n var byte2 = bytes[offset++] & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n }\n else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n var byte2 = bytes[offset++] & 0x3f;\n var byte3 = bytes[offset++] & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n }\n else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n var byte2 = bytes[offset++] & 0x3f;\n var byte3 = bytes[offset++] & 0x3f;\n var byte4 = bytes[offset++] & 0x3f;\n var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n }\n else {\n units.push(byte1);\n }\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode.apply(String, units);\n units.length = 0;\n }\n }\n if (units.length > 0) {\n result += String.fromCharCode.apply(String, units);\n }\n return result;\n}\nvar sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;\nexport var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c[\"TEXT_DECODER\"]) !== \"force\"\n ? 200\n : 0;\nexport function utf8DecodeTD(bytes, inputOffset, byteLength) {\n var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder.decode(stringBytes);\n}\n//# sourceMappingURL=utf8.mjs.map","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { RPC, API_VERSION } from \"./rpc.js\";\nimport {\n assert,\n randId,\n waitFor,\n loadRequirements,\n parseServiceUrl,\n} from \"./utils/index.js\";\nimport { schemaFunction } from \"./utils/schema.js\";\nimport { getRTCService, registerRTCService } from \"./webrtc-client.js\";\n\nexport { RPC, API_VERSION, schemaFunction };\nexport { loadRequirements };\nexport { getRTCService, registerRTCService };\n\nconst MAX_RETRY = 1000000;\n\nclass WebsocketRPCConnection {\n constructor(\n server_url,\n client_id,\n workspace,\n token,\n reconnection_token = null,\n timeout = 60,\n WebSocketClass = null,\n token_refresh_interval = 2 * 60 * 60,\n additional_headers = null,\n ) {\n assert(server_url && client_id, \"server_url and client_id are required\");\n this._server_url = server_url;\n this._client_id = client_id;\n this._workspace = workspace;\n this._token = token;\n this._reconnection_token = reconnection_token;\n this._websocket = null;\n this._handle_message = null;\n this._handle_connected = null; // Connection open event handler\n this._handle_disconnected = null; // Disconnection event handler\n this._timeout = timeout;\n this._WebSocketClass = WebSocketClass || WebSocket; // Allow overriding the WebSocket class\n this._closed = false;\n this._legacy_auth = null;\n this.connection_info = null;\n this._enable_reconnect = false;\n this._token_refresh_interval = token_refresh_interval;\n this.manager_id = null;\n this._refresh_token_task = null;\n this._last_message = null; // Store the last sent message\n this._reconnect_timeouts = new Set(); // Track reconnection timeouts\n this._additional_headers = additional_headers;\n }\n\n /**\n * Centralized cleanup method to clear all timers and prevent resource leaks\n */\n _cleanup() {\n // Clear token refresh interval\n if (this._refresh_token_task) {\n clearInterval(this._refresh_token_task);\n this._refresh_token_task = null;\n }\n\n // Clear all reconnection timeouts\n for (const timeoutId of this._reconnect_timeouts) {\n clearTimeout(timeoutId);\n }\n this._reconnect_timeouts.clear();\n }\n\n on_message(handler) {\n assert(handler, \"handler is required\");\n this._handle_message = handler;\n }\n\n on_connected(handler) {\n this._handle_connected = handler;\n }\n\n on_disconnected(handler) {\n this._handle_disconnected = handler;\n }\n\n async _attempt_connection(server_url, attempt_fallback = true) {\n return new Promise((resolve, reject) => {\n this._legacy_auth = false;\n const websocket = new this._WebSocketClass(server_url);\n websocket.binaryType = \"arraybuffer\";\n\n websocket.onopen = () => {\n console.info(\"WebSocket connection established\");\n resolve(websocket);\n };\n\n websocket.onerror = (event) => {\n console.error(\"WebSocket connection error:\", event);\n reject(new Error(`WebSocket connection error: ${event}`));\n };\n\n websocket.onclose = (event) => {\n if (event.code === 1003 && attempt_fallback) {\n console.info(\n \"Received 1003 error, attempting connection with query parameters.\",\n );\n this._legacy_auth = true;\n this._attempt_connection_with_query_params(server_url)\n .then(resolve)\n .catch(reject);\n } else if (this._handle_disconnected) {\n this._handle_disconnected(event.reason);\n }\n };\n });\n }\n\n async _attempt_connection_with_query_params(server_url) {\n // Initialize an array to hold parts of the query string\n const queryParamsParts = [];\n\n // Conditionally add each parameter if it has a non-empty value\n if (this._client_id)\n queryParamsParts.push(`client_id=${encodeURIComponent(this._client_id)}`);\n if (this._workspace)\n queryParamsParts.push(`workspace=${encodeURIComponent(this._workspace)}`);\n if (this._token)\n queryParamsParts.push(`token=${encodeURIComponent(this._token)}`);\n if (this._reconnection_token)\n queryParamsParts.push(\n `reconnection_token=${encodeURIComponent(this._reconnection_token)}`,\n );\n\n // Join the parts with '&' to form the final query string, prepend '?' if there are any parameters\n const queryString =\n queryParamsParts.length > 0 ? `?${queryParamsParts.join(\"&\")}` : \"\";\n\n // Construct the full URL by appending the query string if it exists\n const full_url = server_url + queryString;\n\n return await this._attempt_connection(full_url, false);\n }\n\n _establish_connection() {\n return new Promise((resolve, reject) => {\n this._websocket.onmessage = (event) => {\n const data = event.data;\n const first_message = JSON.parse(data);\n if (first_message.type == \"connection_info\") {\n this.connection_info = first_message;\n if (this._workspace) {\n assert(\n this.connection_info.workspace === this._workspace,\n `Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`,\n );\n }\n if (this.connection_info.reconnection_token) {\n this._reconnection_token = this.connection_info.reconnection_token;\n }\n if (this.connection_info.reconnection_token_life_time) {\n // make sure the token refresh interval is less than the token life time\n if (\n this.token_refresh_interval >\n this.connection_info.reconnection_token_life_time / 1.5\n ) {\n console.warn(\n `Token refresh interval is too long (${this.token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`,\n );\n this.token_refresh_interval =\n this.connection_info.reconnection_token_life_time / 1.5;\n }\n }\n this.manager_id = this.connection_info.manager_id || null;\n console.log(\n `Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`,\n );\n if (this.connection_info.announcement) {\n console.log(`${this.connection_info.announcement}`);\n }\n resolve(this.connection_info);\n } else if (first_message.type == \"error\") {\n const error = \"ConnectionAbortedError: \" + first_message.message;\n console.error(\"Failed to connect, \" + error);\n reject(new Error(error));\n return;\n } else {\n console.error(\n \"ConnectionAbortedError: Unexpected message received from the server:\",\n data,\n );\n reject(\n new Error(\n \"ConnectionAbortedError: Unexpected message received from the server\",\n ),\n );\n return;\n }\n };\n });\n }\n\n async open() {\n console.log(\n \"Creating a new websocket connection to\",\n this._server_url.split(\"?\")[0],\n );\n try {\n this._websocket = await this._attempt_connection(this._server_url);\n if (this._legacy_auth) {\n throw new Error(\n \"NotImplementedError: Legacy authentication is not supported\",\n );\n }\n // Send authentication info as the first message if connected without query params\n const authInfo = JSON.stringify({\n client_id: this._client_id,\n workspace: this._workspace,\n token: this._token,\n reconnection_token: this._reconnection_token,\n });\n this._websocket.send(authInfo);\n // Wait for the first message from the server\n await waitFor(\n this._establish_connection(),\n this._timeout,\n \"Failed to receive the first message from the server\",\n );\n if (this._token_refresh_interval > 0) {\n setTimeout(() => {\n this._send_refresh_token();\n this._refresh_token_task = setInterval(() => {\n this._send_refresh_token();\n }, this._token_refresh_interval * 1000);\n }, 2000);\n }\n // Listen to messages from the server\n this._enable_reconnect = true;\n this._closed = false;\n this._websocket.onmessage = (event) => {\n if (typeof event.data === \"string\") {\n const parsedData = JSON.parse(event.data);\n // Check if the message is a reconnection token\n if (parsedData.type === \"reconnection_token\") {\n this._reconnection_token = parsedData.reconnection_token;\n // console.log(\"Reconnection token received\");\n } else {\n console.log(\"Received message from the server:\", parsedData);\n }\n } else {\n this._handle_message(event.data);\n }\n };\n\n this._websocket.onerror = (event) => {\n console.error(\"WebSocket connection error:\", event);\n // Clean up timers on error\n this._cleanup();\n };\n\n this._websocket.onclose = this._handle_close.bind(this);\n\n if (this._handle_connected) {\n this._handle_connected(this.connection_info);\n }\n return this.connection_info;\n } catch (error) {\n // Clean up any timers that might have been set up before the error\n this._cleanup();\n console.error(\n \"Failed to connect to\",\n this._server_url.split(\"?\")[0],\n error,\n );\n throw error;\n }\n }\n\n _send_refresh_token() {\n if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {\n const refreshMessage = JSON.stringify({ type: \"refresh_token\" });\n this._websocket.send(refreshMessage);\n // console.log(\"Requested refresh token\");\n }\n }\n\n _handle_close(event) {\n if (\n !this._closed &&\n this._websocket &&\n this._websocket.readyState === WebSocket.CLOSED\n ) {\n // Clean up timers when connection closes\n this._cleanup();\n\n // Even if it's a graceful closure (codes 1000, 1001), if it wasn't user-initiated,\n // we should attempt to reconnect (e.g., server restart, k8s upgrade)\n if (this._enable_reconnect) {\n if ([1000, 1001].includes(event.code)) {\n console.warn(\n `Websocket connection closed gracefully by server (code: ${event.code}): ${event.reason} - attempting reconnect`,\n );\n } else {\n console.warn(\n \"Websocket connection closed unexpectedly (code: %s): %s\",\n event.code,\n event.reason,\n );\n }\n\n let retry = 0;\n const baseDelay = 1000; // Start with 1 second\n const maxDelay = 60000; // Maximum delay of 60 seconds\n const maxJitter = 0.1; // Maximum jitter factor\n\n const reconnect = async () => {\n // Check if we were explicitly closed\n if (this._closed) {\n console.info(\"Connection was closed, stopping reconnection\");\n return;\n }\n\n try {\n console.warn(\n `Reconnecting to ${this._server_url.split(\"?\")[0]} (attempt #${retry})`,\n );\n // Open the connection, this will trigger the on_connected callback\n await this.open();\n\n // Wait a short time for services to be registered\n // This gives time for the on_connected callback to complete\n // which includes re-registering all services to the server\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n // Resend last message if there was one\n if (this._last_message) {\n console.info(\"Resending last message after reconnection\");\n this._websocket.send(this._last_message);\n this._last_message = null;\n }\n console.warn(\n `Successfully reconnected to server ${this._server_url} (services re-registered)`,\n );\n // Emit reconnection success event\n if (this._handle_connected) {\n this._handle_connected(this.connection_info);\n }\n } catch (e) {\n if (`${e}`.includes(\"ConnectionAbortedError:\")) {\n console.warn(\"Failed to reconnect, connection aborted:\", e);\n return;\n } else if (`${e}`.includes(\"NotImplementedError:\")) {\n console.error(\n `${e}\\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`,\n );\n return;\n }\n\n // Log specific error types for better debugging\n if (e.name === \"NetworkError\" || e.message.includes(\"network\")) {\n console.error(`Network error during reconnection: ${e.message}`);\n } else if (\n e.name === \"TimeoutError\" ||\n e.message.includes(\"timeout\")\n ) {\n console.error(\n `Connection timeout during reconnection: ${e.message}`,\n );\n } else {\n console.error(\n `Unexpected error during reconnection: ${e.message}`,\n );\n }\n\n // Calculate exponential backoff with jitter\n const delay = Math.min(baseDelay * Math.pow(2, retry), maxDelay);\n // Add jitter to prevent thundering herd\n const jitter = (Math.random() * 2 - 1) * maxJitter * delay;\n const finalDelay = Math.max(100, delay + jitter);\n\n console.debug(\n `Waiting ${(finalDelay / 1000).toFixed(2)}s before next reconnection attempt`,\n );\n\n // Track the reconnection timeout to prevent leaks\n const timeoutId = setTimeout(async () => {\n this._reconnect_timeouts.delete(timeoutId);\n\n // Check if connection was restored externally\n if (\n this._websocket &&\n this._websocket.readyState === WebSocket.OPEN\n ) {\n console.info(\"Connection restored externally\");\n return;\n }\n\n // Check if we were explicitly closed\n if (this._closed) {\n console.info(\"Connection was closed, stopping reconnection\");\n return;\n }\n\n retry += 1;\n if (retry < MAX_RETRY) {\n await reconnect();\n } else {\n console.error(\n `Failed to reconnect after ${MAX_RETRY} attempts, giving up. Exiting process.`,\n );\n // Notify about max retry exceeded\n if (this._handle_disconnected) {\n this._handle_disconnected(\n \"Max reconnection attempts exceeded\",\n );\n }\n // Exit process to prevent stuck event loop\n if (typeof process !== \"undefined\" && process.exit) {\n console.error(\n \"Forcing process exit due to unrecoverable connection failure\",\n );\n process.exit(1);\n }\n }\n }, finalDelay);\n this._reconnect_timeouts.add(timeoutId);\n }\n };\n reconnect();\n }\n } else {\n // Clean up timers in all cases\n this._cleanup();\n if (this._handle_disconnected) {\n this._handle_disconnected(event.reason);\n }\n }\n }\n\n async emit_message(data) {\n if (this._closed) {\n throw new Error(\"Connection is closed\");\n }\n if (!this._websocket || this._websocket.readyState !== WebSocket.OPEN) {\n await this.open();\n }\n try {\n this._last_message = data; // Store the message before sending\n this._websocket.send(data);\n this._last_message = null; // Clear after successful send\n } catch (exp) {\n console.error(`Failed to send data, error: ${exp}`);\n throw exp;\n }\n }\n\n disconnect(reason) {\n this._closed = true;\n this._last_message = null; // Clear last message on disconnect\n // Ensure websocket is closed if it exists and is not already closed or closing\n if (\n this._websocket &&\n this._websocket.readyState !== WebSocket.CLOSED &&\n this._websocket.readyState !== WebSocket.CLOSING\n ) {\n this._websocket.close(1000, reason);\n }\n // Use centralized cleanup to clear all timers\n this._cleanup();\n console.info(`WebSocket connection disconnected (${reason})`);\n }\n}\n\nfunction normalizeServerUrl(server_url) {\n if (!server_url) throw new Error(\"server_url is required\");\n if (server_url.startsWith(\"http://\")) {\n server_url =\n server_url.replace(\"http://\", \"ws://\").replace(/\\/$/, \"\") + \"/ws\";\n } else if (server_url.startsWith(\"https://\")) {\n server_url =\n server_url.replace(\"https://\", \"wss://\").replace(/\\/$/, \"\") + \"/ws\";\n }\n return server_url;\n}\n\nexport async function login(config) {\n const service_id = config.login_service_id || \"public/hypha-login\";\n const workspace = config.workspace;\n const expires_in = config.expires_in;\n const timeout = config.login_timeout || 60;\n const callback = config.login_callback;\n const profile = config.profile;\n const additional_headers = config.additional_headers;\n\n const server = await connectToServer({\n name: \"initial login client\",\n server_url: config.server_url,\n additional_headers: additional_headers,\n });\n try {\n const svc = await server.getService(service_id);\n assert(svc, `Failed to get the login service: ${service_id}`);\n let context;\n if (workspace) {\n context = await svc.start({ workspace, expires_in, _rkwargs: true });\n } else {\n context = await svc.start();\n }\n if (callback) {\n await callback(context);\n } else {\n console.log(`Please open your browser and login at ${context.login_url}`);\n }\n return await svc.check(context.key, { timeout, profile, _rkwargs: true });\n } catch (error) {\n throw error;\n } finally {\n await server.disconnect();\n }\n}\n\nasync function webrtcGetService(wm, rtc_service_id, query, config) {\n config = config || {};\n const webrtc = config.webrtc;\n const webrtc_config = config.webrtc_config;\n if (config.webrtc !== undefined) delete config.webrtc;\n if (config.webrtc_config !== undefined) delete config.webrtc_config;\n assert(\n [undefined, true, false, \"auto\"].includes(webrtc),\n \"webrtc must be true, false or 'auto'\",\n );\n\n const svc = await wm.getService(query, config);\n if (webrtc === true || webrtc === \"auto\") {\n if (svc.id.includes(\":\") && svc.id.includes(\"/\")) {\n try {\n // Assuming that the client registered a webrtc service with the client_id + \"-rtc\"\n const peer = await getRTCService(wm, rtc_service_id, webrtc_config);\n const rtcSvc = await peer.getService(svc.id.split(\":\")[1], config);\n rtcSvc._webrtc = true;\n rtcSvc._peer = peer;\n rtcSvc._service = svc;\n return rtcSvc;\n } catch (e) {\n console.warn(\n \"Failed to get webrtc service, using websocket connection\",\n e,\n );\n }\n }\n if (webrtc === true) {\n throw new Error(\"Failed to get the service via webrtc\");\n }\n }\n return svc;\n}\n\nexport async function connectToServer(config) {\n if (config.server) {\n config.server_url = config.server_url || config.server.url;\n config.WebSocketClass =\n config.WebSocketClass || config.server.WebSocketClass;\n }\n let clientId = config.client_id;\n if (!clientId) {\n clientId = randId();\n config.client_id = clientId;\n }\n if (Object.keys(config).length === 0) {\n if (typeof process !== \"undefined\" && process.env) {\n // Node.js\n config.server_url = process.env.HYPHA_SERVER_URL;\n config.token = process.env.HYPHA_TOKEN;\n config.client_id = process.env.HYPHA_CLIENT_ID;\n config.workspace = process.env.HYPHA_WORKSPACE;\n } else if (typeof self !== \"undefined\" && self.env) {\n // WebWorker (only if you inject self.env manually)\n config.server_url = self.env.HYPHA_SERVER_URL;\n config.token = self.env.HYPHA_TOKEN;\n config.client_id = self.env.HYPHA_CLIENT_ID;\n config.workspace = self.env.HYPHA_WORKSPACE;\n } else if (typeof globalThis !== \"undefined\" && globalThis.env) {\n // Browser (only if you define globalThis.env beforehand)\n config.server_url = globalThis.env.HYPHA_SERVER_URL;\n config.token = globalThis.env.HYPHA_TOKEN;\n config.client_id = globalThis.env.HYPHA_CLIENT_ID;\n config.workspace = globalThis.env.HYPHA_WORKSPACE;\n }\n }\n\n let server_url = normalizeServerUrl(config.server_url);\n\n let connection = new WebsocketRPCConnection(\n server_url,\n clientId,\n config.workspace,\n config.token,\n config.reconnection_token,\n config.method_timeout || 60,\n config.WebSocketClass,\n config.token_refresh_interval,\n config.additional_headers,\n );\n const connection_info = await connection.open();\n assert(\n connection_info,\n \"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version.\",\n );\n // wait for 0.5 seconds\n await new Promise((resolve) => setTimeout(resolve, 100));\n // Ensure manager_id is set before proceeding\n if (!connection.manager_id) {\n console.warn(\"Manager ID not set immediately, waiting...\");\n\n // Wait for manager_id to be set with timeout\n const maxWaitTime = 5000; // 5 seconds\n const checkInterval = 100; // 100ms\n const startTime = Date.now();\n\n while (!connection.manager_id && Date.now() - startTime < maxWaitTime) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n }\n\n if (!connection.manager_id) {\n console.error(\"Manager ID still not set after waiting\");\n throw new Error(\"Failed to get manager ID from server\");\n } else {\n console.info(`Manager ID set after waiting: ${connection.manager_id}`);\n }\n }\n if (config.workspace && connection_info.workspace !== config.workspace) {\n throw new Error(\n `Connected to the wrong workspace: ${connection_info.workspace}, expected: ${config.workspace}`,\n );\n }\n\n const workspace = connection_info.workspace;\n const rpc = new RPC(connection, {\n client_id: clientId,\n workspace,\n default_context: { connection_type: \"websocket\" },\n name: config.name,\n method_timeout: config.method_timeout,\n app_id: config.app_id,\n server_base_url: connection_info.public_base_url,\n long_message_chunk_size: config.long_message_chunk_size,\n });\n await rpc.waitFor(\"services_registered\", config.method_timeout || 120);\n const wm = await rpc.get_manager_service({\n timeout: config.method_timeout,\n case_conversion: \"camel\",\n kwargs_expansion: config.kwargs_expansion || false,\n });\n wm.rpc = rpc;\n\n async function _export(api) {\n api.id = \"default\";\n api.name = api.name || config.name || api.id;\n api.description = api.description || config.description;\n await rpc.register_service(api, { overwrite: true });\n }\n\n async function getApp(clientId) {\n clientId = clientId || \"*\";\n assert(!clientId.includes(\":\"), \"clientId should not contain ':'\");\n if (!clientId.includes(\"/\")) {\n clientId = connection_info.workspace + \"/\" + clientId;\n }\n assert(\n clientId.split(\"/\").length === 2,\n \"clientId should match pattern workspace/clientId\",\n );\n return await wm.getService(`${clientId}:default`);\n }\n\n async function listApps(ws) {\n ws = ws || workspace;\n assert(!ws.includes(\":\"), \"workspace should not contain ':'\");\n assert(!ws.includes(\"/\"), \"workspace should not contain '/'\");\n const query = { workspace: ws, service_id: \"default\" };\n return await wm.listServices(query);\n }\n\n if (connection_info) {\n wm.config = Object.assign(wm.config, connection_info);\n }\n wm.export = schemaFunction(_export, {\n name: \"export\",\n description: \"Export the api.\",\n parameters: {\n properties: { api: { description: \"The api to export\", type: \"object\" } },\n required: [\"api\"],\n type: \"object\",\n },\n });\n wm.getApp = schemaFunction(getApp, {\n name: \"getApp\",\n description: \"Get the app.\",\n parameters: {\n properties: {\n clientId: { default: \"*\", description: \"The clientId\", type: \"string\" },\n },\n type: \"object\",\n },\n });\n wm.listApps = schemaFunction(listApps, {\n name: \"listApps\",\n description: \"List the apps.\",\n parameters: {\n properties: {\n workspace: {\n default: workspace,\n description: \"The workspace\",\n type: \"string\",\n },\n },\n type: \"object\",\n },\n });\n wm.disconnect = schemaFunction(rpc.disconnect.bind(rpc), {\n name: \"disconnect\",\n description: \"Disconnect from the server.\",\n parameters: { type: \"object\", properties: {}, required: [] },\n });\n wm.registerCodec = schemaFunction(rpc.register_codec.bind(rpc), {\n name: \"registerCodec\",\n description: \"Register a codec for the webrtc connection\",\n parameters: {\n type: \"object\",\n properties: {\n codec: {\n type: \"object\",\n description: \"Codec to register\",\n properties: {\n name: { type: \"string\" },\n type: {},\n encoder: { type: \"function\" },\n decoder: { type: \"function\" },\n },\n },\n },\n },\n });\n\n wm.emit = schemaFunction(rpc.emit.bind(rpc), {\n name: \"emit\",\n description: \"Emit a message.\",\n parameters: {\n properties: { data: { description: \"The data to emit\", type: \"object\" } },\n required: [\"data\"],\n type: \"object\",\n },\n });\n\n wm.on = schemaFunction(rpc.on.bind(rpc), {\n name: \"on\",\n description: \"Register a message handler.\",\n parameters: {\n properties: {\n event: { description: \"The event to listen to\", type: \"string\" },\n handler: { description: \"The handler function\", type: \"function\" },\n },\n required: [\"event\", \"handler\"],\n type: \"object\",\n },\n });\n\n wm.off = schemaFunction(rpc.off.bind(rpc), {\n name: \"off\",\n description: \"Remove a message handler.\",\n parameters: {\n properties: {\n event: { description: \"The event to remove\", type: \"string\" },\n handler: { description: \"The handler function\", type: \"function\" },\n },\n required: [\"event\", \"handler\"],\n type: \"object\",\n },\n });\n\n wm.once = schemaFunction(rpc.once.bind(rpc), {\n name: \"once\",\n description: \"Register a one-time message handler.\",\n parameters: {\n properties: {\n event: { description: \"The event to listen to\", type: \"string\" },\n handler: { description: \"The handler function\", type: \"function\" },\n },\n required: [\"event\", \"handler\"],\n type: \"object\",\n },\n });\n\n wm.getServiceSchema = schemaFunction(rpc.get_service_schema, {\n name: \"getServiceSchema\",\n description: \"Get the service schema.\",\n parameters: {\n properties: {\n service: {\n description: \"The service to extract schema\",\n type: \"object\",\n },\n },\n required: [\"service\"],\n type: \"object\",\n },\n });\n\n wm.registerService = schemaFunction(rpc.register_service.bind(rpc), {\n name: \"registerService\",\n description: \"Register a service.\",\n parameters: {\n properties: {\n service: { description: \"The service to register\", type: \"object\" },\n force: {\n default: false,\n description: \"Force to register the service\",\n type: \"boolean\",\n },\n },\n required: [\"service\"],\n type: \"object\",\n },\n });\n wm.unregisterService = schemaFunction(rpc.unregister_service.bind(rpc), {\n name: \"unregisterService\",\n description: \"Unregister a service.\",\n parameters: {\n properties: {\n service: {\n description: \"The service id to unregister\",\n type: \"string\",\n },\n notify: {\n default: true,\n description: \"Notify the workspace manager\",\n type: \"boolean\",\n },\n },\n required: [\"service\"],\n type: \"object\",\n },\n });\n if (connection.manager_id) {\n rpc.on(\"force-exit\", async (message) => {\n if (message.from === \"*/\" + connection.manager_id) {\n console.log(\"Disconnecting from server, reason:\", message.reason);\n await rpc.disconnect();\n }\n });\n }\n if (config.webrtc) {\n await registerRTCService(wm, `${clientId}-rtc`, config.webrtc_config);\n // make a copy of wm, so webrtc can use the original wm.getService\n const _wm = Object.assign({}, wm);\n const description = _wm.getService.__schema__.description;\n // TODO: Fix the schema for adding options for webrtc\n const parameters = _wm.getService.__schema__.parameters;\n wm.getService = schemaFunction(\n webrtcGetService.bind(null, _wm, `${workspace}/${clientId}-rtc`),\n {\n name: \"getService\",\n description,\n parameters,\n },\n );\n\n wm.getRTCService = schemaFunction(getRTCService.bind(null, wm), {\n name: \"getRTCService\",\n description: \"Get the webrtc connection, returns a peer connection.\",\n parameters: {\n properties: {\n config: {\n description: \"The config for the webrtc service\",\n type: \"object\",\n },\n },\n required: [\"config\"],\n type: \"object\",\n },\n });\n } else {\n const _getService = wm.getService;\n wm.getService = (query, config) => {\n config = config || {};\n return _getService(query, config);\n };\n wm.getService.__schema__ = _getService.__schema__;\n }\n\n async function registerProbes(probes) {\n probes.id = \"probes\";\n probes.name = \"Probes\";\n probes.config = { visibility: \"public\" };\n probes.type = \"probes\";\n probes.description = `Probes Service, visit ${server_url}/${workspace}services/probes for the available probes.`;\n return await wm.registerService(probes, { overwrite: true });\n }\n\n wm.registerProbes = schemaFunction(registerProbes, {\n name: \"registerProbes\",\n description: \"Register probes service\",\n parameters: {\n properties: {\n probes: {\n description:\n \"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}\",\n type: \"object\",\n },\n },\n required: [\"probes\"],\n type: \"object\",\n },\n });\n return wm;\n}\n\nexport async function getRemoteService(serviceUri, config = {}) {\n const { serverUrl, workspace, clientId, serviceId, appId } =\n parseServiceUrl(serviceUri);\n const fullServiceId = `${workspace}/${clientId}:${serviceId}@${appId}`;\n\n if (config.serverUrl) {\n if (config.serverUrl !== serverUrl) {\n throw new Error(\n \"server_url in config does not match the server_url in the url\",\n );\n }\n }\n config.serverUrl = serverUrl;\n const server = await connectToServer(config);\n return await server.getService(fullServiceId);\n}\n\nexport class LocalWebSocket {\n constructor(url, client_id, workspace) {\n this.url = url;\n this.onopen = () => {};\n this.onmessage = () => {};\n this.onclose = () => {};\n this.onerror = () => {};\n this.client_id = client_id;\n this.workspace = workspace;\n const context = typeof window !== \"undefined\" ? window : self;\n const isWindow = typeof window !== \"undefined\";\n this.postMessage = (message) => {\n if (isWindow) {\n window.parent.postMessage(message, \"*\");\n } else {\n self.postMessage(message);\n }\n };\n\n this.readyState = WebSocket.CONNECTING;\n context.addEventListener(\n \"message\",\n (event) => {\n const { type, data, to } = event.data;\n if (to !== this.client_id) {\n // console.debug(\"message not for me\", to, this.client_id);\n return;\n }\n switch (type) {\n case \"message\":\n if (this.readyState === WebSocket.OPEN && this.onmessage) {\n this.onmessage({ data: data });\n }\n break;\n case \"connected\":\n this.readyState = WebSocket.OPEN;\n this.onopen(event);\n break;\n case \"closed\":\n this.readyState = WebSocket.CLOSED;\n this.onclose(event);\n break;\n default:\n break;\n }\n },\n false,\n );\n\n if (!this.client_id) throw new Error(\"client_id is required\");\n if (!this.workspace) throw new Error(\"workspace is required\");\n this.postMessage({\n type: \"connect\",\n url: this.url,\n from: this.client_id,\n workspace: this.workspace,\n });\n }\n\n send(data) {\n if (this.readyState === WebSocket.OPEN) {\n this.postMessage({\n type: \"message\",\n data: data,\n from: this.client_id,\n workspace: this.workspace,\n });\n }\n }\n\n close() {\n this.readyState = WebSocket.CLOSING;\n this.postMessage({\n type: \"close\",\n from: this.client_id,\n workspace: this.workspace,\n });\n this.onclose();\n }\n\n addEventListener(type, listener) {\n if (type === \"message\") {\n this.onmessage = listener;\n }\n if (type === \"open\") {\n this.onopen = listener;\n }\n if (type === \"close\") {\n this.onclose = listener;\n }\n if (type === \"error\") {\n this.onerror = listener;\n }\n }\n}\n\nexport function setupLocalClient({\n enable_execution = false,\n on_ready = null,\n}) {\n return new Promise((resolve, reject) => {\n const context = typeof window !== \"undefined\" ? window : self;\n const isWindow = typeof window !== \"undefined\";\n context.addEventListener(\n \"message\",\n (event) => {\n const {\n type,\n server_url,\n workspace,\n client_id,\n token,\n method_timeout,\n name,\n config,\n } = event.data;\n\n if (type === \"initializeHyphaClient\") {\n if (!server_url || !workspace || !client_id) {\n console.error(\"server_url, workspace, and client_id are required.\");\n return;\n }\n\n if (!server_url.startsWith(\"https://local-hypha-server:\")) {\n console.error(\n \"server_url should start with https://local-hypha-server:\",\n );\n return;\n }\n\n class FixedLocalWebSocket extends LocalWebSocket {\n constructor(url) {\n // Call the parent class's constructor with fixed values\n super(url, client_id, workspace);\n }\n }\n connectToServer({\n server_url,\n workspace,\n client_id,\n token,\n method_timeout,\n name,\n WebSocketClass: FixedLocalWebSocket,\n }).then(async (server) => {\n globalThis.api = server;\n try {\n // for iframe\n if (isWindow && enable_execution) {\n function loadScript(script) {\n return new Promise((resolve, reject) => {\n const scriptElement = document.createElement(\"script\");\n scriptElement.innerHTML = script.content;\n scriptElement.lang = script.lang;\n\n scriptElement.onload = () => resolve();\n scriptElement.onerror = (e) => reject(e);\n\n document.head.appendChild(scriptElement);\n });\n }\n if (config.styles && config.styles.length > 0) {\n for (const style of config.styles) {\n const styleElement = document.createElement(\"style\");\n styleElement.innerHTML = style.content;\n styleElement.lang = style.lang;\n document.head.appendChild(styleElement);\n }\n }\n if (config.links && config.links.length > 0) {\n for (const link of config.links) {\n const linkElement = document.createElement(\"a\");\n linkElement.href = link.url;\n linkElement.innerText = link.text;\n document.body.appendChild(linkElement);\n }\n }\n if (config.windows && config.windows.length > 0) {\n for (const w of config.windows) {\n document.body.innerHTML = w.content;\n break;\n }\n }\n if (config.scripts && config.scripts.length > 0) {\n for (const script of config.scripts) {\n if (script.lang !== \"javascript\")\n throw new Error(\"Only javascript scripts are supported\");\n await loadScript(script); // Await the loading of each script\n }\n }\n }\n // for web worker\n else if (\n !isWindow &&\n enable_execution &&\n config.scripts &&\n config.scripts.length > 0\n ) {\n for (const script of config.scripts) {\n if (script.lang !== \"javascript\")\n throw new Error(\"Only javascript scripts are supported\");\n eval(script.content);\n }\n }\n\n if (on_ready) {\n await on_ready(server, config);\n }\n resolve(server);\n } catch (e) {\n reject(e);\n }\n });\n }\n },\n false,\n );\n if (isWindow) {\n window.parent.postMessage({ type: \"hyphaClientReady\" }, \"*\");\n } else {\n self.postMessage({ type: \"hyphaClientReady\" });\n }\n });\n}\n"],"names":[],"sourceRoot":""}
|