nervoscan-js-sdk 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var P1=Object.defineProperty;var L1=(t,e,n)=>e in t?P1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var _=(t,e,n)=>L1(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Zn=typeof document<"u"?document.currentScript:null;class K extends Error{constructor(e){super(e)}}class Od extends K{constructor(e){super(e)}}class Md extends K{constructor(e){super(e)}}class Bd extends K{constructor(e){super(e)}}class Ud extends K{constructor(e){super(e)}}class Vd extends K{constructor(e){super(e)}}class $d extends K{constructor(e){super(e)}}class Hd extends K{constructor(e){super(e)}}class Wd extends K{constructor(e){super(e)}}class Gd extends K{constructor(e){super(e)}}class jd extends K{constructor(e){super(e)}}class qd extends K{constructor(e){super(e)}}class zd extends K{constructor(e){super(e)}}class Kd extends K{constructor(e){super(e)}}class Yd extends K{constructor(e){super(e)}}class Xd extends K{constructor(e){super(e)}}class Qd extends K{constructor(e){super(e)}}class Jd extends K{constructor(e){super(e)}}class Zd extends K{constructor(e){super(e)}}class ef extends K{constructor(n){super(n.message);_(this,"errorCode");this.errorCode=n.code}}class tf extends K{constructor(e){super(e)}}class nf extends K{constructor(e){super(e)}}class sf extends K{constructor(e){super(e)}}class rf extends K{constructor(e){super(e)}}class of extends K{constructor(e){super(e)}}class af extends K{constructor(e){super(e)}}class cf extends K{constructor(e){super(e)}}class lf extends K{constructor(e){super(e)}}class hf extends K{constructor(e){super(e)}}class uf extends K{constructor(e){super(e)}}class df extends K{constructor(e){super(e)}}class ff extends K{constructor(e){super(e)}}class pf extends K{constructor(e){super(e)}}const Y={NotInitializedError:Od,EmptyVideoError:Md,VideoTypeError:Bd,InvalidUsernameError:Ud,InvalidPasswordError:Vd,NoScansAvailableError:$d,InvalidAccessTokenError:Hd,NoScanDataError:Wd,InvalidServerTypeError:Gd,NotImplementedError:jd,LowFPSError:qd,FPSCalculationError:zd,FaceNotCenteredError:Kd,FaceTooFarError:Yd,FaceTooCloseError:Xd,FaceLookingLeftError:Qd,FaceLookingRightError:Jd,ErrorCallbackNotSetError:Zd,UnhandledScanError:ef,SkinExtractionError:tf,InvalidContentTypeError:nf,JobNotRegisteredError:sf,LowFrameCountError:of,ConnectionLostError:af,ScanFailedError:cf,VideoError:lf,InvalidCredentialsError:hf,LicenseInactiveError:uf,RGBError:df,FaceLandmarkerNotInitializedError:ff,EnvIncompatibleError:pf,UnhandledError:rf},O={NotInitializedError:new Y.NotInitializedError("Nervoscan Client not initialized!"),EmptyVideoError:new Y.EmptyVideoError("Video is empty!"),VideoTypeError:new Y.VideoTypeError("Video is not a Blob!"),InvalidUsernameError:new Y.InvalidUsernameError("Invalid username!"),InvalidPasswordError:new Y.InvalidPasswordError("Invalid password!"),NoScansAvailableError:new Y.NoScansAvailableError("No scans available, Please purchase a plan!"),InvalidAccessTokenError:new Y.InvalidAccessTokenError("Invalid access token!"),NoScanDataError:new Y.NoScanDataError("No scan data found!"),InvalidServerTypeError:new Y.InvalidServerTypeError("Invalid server type!"),NotImplementedError:new Y.NotImplementedError("Not implemented!"),LowFPSError:new Y.LowFPSError("Low FPS!"),FPSCalculationError:new Y.FPSCalculationError("Error calculating FPS!"),FaceNotCenteredError:new Y.FaceNotCenteredError("Face not centered!"),FaceTooFarError:new Y.FaceTooFarError("Face too far!"),FaceTooCloseError:new Y.FaceTooCloseError("Face too close!"),FaceLookingLeftError:new Y.FaceLookingLeftError("Face looking left!"),FaceLookingRightError:new Y.FaceLookingRightError("Face looking right!"),ErrorCallbackNotSetError:new Y.ErrorCallbackNotSetError("Error callback not set!"),SkinExtractionError:new Y.SkinExtractionError("Skin extraction error! Please use a better lighting!"),InvalidContentTypeError:new Y.InvalidContentTypeError("Invalid content type!"),JobNotRegisteredError:new Y.JobNotRegisteredError("Job not registered! Please await initializeStreaming method!"),LowFrameCountError:new Y.LowFrameCountError("Low frame count! Don't stop streaming prematurely!"),ConnectionLostError:new Y.ConnectionLostError("Connection lost! Run Client.initializeStreaming() again!"),ScanFailedError:new Y.ScanFailedError("Scan failed! Please try again!"),VideoError:new Y.VideoError("Video error! Please check your video source! FPS could be very low!"),InvalidCredentialsError:new Y.InvalidCredentialsError("Invalid credentials! Please provide correct username and password or license key!"),LicenseInactiveError:new Y.LicenseInactiveError("License inactive! Please enter a valid license key!"),RGBError:new Y.RGBError("RGB error! Please check your video source! FPS could be very low!"),FaceLandmarkerNotInitializedError:new Y.FaceLandmarkerNotInitializedError("Face landmarker not initialized!"),EnvIncompatibleError:new Y.EnvIncompatibleError("Environment not found! Please check your environment variables!"),UnhandledError:new Y.UnhandledError("Unhandled error! Please contact support! If you are on production, retry scan!")};function O1(){try{const t=typeof globalThis<"u"?globalThis:{},e=t.NERVOSCAN_DEBUG??t.__NERVOSCAN_DEBUG__;if(typeof e=="string"){const s=e.trim().toLowerCase();if(s==="1"||s==="true"||s==="yes"||s==="on")return!0;if(s==="0"||s==="false"||s==="no"||s==="off")return!1}else{if(typeof e=="number")return e===1;if(typeof e=="boolean")return e}const n=t.VITE_IS_DEV;if(typeof n=="string"){const s=n.trim().toLowerCase();if(s==="1"||s==="true"||s==="yes"||s==="on")return!0;if(s==="0"||s==="false"||s==="no"||s==="off")return!1}else{if(typeof n=="number")return n===1;if(typeof n=="boolean")return n}try{const s=typeof localStorage<"u"?localStorage:void 0,i=s==null?void 0:s.getItem("NERVOSCAN_DEBUG");if(typeof i=="string"){const r=i.trim().toLowerCase();if(r==="1"||r==="true"||r==="yes"||r==="on")return!0;if(r==="0"||r==="false"||r==="no"||r==="off")return!1}}catch{}}catch{}try{const t={url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Zn&&Zn.tagName.toUpperCase()==="SCRIPT"&&Zn.src||new URL("nervoscan-js-sdk.cjs",document.baseURI).href},e=(t==null?void 0:t.env)??{};if(typeof e.VITE_IS_DEV=="string"){const n=e.VITE_IS_DEV.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes"||n==="on")return!0;if(n==="0"||n==="false"||n==="no"||n==="off")return!1}if(typeof e.VITE_IS_DEV=="number")return e.VITE_IS_DEV===1;if(typeof e.PROD=="boolean")return e.PROD===!1;if(typeof e.DEV=="boolean")return e.DEV===!0}catch{}try{const e=typeof process<"u"&&process.env?process.env.NODE_ENV:void 0;return typeof e=="string"?e!=="production":!1}catch{return!1}}const Ui=O1(),Uo=()=>{},f={log:Ui?console.log.bind(console):Uo,info:Ui?console.info.bind(console):Uo,debug:Ui?console.debug.bind(console):Uo,warn:console.warn.bind(console),error:console.error.bind(console),isDev:Ui},De=class De{constructor(){}static getInstance(){return De.instance||(De.instance=new De),De.instance}static throwKnownError(e){throw e}static throwUnknownError(e){throw O.UnhandledError}static handleErrorResponse(e){var n,s,i,r,o,a,c,l,h,u,d,p,m,y,w,k,E,T,P,C,v,R,D;((i=(s=(n=e.response)==null?void 0:n.data)==null?void 0:s.error)==null?void 0:i.code)==="INVALID_USERNAME"?De.throwKnownError(O.InvalidUsernameError):((a=(o=(r=e.response)==null?void 0:r.data)==null?void 0:o.error)==null?void 0:a.code)==="INVALID_PASSWORD"?De.throwKnownError(O.InvalidPasswordError):((h=(l=(c=e.response)==null?void 0:c.data)==null?void 0:l.error)==null?void 0:h.code)==="NO_SCANS_AVAILABLE"||((d=(u=e.response)==null?void 0:u.data)==null?void 0:d.message)==="No packages available!"||((m=(p=e.response)==null?void 0:p.data)==null?void 0:m.message)==="No scans available!"?De.throwKnownError(O.NoScansAvailableError):((y=e.error)==null?void 0:y.code)==="INVALID_CONTENT_TYPE"?De.throwKnownError(O.InvalidContentTypeError):((E=(k=(w=e.response)==null?void 0:w.data)==null?void 0:k.error)==null?void 0:E.code)==="JOB_NOT_REGISTERED"?De.throwKnownError(O.JobNotRegisteredError):((C=(P=(T=e.response)==null?void 0:T.data)==null?void 0:P.error)==null?void 0:C.code)==="LICENSE_KEY_INVALID"?De.throwKnownError(O.InvalidCredentialsError):((D=(R=(v=e.response)==null?void 0:v.data)==null?void 0:R.error)==null?void 0:D.code)==="LICENSE_INACTIVE"?De.throwKnownError(O.LicenseInactiveError):(f.error("Unknown error:",e),De.throwUnknownError(e))}static handleScanError(e){return e.code==="LOW_FPS_ERROR"?O.LowFPSError:e.code==="FPS_CALCULATION_ERROR"?O.FPSCalculationError:e.code==="FACE_NOT_CENTERED_ERROR"?O.FaceNotCenteredError:e.code==="FACE_TOO_FAR_ERROR"?O.FaceTooFarError:e.code==="FACE_TOO_CLOSE_ERROR"?O.FaceTooCloseError:e.code==="FACE_LOOKING_LEFT_ERROR"?O.FaceLookingLeftError:e.code==="FACE_LOOKING_RIGHT_ERROR"?O.FaceLookingRightError:e.code==="SKIN_EXTRACTION_ERROR"?O.SkinExtractionError:e.code==="LOW_FRAME_COUNT_ERROR"?O.LowFrameCountError:e.code==="VIDEO_ERROR"?O.VideoError:e.code==="UNHANDLED_ERROR"?O.UnhandledError:O.ScanFailedError}};_(De,"instance");let q=De;const M1=()=>{};/**
1
+ "use strict";var L1=Object.defineProperty;var O1=(t,e,n)=>e in t?L1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var _=(t,e,n)=>O1(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Zn=typeof document<"u"?document.currentScript:null;class K extends Error{constructor(e){super(e)}}class Od extends K{constructor(e){super(e)}}class Md extends K{constructor(e){super(e)}}class Bd extends K{constructor(e){super(e)}}class Ud extends K{constructor(e){super(e)}}class Vd extends K{constructor(e){super(e)}}class $d extends K{constructor(e){super(e)}}class Hd extends K{constructor(e){super(e)}}class Wd extends K{constructor(e){super(e)}}class Gd extends K{constructor(e){super(e)}}class jd extends K{constructor(e){super(e)}}class qd extends K{constructor(e){super(e)}}class zd extends K{constructor(e){super(e)}}class Kd extends K{constructor(e){super(e)}}class Yd extends K{constructor(e){super(e)}}class Xd extends K{constructor(e){super(e)}}class Qd extends K{constructor(e){super(e)}}class Jd extends K{constructor(e){super(e)}}class Zd extends K{constructor(e){super(e)}}class ef extends K{constructor(n){super(n.message);_(this,"errorCode");this.errorCode=n.code}}class tf extends K{constructor(e){super(e)}}class nf extends K{constructor(e){super(e)}}class sf extends K{constructor(e){super(e)}}class rf extends K{constructor(e){super(e)}}class of extends K{constructor(e){super(e)}}class af extends K{constructor(e){super(e)}}class cf extends K{constructor(e){super(e)}}class lf extends K{constructor(e){super(e)}}class hf extends K{constructor(e){super(e)}}class uf extends K{constructor(e){super(e)}}class df extends K{constructor(e){super(e)}}class ff extends K{constructor(e){super(e)}}class pf extends K{constructor(e){super(e)}}class mf extends K{constructor(e){super(e)}}const z={NotInitializedError:Od,EmptyVideoError:Md,VideoTypeError:Bd,InvalidUsernameError:Ud,InvalidPasswordError:Vd,NoScansAvailableError:$d,InvalidAccessTokenError:Hd,NoScanDataError:Wd,InvalidServerTypeError:Gd,NotImplementedError:jd,LowFPSError:qd,FPSCalculationError:zd,FaceNotCenteredError:Kd,FaceTooFarError:Yd,FaceTooCloseError:Xd,FaceLookingLeftError:Qd,FaceLookingRightError:Jd,ErrorCallbackNotSetError:Zd,UnhandledScanError:ef,SkinExtractionError:tf,InvalidContentTypeError:nf,JobNotRegisteredError:sf,LowFrameCountError:of,ConnectionLostError:af,ScanFailedError:cf,VideoError:lf,InvalidCredentialsError:hf,LicenseInactiveError:uf,RGBError:df,FaceLandmarkerNotInitializedError:ff,EnvIncompatibleError:pf,UnhandledError:rf,InsufficientDataError:mf},L={NotInitializedError:new z.NotInitializedError("Nervoscan Client not initialized!"),EmptyVideoError:new z.EmptyVideoError("Video is empty!"),VideoTypeError:new z.VideoTypeError("Video is not a Blob!"),InvalidUsernameError:new z.InvalidUsernameError("Invalid username!"),InvalidPasswordError:new z.InvalidPasswordError("Invalid password!"),NoScansAvailableError:new z.NoScansAvailableError("No scans available, Please purchase a plan!"),InvalidAccessTokenError:new z.InvalidAccessTokenError("Invalid access token!"),NoScanDataError:new z.NoScanDataError("No scan data found!"),InvalidServerTypeError:new z.InvalidServerTypeError("Invalid server type!"),NotImplementedError:new z.NotImplementedError("Not implemented!"),LowFPSError:new z.LowFPSError("Low FPS!"),FPSCalculationError:new z.FPSCalculationError("Error calculating FPS!"),FaceNotCenteredError:new z.FaceNotCenteredError("Face not centered!"),FaceTooFarError:new z.FaceTooFarError("Face too far!"),FaceTooCloseError:new z.FaceTooCloseError("Face too close!"),FaceLookingLeftError:new z.FaceLookingLeftError("Face looking left!"),FaceLookingRightError:new z.FaceLookingRightError("Face looking right!"),ErrorCallbackNotSetError:new z.ErrorCallbackNotSetError("Error callback not set!"),SkinExtractionError:new z.SkinExtractionError("Skin extraction error! Please use a better lighting!"),InvalidContentTypeError:new z.InvalidContentTypeError("Invalid content type!"),JobNotRegisteredError:new z.JobNotRegisteredError("Job not registered! Please await initializeStreaming method!"),LowFrameCountError:new z.LowFrameCountError("Low frame count! Don't stop streaming prematurely!"),ConnectionLostError:new z.ConnectionLostError("Connection lost! Run Client.initializeStreaming() again!"),ScanFailedError:new z.ScanFailedError("Scan failed! Please try again!"),VideoError:new z.VideoError("Video error! Please check your video source! FPS could be very low!"),InvalidCredentialsError:new z.InvalidCredentialsError("Invalid credentials! Please provide correct username and password or license key!"),LicenseInactiveError:new z.LicenseInactiveError("License inactive! Please enter a valid license key!"),RGBError:new z.RGBError("RGB error! Please check your video source! FPS could be very low!"),FaceLandmarkerNotInitializedError:new z.FaceLandmarkerNotInitializedError("Face landmarker not initialized!"),EnvIncompatibleError:new z.EnvIncompatibleError("Environment not found! Please check your environment variables!"),UnhandledError:new z.UnhandledError("Unhandled error! Please contact support! If you are on production, retry scan!"),InsufficientDataError:new z.InsufficientDataError("Insufficient data received for calculations. Please try again with better lighting and good visibility of the face.")};function M1(){try{const t=typeof globalThis<"u"?globalThis:{},e=t.NERVOSCAN_DEBUG??t.__NERVOSCAN_DEBUG__;if(typeof e=="string"){const s=e.trim().toLowerCase();if(s==="1"||s==="true"||s==="yes"||s==="on")return!0;if(s==="0"||s==="false"||s==="no"||s==="off")return!1}else{if(typeof e=="number")return e===1;if(typeof e=="boolean")return e}const n=t.VITE_IS_DEV;if(typeof n=="string"){const s=n.trim().toLowerCase();if(s==="1"||s==="true"||s==="yes"||s==="on")return!0;if(s==="0"||s==="false"||s==="no"||s==="off")return!1}else{if(typeof n=="number")return n===1;if(typeof n=="boolean")return n}try{const s=typeof localStorage<"u"?localStorage:void 0,i=s==null?void 0:s.getItem("NERVOSCAN_DEBUG");if(typeof i=="string"){const r=i.trim().toLowerCase();if(r==="1"||r==="true"||r==="yes"||r==="on")return!0;if(r==="0"||r==="false"||r==="no"||r==="off")return!1}}catch{}}catch{}try{const t={url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Zn&&Zn.tagName.toUpperCase()==="SCRIPT"&&Zn.src||new URL("nervoscan-js-sdk.cjs",document.baseURI).href},e=(t==null?void 0:t.env)??{};if(typeof e.VITE_IS_DEV=="string"){const n=e.VITE_IS_DEV.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes"||n==="on")return!0;if(n==="0"||n==="false"||n==="no"||n==="off")return!1}if(typeof e.VITE_IS_DEV=="number")return e.VITE_IS_DEV===1;if(typeof e.PROD=="boolean")return e.PROD===!1;if(typeof e.DEV=="boolean")return e.DEV===!0}catch{}try{const e=typeof process<"u"&&process.env?process.env.NODE_ENV:void 0;return typeof e=="string"?e!=="production":!1}catch{return!1}}const Ui=M1(),Bo=()=>{},f={log:Ui?(...t)=>console.log(...t):Bo,info:Ui?(...t)=>console.info(...t):Bo,debug:Ui?(...t)=>console.debug(...t):Bo,warn:(...t)=>console.warn(...t),error:(...t)=>console.error(...t),isDev:Ui},De=class De{constructor(){}static getInstance(){return De.instance||(De.instance=new De),De.instance}static throwKnownError(e){throw e}static throwUnknownError(e){throw L.UnhandledError}static handleErrorResponse(e){var n,s,i,r,o,a,c,l,h,u,d,p,m,y,w,k,E,T,P,C,v,R,D;((i=(s=(n=e.response)==null?void 0:n.data)==null?void 0:s.error)==null?void 0:i.code)==="INVALID_USERNAME"?De.throwKnownError(L.InvalidUsernameError):((a=(o=(r=e.response)==null?void 0:r.data)==null?void 0:o.error)==null?void 0:a.code)==="INVALID_PASSWORD"?De.throwKnownError(L.InvalidPasswordError):((h=(l=(c=e.response)==null?void 0:c.data)==null?void 0:l.error)==null?void 0:h.code)==="NO_SCANS_AVAILABLE"||((d=(u=e.response)==null?void 0:u.data)==null?void 0:d.message)==="No packages available!"||((m=(p=e.response)==null?void 0:p.data)==null?void 0:m.message)==="No scans available!"?De.throwKnownError(L.NoScansAvailableError):((y=e.error)==null?void 0:y.code)==="INVALID_CONTENT_TYPE"?De.throwKnownError(L.InvalidContentTypeError):((E=(k=(w=e.response)==null?void 0:w.data)==null?void 0:k.error)==null?void 0:E.code)==="JOB_NOT_REGISTERED"?De.throwKnownError(L.JobNotRegisteredError):((C=(P=(T=e.response)==null?void 0:T.data)==null?void 0:P.error)==null?void 0:C.code)==="LICENSE_KEY_INVALID"?De.throwKnownError(L.InvalidCredentialsError):((D=(R=(v=e.response)==null?void 0:v.data)==null?void 0:R.error)==null?void 0:D.code)==="LICENSE_INACTIVE"?De.throwKnownError(L.LicenseInactiveError):(f.error("Unhandled error encountered in handleErrorResponse:",e),De.throwUnknownError(e))}static handleScanError(e){return e.code==="LOW_FPS_ERROR"?L.LowFPSError:e.code==="FPS_CALCULATION_ERROR"?L.FPSCalculationError:e.code==="FACE_NOT_CENTERED_ERROR"?L.FaceNotCenteredError:e.code==="FACE_TOO_FAR_ERROR"?L.FaceTooFarError:e.code==="FACE_TOO_CLOSE_ERROR"?L.FaceTooCloseError:e.code==="FACE_LOOKING_LEFT_ERROR"?L.FaceLookingLeftError:e.code==="FACE_LOOKING_RIGHT_ERROR"?L.FaceLookingRightError:e.code==="SKIN_EXTRACTION_ERROR"?L.SkinExtractionError:e.code==="LOW_FRAME_COUNT_ERROR"?L.LowFrameCountError:e.code==="VIDEO_ERROR"?L.VideoError:e.code==="UNHANDLED_ERROR"?L.UnhandledError:L.ScanFailedError}};_(De,"instance");let W=De;const B1=()=>{};/**
2
2
  * @license
3
3
  * Copyright 2017 Google LLC
4
4
  *
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */const mf={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};/**
16
+ */const gf={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};/**
17
17
  * @license
18
18
  * Copyright 2017 Google LLC
19
19
  *
@@ -28,7 +28,7 @@
28
28
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
29
  * See the License for the specific language governing permissions and
30
30
  * limitations under the License.
31
- */const b=function(t,e){if(!t)throw Ts(e)},Ts=function(t){return new Error("Firebase Database ("+mf.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};/**
31
+ */const b=function(t,e){if(!t)throw Ts(e)},Ts=function(t){return new Error("Firebase Database ("+gf.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};/**
32
32
  * @license
33
33
  * Copyright 2017 Google LLC
34
34
  *
@@ -43,7 +43,7 @@
43
43
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44
44
  * See the License for the specific language governing permissions and
45
45
  * limitations under the License.
46
- */const gf=function(t){const e=[];let n=0;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++s)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},B1=function(t){const e=[];let n=0,s=0;for(;n<t.length;){const i=t[n++];if(i<128)e[s++]=String.fromCharCode(i);else if(i>191&&i<224){const r=t[n++];e[s++]=String.fromCharCode((i&31)<<6|r&63)}else if(i>239&&i<365){const r=t[n++],o=t[n++],a=t[n++],c=((i&7)<<18|(r&63)<<12|(o&63)<<6|a&63)-65536;e[s++]=String.fromCharCode(55296+(c>>10)),e[s++]=String.fromCharCode(56320+(c&1023))}else{const r=t[n++],o=t[n++];e[s++]=String.fromCharCode((i&15)<<12|(r&63)<<6|o&63)}}return e.join("")},_c={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let i=0;i<t.length;i+=3){const r=t[i],o=i+1<t.length,a=o?t[i+1]:0,c=i+2<t.length,l=c?t[i+2]:0,h=r>>2,u=(r&3)<<4|a>>4;let d=(a&15)<<2|l>>6,p=l&63;c||(p=64,o||(d=64)),s.push(n[h],n[u],n[d],n[p])}return s.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(gf(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):B1(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const n=e?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let i=0;i<t.length;){const r=n[t.charAt(i++)],a=i<t.length?n[t.charAt(i)]:0;++i;const l=i<t.length?n[t.charAt(i)]:64;++i;const u=i<t.length?n[t.charAt(i)]:64;if(++i,r==null||a==null||l==null||u==null)throw new U1;const d=r<<2|a>>4;if(s.push(d),l!==64){const p=a<<4&240|l>>2;if(s.push(p),u!==64){const m=l<<6&192|u;s.push(m)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};class U1 extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const _f=function(t){const e=gf(t);return _c.encodeByteArray(e,!0)},mr=function(t){return _f(t).replace(/\./g,"")},ba=function(t){try{return _c.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};/**
46
+ */const _f=function(t){const e=[];let n=0;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):(i&64512)===55296&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++s)&1023),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},U1=function(t){const e=[];let n=0,s=0;for(;n<t.length;){const i=t[n++];if(i<128)e[s++]=String.fromCharCode(i);else if(i>191&&i<224){const r=t[n++];e[s++]=String.fromCharCode((i&31)<<6|r&63)}else if(i>239&&i<365){const r=t[n++],o=t[n++],a=t[n++],c=((i&7)<<18|(r&63)<<12|(o&63)<<6|a&63)-65536;e[s++]=String.fromCharCode(55296+(c>>10)),e[s++]=String.fromCharCode(56320+(c&1023))}else{const r=t[n++],o=t[n++];e[s++]=String.fromCharCode((i&15)<<12|(r&63)<<6|o&63)}}return e.join("")},_c={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let i=0;i<t.length;i+=3){const r=t[i],o=i+1<t.length,a=o?t[i+1]:0,c=i+2<t.length,l=c?t[i+2]:0,h=r>>2,u=(r&3)<<4|a>>4;let d=(a&15)<<2|l>>6,p=l&63;c||(p=64,o||(d=64)),s.push(n[h],n[u],n[d],n[p])}return s.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(_f(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):U1(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const n=e?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let i=0;i<t.length;){const r=n[t.charAt(i++)],a=i<t.length?n[t.charAt(i)]:0;++i;const l=i<t.length?n[t.charAt(i)]:64;++i;const u=i<t.length?n[t.charAt(i)]:64;if(++i,r==null||a==null||l==null||u==null)throw new V1;const d=r<<2|a>>4;if(s.push(d),l!==64){const p=a<<4&240|l>>2;if(s.push(p),u!==64){const m=l<<6&192|u;s.push(m)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};class V1 extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const yf=function(t){const e=_f(t);return _c.encodeByteArray(e,!0)},mr=function(t){return yf(t).replace(/\./g,"")},wa=function(t){try{return _c.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};/**
47
47
  * @license
48
48
  * Copyright 2017 Google LLC
49
49
  *
@@ -58,7 +58,7 @@
58
58
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
59
59
  * See the License for the specific language governing permissions and
60
60
  * limitations under the License.
61
- */function V1(t){return yf(void 0,t)}function yf(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:const n=e;return new Date(n.getTime());case Object:t===void 0&&(t={});break;case Array:t=[];break;default:return e}for(const n in e)!e.hasOwnProperty(n)||!$1(n)||(t[n]=yf(t[n],e[n]));return t}function $1(t){return t!=="__proto__"}/**
61
+ */function $1(t){return vf(void 0,t)}function vf(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:const n=e;return new Date(n.getTime());case Object:t===void 0&&(t={});break;case Array:t=[];break;default:return e}for(const n in e)!e.hasOwnProperty(n)||!H1(n)||(t[n]=vf(t[n],e[n]));return t}function H1(t){return t!=="__proto__"}/**
62
62
  * @license
63
63
  * Copyright 2022 Google LLC
64
64
  *
@@ -73,7 +73,7 @@
73
73
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
74
74
  * See the License for the specific language governing permissions and
75
75
  * limitations under the License.
76
- */function H1(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}/**
76
+ */function W1(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}/**
77
77
  * @license
78
78
  * Copyright 2022 Google LLC
79
79
  *
@@ -88,7 +88,7 @@
88
88
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
89
89
  * See the License for the specific language governing permissions and
90
90
  * limitations under the License.
91
- */const W1=()=>H1().__FIREBASE_DEFAULTS__,G1=()=>{if(typeof process>"u"||typeof process.env>"u")return;const t=process.env.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},j1=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=t&&ba(t[1]);return e&&JSON.parse(e)},vf=()=>{try{return M1()||W1()||G1()||j1()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},q1=t=>{var e,n;return(n=(e=vf())===null||e===void 0?void 0:e.emulatorHosts)===null||n===void 0?void 0:n[t]},z1=t=>{const e=q1(t);if(!e)return;const n=e.lastIndexOf(":");if(n<=0||n+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const s=parseInt(e.substring(n+1),10);return e[0]==="["?[e.substring(1,n-1),s]:[e.substring(0,n),s]},Ef=()=>{var t;return(t=vf())===null||t===void 0?void 0:t.config};/**
91
+ */const G1=()=>W1().__FIREBASE_DEFAULTS__,j1=()=>{if(typeof process>"u"||typeof process.env>"u")return;const t=process.env.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},q1=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=t&&wa(t[1]);return e&&JSON.parse(e)},Ef=()=>{try{return B1()||G1()||j1()||q1()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},z1=t=>{var e,n;return(n=(e=Ef())===null||e===void 0?void 0:e.emulatorHosts)===null||n===void 0?void 0:n[t]},K1=t=>{const e=z1(t);if(!e)return;const n=e.lastIndexOf(":");if(n<=0||n+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const s=parseInt(e.substring(n+1),10);return e[0]==="["?[e.substring(1,n-1),s]:[e.substring(0,n),s]},wf=()=>{var t;return(t=Ef())===null||t===void 0?void 0:t.config};/**
92
92
  * @license
93
93
  * Copyright 2017 Google LLC
94
94
  *
@@ -118,7 +118,7 @@
118
118
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
119
119
  * See the License for the specific language governing permissions and
120
120
  * limitations under the License.
121
- */function K1(t,e){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n={alg:"none",type:"JWT"},s=e||"demo-project",i=t.iat||0,r=t.sub||t.user_id;if(!r)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o=Object.assign({iss:`https://securetoken.google.com/${s}`,aud:s,iat:i,exp:i+3600,auth_time:i,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}}},t);return[mr(JSON.stringify(n)),mr(JSON.stringify(o)),""].join(".")}/**
121
+ */function Y1(t,e){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n={alg:"none",type:"JWT"},s=e||"demo-project",i=t.iat||0,r=t.sub||t.user_id;if(!r)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o=Object.assign({iss:`https://securetoken.google.com/${s}`,aud:s,iat:i,exp:i+3600,auth_time:i,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}}},t);return[mr(JSON.stringify(n)),mr(JSON.stringify(o)),""].join(".")}/**
122
122
  * @license
123
123
  * Copyright 2017 Google LLC
124
124
  *
@@ -133,7 +133,7 @@
133
133
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
134
134
  * See the License for the specific language governing permissions and
135
135
  * limitations under the License.
136
- */function Y1(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function wf(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(Y1())}function X1(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Q1(){return mf.NODE_ADMIN===!0}function J1(){try{return typeof indexedDB=="object"}catch{return!1}}function Z1(){return new Promise((t,e)=>{try{let n=!0;const s="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(s);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(s),t(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var r;e(((r=i.error)===null||r===void 0?void 0:r.message)||"")}}catch(n){e(n)}})}/**
136
+ */function X1(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function bf(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(X1())}function Q1(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function J1(){return gf.NODE_ADMIN===!0}function Z1(){try{return typeof indexedDB=="object"}catch{return!1}}function e_(){return new Promise((t,e)=>{try{let n=!0;const s="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(s);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(s),t(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var r;e(((r=i.error)===null||r===void 0?void 0:r.message)||"")}}catch(n){e(n)}})}/**
137
137
  * @license
138
138
  * Copyright 2017 Google LLC
139
139
  *
@@ -148,7 +148,7 @@
148
148
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
149
149
  * See the License for the specific language governing permissions and
150
150
  * limitations under the License.
151
- */const e_="FirebaseError";class Ci extends Error{constructor(e,n,s){super(n),this.code=e,this.customData=s,this.name=e_,Object.setPrototypeOf(this,Ci.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,bf.prototype.create)}}class bf{constructor(e,n,s){this.service=e,this.serviceName=n,this.errors=s}create(e,...n){const s=n[0]||{},i=`${this.service}/${e}`,r=this.errors[e],o=r?t_(r,s):"Error",a=`${this.serviceName}: ${o} (${i}).`;return new Ci(i,a,s)}}function t_(t,e){return t.replace(n_,(n,s)=>{const i=e[s];return i!=null?String(i):`<${s}?>`})}const n_=/\{\$([^}]+)}/g;/**
151
+ */const t_="FirebaseError";class Ci extends Error{constructor(e,n,s){super(n),this.code=e,this.customData=s,this.name=t_,Object.setPrototypeOf(this,Ci.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Cf.prototype.create)}}class Cf{constructor(e,n,s){this.service=e,this.serviceName=n,this.errors=s}create(e,...n){const s=n[0]||{},i=`${this.service}/${e}`,r=this.errors[e],o=r?n_(r,s):"Error",a=`${this.serviceName}: ${o} (${i}).`;return new Ci(i,a,s)}}function n_(t,e){return t.replace(s_,(n,s)=>{const i=e[s];return i!=null?String(i):`<${s}?>`})}const s_=/\{\$([^}]+)}/g;/**
152
152
  * @license
153
153
  * Copyright 2017 Google LLC
154
154
  *
@@ -163,7 +163,7 @@
163
163
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
164
164
  * See the License for the specific language governing permissions and
165
165
  * limitations under the License.
166
- */function ai(t){return JSON.parse(t)}function Ne(t){return JSON.stringify(t)}/**
166
+ */function ai(t){return JSON.parse(t)}function Fe(t){return JSON.stringify(t)}/**
167
167
  * @license
168
168
  * Copyright 2017 Google LLC
169
169
  *
@@ -178,7 +178,7 @@
178
178
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
179
179
  * See the License for the specific language governing permissions and
180
180
  * limitations under the License.
181
- */const Cf=function(t){let e={},n={},s={},i="";try{const r=t.split(".");e=ai(ba(r[0])||""),n=ai(ba(r[1])||""),i=r[2],s=n.d||{},delete n.d}catch{}return{header:e,claims:n,data:s,signature:i}},s_=function(t){const e=Cf(t),n=e.claims;return!!n&&typeof n=="object"&&n.hasOwnProperty("iat")},i_=function(t){const e=Cf(t).claims;return typeof e=="object"&&e.admin===!0};/**
181
+ */const Tf=function(t){let e={},n={},s={},i="";try{const r=t.split(".");e=ai(wa(r[0])||""),n=ai(wa(r[1])||""),i=r[2],s=n.d||{},delete n.d}catch{}return{header:e,claims:n,data:s,signature:i}},i_=function(t){const e=Tf(t),n=e.claims;return!!n&&typeof n=="object"&&n.hasOwnProperty("iat")},r_=function(t){const e=Tf(t).claims;return typeof e=="object"&&e.admin===!0};/**
182
182
  * @license
183
183
  * Copyright 2017 Google LLC
184
184
  *
@@ -208,7 +208,7 @@
208
208
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
209
209
  * See the License for the specific language governing permissions and
210
210
  * limitations under the License.
211
- */function r_(t){const e=[];for(const[n,s]of Object.entries(t))Array.isArray(s)?s.forEach(i=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(n)+"="+encodeURIComponent(s));return e.length?"&"+e.join("&"):""}/**
211
+ */function o_(t){const e=[];for(const[n,s]of Object.entries(t))Array.isArray(s)?s.forEach(i=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(n)+"="+encodeURIComponent(s));return e.length?"&"+e.join("&"):""}/**
212
212
  * @license
213
213
  * Copyright 2017 Google LLC
214
214
  *
@@ -223,7 +223,7 @@
223
223
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
224
224
  * See the License for the specific language governing permissions and
225
225
  * limitations under the License.
226
- */class o_{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,n){n||(n=0);const s=this.W_;if(typeof e=="string")for(let u=0;u<16;u++)s[u]=e.charCodeAt(n)<<24|e.charCodeAt(n+1)<<16|e.charCodeAt(n+2)<<8|e.charCodeAt(n+3),n+=4;else for(let u=0;u<16;u++)s[u]=e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3],n+=4;for(let u=16;u<80;u++){const d=s[u-3]^s[u-8]^s[u-14]^s[u-16];s[u]=(d<<1|d>>>31)&4294967295}let i=this.chain_[0],r=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,h;for(let u=0;u<80;u++){u<40?u<20?(l=a^r&(o^a),h=1518500249):(l=r^o^a,h=1859775393):u<60?(l=r&o|a&(r|o),h=2400959708):(l=r^o^a,h=3395469782);const d=(i<<5|i>>>27)+l+c+h+s[u]&4294967295;c=a,a=o,o=(r<<30|r>>>2)&4294967295,r=i,i=d}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+r&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(e,n){if(e==null)return;n===void 0&&(n=e.length);const s=n-this.blockSize;let i=0;const r=this.buf_;let o=this.inbuf_;for(;i<n;){if(o===0)for(;i<=s;)this.compress_(e,i),i+=this.blockSize;if(typeof e=="string"){for(;i<n;)if(r[o]=e.charCodeAt(i),++o,++i,o===this.blockSize){this.compress_(r),o=0;break}}else for(;i<n;)if(r[o]=e[i],++o,++i,o===this.blockSize){this.compress_(r),o=0;break}}this.inbuf_=o,this.total_+=n}digest(){const e=[];let n=this.total_*8;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let i=this.blockSize-1;i>=56;i--)this.buf_[i]=n&255,n/=256;this.compress_(this.buf_);let s=0;for(let i=0;i<5;i++)for(let r=24;r>=0;r-=8)e[s]=this.chain_[i]>>r&255,++s;return e}}function Tf(t,e){return`${t} failed: ${e} argument `}/**
226
+ */class a_{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,n){n||(n=0);const s=this.W_;if(typeof e=="string")for(let u=0;u<16;u++)s[u]=e.charCodeAt(n)<<24|e.charCodeAt(n+1)<<16|e.charCodeAt(n+2)<<8|e.charCodeAt(n+3),n+=4;else for(let u=0;u<16;u++)s[u]=e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3],n+=4;for(let u=16;u<80;u++){const d=s[u-3]^s[u-8]^s[u-14]^s[u-16];s[u]=(d<<1|d>>>31)&4294967295}let i=this.chain_[0],r=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,h;for(let u=0;u<80;u++){u<40?u<20?(l=a^r&(o^a),h=1518500249):(l=r^o^a,h=1859775393):u<60?(l=r&o|a&(r|o),h=2400959708):(l=r^o^a,h=3395469782);const d=(i<<5|i>>>27)+l+c+h+s[u]&4294967295;c=a,a=o,o=(r<<30|r>>>2)&4294967295,r=i,i=d}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+r&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(e,n){if(e==null)return;n===void 0&&(n=e.length);const s=n-this.blockSize;let i=0;const r=this.buf_;let o=this.inbuf_;for(;i<n;){if(o===0)for(;i<=s;)this.compress_(e,i),i+=this.blockSize;if(typeof e=="string"){for(;i<n;)if(r[o]=e.charCodeAt(i),++o,++i,o===this.blockSize){this.compress_(r),o=0;break}}else for(;i<n;)if(r[o]=e[i],++o,++i,o===this.blockSize){this.compress_(r),o=0;break}}this.inbuf_=o,this.total_+=n}digest(){const e=[];let n=this.total_*8;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let i=this.blockSize-1;i>=56;i--)this.buf_[i]=n&255,n/=256;this.compress_(this.buf_);let s=0;for(let i=0;i<5;i++)for(let r=24;r>=0;r-=8)e[s]=this.chain_[i]>>r&255,++s;return e}}function Sf(t,e){return`${t} failed: ${e} argument `}/**
227
227
  * @license
228
228
  * Copyright 2017 Google LLC
229
229
  *
@@ -238,7 +238,7 @@
238
238
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
239
239
  * See the License for the specific language governing permissions and
240
240
  * limitations under the License.
241
- */const a_=function(t){const e=[];let n=0;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);if(i>=55296&&i<=56319){const r=i-55296;s++,b(s<t.length,"Surrogate pair missing trail surrogate.");const o=t.charCodeAt(s)-56320;i=65536+(r<<10)+o}i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},Kr=function(t){let e=0;for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);s<128?e++:s<2048?e+=2:s>=55296&&s<=56319?(e+=4,n++):e+=3}return e};/**
241
+ */const c_=function(t){const e=[];let n=0;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);if(i>=55296&&i<=56319){const r=i-55296;s++,b(s<t.length,"Surrogate pair missing trail surrogate.");const o=t.charCodeAt(s)-56320;i=65536+(r<<10)+o}i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=i&63|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=i&63|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=i&63|128)}return e},zr=function(t){let e=0;for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);s<128?e++:s<2048?e+=2:s>=55296&&s<=56319?(e+=4,n++):e+=3}return e};/**
242
242
  * @license
243
243
  * Copyright 2021 Google LLC
244
244
  *
@@ -253,7 +253,7 @@
253
253
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
254
254
  * See the License for the specific language governing permissions and
255
255
  * limitations under the License.
256
- */function Yr(t){return t&&t._delegate?t._delegate:t}class ci{constructor(e,n,s){this.name=e,this.instanceFactory=n,this.type=s,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}/**
256
+ */function Kr(t){return t&&t._delegate?t._delegate:t}class ci{constructor(e,n,s){this.name=e,this.instanceFactory=n,this.type=s,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}/**
257
257
  * @license
258
258
  * Copyright 2019 Google LLC
259
259
  *
@@ -283,7 +283,7 @@
283
283
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
284
284
  * See the License for the specific language governing permissions and
285
285
  * limitations under the License.
286
- */class c_{constructor(e,n){this.name=e,this.container=n,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){const s=new yc;if(this.instancesDeferred.set(n,s),this.isInitialized(n)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:n});i&&s.resolve(i)}catch{}}return this.instancesDeferred.get(n).promise}getImmediate(e){var n;const s=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),i=(n=e==null?void 0:e.optional)!==null&&n!==void 0?n:!1;if(this.isInitialized(s)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:s})}catch(r){if(i)return null;throw r}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(h_(e))try{this.getOrInitializeService({instanceIdentifier:Cn})}catch{}for(const[n,s]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(n);try{const r=this.getOrInitializeService({instanceIdentifier:i});s.resolve(r)}catch{}}}}clearInstance(e=Cn){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(n=>"INTERNAL"in n).map(n=>n.INTERNAL.delete()),...e.filter(n=>"_delete"in n).map(n=>n._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=Cn){return this.instances.has(e)}getOptions(e=Cn){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:n={}}=e,s=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(s))throw Error(`${this.name}(${s}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:s,options:n});for(const[r,o]of this.instancesDeferred.entries()){const a=this.normalizeInstanceIdentifier(r);s===a&&o.resolve(i)}return i}onInit(e,n){var s;const i=this.normalizeInstanceIdentifier(n),r=(s=this.onInitCallbacks.get(i))!==null&&s!==void 0?s:new Set;r.add(e),this.onInitCallbacks.set(i,r);const o=this.instances.get(i);return o&&e(o,i),()=>{r.delete(e)}}invokeOnInitCallbacks(e,n){const s=this.onInitCallbacks.get(n);if(s)for(const i of s)try{i(e,n)}catch{}}getOrInitializeService({instanceIdentifier:e,options:n={}}){let s=this.instances.get(e);if(!s&&this.component&&(s=this.component.instanceFactory(this.container,{instanceIdentifier:l_(e),options:n}),this.instances.set(e,s),this.instancesOptions.set(e,n),this.invokeOnInitCallbacks(s,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,s)}catch{}return s||null}normalizeInstanceIdentifier(e=Cn){return this.component?this.component.multipleInstances?e:Cn:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function l_(t){return t===Cn?void 0:t}function h_(t){return t.instantiationMode==="EAGER"}/**
286
+ */class l_{constructor(e,n){this.name=e,this.container=n,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const n=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(n)){const s=new yc;if(this.instancesDeferred.set(n,s),this.isInitialized(n)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:n});i&&s.resolve(i)}catch{}}return this.instancesDeferred.get(n).promise}getImmediate(e){var n;const s=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),i=(n=e==null?void 0:e.optional)!==null&&n!==void 0?n:!1;if(this.isInitialized(s)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:s})}catch(r){if(i)return null;throw r}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(u_(e))try{this.getOrInitializeService({instanceIdentifier:Cn})}catch{}for(const[n,s]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(n);try{const r=this.getOrInitializeService({instanceIdentifier:i});s.resolve(r)}catch{}}}}clearInstance(e=Cn){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(n=>"INTERNAL"in n).map(n=>n.INTERNAL.delete()),...e.filter(n=>"_delete"in n).map(n=>n._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=Cn){return this.instances.has(e)}getOptions(e=Cn){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:n={}}=e,s=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(s))throw Error(`${this.name}(${s}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:s,options:n});for(const[r,o]of this.instancesDeferred.entries()){const a=this.normalizeInstanceIdentifier(r);s===a&&o.resolve(i)}return i}onInit(e,n){var s;const i=this.normalizeInstanceIdentifier(n),r=(s=this.onInitCallbacks.get(i))!==null&&s!==void 0?s:new Set;r.add(e),this.onInitCallbacks.set(i,r);const o=this.instances.get(i);return o&&e(o,i),()=>{r.delete(e)}}invokeOnInitCallbacks(e,n){const s=this.onInitCallbacks.get(n);if(s)for(const i of s)try{i(e,n)}catch{}}getOrInitializeService({instanceIdentifier:e,options:n={}}){let s=this.instances.get(e);if(!s&&this.component&&(s=this.component.instanceFactory(this.container,{instanceIdentifier:h_(e),options:n}),this.instances.set(e,s),this.instancesOptions.set(e,n),this.invokeOnInitCallbacks(s,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,s)}catch{}return s||null}normalizeInstanceIdentifier(e=Cn){return this.component?this.component.multipleInstances?e:Cn:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function h_(t){return t===Cn?void 0:t}function u_(t){return t.instantiationMode==="EAGER"}/**
287
287
  * @license
288
288
  * Copyright 2019 Google LLC
289
289
  *
@@ -298,7 +298,7 @@
298
298
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
299
299
  * See the License for the specific language governing permissions and
300
300
  * limitations under the License.
301
- */class u_{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const n=this.getProvider(e.name);if(n.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);n.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const n=new c_(e,this);return this.providers.set(e,n),n}getProviders(){return Array.from(this.providers.values())}}/**
301
+ */class d_{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const n=this.getProvider(e.name);if(n.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);n.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const n=new l_(e,this);return this.providers.set(e,n),n}getProviders(){return Array.from(this.providers.values())}}/**
302
302
  * @license
303
303
  * Copyright 2017 Google LLC
304
304
  *
@@ -313,7 +313,7 @@
313
313
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
314
314
  * See the License for the specific language governing permissions and
315
315
  * limitations under the License.
316
- */var re;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(re||(re={}));const d_={debug:re.DEBUG,verbose:re.VERBOSE,info:re.INFO,warn:re.WARN,error:re.ERROR,silent:re.SILENT},f_=re.INFO,p_={[re.DEBUG]:"log",[re.VERBOSE]:"log",[re.INFO]:"info",[re.WARN]:"warn",[re.ERROR]:"error"},m_=(t,e,...n)=>{if(e<t.logLevel)return;const s=new Date().toISOString(),i=p_[e];if(i)console[i](`[${s}] ${t.name}:`,...n);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)};class Sf{constructor(e){this.name=e,this._logLevel=f_,this._logHandler=m_,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in re))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?d_[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,re.DEBUG,...e),this._logHandler(this,re.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,re.VERBOSE,...e),this._logHandler(this,re.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,re.INFO,...e),this._logHandler(this,re.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,re.WARN,...e),this._logHandler(this,re.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,re.ERROR,...e),this._logHandler(this,re.ERROR,...e)}}const g_=(t,e)=>e.some(n=>t instanceof n);let hh,uh;function __(){return hh||(hh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function y_(){return uh||(uh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const kf=new WeakMap,Ca=new WeakMap,Af=new WeakMap,Vo=new WeakMap,vc=new WeakMap;function v_(t){const e=new Promise((n,s)=>{const i=()=>{t.removeEventListener("success",r),t.removeEventListener("error",o)},r=()=>{n(on(t.result)),i()},o=()=>{s(t.error),i()};t.addEventListener("success",r),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&kf.set(n,t)}).catch(()=>{}),vc.set(e,t),e}function E_(t){if(Ca.has(t))return;const e=new Promise((n,s)=>{const i=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",o),t.removeEventListener("abort",o)},r=()=>{n(),i()},o=()=>{s(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",r),t.addEventListener("error",o),t.addEventListener("abort",o)});Ca.set(t,e)}let Ta={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Ca.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Af.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return on(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function w_(t){Ta=t(Ta)}function b_(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){const s=t.call($o(this),e,...n);return Af.set(s,e.sort?e.sort():[e]),on(s)}:y_().includes(t)?function(...e){return t.apply($o(this),e),on(kf.get(this))}:function(...e){return on(t.apply($o(this),e))}}function C_(t){return typeof t=="function"?b_(t):(t instanceof IDBTransaction&&E_(t),g_(t,__())?new Proxy(t,Ta):t)}function on(t){if(t instanceof IDBRequest)return v_(t);if(Vo.has(t))return Vo.get(t);const e=C_(t);return e!==t&&(Vo.set(t,e),vc.set(e,t)),e}const $o=t=>vc.get(t);function T_(t,e,{blocked:n,upgrade:s,blocking:i,terminated:r}={}){const o=indexedDB.open(t,e),a=on(o);return s&&o.addEventListener("upgradeneeded",c=>{s(on(o.result),c.oldVersion,c.newVersion,on(o.transaction),c)}),n&&o.addEventListener("blocked",c=>n(c.oldVersion,c.newVersion,c)),a.then(c=>{r&&c.addEventListener("close",()=>r()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}const S_=["get","getKey","getAll","getAllKeys","count"],k_=["put","add","delete","clear"],Ho=new Map;function dh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Ho.get(e))return Ho.get(e);const n=e.replace(/FromIndex$/,""),s=e!==n,i=k_.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!(i||S_.includes(n)))return;const r=async function(o,...a){const c=this.transaction(o,i?"readwrite":"readonly");let l=c.store;return s&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),i&&c.done]))[0]};return Ho.set(e,r),r}w_(t=>({...t,get:(e,n,s)=>dh(e,n)||t.get(e,n,s),has:(e,n)=>!!dh(e,n)||t.has(e,n)}));/**
316
+ */var re;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(re||(re={}));const f_={debug:re.DEBUG,verbose:re.VERBOSE,info:re.INFO,warn:re.WARN,error:re.ERROR,silent:re.SILENT},p_=re.INFO,m_={[re.DEBUG]:"log",[re.VERBOSE]:"log",[re.INFO]:"info",[re.WARN]:"warn",[re.ERROR]:"error"},g_=(t,e,...n)=>{if(e<t.logLevel)return;const s=new Date().toISOString(),i=m_[e];if(i)console[i](`[${s}] ${t.name}:`,...n);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)};class kf{constructor(e){this.name=e,this._logLevel=p_,this._logHandler=g_,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in re))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?f_[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,re.DEBUG,...e),this._logHandler(this,re.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,re.VERBOSE,...e),this._logHandler(this,re.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,re.INFO,...e),this._logHandler(this,re.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,re.WARN,...e),this._logHandler(this,re.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,re.ERROR,...e),this._logHandler(this,re.ERROR,...e)}}const __=(t,e)=>e.some(n=>t instanceof n);let hh,uh;function y_(){return hh||(hh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function v_(){return uh||(uh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Af=new WeakMap,ba=new WeakMap,Rf=new WeakMap,Uo=new WeakMap,vc=new WeakMap;function E_(t){const e=new Promise((n,s)=>{const i=()=>{t.removeEventListener("success",r),t.removeEventListener("error",o)},r=()=>{n(on(t.result)),i()},o=()=>{s(t.error),i()};t.addEventListener("success",r),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&Af.set(n,t)}).catch(()=>{}),vc.set(e,t),e}function w_(t){if(ba.has(t))return;const e=new Promise((n,s)=>{const i=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",o),t.removeEventListener("abort",o)},r=()=>{n(),i()},o=()=>{s(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",r),t.addEventListener("error",o),t.addEventListener("abort",o)});ba.set(t,e)}let Ca={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return ba.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Rf.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return on(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function b_(t){Ca=t(Ca)}function C_(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){const s=t.call(Vo(this),e,...n);return Rf.set(s,e.sort?e.sort():[e]),on(s)}:v_().includes(t)?function(...e){return t.apply(Vo(this),e),on(Af.get(this))}:function(...e){return on(t.apply(Vo(this),e))}}function T_(t){return typeof t=="function"?C_(t):(t instanceof IDBTransaction&&w_(t),__(t,y_())?new Proxy(t,Ca):t)}function on(t){if(t instanceof IDBRequest)return E_(t);if(Uo.has(t))return Uo.get(t);const e=T_(t);return e!==t&&(Uo.set(t,e),vc.set(e,t)),e}const Vo=t=>vc.get(t);function S_(t,e,{blocked:n,upgrade:s,blocking:i,terminated:r}={}){const o=indexedDB.open(t,e),a=on(o);return s&&o.addEventListener("upgradeneeded",c=>{s(on(o.result),c.oldVersion,c.newVersion,on(o.transaction),c)}),n&&o.addEventListener("blocked",c=>n(c.oldVersion,c.newVersion,c)),a.then(c=>{r&&c.addEventListener("close",()=>r()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}const k_=["get","getKey","getAll","getAllKeys","count"],A_=["put","add","delete","clear"],$o=new Map;function dh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if($o.get(e))return $o.get(e);const n=e.replace(/FromIndex$/,""),s=e!==n,i=A_.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!(i||k_.includes(n)))return;const r=async function(o,...a){const c=this.transaction(o,i?"readwrite":"readonly");let l=c.store;return s&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),i&&c.done]))[0]};return $o.set(e,r),r}b_(t=>({...t,get:(e,n,s)=>dh(e,n)||t.get(e,n,s),has:(e,n)=>!!dh(e,n)||t.has(e,n)}));/**
317
317
  * @license
318
318
  * Copyright 2019 Google LLC
319
319
  *
@@ -328,7 +328,7 @@
328
328
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
329
329
  * See the License for the specific language governing permissions and
330
330
  * limitations under the License.
331
- */class A_{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(R_(n)){const s=n.getImmediate();return`${s.library}/${s.version}`}else return null}).filter(n=>n).join(" ")}}function R_(t){const e=t.getComponent();return(e==null?void 0:e.type)==="VERSION"}const Sa="@firebase/app",fh="0.11.5";/**
331
+ */class R_{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(n=>{if(I_(n)){const s=n.getImmediate();return`${s.library}/${s.version}`}else return null}).filter(n=>n).join(" ")}}function I_(t){const e=t.getComponent();return(e==null?void 0:e.type)==="VERSION"}const Ta="@firebase/app",fh="0.11.5";/**
332
332
  * @license
333
333
  * Copyright 2019 Google LLC
334
334
  *
@@ -343,7 +343,7 @@
343
343
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
344
344
  * See the License for the specific language governing permissions and
345
345
  * limitations under the License.
346
- */const Yt=new Sf("@firebase/app"),I_="@firebase/app-compat",x_="@firebase/analytics-compat",F_="@firebase/analytics",N_="@firebase/app-check-compat",D_="@firebase/app-check",P_="@firebase/auth",L_="@firebase/auth-compat",O_="@firebase/database",M_="@firebase/data-connect",B_="@firebase/database-compat",U_="@firebase/functions",V_="@firebase/functions-compat",$_="@firebase/installations",H_="@firebase/installations-compat",W_="@firebase/messaging",G_="@firebase/messaging-compat",j_="@firebase/performance",q_="@firebase/performance-compat",z_="@firebase/remote-config",K_="@firebase/remote-config-compat",Y_="@firebase/storage",X_="@firebase/storage-compat",Q_="@firebase/firestore",J_="@firebase/vertexai",Z_="@firebase/firestore-compat",e2="firebase",t2="11.6.1";/**
346
+ */const Yt=new kf("@firebase/app"),x_="@firebase/app-compat",N_="@firebase/analytics-compat",F_="@firebase/analytics",D_="@firebase/app-check-compat",P_="@firebase/app-check",L_="@firebase/auth",O_="@firebase/auth-compat",M_="@firebase/database",B_="@firebase/data-connect",U_="@firebase/database-compat",V_="@firebase/functions",$_="@firebase/functions-compat",H_="@firebase/installations",W_="@firebase/installations-compat",G_="@firebase/messaging",j_="@firebase/messaging-compat",q_="@firebase/performance",z_="@firebase/performance-compat",K_="@firebase/remote-config",Y_="@firebase/remote-config-compat",X_="@firebase/storage",Q_="@firebase/storage-compat",J_="@firebase/firestore",Z_="@firebase/vertexai",e2="@firebase/firestore-compat",t2="firebase",n2="11.6.1";/**
347
347
  * @license
348
348
  * Copyright 2019 Google LLC
349
349
  *
@@ -358,7 +358,7 @@
358
358
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
359
359
  * See the License for the specific language governing permissions and
360
360
  * limitations under the License.
361
- */const ka="[DEFAULT]",n2={[Sa]:"fire-core",[I_]:"fire-core-compat",[F_]:"fire-analytics",[x_]:"fire-analytics-compat",[D_]:"fire-app-check",[N_]:"fire-app-check-compat",[P_]:"fire-auth",[L_]:"fire-auth-compat",[O_]:"fire-rtdb",[M_]:"fire-data-connect",[B_]:"fire-rtdb-compat",[U_]:"fire-fn",[V_]:"fire-fn-compat",[$_]:"fire-iid",[H_]:"fire-iid-compat",[W_]:"fire-fcm",[G_]:"fire-fcm-compat",[j_]:"fire-perf",[q_]:"fire-perf-compat",[z_]:"fire-rc",[K_]:"fire-rc-compat",[Y_]:"fire-gcs",[X_]:"fire-gcs-compat",[Q_]:"fire-fst",[Z_]:"fire-fst-compat",[J_]:"fire-vertex","fire-js":"fire-js",[e2]:"fire-js-all"};/**
361
+ */const Sa="[DEFAULT]",s2={[Ta]:"fire-core",[x_]:"fire-core-compat",[F_]:"fire-analytics",[N_]:"fire-analytics-compat",[P_]:"fire-app-check",[D_]:"fire-app-check-compat",[L_]:"fire-auth",[O_]:"fire-auth-compat",[M_]:"fire-rtdb",[B_]:"fire-data-connect",[U_]:"fire-rtdb-compat",[V_]:"fire-fn",[$_]:"fire-fn-compat",[H_]:"fire-iid",[W_]:"fire-iid-compat",[G_]:"fire-fcm",[j_]:"fire-fcm-compat",[q_]:"fire-perf",[z_]:"fire-perf-compat",[K_]:"fire-rc",[Y_]:"fire-rc-compat",[X_]:"fire-gcs",[Q_]:"fire-gcs-compat",[J_]:"fire-fst",[e2]:"fire-fst-compat",[Z_]:"fire-vertex","fire-js":"fire-js",[t2]:"fire-js-all"};/**
362
362
  * @license
363
363
  * Copyright 2019 Google LLC
364
364
  *
@@ -373,7 +373,7 @@
373
373
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
374
374
  * See the License for the specific language governing permissions and
375
375
  * limitations under the License.
376
- */const yr=new Map,s2=new Map,Aa=new Map;function ph(t,e){try{t.container.addComponent(e)}catch(n){Yt.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function vr(t){const e=t.name;if(Aa.has(e))return Yt.debug(`There were multiple attempts to register component ${e}.`),!1;Aa.set(e,t);for(const n of yr.values())ph(n,t);for(const n of s2.values())ph(n,t);return!0}function i2(t,e){const n=t.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),t.container.getProvider(e)}function r2(t){return t==null?!1:t.settings!==void 0}/**
376
+ */const yr=new Map,i2=new Map,ka=new Map;function ph(t,e){try{t.container.addComponent(e)}catch(n){Yt.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function vr(t){const e=t.name;if(ka.has(e))return Yt.debug(`There were multiple attempts to register component ${e}.`),!1;ka.set(e,t);for(const n of yr.values())ph(n,t);for(const n of i2.values())ph(n,t);return!0}function r2(t,e){const n=t.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),t.container.getProvider(e)}function o2(t){return t==null?!1:t.settings!==void 0}/**
377
377
  * @license
378
378
  * Copyright 2019 Google LLC
379
379
  *
@@ -388,7 +388,7 @@
388
388
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
389
389
  * See the License for the specific language governing permissions and
390
390
  * limitations under the License.
391
- */const o2={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},an=new bf("app","Firebase",o2);/**
391
+ */const a2={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},an=new Cf("app","Firebase",a2);/**
392
392
  * @license
393
393
  * Copyright 2019 Google LLC
394
394
  *
@@ -403,7 +403,7 @@
403
403
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
404
404
  * See the License for the specific language governing permissions and
405
405
  * limitations under the License.
406
- */class a2{constructor(e,n,s){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},n),this._name=n.name,this._automaticDataCollectionEnabled=n.automaticDataCollectionEnabled,this._container=s,this.container.addComponent(new ci("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw an.create("app-deleted",{appName:this._name})}}/**
406
+ */class c2{constructor(e,n,s){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},n),this._name=n.name,this._automaticDataCollectionEnabled=n.automaticDataCollectionEnabled,this._container=s,this.container.addComponent(new ci("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw an.create("app-deleted",{appName:this._name})}}/**
407
407
  * @license
408
408
  * Copyright 2019 Google LLC
409
409
  *
@@ -418,7 +418,7 @@
418
418
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
419
419
  * See the License for the specific language governing permissions and
420
420
  * limitations under the License.
421
- */const c2=t2;function Rf(t,e={}){let n=t;typeof e!="object"&&(e={name:e});const s=Object.assign({name:ka,automaticDataCollectionEnabled:!1},e),i=s.name;if(typeof i!="string"||!i)throw an.create("bad-app-name",{appName:String(i)});if(n||(n=Ef()),!n)throw an.create("no-options");const r=yr.get(i);if(r){if(_r(n,r.options)&&_r(s,r.config))return r;throw an.create("duplicate-app",{appName:i})}const o=new u_(i);for(const c of Aa.values())o.addComponent(c);const a=new a2(n,s,o);return yr.set(i,a),a}function l2(t=ka){const e=yr.get(t);if(!e&&t===ka&&Ef())return Rf();if(!e)throw an.create("no-app",{appName:t});return e}function es(t,e,n){var s;let i=(s=n2[t])!==null&&s!==void 0?s:t;n&&(i+=`-${n}`);const r=i.match(/\s|\//),o=e.match(/\s|\//);if(r||o){const a=[`Unable to register library "${i}" with version "${e}":`];r&&a.push(`library name "${i}" contains illegal characters (whitespace or "/")`),r&&o&&a.push("and"),o&&a.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Yt.warn(a.join(" "));return}vr(new ci(`${i}-version`,()=>({library:i,version:e}),"VERSION"))}/**
421
+ */const l2=n2;function If(t,e={}){let n=t;typeof e!="object"&&(e={name:e});const s=Object.assign({name:Sa,automaticDataCollectionEnabled:!1},e),i=s.name;if(typeof i!="string"||!i)throw an.create("bad-app-name",{appName:String(i)});if(n||(n=wf()),!n)throw an.create("no-options");const r=yr.get(i);if(r){if(_r(n,r.options)&&_r(s,r.config))return r;throw an.create("duplicate-app",{appName:i})}const o=new d_(i);for(const c of ka.values())o.addComponent(c);const a=new c2(n,s,o);return yr.set(i,a),a}function h2(t=Sa){const e=yr.get(t);if(!e&&t===Sa&&wf())return If();if(!e)throw an.create("no-app",{appName:t});return e}function es(t,e,n){var s;let i=(s=s2[t])!==null&&s!==void 0?s:t;n&&(i+=`-${n}`);const r=i.match(/\s|\//),o=e.match(/\s|\//);if(r||o){const a=[`Unable to register library "${i}" with version "${e}":`];r&&a.push(`library name "${i}" contains illegal characters (whitespace or "/")`),r&&o&&a.push("and"),o&&a.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Yt.warn(a.join(" "));return}vr(new ci(`${i}-version`,()=>({library:i,version:e}),"VERSION"))}/**
422
422
  * @license
423
423
  * Copyright 2021 Google LLC
424
424
  *
@@ -433,7 +433,7 @@
433
433
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
434
434
  * See the License for the specific language governing permissions and
435
435
  * limitations under the License.
436
- */const h2="firebase-heartbeat-database",u2=1,li="firebase-heartbeat-store";let Wo=null;function If(){return Wo||(Wo=T_(h2,u2,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(li)}catch(n){console.warn(n)}}}}).catch(t=>{throw an.create("idb-open",{originalErrorMessage:t.message})})),Wo}async function d2(t){try{const n=(await If()).transaction(li),s=await n.objectStore(li).get(xf(t));return await n.done,s}catch(e){if(e instanceof Ci)Yt.warn(e.message);else{const n=an.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});Yt.warn(n.message)}}}async function mh(t,e){try{const s=(await If()).transaction(li,"readwrite");await s.objectStore(li).put(e,xf(t)),await s.done}catch(n){if(n instanceof Ci)Yt.warn(n.message);else{const s=an.create("idb-set",{originalErrorMessage:n==null?void 0:n.message});Yt.warn(s.message)}}}function xf(t){return`${t.name}!${t.options.appId}`}/**
436
+ */const u2="firebase-heartbeat-database",d2=1,li="firebase-heartbeat-store";let Ho=null;function xf(){return Ho||(Ho=S_(u2,d2,{upgrade:(t,e)=>{switch(e){case 0:try{t.createObjectStore(li)}catch(n){console.warn(n)}}}}).catch(t=>{throw an.create("idb-open",{originalErrorMessage:t.message})})),Ho}async function f2(t){try{const n=(await xf()).transaction(li),s=await n.objectStore(li).get(Nf(t));return await n.done,s}catch(e){if(e instanceof Ci)Yt.warn(e.message);else{const n=an.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});Yt.warn(n.message)}}}async function mh(t,e){try{const s=(await xf()).transaction(li,"readwrite");await s.objectStore(li).put(e,Nf(t)),await s.done}catch(n){if(n instanceof Ci)Yt.warn(n.message);else{const s=an.create("idb-set",{originalErrorMessage:n==null?void 0:n.message});Yt.warn(s.message)}}}function Nf(t){return`${t.name}!${t.options.appId}`}/**
437
437
  * @license
438
438
  * Copyright 2021 Google LLC
439
439
  *
@@ -448,7 +448,7 @@
448
448
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
449
449
  * See the License for the specific language governing permissions and
450
450
  * limitations under the License.
451
- */const f2=1024,p2=30;class m2{constructor(e){this.container=e,this._heartbeatsCache=null;const n=this.container.getProvider("app").getImmediate();this._storage=new _2(n),this._heartbeatsCachePromise=this._storage.read().then(s=>(this._heartbeatsCache=s,s))}async triggerHeartbeat(){var e,n;try{const i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=gh();if(((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((n=this._heartbeatsCache)===null||n===void 0?void 0:n.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(o=>o.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:i}),this._heartbeatsCache.heartbeats.length>p2){const o=y2(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(o,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(s){Yt.warn(s)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const n=gh(),{heartbeatsToSend:s,unsentEntries:i}=g2(this._heartbeatsCache.heartbeats),r=mr(JSON.stringify({version:2,heartbeats:s}));return this._heartbeatsCache.lastSentHeartbeatDate=n,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}catch(n){return Yt.warn(n),""}}}function gh(){return new Date().toISOString().substring(0,10)}function g2(t,e=f2){const n=[];let s=t.slice();for(const i of t){const r=n.find(o=>o.agent===i.agent);if(r){if(r.dates.push(i.date),_h(n)>e){r.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),_h(n)>e){n.pop();break}s=s.slice(1)}return{heartbeatsToSend:n,unsentEntries:s}}class _2{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return J1()?Z1().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const n=await d2(this.app);return n!=null&&n.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return mh(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return mh(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}else return}}function _h(t){return mr(JSON.stringify({version:2,heartbeats:t})).length}function y2(t){if(t.length===0)return-1;let e=0,n=t[0].date;for(let s=1;s<t.length;s++)t[s].date<n&&(n=t[s].date,e=s);return e}/**
451
+ */const p2=1024,m2=30;class g2{constructor(e){this.container=e,this._heartbeatsCache=null;const n=this.container.getProvider("app").getImmediate();this._storage=new y2(n),this._heartbeatsCachePromise=this._storage.read().then(s=>(this._heartbeatsCache=s,s))}async triggerHeartbeat(){var e,n;try{const i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=gh();if(((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((n=this._heartbeatsCache)===null||n===void 0?void 0:n.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(o=>o.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:i}),this._heartbeatsCache.heartbeats.length>m2){const o=v2(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(o,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(s){Yt.warn(s)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const n=gh(),{heartbeatsToSend:s,unsentEntries:i}=_2(this._heartbeatsCache.heartbeats),r=mr(JSON.stringify({version:2,heartbeats:s}));return this._heartbeatsCache.lastSentHeartbeatDate=n,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}catch(n){return Yt.warn(n),""}}}function gh(){return new Date().toISOString().substring(0,10)}function _2(t,e=p2){const n=[];let s=t.slice();for(const i of t){const r=n.find(o=>o.agent===i.agent);if(r){if(r.dates.push(i.date),_h(n)>e){r.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),_h(n)>e){n.pop();break}s=s.slice(1)}return{heartbeatsToSend:n,unsentEntries:s}}class y2{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Z1()?e_().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const n=await f2(this.app);return n!=null&&n.heartbeats?n:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return mh(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var n;if(await this._canUseIndexedDBPromise){const i=await this.read();return mh(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!==null&&n!==void 0?n:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}else return}}function _h(t){return mr(JSON.stringify({version:2,heartbeats:t})).length}function v2(t){if(t.length===0)return-1;let e=0,n=t[0].date;for(let s=1;s<t.length;s++)t[s].date<n&&(n=t[s].date,e=s);return e}/**
452
452
  * @license
453
453
  * Copyright 2019 Google LLC
454
454
  *
@@ -463,7 +463,7 @@
463
463
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
464
464
  * See the License for the specific language governing permissions and
465
465
  * limitations under the License.
466
- */function v2(t){vr(new ci("platform-logger",e=>new A_(e),"PRIVATE")),vr(new ci("heartbeat",e=>new m2(e),"PRIVATE")),es(Sa,fh,t),es(Sa,fh,"esm2017"),es("fire-js","")}v2("");const yh="@firebase/database",vh="1.0.14";/**
466
+ */function E2(t){vr(new ci("platform-logger",e=>new R_(e),"PRIVATE")),vr(new ci("heartbeat",e=>new g2(e),"PRIVATE")),es(Ta,fh,t),es(Ta,fh,"esm2017"),es("fire-js","")}E2("");const yh="@firebase/database",vh="1.0.14";/**
467
467
  * @license
468
468
  * Copyright 2019 Google LLC
469
469
  *
@@ -478,7 +478,7 @@
478
478
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
479
479
  * See the License for the specific language governing permissions and
480
480
  * limitations under the License.
481
- */let Ff="";function E2(t){Ff=t}/**
481
+ */let Ff="";function w2(t){Ff=t}/**
482
482
  * @license
483
483
  * Copyright 2017 Google LLC
484
484
  *
@@ -493,7 +493,7 @@
493
493
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
494
494
  * See the License for the specific language governing permissions and
495
495
  * limitations under the License.
496
- */class w2{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,n){n==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Ne(n))}get(e){const n=this.domStorage_.getItem(this.prefixedName_(e));return n==null?null:ai(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}/**
496
+ */class b2{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,n){n==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),Fe(n))}get(e){const n=this.domStorage_.getItem(this.prefixedName_(e));return n==null?null:ai(n)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}/**
497
497
  * @license
498
498
  * Copyright 2017 Google LLC
499
499
  *
@@ -508,7 +508,7 @@
508
508
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
509
509
  * See the License for the specific language governing permissions and
510
510
  * limitations under the License.
511
- */class b2{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,n){n==null?delete this.cache_[e]:this.cache_[e]=n}get(e){return Zt(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}/**
511
+ */class C2{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,n){n==null?delete this.cache_[e]:this.cache_[e]=n}get(e){return Zt(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}/**
512
512
  * @license
513
513
  * Copyright 2017 Google LLC
514
514
  *
@@ -523,7 +523,7 @@
523
523
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
524
524
  * See the License for the specific language governing permissions and
525
525
  * limitations under the License.
526
- */const Nf=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){const e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new w2(e)}}catch{}return new b2},In=Nf("localStorage"),C2=Nf("sessionStorage");/**
526
+ */const Df=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){const e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new b2(e)}}catch{}return new C2},In=Df("localStorage"),T2=Df("sessionStorage");/**
527
527
  * @license
528
528
  * Copyright 2017 Google LLC
529
529
  *
@@ -538,7 +538,7 @@
538
538
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
539
539
  * See the License for the specific language governing permissions and
540
540
  * limitations under the License.
541
- */const ts=new Sf("@firebase/database"),T2=function(){let t=1;return function(){return t++}}(),Df=function(t){const e=a_(t),n=new o_;n.update(e);const s=n.digest();return _c.encodeByteArray(s)},Ti=function(...t){let e="";for(let n=0;n<t.length;n++){const s=t[n];Array.isArray(s)||s&&typeof s=="object"&&typeof s.length=="number"?e+=Ti.apply(null,s):typeof s=="object"?e+=Ne(s):e+=s,e+=" "}return e};let Zs=null,Eh=!0;const S2=function(t,e){b(!0,"Can't turn on custom loggers persistently."),ts.logLevel=re.VERBOSE,Zs=ts.log.bind(ts)},Oe=function(...t){if(Eh===!0&&(Eh=!1,Zs===null&&C2.get("logging_enabled")===!0&&S2()),Zs){const e=Ti.apply(null,t);Zs(e)}},Si=function(t){return function(...e){Oe(t,...e)}},Ra=function(...t){const e="FIREBASE INTERNAL ERROR: "+Ti(...t);ts.error(e)},Xt=function(...t){const e=`FIREBASE FATAL ERROR: ${Ti(...t)}`;throw ts.error(e),new Error(e)},nt=function(...t){const e="FIREBASE WARNING: "+Ti(...t);ts.warn(e)},k2=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&nt("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Pf=function(t){return typeof t=="number"&&(t!==t||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)},A2=function(t){if(document.readyState==="complete")t();else{let e=!1;const n=function(){if(!document.body){setTimeout(n,Math.floor(10));return}e||(e=!0,t())};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&n()}),window.attachEvent("onload",n))}},us="[MIN_NAME]",Ln="[MAX_NAME]",Ss=function(t,e){if(t===e)return 0;if(t===us||e===Ln)return-1;if(e===us||t===Ln)return 1;{const n=wh(t),s=wh(e);return n!==null?s!==null?n-s===0?t.length-e.length:n-s:-1:s!==null?1:t<e?-1:1}},R2=function(t,e){return t===e?0:t<e?-1:1},Vs=function(t,e){if(e&&t in e)return e[t];throw new Error("Missing required key ("+t+") in object: "+Ne(e))},Ec=function(t){if(typeof t!="object"||t===null)return Ne(t);const e=[];for(const s in t)e.push(s);e.sort();let n="{";for(let s=0;s<e.length;s++)s!==0&&(n+=","),n+=Ne(e[s]),n+=":",n+=Ec(t[e[s]]);return n+="}",n},Lf=function(t,e){const n=t.length;if(n<=e)return[t];const s=[];for(let i=0;i<n;i+=e)i+e>n?s.push(t.substring(i,n)):s.push(t.substring(i,i+e));return s};function Ye(t,e){for(const n in t)t.hasOwnProperty(n)&&e(n,t[n])}const Of=function(t){b(!Pf(t),"Invalid JSON number");const e=11,n=52,s=(1<<e-1)-1;let i,r,o,a,c;t===0?(r=0,o=0,i=1/t===-1/0?1:0):(i=t<0,t=Math.abs(t),t>=Math.pow(2,1-s)?(a=Math.min(Math.floor(Math.log(t)/Math.LN2),s),r=a+s,o=Math.round(t*Math.pow(2,n-a)-Math.pow(2,n))):(r=0,o=Math.round(t/Math.pow(2,1-s-n))));const l=[];for(c=n;c;c-=1)l.push(o%2?1:0),o=Math.floor(o/2);for(c=e;c;c-=1)l.push(r%2?1:0),r=Math.floor(r/2);l.push(i?1:0),l.reverse();const h=l.join("");let u="";for(c=0;c<64;c+=8){let d=parseInt(h.substr(c,8),2).toString(16);d.length===1&&(d="0"+d),u=u+d}return u.toLowerCase()},I2=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},x2=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function F2(t,e){let n="Unknown Error";t==="too_big"?n="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?n="Client doesn't have permission to access the desired data.":t==="unavailable"&&(n="The service is unavailable");const s=new Error(t+" at "+e._path.toString()+": "+n);return s.code=t.toUpperCase(),s}const N2=new RegExp("^-?(0*)\\d{1,10}$"),D2=-2147483648,P2=2147483647,wh=function(t){if(N2.test(t)){const e=Number(t);if(e>=D2&&e<=P2)return e}return null},ki=function(t){try{t()}catch(e){setTimeout(()=>{const n=e.stack||"";throw nt("Exception was thrown by user callback.",n),e},Math.floor(0))}},L2=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},ei=function(t,e){const n=setTimeout(t,e);return typeof n=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n=="object"&&n.unref&&n.unref(),n};/**
541
+ */const ts=new kf("@firebase/database"),S2=function(){let t=1;return function(){return t++}}(),Pf=function(t){const e=c_(t),n=new a_;n.update(e);const s=n.digest();return _c.encodeByteArray(s)},Ti=function(...t){let e="";for(let n=0;n<t.length;n++){const s=t[n];Array.isArray(s)||s&&typeof s=="object"&&typeof s.length=="number"?e+=Ti.apply(null,s):typeof s=="object"?e+=Fe(s):e+=s,e+=" "}return e};let Zs=null,Eh=!0;const k2=function(t,e){b(!0,"Can't turn on custom loggers persistently."),ts.logLevel=re.VERBOSE,Zs=ts.log.bind(ts)},Oe=function(...t){if(Eh===!0&&(Eh=!1,Zs===null&&T2.get("logging_enabled")===!0&&k2()),Zs){const e=Ti.apply(null,t);Zs(e)}},Si=function(t){return function(...e){Oe(t,...e)}},Aa=function(...t){const e="FIREBASE INTERNAL ERROR: "+Ti(...t);ts.error(e)},Xt=function(...t){const e=`FIREBASE FATAL ERROR: ${Ti(...t)}`;throw ts.error(e),new Error(e)},nt=function(...t){const e="FIREBASE WARNING: "+Ti(...t);ts.warn(e)},A2=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&nt("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Lf=function(t){return typeof t=="number"&&(t!==t||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)},R2=function(t){if(document.readyState==="complete")t();else{let e=!1;const n=function(){if(!document.body){setTimeout(n,Math.floor(10));return}e||(e=!0,t())};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&n()}),window.attachEvent("onload",n))}},us="[MIN_NAME]",Ln="[MAX_NAME]",Ss=function(t,e){if(t===e)return 0;if(t===us||e===Ln)return-1;if(e===us||t===Ln)return 1;{const n=wh(t),s=wh(e);return n!==null?s!==null?n-s===0?t.length-e.length:n-s:-1:s!==null?1:t<e?-1:1}},I2=function(t,e){return t===e?0:t<e?-1:1},Vs=function(t,e){if(e&&t in e)return e[t];throw new Error("Missing required key ("+t+") in object: "+Fe(e))},Ec=function(t){if(typeof t!="object"||t===null)return Fe(t);const e=[];for(const s in t)e.push(s);e.sort();let n="{";for(let s=0;s<e.length;s++)s!==0&&(n+=","),n+=Fe(e[s]),n+=":",n+=Ec(t[e[s]]);return n+="}",n},Of=function(t,e){const n=t.length;if(n<=e)return[t];const s=[];for(let i=0;i<n;i+=e)i+e>n?s.push(t.substring(i,n)):s.push(t.substring(i,i+e));return s};function Ye(t,e){for(const n in t)t.hasOwnProperty(n)&&e(n,t[n])}const Mf=function(t){b(!Lf(t),"Invalid JSON number");const e=11,n=52,s=(1<<e-1)-1;let i,r,o,a,c;t===0?(r=0,o=0,i=1/t===-1/0?1:0):(i=t<0,t=Math.abs(t),t>=Math.pow(2,1-s)?(a=Math.min(Math.floor(Math.log(t)/Math.LN2),s),r=a+s,o=Math.round(t*Math.pow(2,n-a)-Math.pow(2,n))):(r=0,o=Math.round(t/Math.pow(2,1-s-n))));const l=[];for(c=n;c;c-=1)l.push(o%2?1:0),o=Math.floor(o/2);for(c=e;c;c-=1)l.push(r%2?1:0),r=Math.floor(r/2);l.push(i?1:0),l.reverse();const h=l.join("");let u="";for(c=0;c<64;c+=8){let d=parseInt(h.substr(c,8),2).toString(16);d.length===1&&(d="0"+d),u=u+d}return u.toLowerCase()},x2=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},N2=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function F2(t,e){let n="Unknown Error";t==="too_big"?n="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?n="Client doesn't have permission to access the desired data.":t==="unavailable"&&(n="The service is unavailable");const s=new Error(t+" at "+e._path.toString()+": "+n);return s.code=t.toUpperCase(),s}const D2=new RegExp("^-?(0*)\\d{1,10}$"),P2=-2147483648,L2=2147483647,wh=function(t){if(D2.test(t)){const e=Number(t);if(e>=P2&&e<=L2)return e}return null},ki=function(t){try{t()}catch(e){setTimeout(()=>{const n=e.stack||"";throw nt("Exception was thrown by user callback.",n),e},Math.floor(0))}},O2=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},ei=function(t,e){const n=setTimeout(t,e);return typeof n=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n=="object"&&n.unref&&n.unref(),n};/**
542
542
  * @license
543
543
  * Copyright 2021 Google LLC
544
544
  *
@@ -553,7 +553,7 @@
553
553
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
554
554
  * See the License for the specific language governing permissions and
555
555
  * limitations under the License.
556
- */class O2{constructor(e,n){this.appCheckProvider=n,this.appName=e.name,r2(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=n==null?void 0:n.getImmediate({optional:!0}),this.appCheck||n==null||n.get().then(s=>this.appCheck=s)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise((n,s)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(n,s):n(null)},0)})}addTokenChangeListener(e){var n;(n=this.appCheckProvider)===null||n===void 0||n.get().then(s=>s.addTokenListener(e))}notifyForInvalidToken(){nt(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}/**
556
+ */class M2{constructor(e,n){this.appCheckProvider=n,this.appName=e.name,o2(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=n==null?void 0:n.getImmediate({optional:!0}),this.appCheck||n==null||n.get().then(s=>this.appCheck=s)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise((n,s)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(n,s):n(null)},0)})}addTokenChangeListener(e){var n;(n=this.appCheckProvider)===null||n===void 0||n.get().then(s=>s.addTokenListener(e))}notifyForInvalidToken(){nt(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}/**
557
557
  * @license
558
558
  * Copyright 2017 Google LLC
559
559
  *
@@ -568,7 +568,7 @@
568
568
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
569
569
  * See the License for the specific language governing permissions and
570
570
  * limitations under the License.
571
- */class M2{constructor(e,n,s){this.appName_=e,this.firebaseOptions_=n,this.authProvider_=s,this.auth_=null,this.auth_=s.getImmediate({optional:!0}),this.auth_||s.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(n=>n&&n.code==="auth/token-not-initialized"?(Oe("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(n)):new Promise((n,s)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(n,s):n(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(n=>n.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(n=>n.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',nt(e)}}class Ji{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Ji.OWNER="owner";/**
571
+ */class B2{constructor(e,n,s){this.appName_=e,this.firebaseOptions_=n,this.authProvider_=s,this.auth_=null,this.auth_=s.getImmediate({optional:!0}),this.auth_||s.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(n=>n&&n.code==="auth/token-not-initialized"?(Oe("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(n)):new Promise((n,s)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(n,s):n(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then(n=>n.addAuthTokenListener(e))}removeTokenChangeListener(e){this.authProvider_.get().then(n=>n.removeAuthTokenListener(e))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',nt(e)}}class Ji{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Ji.OWNER="owner";/**
572
572
  * @license
573
573
  * Copyright 2017 Google LLC
574
574
  *
@@ -583,7 +583,7 @@
583
583
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
584
584
  * See the License for the specific language governing permissions and
585
585
  * limitations under the License.
586
- */const wc="5",Mf="v",Bf="s",Uf="r",Vf="f",$f=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Hf="ls",Wf="p",Ia="ac",Gf="websocket",jf="long_polling";/**
586
+ */const wc="5",Bf="v",Uf="s",Vf="r",$f="f",Hf=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Wf="ls",Gf="p",Ra="ac",jf="websocket",qf="long_polling";/**
587
587
  * @license
588
588
  * Copyright 2017 Google LLC
589
589
  *
@@ -598,7 +598,7 @@
598
598
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
599
599
  * See the License for the specific language governing permissions and
600
600
  * limitations under the License.
601
- */class qf{constructor(e,n,s,i,r=!1,o="",a=!1,c=!1,l=null){this.secure=n,this.namespace=s,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=o,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=c,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=In.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&In.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",n=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${n}`}}function B2(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function zf(t,e,n){b(typeof e=="string","typeof type must == string"),b(typeof n=="object","typeof params must == object");let s;if(e===Gf)s=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(e===jf)s=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);B2(t)&&(n.ns=t.namespace);const i=[];return Ye(n,(r,o)=>{i.push(r+"="+o)}),s+i.join("&")}/**
601
+ */class zf{constructor(e,n,s,i,r=!1,o="",a=!1,c=!1,l=null){this.secure=n,this.namespace=s,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=o,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=c,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=In.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&In.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",n=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${n}`}}function U2(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function Kf(t,e,n){b(typeof e=="string","typeof type must == string"),b(typeof n=="object","typeof params must == object");let s;if(e===jf)s=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(e===qf)s=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);U2(t)&&(n.ns=t.namespace);const i=[];return Ye(n,(r,o)=>{i.push(r+"="+o)}),s+i.join("&")}/**
602
602
  * @license
603
603
  * Copyright 2017 Google LLC
604
604
  *
@@ -613,7 +613,7 @@
613
613
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
614
614
  * See the License for the specific language governing permissions and
615
615
  * limitations under the License.
616
- */class U2{constructor(){this.counters_={}}incrementCounter(e,n=1){Zt(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=n}get(){return V1(this.counters_)}}/**
616
+ */class V2{constructor(){this.counters_={}}incrementCounter(e,n=1){Zt(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=n}get(){return $1(this.counters_)}}/**
617
617
  * @license
618
618
  * Copyright 2017 Google LLC
619
619
  *
@@ -628,7 +628,7 @@
628
628
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
629
629
  * See the License for the specific language governing permissions and
630
630
  * limitations under the License.
631
- */const Go={},jo={};function bc(t){const e=t.toString();return Go[e]||(Go[e]=new U2),Go[e]}function V2(t,e){const n=t.toString();return jo[n]||(jo[n]=e()),jo[n]}/**
631
+ */const Wo={},Go={};function bc(t){const e=t.toString();return Wo[e]||(Wo[e]=new V2),Wo[e]}function $2(t,e){const n=t.toString();return Go[n]||(Go[n]=e()),Go[n]}/**
632
632
  * @license
633
633
  * Copyright 2017 Google LLC
634
634
  *
@@ -643,7 +643,7 @@
643
643
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
644
644
  * See the License for the specific language governing permissions and
645
645
  * limitations under the License.
646
- */class $2{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,n){this.closeAfterResponse=e,this.onClose=n,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,n){for(this.pendingResponses[e]=n;this.pendingResponses[this.currentResponseNum];){const s=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<s.length;++i)s[i]&&ki(()=>{this.onMessage_(s[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/**
646
+ */class H2{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,n){this.closeAfterResponse=e,this.onClose=n,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,n){for(this.pendingResponses[e]=n;this.pendingResponses[this.currentResponseNum];){const s=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<s.length;++i)s[i]&&ki(()=>{this.onMessage_(s[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/**
647
647
  * @license
648
648
  * Copyright 2017 Google LLC
649
649
  *
@@ -658,7 +658,7 @@
658
658
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
659
659
  * See the License for the specific language governing permissions and
660
660
  * limitations under the License.
661
- */const bh="start",H2="close",W2="pLPCommand",G2="pRTLPCB",Kf="id",Yf="pw",Xf="ser",j2="cb",q2="seg",z2="ts",K2="d",Y2="dframe",Qf=1870,Jf=30,X2=Qf-Jf,Q2=25e3,J2=3e4;class Yn{constructor(e,n,s,i,r,o,a){this.connId=e,this.repoInfo=n,this.applicationId=s,this.appCheckToken=i,this.authToken=r,this.transportSessionId=o,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Si(e),this.stats_=bc(n),this.urlFn=c=>(this.appCheckToken&&(c[Ia]=this.appCheckToken),zf(n,jf,c))}open(e,n){this.curSegmentNum=0,this.onDisconnect_=n,this.myPacketOrderer=new $2(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(J2)),A2(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Cc((...r)=>{const[o,a,c,l,h]=r;if(this.incrementIncomingBytes_(r),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===bh)this.id=a,this.password=c;else if(o===H2)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...r)=>{const[o,a]=r;this.incrementIncomingBytes_(r),this.myPacketOrderer.handleResponse(o,a)},()=>{this.onClosed_()},this.urlFn);const s={};s[bh]="t",s[Xf]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(s[j2]=this.scriptTagHolder.uniqueCallbackIdentifier),s[Mf]=wc,this.transportSessionId&&(s[Bf]=this.transportSessionId),this.lastSessionId&&(s[Hf]=this.lastSessionId),this.applicationId&&(s[Wf]=this.applicationId),this.appCheckToken&&(s[Ia]=this.appCheckToken),typeof location<"u"&&location.hostname&&$f.test(location.hostname)&&(s[Uf]=Vf);const i=this.urlFn(s);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Yn.forceAllow_=!0}static forceDisallow(){Yn.forceDisallow_=!0}static isAvailable(){return Yn.forceAllow_?!0:!Yn.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!I2()&&!x2()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const n=Ne(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const s=_f(n),i=Lf(s,X2);for(let r=0;r<i.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[r]),this.curSegmentNum++}addDisconnectPingFrame(e,n){this.myDisconnFrame=document.createElement("iframe");const s={};s[Y2]="t",s[Kf]=e,s[Yf]=n,this.myDisconnFrame.src=this.urlFn(s),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const n=Ne(e).length;this.bytesReceived+=n,this.stats_.incrementCounter("bytes_received",n)}}class Cc{constructor(e,n,s,i){this.onDisconnect=s,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=T2(),window[W2+this.uniqueCallbackIdentifier]=e,window[G2+this.uniqueCallbackIdentifier]=n,this.myIFrame=Cc.createIFrame_();let r="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(r='<script>document.domain="'+document.domain+'";<\/script>');const o="<html><body>"+r+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(a){Oe("frame writing exception"),a.stack&&Oe(a.stack),Oe(a)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||Oe("No IE domain setting required")}catch{const s=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+s+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,n){for(this.myID=e,this.myPW=n,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e[Kf]=this.myID,e[Yf]=this.myPW,e[Xf]=this.currentSerial;let n=this.urlFn(e),s="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+Jf+s.length<=Qf;){const o=this.pendingSegs.shift();s=s+"&"+q2+i+"="+o.seg+"&"+z2+i+"="+o.ts+"&"+K2+i+"="+o.d,i++}return n=n+s,this.addLongPollTag_(n,this.currentSerial),!0}else return!1}enqueueSegment(e,n,s){this.pendingSegs.push({seg:e,ts:n,d:s}),this.alive&&this.newRequest_()}addLongPollTag_(e,n){this.outstandingRequests.add(n);const s=()=>{this.outstandingRequests.delete(n),this.newRequest_()},i=setTimeout(s,Math.floor(Q2)),r=()=>{clearTimeout(i),s()};this.addTag(e,r)}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const s=this.myIFrame.doc.createElement("script");s.type="text/javascript",s.async=!0,s.src=e,s.onload=s.onreadystatechange=function(){const i=s.readyState;(!i||i==="loaded"||i==="complete")&&(s.onload=s.onreadystatechange=null,s.parentNode&&s.parentNode.removeChild(s),n())},s.onerror=()=>{Oe("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(s)}catch{}},Math.floor(1))}}/**
661
+ */const bh="start",W2="close",G2="pLPCommand",j2="pRTLPCB",Yf="id",Xf="pw",Qf="ser",q2="cb",z2="seg",K2="ts",Y2="d",X2="dframe",Jf=1870,Zf=30,Q2=Jf-Zf,J2=25e3,Z2=3e4;class Yn{constructor(e,n,s,i,r,o,a){this.connId=e,this.repoInfo=n,this.applicationId=s,this.appCheckToken=i,this.authToken=r,this.transportSessionId=o,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Si(e),this.stats_=bc(n),this.urlFn=c=>(this.appCheckToken&&(c[Ra]=this.appCheckToken),Kf(n,qf,c))}open(e,n){this.curSegmentNum=0,this.onDisconnect_=n,this.myPacketOrderer=new H2(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Z2)),R2(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Cc((...r)=>{const[o,a,c,l,h]=r;if(this.incrementIncomingBytes_(r),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===bh)this.id=a,this.password=c;else if(o===W2)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...r)=>{const[o,a]=r;this.incrementIncomingBytes_(r),this.myPacketOrderer.handleResponse(o,a)},()=>{this.onClosed_()},this.urlFn);const s={};s[bh]="t",s[Qf]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(s[q2]=this.scriptTagHolder.uniqueCallbackIdentifier),s[Bf]=wc,this.transportSessionId&&(s[Uf]=this.transportSessionId),this.lastSessionId&&(s[Wf]=this.lastSessionId),this.applicationId&&(s[Gf]=this.applicationId),this.appCheckToken&&(s[Ra]=this.appCheckToken),typeof location<"u"&&location.hostname&&Hf.test(location.hostname)&&(s[Vf]=$f);const i=this.urlFn(s);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Yn.forceAllow_=!0}static forceDisallow(){Yn.forceDisallow_=!0}static isAvailable(){return Yn.forceAllow_?!0:!Yn.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!x2()&&!N2()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const n=Fe(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const s=yf(n),i=Of(s,Q2);for(let r=0;r<i.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[r]),this.curSegmentNum++}addDisconnectPingFrame(e,n){this.myDisconnFrame=document.createElement("iframe");const s={};s[X2]="t",s[Yf]=e,s[Xf]=n,this.myDisconnFrame.src=this.urlFn(s),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const n=Fe(e).length;this.bytesReceived+=n,this.stats_.incrementCounter("bytes_received",n)}}class Cc{constructor(e,n,s,i){this.onDisconnect=s,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=S2(),window[G2+this.uniqueCallbackIdentifier]=e,window[j2+this.uniqueCallbackIdentifier]=n,this.myIFrame=Cc.createIFrame_();let r="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(r='<script>document.domain="'+document.domain+'";<\/script>');const o="<html><body>"+r+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(a){Oe("frame writing exception"),a.stack&&Oe(a.stack),Oe(a)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||Oe("No IE domain setting required")}catch{const s=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+s+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,n){for(this.myID=e,this.myPW=n,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e[Yf]=this.myID,e[Xf]=this.myPW,e[Qf]=this.currentSerial;let n=this.urlFn(e),s="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+Zf+s.length<=Jf;){const o=this.pendingSegs.shift();s=s+"&"+z2+i+"="+o.seg+"&"+K2+i+"="+o.ts+"&"+Y2+i+"="+o.d,i++}return n=n+s,this.addLongPollTag_(n,this.currentSerial),!0}else return!1}enqueueSegment(e,n,s){this.pendingSegs.push({seg:e,ts:n,d:s}),this.alive&&this.newRequest_()}addLongPollTag_(e,n){this.outstandingRequests.add(n);const s=()=>{this.outstandingRequests.delete(n),this.newRequest_()},i=setTimeout(s,Math.floor(J2)),r=()=>{clearTimeout(i),s()};this.addTag(e,r)}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const s=this.myIFrame.doc.createElement("script");s.type="text/javascript",s.async=!0,s.src=e,s.onload=s.onreadystatechange=function(){const i=s.readyState;(!i||i==="loaded"||i==="complete")&&(s.onload=s.onreadystatechange=null,s.parentNode&&s.parentNode.removeChild(s),n())},s.onerror=()=>{Oe("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(s)}catch{}},Math.floor(1))}}/**
662
662
  * @license
663
663
  * Copyright 2017 Google LLC
664
664
  *
@@ -673,7 +673,7 @@
673
673
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
674
674
  * See the License for the specific language governing permissions and
675
675
  * limitations under the License.
676
- */const Z2=16384,e0=45e3;let Er=null;typeof MozWebSocket<"u"?Er=MozWebSocket:typeof WebSocket<"u"&&(Er=WebSocket);class wt{constructor(e,n,s,i,r,o,a){this.connId=e,this.applicationId=s,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Si(this.connId),this.stats_=bc(n),this.connURL=wt.connectionURL_(n,o,a,i,s),this.nodeAdmin=n.nodeAdmin}static connectionURL_(e,n,s,i,r){const o={};return o[Mf]=wc,typeof location<"u"&&location.hostname&&$f.test(location.hostname)&&(o[Uf]=Vf),n&&(o[Bf]=n),s&&(o[Hf]=s),i&&(o[Ia]=i),r&&(o[Wf]=r),zf(e,Gf,o)}open(e,n){this.onDisconnect=n,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,In.set("previous_websocket_failure",!0);try{let s;Q1(),this.mySock=new Er(this.connURL,[],s)}catch(s){this.log_("Error instantiating WebSocket.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=s=>{this.handleIncomingFrame(s)},this.mySock.onerror=s=>{this.log_("WebSocket error. Closing connection.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){wt.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<"u"&&navigator.userAgent){const n=/Android ([0-9]{0,}\.[0-9]{0,})/,s=navigator.userAgent.match(n);s&&s.length>1&&parseFloat(s[1])<4.4&&(e=!0)}return!e&&Er!==null&&!wt.forceDisallow_}static previouslyFailed(){return In.isInMemoryStorage||In.get("previous_websocket_failure")===!0}markConnectionHealthy(){In.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const n=this.frames.join("");this.frames=null;const s=ai(n);this.onMessage(s)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(b(this.frames===null,"We already have a frame buffer"),e.length<=6){const n=Number(e);if(!isNaN(n))return this.handleNewFrameCount_(n),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;const n=e.data;if(this.bytesReceived+=n.length,this.stats_.incrementCounter("bytes_received",n.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(n);else{const s=this.extractFrameCount_(n);s!==null&&this.appendFrame_(s)}}send(e){this.resetKeepAlive();const n=Ne(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const s=Lf(n,Z2);s.length>1&&this.sendString_(String(s.length));for(let i=0;i<s.length;i++)this.sendString_(s[i])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(e0))}sendString_(e){try{this.mySock.send(e)}catch(n){this.log_("Exception thrown from WebSocket.send():",n.message||n.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}wt.responsesRequiredToBeHealthy=2;wt.healthyTimeout=3e4;/**
676
+ */const e0=16384,t0=45e3;let Er=null;typeof MozWebSocket<"u"?Er=MozWebSocket:typeof WebSocket<"u"&&(Er=WebSocket);class wt{constructor(e,n,s,i,r,o,a){this.connId=e,this.applicationId=s,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Si(this.connId),this.stats_=bc(n),this.connURL=wt.connectionURL_(n,o,a,i,s),this.nodeAdmin=n.nodeAdmin}static connectionURL_(e,n,s,i,r){const o={};return o[Bf]=wc,typeof location<"u"&&location.hostname&&Hf.test(location.hostname)&&(o[Vf]=$f),n&&(o[Uf]=n),s&&(o[Wf]=s),i&&(o[Ra]=i),r&&(o[Gf]=r),Kf(e,jf,o)}open(e,n){this.onDisconnect=n,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,In.set("previous_websocket_failure",!0);try{let s;J1(),this.mySock=new Er(this.connURL,[],s)}catch(s){this.log_("Error instantiating WebSocket.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=s=>{this.handleIncomingFrame(s)},this.mySock.onerror=s=>{this.log_("WebSocket error. Closing connection.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){wt.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<"u"&&navigator.userAgent){const n=/Android ([0-9]{0,}\.[0-9]{0,})/,s=navigator.userAgent.match(n);s&&s.length>1&&parseFloat(s[1])<4.4&&(e=!0)}return!e&&Er!==null&&!wt.forceDisallow_}static previouslyFailed(){return In.isInMemoryStorage||In.get("previous_websocket_failure")===!0}markConnectionHealthy(){In.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const n=this.frames.join("");this.frames=null;const s=ai(n);this.onMessage(s)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(b(this.frames===null,"We already have a frame buffer"),e.length<=6){const n=Number(e);if(!isNaN(n))return this.handleNewFrameCount_(n),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;const n=e.data;if(this.bytesReceived+=n.length,this.stats_.incrementCounter("bytes_received",n.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(n);else{const s=this.extractFrameCount_(n);s!==null&&this.appendFrame_(s)}}send(e){this.resetKeepAlive();const n=Fe(e);this.bytesSent+=n.length,this.stats_.incrementCounter("bytes_sent",n.length);const s=Of(n,e0);s.length>1&&this.sendString_(String(s.length));for(let i=0;i<s.length;i++)this.sendString_(s[i])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(t0))}sendString_(e){try{this.mySock.send(e)}catch(n){this.log_("Exception thrown from WebSocket.send():",n.message||n.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}wt.responsesRequiredToBeHealthy=2;wt.healthyTimeout=3e4;/**
677
677
  * @license
678
678
  * Copyright 2017 Google LLC
679
679
  *
@@ -703,7 +703,7 @@
703
703
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
704
704
  * See the License for the specific language governing permissions and
705
705
  * limitations under the License.
706
- */const t0=6e4,n0=5e3,s0=10*1024,i0=100*1024,qo="t",Ch="d",r0="s",Th="r",o0="e",Sh="o",kh="a",Ah="n",Rh="p",a0="h";class c0{constructor(e,n,s,i,r,o,a,c,l,h){this.id=e,this.repoInfo_=n,this.applicationId_=s,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=o,this.onReady_=a,this.onDisconnect_=c,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Si("c:"+this.id+":"),this.transportManager_=new hi(n),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const n=this.connReceiver_(this.conn_),s=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(n,s)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=ei(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>i0?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>s0?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return n=>{e===this.conn_?this.onConnectionLost_(n):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return n=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(n):e===this.secondaryConn_?this.onSecondaryMessageReceived_(n):this.log_("message on old connection"))}}sendRequest(e){const n={t:"d",d:e};this.sendData_(n)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(qo in e){const n=e[qo];n===kh?this.upgradeIfSecondaryHealthy_():n===Th?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):n===Sh&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const n=Vs("t",e),s=Vs("d",e);if(n==="c")this.onSecondaryControl_(s);else if(n==="d")this.pendingDataMessages.push(s);else throw new Error("Unknown protocol layer: "+n)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:Rh,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:kh,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Ah,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const n=Vs("t",e),s=Vs("d",e);n==="c"?this.onControl_(s):n==="d"&&this.onDataMessage_(s)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const n=Vs(qo,e);if(Ch in e){const s=e[Ch];if(n===a0){const i=Object.assign({},s);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(n===Ah){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else n===r0?this.onConnectionShutdown_(s):n===Th?this.onReset_(s):n===o0?Ra("Server Error: "+s):n===Sh?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Ra("Unknown control packet command: "+n)}}onHandshake_(e){const n=e.ts,s=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,n),wc!==s&&nt("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const n=this.connReceiver_(this.secondaryConn_),s=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,s),ei(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(t0))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,n){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(n,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):ei(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(n0))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:Rh,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(In.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}/**
706
+ */const n0=6e4,s0=5e3,i0=10*1024,r0=100*1024,jo="t",Ch="d",o0="s",Th="r",a0="e",Sh="o",kh="a",Ah="n",Rh="p",c0="h";class l0{constructor(e,n,s,i,r,o,a,c,l,h){this.id=e,this.repoInfo_=n,this.applicationId_=s,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=o,this.onReady_=a,this.onDisconnect_=c,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Si("c:"+this.id+":"),this.transportManager_=new hi(n),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const n=this.connReceiver_(this.conn_),s=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(n,s)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=ei(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>r0?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>i0?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return n=>{e===this.conn_?this.onConnectionLost_(n):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return n=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(n):e===this.secondaryConn_?this.onSecondaryMessageReceived_(n):this.log_("message on old connection"))}}sendRequest(e){const n={t:"d",d:e};this.sendData_(n)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if(jo in e){const n=e[jo];n===kh?this.upgradeIfSecondaryHealthy_():n===Th?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):n===Sh&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const n=Vs("t",e),s=Vs("d",e);if(n==="c")this.onSecondaryControl_(s);else if(n==="d")this.pendingDataMessages.push(s);else throw new Error("Unknown protocol layer: "+n)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:Rh,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:kh,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:Ah,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const n=Vs("t",e),s=Vs("d",e);n==="c"?this.onControl_(s):n==="d"&&this.onDataMessage_(s)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const n=Vs(jo,e);if(Ch in e){const s=e[Ch];if(n===c0){const i=Object.assign({},s);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(n===Ah){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else n===o0?this.onConnectionShutdown_(s):n===Th?this.onReset_(s):n===a0?Aa("Server Error: "+s):n===Sh?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Aa("Unknown control packet command: "+n)}}onHandshake_(e){const n=e.ts,s=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,n),wc!==s&&nt("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const n=this.connReceiver_(this.secondaryConn_),s=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,s),ei(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(n0))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,n){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(n,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):ei(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(s0))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:Rh,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(In.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}/**
707
707
  * @license
708
708
  * Copyright 2017 Google LLC
709
709
  *
@@ -718,7 +718,7 @@
718
718
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
719
719
  * See the License for the specific language governing permissions and
720
720
  * limitations under the License.
721
- */class Zf{put(e,n,s,i){}merge(e,n,s,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,n,s){}onDisconnectMerge(e,n,s){}onDisconnectCancel(e,n){}reportStats(e){}}/**
721
+ */class ep{put(e,n,s,i){}merge(e,n,s,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,n,s){}onDisconnectMerge(e,n,s){}onDisconnectCancel(e,n){}reportStats(e){}}/**
722
722
  * @license
723
723
  * Copyright 2017 Google LLC
724
724
  *
@@ -733,7 +733,7 @@
733
733
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
734
734
  * See the License for the specific language governing permissions and
735
735
  * limitations under the License.
736
- */class ep{constructor(e){this.allowedEvents_=e,this.listeners_={},b(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...n){if(Array.isArray(this.listeners_[e])){const s=[...this.listeners_[e]];for(let i=0;i<s.length;i++)s[i].callback.apply(s[i].context,n)}}on(e,n,s){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:n,context:s});const i=this.getInitialEvent(e);i&&n.apply(s,i)}off(e,n,s){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let r=0;r<i.length;r++)if(i[r].callback===n&&(!s||s===i[r].context)){i.splice(r,1);return}}validateEventType_(e){b(this.allowedEvents_.find(n=>n===e),"Unknown event: "+e)}}/**
736
+ */class tp{constructor(e){this.allowedEvents_=e,this.listeners_={},b(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...n){if(Array.isArray(this.listeners_[e])){const s=[...this.listeners_[e]];for(let i=0;i<s.length;i++)s[i].callback.apply(s[i].context,n)}}on(e,n,s){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:n,context:s});const i=this.getInitialEvent(e);i&&n.apply(s,i)}off(e,n,s){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let r=0;r<i.length;r++)if(i[r].callback===n&&(!s||s===i[r].context)){i.splice(r,1);return}}validateEventType_(e){b(this.allowedEvents_.find(n=>n===e),"Unknown event: "+e)}}/**
737
737
  * @license
738
738
  * Copyright 2017 Google LLC
739
739
  *
@@ -748,7 +748,7 @@
748
748
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
749
749
  * See the License for the specific language governing permissions and
750
750
  * limitations under the License.
751
- */class wr extends ep{static getInstance(){return new wr}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!wf()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return b(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}/**
751
+ */class wr extends tp{static getInstance(){return new wr}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!bf()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return b(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}/**
752
752
  * @license
753
753
  * Copyright 2017 Google LLC
754
754
  *
@@ -763,7 +763,7 @@
763
763
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
764
764
  * See the License for the specific language governing permissions and
765
765
  * limitations under the License.
766
- */const Ih=32,xh=768;class ie{constructor(e,n){if(n===void 0){this.pieces_=e.split("/");let s=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[s]=this.pieces_[i],s++);this.pieces_.length=s,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=n}toString(){let e="";for(let n=this.pieceNum_;n<this.pieces_.length;n++)this.pieces_[n]!==""&&(e+="/"+this.pieces_[n]);return e||"/"}}function J(){return new ie("")}function $(t){return t.pieceNum_>=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function dn(t){return t.pieces_.length-t.pieceNum_}function oe(t){let e=t.pieceNum_;return e<t.pieces_.length&&e++,new ie(t.pieces_,e)}function tp(t){return t.pieceNum_<t.pieces_.length?t.pieces_[t.pieces_.length-1]:null}function l0(t){let e="";for(let n=t.pieceNum_;n<t.pieces_.length;n++)t.pieces_[n]!==""&&(e+="/"+encodeURIComponent(String(t.pieces_[n])));return e||"/"}function np(t,e=0){return t.pieces_.slice(t.pieceNum_+e)}function sp(t){if(t.pieceNum_>=t.pieces_.length)return null;const e=[];for(let n=t.pieceNum_;n<t.pieces_.length-1;n++)e.push(t.pieces_[n]);return new ie(e,0)}function Re(t,e){const n=[];for(let s=t.pieceNum_;s<t.pieces_.length;s++)n.push(t.pieces_[s]);if(e instanceof ie)for(let s=e.pieceNum_;s<e.pieces_.length;s++)n.push(e.pieces_[s]);else{const s=e.split("/");for(let i=0;i<s.length;i++)s[i].length>0&&n.push(s[i])}return new ie(n,0)}function H(t){return t.pieceNum_>=t.pieces_.length}function je(t,e){const n=$(t),s=$(e);if(n===null)return e;if(n===s)return je(oe(t),oe(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+t+")")}function Tc(t,e){if(dn(t)!==dn(e))return!1;for(let n=t.pieceNum_,s=e.pieceNum_;n<=t.pieces_.length;n++,s++)if(t.pieces_[n]!==e.pieces_[s])return!1;return!0}function bt(t,e){let n=t.pieceNum_,s=e.pieceNum_;if(dn(t)>dn(e))return!1;for(;n<t.pieces_.length;){if(t.pieces_[n]!==e.pieces_[s])return!1;++n,++s}return!0}class h0{constructor(e,n){this.errorPrefix_=n,this.parts_=np(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let s=0;s<this.parts_.length;s++)this.byteLength_+=Kr(this.parts_[s]);ip(this)}}function u0(t,e){t.parts_.length>0&&(t.byteLength_+=1),t.parts_.push(e),t.byteLength_+=Kr(e),ip(t)}function d0(t){const e=t.parts_.pop();t.byteLength_-=Kr(e),t.parts_.length>0&&(t.byteLength_-=1)}function ip(t){if(t.byteLength_>xh)throw new Error(t.errorPrefix_+"has a key path longer than "+xh+" bytes ("+t.byteLength_+").");if(t.parts_.length>Ih)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Ih+") or object contains a cycle "+Tn(t))}function Tn(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}/**
766
+ */const Ih=32,xh=768;class ie{constructor(e,n){if(n===void 0){this.pieces_=e.split("/");let s=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[s]=this.pieces_[i],s++);this.pieces_.length=s,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=n}toString(){let e="";for(let n=this.pieceNum_;n<this.pieces_.length;n++)this.pieces_[n]!==""&&(e+="/"+this.pieces_[n]);return e||"/"}}function J(){return new ie("")}function $(t){return t.pieceNum_>=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function dn(t){return t.pieces_.length-t.pieceNum_}function oe(t){let e=t.pieceNum_;return e<t.pieces_.length&&e++,new ie(t.pieces_,e)}function np(t){return t.pieceNum_<t.pieces_.length?t.pieces_[t.pieces_.length-1]:null}function h0(t){let e="";for(let n=t.pieceNum_;n<t.pieces_.length;n++)t.pieces_[n]!==""&&(e+="/"+encodeURIComponent(String(t.pieces_[n])));return e||"/"}function sp(t,e=0){return t.pieces_.slice(t.pieceNum_+e)}function ip(t){if(t.pieceNum_>=t.pieces_.length)return null;const e=[];for(let n=t.pieceNum_;n<t.pieces_.length-1;n++)e.push(t.pieces_[n]);return new ie(e,0)}function Re(t,e){const n=[];for(let s=t.pieceNum_;s<t.pieces_.length;s++)n.push(t.pieces_[s]);if(e instanceof ie)for(let s=e.pieceNum_;s<e.pieces_.length;s++)n.push(e.pieces_[s]);else{const s=e.split("/");for(let i=0;i<s.length;i++)s[i].length>0&&n.push(s[i])}return new ie(n,0)}function H(t){return t.pieceNum_>=t.pieces_.length}function je(t,e){const n=$(t),s=$(e);if(n===null)return e;if(n===s)return je(oe(t),oe(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+t+")")}function Tc(t,e){if(dn(t)!==dn(e))return!1;for(let n=t.pieceNum_,s=e.pieceNum_;n<=t.pieces_.length;n++,s++)if(t.pieces_[n]!==e.pieces_[s])return!1;return!0}function bt(t,e){let n=t.pieceNum_,s=e.pieceNum_;if(dn(t)>dn(e))return!1;for(;n<t.pieces_.length;){if(t.pieces_[n]!==e.pieces_[s])return!1;++n,++s}return!0}class u0{constructor(e,n){this.errorPrefix_=n,this.parts_=sp(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let s=0;s<this.parts_.length;s++)this.byteLength_+=zr(this.parts_[s]);rp(this)}}function d0(t,e){t.parts_.length>0&&(t.byteLength_+=1),t.parts_.push(e),t.byteLength_+=zr(e),rp(t)}function f0(t){const e=t.parts_.pop();t.byteLength_-=zr(e),t.parts_.length>0&&(t.byteLength_-=1)}function rp(t){if(t.byteLength_>xh)throw new Error(t.errorPrefix_+"has a key path longer than "+xh+" bytes ("+t.byteLength_+").");if(t.parts_.length>Ih)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Ih+") or object contains a cycle "+Tn(t))}function Tn(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}/**
767
767
  * @license
768
768
  * Copyright 2017 Google LLC
769
769
  *
@@ -778,7 +778,7 @@
778
778
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
779
779
  * See the License for the specific language governing permissions and
780
780
  * limitations under the License.
781
- */class Sc extends ep{static getInstance(){return new Sc}constructor(){super(["visible"]);let e,n;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(n="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(n="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(n="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(n="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,n&&document.addEventListener(n,()=>{const s=!document[e];s!==this.visible_&&(this.visible_=s,this.trigger("visible",s))},!1)}getInitialEvent(e){return b(e==="visible","Unknown event type: "+e),[this.visible_]}}/**
781
+ */class Sc extends tp{static getInstance(){return new Sc}constructor(){super(["visible"]);let e,n;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(n="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(n="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(n="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(n="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,n&&document.addEventListener(n,()=>{const s=!document[e];s!==this.visible_&&(this.visible_=s,this.trigger("visible",s))},!1)}getInitialEvent(e){return b(e==="visible","Unknown event type: "+e),[this.visible_]}}/**
782
782
  * @license
783
783
  * Copyright 2017 Google LLC
784
784
  *
@@ -793,10 +793,10 @@
793
793
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
794
794
  * See the License for the specific language governing permissions and
795
795
  * limitations under the License.
796
- */const $s=1e3,f0=60*5*1e3,Fh=30*1e3,p0=1.3,m0=3e4,g0="server_kill",Nh=3;class qt extends Zf{constructor(e,n,s,i,r,o,a,c){if(super(),this.repoInfo_=e,this.applicationId_=n,this.onDataUpdate_=s,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=c,this.id=qt.nextPersistentConnectionId_++,this.log_=Si("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=$s,this.maxReconnectDelay_=f0,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,c)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Sc.getInstance().on("visible",this.onVisible_,this),e.host.indexOf("fblocal")===-1&&wr.getInstance().on("online",this.onOnline_,this)}sendRequest(e,n,s){const i=++this.requestNumber_,r={r:i,a:e,b:n};this.log_(Ne(r)),b(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),s&&(this.requestCBHash_[i]=s)}get(e){this.initConnection_();const n=new yc,i={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:o=>{const a=o.d;o.s==="ok"?n.resolve(a):n.reject(a)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),n.promise}listen(e,n,s,i){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),b(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),b(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:i,hashFn:n,query:e,tag:s};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const n=this.outstandingGets_[e];this.sendRequest("g",n.request,s=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(s)})}sendListen_(e){const n=e.query,s=n._path.toString(),i=n._queryIdentifier;this.log_("Listen on "+s+" for "+i);const r={p:s},o="q";e.tag&&(r.q=n._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest(o,r,a=>{const c=a.d,l=a.s;qt.warnOnListenWarnings_(c,n),(this.listens.get(s)&&this.listens.get(s).get(i))===e&&(this.log_("listen response",a),l!=="ok"&&this.removeListen_(s,i),e.onComplete&&e.onComplete(l,c))})}static warnOnListenWarnings_(e,n){if(e&&typeof e=="object"&&Zt(e,"w")){const s=hs(e,"w");if(Array.isArray(s)&&~s.indexOf("no_index")){const i='".indexOn": "'+n._queryParams.getIndex().toString()+'"',r=n._path.toString();nt(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${r} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&e.length===40||i_(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=Fh)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,n=s_(e)?"auth":"gauth",s={cred:e};this.authOverride_===null?s.noauth=!0:typeof this.authOverride_=="object"&&(s.authvar=this.authOverride_),this.sendRequest(n,s,i=>{const r=i.s,o=i.d||"error";this.authToken_===e&&(r==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(r,o))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const n=e.s,s=e.d||"error";n==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(n,s)})}unlisten(e,n){const s=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+s+" "+i),b(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(s,i)&&this.connected_&&this.sendUnlisten_(s,i,e._queryObject,n)}sendUnlisten_(e,n,s,i){this.log_("Unlisten on "+e+" for "+n);const r={p:e},o="n";i&&(r.q=s,r.t=i),this.sendRequest(o,r)}onDisconnectPut(e,n,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,n,s):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:n,onComplete:s})}onDisconnectMerge(e,n,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,n,s):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:n,onComplete:s})}onDisconnectCancel(e,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:n})}sendOnDisconnect_(e,n,s,i){const r={p:n,d:s};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,o=>{i&&setTimeout(()=>{i(o.s,o.d)},Math.floor(0))})}put(e,n,s,i){this.putInternal("p",e,n,s,i)}merge(e,n,s,i){this.putInternal("m",e,n,s,i)}putInternal(e,n,s,i,r){this.initConnection_();const o={p:n,d:s};r!==void 0&&(o.h=r),this.outstandingPuts_.push({action:e,request:o,onComplete:i}),this.outstandingPutCount_++;const a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+n)}sendPut_(e){const n=this.outstandingPuts_[e].action,s=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(n,s,r=>{this.log_(n+" response",r),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(r.s,r.d)})}reportStats(e){if(this.connected_){const n={c:e};this.log_("reportStats",n),this.sendRequest("s",n,s=>{if(s.s!=="ok"){const r=s.d;this.log_("reportStats","Error sending stats: "+r)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+Ne(e));const n=e.r,s=this.requestCBHash_[n];s&&(delete this.requestCBHash_[n],s(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,n){this.log_("handleServerMessage",e,n),e==="d"?this.onDataUpdate_(n.p,n.d,!1,n.t):e==="m"?this.onDataUpdate_(n.p,n.d,!0,n.t):e==="c"?this.onListenRevoked_(n.p,n.q):e==="ac"?this.onAuthRevoked_(n.s,n.d):e==="apc"?this.onAppCheckRevoked_(n.s,n.d):e==="sd"?this.onSecurityDebugPacket_(n):Ra("Unrecognized action received from server: "+Ne(e)+`
797
- Are you using the latest client?`)}onReady_(e,n){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=n,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){b(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=$s,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=$s,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>m0&&(this.reconnectDelay_=$s),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const e=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_);let n=Math.max(0,this.reconnectDelay_-e);n=Math.random()*n,this.log_("Trying to reconnect in "+n+"ms"),this.scheduleConnect_(n),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*p0)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),s=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+qt.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,s())},l=function(u){b(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(u)};this.realtime_={close:c,sendRequest:l};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[u,d]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?Oe("getToken() completed but was canceled"):(Oe("getToken() completed. Creating connection."),this.authToken_=u&&u.accessToken,this.appCheckToken_=d&&d.token,a=new c0(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,n,s,p=>{nt(p+" ("+this.repoInfo_.toString()+")"),this.interrupt(g0)},r))}catch(u){this.log_("Failed to get token: "+u),o||(this.repoInfo_.nodeAdmin&&nt(u),c())}}}interrupt(e){Oe("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){Oe("Resuming connection for reason: "+e),delete this.interruptReasons_[e],ch(this.interruptReasons_)&&(this.reconnectDelay_=$s,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const n=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:n})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const n=this.outstandingPuts_[e];n&&"h"in n.request&&n.queued&&(n.onComplete&&n.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(e,n){let s;n?s=n.map(r=>Ec(r)).join("$"):s="default";const i=this.removeListen_(e,s);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,n){const s=new ie(e).toString();let i;if(this.listens.has(s)){const r=this.listens.get(s);i=r.get(n),r.delete(n),r.size===0&&this.listens.delete(s)}else i=void 0;return i}onAuthRevoked_(e,n){Oe("Auth token revoked: "+e+"/"+n),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e==="invalid_token"||e==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Nh&&(this.reconnectDelay_=Fh,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,n){Oe("App check token revoked: "+e+"/"+n),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e==="invalid_token"||e==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Nh&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(`
796
+ */const $s=1e3,p0=60*5*1e3,Nh=30*1e3,m0=1.3,g0=3e4,_0="server_kill",Fh=3;class qt extends ep{constructor(e,n,s,i,r,o,a,c){if(super(),this.repoInfo_=e,this.applicationId_=n,this.onDataUpdate_=s,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=c,this.id=qt.nextPersistentConnectionId_++,this.log_=Si("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=$s,this.maxReconnectDelay_=p0,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,c)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Sc.getInstance().on("visible",this.onVisible_,this),e.host.indexOf("fblocal")===-1&&wr.getInstance().on("online",this.onOnline_,this)}sendRequest(e,n,s){const i=++this.requestNumber_,r={r:i,a:e,b:n};this.log_(Fe(r)),b(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),s&&(this.requestCBHash_[i]=s)}get(e){this.initConnection_();const n=new yc,i={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:o=>{const a=o.d;o.s==="ok"?n.resolve(a):n.reject(a)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),n.promise}listen(e,n,s,i){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),b(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),b(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:i,hashFn:n,query:e,tag:s};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const n=this.outstandingGets_[e];this.sendRequest("g",n.request,s=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(s)})}sendListen_(e){const n=e.query,s=n._path.toString(),i=n._queryIdentifier;this.log_("Listen on "+s+" for "+i);const r={p:s},o="q";e.tag&&(r.q=n._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest(o,r,a=>{const c=a.d,l=a.s;qt.warnOnListenWarnings_(c,n),(this.listens.get(s)&&this.listens.get(s).get(i))===e&&(this.log_("listen response",a),l!=="ok"&&this.removeListen_(s,i),e.onComplete&&e.onComplete(l,c))})}static warnOnListenWarnings_(e,n){if(e&&typeof e=="object"&&Zt(e,"w")){const s=hs(e,"w");if(Array.isArray(s)&&~s.indexOf("no_index")){const i='".indexOn": "'+n._queryParams.getIndex().toString()+'"',r=n._path.toString();nt(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${r} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&e.length===40||r_(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=Nh)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,n=i_(e)?"auth":"gauth",s={cred:e};this.authOverride_===null?s.noauth=!0:typeof this.authOverride_=="object"&&(s.authvar=this.authOverride_),this.sendRequest(n,s,i=>{const r=i.s,o=i.d||"error";this.authToken_===e&&(r==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(r,o))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const n=e.s,s=e.d||"error";n==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(n,s)})}unlisten(e,n){const s=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+s+" "+i),b(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(s,i)&&this.connected_&&this.sendUnlisten_(s,i,e._queryObject,n)}sendUnlisten_(e,n,s,i){this.log_("Unlisten on "+e+" for "+n);const r={p:e},o="n";i&&(r.q=s,r.t=i),this.sendRequest(o,r)}onDisconnectPut(e,n,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,n,s):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:n,onComplete:s})}onDisconnectMerge(e,n,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,n,s):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:n,onComplete:s})}onDisconnectCancel(e,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:n})}sendOnDisconnect_(e,n,s,i){const r={p:n,d:s};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,o=>{i&&setTimeout(()=>{i(o.s,o.d)},Math.floor(0))})}put(e,n,s,i){this.putInternal("p",e,n,s,i)}merge(e,n,s,i){this.putInternal("m",e,n,s,i)}putInternal(e,n,s,i,r){this.initConnection_();const o={p:n,d:s};r!==void 0&&(o.h=r),this.outstandingPuts_.push({action:e,request:o,onComplete:i}),this.outstandingPutCount_++;const a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+n)}sendPut_(e){const n=this.outstandingPuts_[e].action,s=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(n,s,r=>{this.log_(n+" response",r),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(r.s,r.d)})}reportStats(e){if(this.connected_){const n={c:e};this.log_("reportStats",n),this.sendRequest("s",n,s=>{if(s.s!=="ok"){const r=s.d;this.log_("reportStats","Error sending stats: "+r)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+Fe(e));const n=e.r,s=this.requestCBHash_[n];s&&(delete this.requestCBHash_[n],s(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,n){this.log_("handleServerMessage",e,n),e==="d"?this.onDataUpdate_(n.p,n.d,!1,n.t):e==="m"?this.onDataUpdate_(n.p,n.d,!0,n.t):e==="c"?this.onListenRevoked_(n.p,n.q):e==="ac"?this.onAuthRevoked_(n.s,n.d):e==="apc"?this.onAppCheckRevoked_(n.s,n.d):e==="sd"?this.onSecurityDebugPacket_(n):Aa("Unrecognized action received from server: "+Fe(e)+`
797
+ Are you using the latest client?`)}onReady_(e,n){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=n,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){b(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=$s,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=$s,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>g0&&(this.reconnectDelay_=$s),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const e=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_);let n=Math.max(0,this.reconnectDelay_-e);n=Math.random()*n,this.log_("Trying to reconnect in "+n+"ms"),this.scheduleConnect_(n),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*m0)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),s=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+qt.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,s())},l=function(u){b(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(u)};this.realtime_={close:c,sendRequest:l};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[u,d]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?Oe("getToken() completed but was canceled"):(Oe("getToken() completed. Creating connection."),this.authToken_=u&&u.accessToken,this.appCheckToken_=d&&d.token,a=new l0(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,n,s,p=>{nt(p+" ("+this.repoInfo_.toString()+")"),this.interrupt(_0)},r))}catch(u){this.log_("Failed to get token: "+u),o||(this.repoInfo_.nodeAdmin&&nt(u),c())}}}interrupt(e){Oe("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){Oe("Resuming connection for reason: "+e),delete this.interruptReasons_[e],ch(this.interruptReasons_)&&(this.reconnectDelay_=$s,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const n=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:n})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const n=this.outstandingPuts_[e];n&&"h"in n.request&&n.queued&&(n.onComplete&&n.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(e,n){let s;n?s=n.map(r=>Ec(r)).join("$"):s="default";const i=this.removeListen_(e,s);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,n){const s=new ie(e).toString();let i;if(this.listens.has(s)){const r=this.listens.get(s);i=r.get(n),r.delete(n),r.size===0&&this.listens.delete(s)}else i=void 0;return i}onAuthRevoked_(e,n){Oe("Auth token revoked: "+e+"/"+n),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e==="invalid_token"||e==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Fh&&(this.reconnectDelay_=Nh,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,n){Oe("App check token revoked: "+e+"/"+n),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e==="invalid_token"||e==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Fh&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(`
798
798
  `,`
799
- FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const n of e.values())this.sendListen_(n);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let n="js";e["sdk."+n+"."+Ff.replace(/\./g,"-")]=1,wf()?e["framework.cordova"]=1:X1()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=wr.getInstance().currentlyOnline();return ch(this.interruptReasons_)&&e}}qt.nextPersistentConnectionId_=0;qt.nextConnectionId_=0;/**
799
+ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const n of e.values())this.sendListen_(n);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let n="js";e["sdk."+n+"."+Ff.replace(/\./g,"-")]=1,bf()?e["framework.cordova"]=1:Q1()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=wr.getInstance().currentlyOnline();return ch(this.interruptReasons_)&&e}}qt.nextPersistentConnectionId_=0;qt.nextConnectionId_=0;/**
800
800
  * @license
801
801
  * Copyright 2017 Google LLC
802
802
  *
@@ -826,7 +826,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
826
826
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
827
827
  * See the License for the specific language governing permissions and
828
828
  * limitations under the License.
829
- */class Xr{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,n){const s=new B(us,e),i=new B(us,n);return this.compare(s,i)!==0}minPost(){return B.MIN}}/**
829
+ */class Yr{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,n){const s=new B(us,e),i=new B(us,n);return this.compare(s,i)!==0}minPost(){return B.MIN}}/**
830
830
  * @license
831
831
  * Copyright 2017 Google LLC
832
832
  *
@@ -841,7 +841,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
841
841
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
842
842
  * See the License for the specific language governing permissions and
843
843
  * limitations under the License.
844
- */let Vi;class rp extends Xr{static get __EMPTY_NODE(){return Vi}static set __EMPTY_NODE(e){Vi=e}compare(e,n){return Ss(e.name,n.name)}isDefinedOn(e){throw Ts("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,n){return!1}minPost(){return B.MIN}maxPost(){return new B(Ln,Vi)}makePost(e,n){return b(typeof e=="string","KeyIndex indexValue must always be a string."),new B(e,Vi)}toString(){return".key"}}const ns=new rp;/**
844
+ */let Vi;class op extends Yr{static get __EMPTY_NODE(){return Vi}static set __EMPTY_NODE(e){Vi=e}compare(e,n){return Ss(e.name,n.name)}isDefinedOn(e){throw Ts("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,n){return!1}minPost(){return B.MIN}maxPost(){return new B(Ln,Vi)}makePost(e,n){return b(typeof e=="string","KeyIndex indexValue must always be a string."),new B(e,Vi)}toString(){return".key"}}const ns=new op;/**
845
845
  * @license
846
846
  * Copyright 2017 Google LLC
847
847
  *
@@ -856,7 +856,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
856
856
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
857
857
  * See the License for the specific language governing permissions and
858
858
  * limitations under the License.
859
- */class $i{constructor(e,n,s,i,r=null){this.isReverse_=i,this.resultGenerator_=r,this.nodeStack_=[];let o=1;for(;!e.isEmpty();)if(e=e,o=n?s(e.key,n):1,i&&(o*=-1),o<0)this.isReverse_?e=e.left:e=e.right;else if(o===0){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),this.isReverse_?e=e.right:e=e.left}getNext(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_.pop(),n;if(this.resultGenerator_?n=this.resultGenerator_(e.key,e.value):n={key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return n}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Fe{constructor(e,n,s,i,r){this.key=e,this.value=n,this.color=s??Fe.RED,this.left=i??qe.EMPTY_NODE,this.right=r??qe.EMPTY_NODE}copy(e,n,s,i,r){return new Fe(e??this.key,n??this.value,s??this.color,i??this.left,r??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,n,s){let i=this;const r=s(e,i.key);return r<0?i=i.copy(null,null,null,i.left.insert(e,n,s),null):r===0?i=i.copy(null,n,null,null,null):i=i.copy(null,null,null,null,i.right.insert(e,n,s)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return qe.EMPTY_NODE;let e=this;return!e.left.isRed_()&&!e.left.left.isRed_()&&(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,n){let s,i;if(s=this,n(e,s.key)<0)!s.left.isEmpty()&&!s.left.isRed_()&&!s.left.left.isRed_()&&(s=s.moveRedLeft_()),s=s.copy(null,null,null,s.left.remove(e,n),null);else{if(s.left.isRed_()&&(s=s.rotateRight_()),!s.right.isEmpty()&&!s.right.isRed_()&&!s.right.left.isRed_()&&(s=s.moveRedRight_()),n(e,s.key)===0){if(s.right.isEmpty())return qe.EMPTY_NODE;i=s.right.min_(),s=s.copy(i.key,i.value,null,null,s.right.removeMin_())}s=s.copy(null,null,null,null,s.right.remove(e,n))}return s.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,Fe.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,Fe.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),n=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,n)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Fe.RED=!0;Fe.BLACK=!1;class _0{copy(e,n,s,i,r){return this}insert(e,n,s){return new Fe(e,n,null)}remove(e,n){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}}class qe{constructor(e,n=qe.EMPTY_NODE){this.comparator_=e,this.root_=n}insert(e,n){return new qe(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,Fe.BLACK,null,null))}remove(e){return new qe(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Fe.BLACK,null,null))}get(e){let n,s=this.root_;for(;!s.isEmpty();){if(n=this.comparator_(e,s.key),n===0)return s.value;n<0?s=s.left:n>0&&(s=s.right)}return null}getPredecessorKey(e){let n,s=this.root_,i=null;for(;!s.isEmpty();)if(n=this.comparator_(e,s.key),n===0){if(s.left.isEmpty())return i?i.key:null;for(s=s.left;!s.right.isEmpty();)s=s.right;return s.key}else n<0?s=s.left:n>0&&(i=s,s=s.right);throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new $i(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,n){return new $i(this.root_,e,this.comparator_,!1,n)}getReverseIteratorFrom(e,n){return new $i(this.root_,e,this.comparator_,!0,n)}getReverseIterator(e){return new $i(this.root_,null,this.comparator_,!0,e)}}qe.EMPTY_NODE=new _0;/**
859
+ */class $i{constructor(e,n,s,i,r=null){this.isReverse_=i,this.resultGenerator_=r,this.nodeStack_=[];let o=1;for(;!e.isEmpty();)if(e=e,o=n?s(e.key,n):1,i&&(o*=-1),o<0)this.isReverse_?e=e.left:e=e.right;else if(o===0){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),this.isReverse_?e=e.right:e=e.left}getNext(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_.pop(),n;if(this.resultGenerator_?n=this.resultGenerator_(e.key,e.value):n={key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return n}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Ne{constructor(e,n,s,i,r){this.key=e,this.value=n,this.color=s??Ne.RED,this.left=i??qe.EMPTY_NODE,this.right=r??qe.EMPTY_NODE}copy(e,n,s,i,r){return new Ne(e??this.key,n??this.value,s??this.color,i??this.left,r??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,n,s){let i=this;const r=s(e,i.key);return r<0?i=i.copy(null,null,null,i.left.insert(e,n,s),null):r===0?i=i.copy(null,n,null,null,null):i=i.copy(null,null,null,null,i.right.insert(e,n,s)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return qe.EMPTY_NODE;let e=this;return!e.left.isRed_()&&!e.left.left.isRed_()&&(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,n){let s,i;if(s=this,n(e,s.key)<0)!s.left.isEmpty()&&!s.left.isRed_()&&!s.left.left.isRed_()&&(s=s.moveRedLeft_()),s=s.copy(null,null,null,s.left.remove(e,n),null);else{if(s.left.isRed_()&&(s=s.rotateRight_()),!s.right.isEmpty()&&!s.right.isRed_()&&!s.right.left.isRed_()&&(s=s.moveRedRight_()),n(e,s.key)===0){if(s.right.isEmpty())return qe.EMPTY_NODE;i=s.right.min_(),s=s.copy(i.key,i.value,null,null,s.right.removeMin_())}s=s.copy(null,null,null,null,s.right.remove(e,n))}return s.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,Ne.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,Ne.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),n=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,n)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Ne.RED=!0;Ne.BLACK=!1;class y0{copy(e,n,s,i,r){return this}insert(e,n,s){return new Ne(e,n,null)}remove(e,n){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}}class qe{constructor(e,n=qe.EMPTY_NODE){this.comparator_=e,this.root_=n}insert(e,n){return new qe(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,Ne.BLACK,null,null))}remove(e){return new qe(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Ne.BLACK,null,null))}get(e){let n,s=this.root_;for(;!s.isEmpty();){if(n=this.comparator_(e,s.key),n===0)return s.value;n<0?s=s.left:n>0&&(s=s.right)}return null}getPredecessorKey(e){let n,s=this.root_,i=null;for(;!s.isEmpty();)if(n=this.comparator_(e,s.key),n===0){if(s.left.isEmpty())return i?i.key:null;for(s=s.left;!s.right.isEmpty();)s=s.right;return s.key}else n<0?s=s.left:n>0&&(i=s,s=s.right);throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new $i(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,n){return new $i(this.root_,e,this.comparator_,!1,n)}getReverseIteratorFrom(e,n){return new $i(this.root_,e,this.comparator_,!0,n)}getReverseIterator(e){return new $i(this.root_,null,this.comparator_,!0,e)}}qe.EMPTY_NODE=new y0;/**
860
860
  * @license
861
861
  * Copyright 2017 Google LLC
862
862
  *
@@ -871,7 +871,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
871
871
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
872
872
  * See the License for the specific language governing permissions and
873
873
  * limitations under the License.
874
- */function y0(t,e){return Ss(t.name,e.name)}function kc(t,e){return Ss(t,e)}/**
874
+ */function v0(t,e){return Ss(t.name,e.name)}function kc(t,e){return Ss(t,e)}/**
875
875
  * @license
876
876
  * Copyright 2017 Google LLC
877
877
  *
@@ -886,7 +886,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
886
886
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
887
887
  * See the License for the specific language governing permissions and
888
888
  * limitations under the License.
889
- */let xa;function v0(t){xa=t}const op=function(t){return typeof t=="number"?"number:"+Of(t):"string:"+t},ap=function(t){if(t.isLeafNode()){const e=t.val();b(typeof e=="string"||typeof e=="number"||typeof e=="object"&&Zt(e,".sv"),"Priority must be a string or number.")}else b(t===xa||t.isEmpty(),"priority of unexpected type.");b(t===xa||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};/**
889
+ */let Ia;function E0(t){Ia=t}const ap=function(t){return typeof t=="number"?"number:"+Mf(t):"string:"+t},cp=function(t){if(t.isLeafNode()){const e=t.val();b(typeof e=="string"||typeof e=="number"||typeof e=="object"&&Zt(e,".sv"),"Priority must be a string or number.")}else b(t===Ia||t.isEmpty(),"priority of unexpected type.");b(t===Ia||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};/**
890
890
  * @license
891
891
  * Copyright 2017 Google LLC
892
892
  *
@@ -901,7 +901,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
901
901
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
902
902
  * See the License for the specific language governing permissions and
903
903
  * limitations under the License.
904
- */let Dh;class xe{static set __childrenNodeConstructor(e){Dh=e}static get __childrenNodeConstructor(){return Dh}constructor(e,n=xe.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=n,this.lazyHash_=null,b(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),ap(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new xe(this.value_,e)}getImmediateChild(e){return e===".priority"?this.priorityNode_:xe.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return H(e)?this:$(e)===".priority"?this.priorityNode_:xe.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,n){return null}updateImmediateChild(e,n){return e===".priority"?this.updatePriority(n):n.isEmpty()&&e!==".priority"?this:xe.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)}updateChild(e,n){const s=$(e);return s===null?n:n.isEmpty()&&s!==".priority"?this:(b(s!==".priority"||dn(e)===1,".priority must be the last token in a path"),this.updateImmediateChild(s,xe.__childrenNodeConstructor.EMPTY_NODE.updateChild(oe(e),n)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,n){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+op(this.priorityNode_.val())+":");const n=typeof this.value_;e+=n+":",n==="number"?e+=Of(this.value_):e+=this.value_,this.lazyHash_=Df(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===xe.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof xe.__childrenNodeConstructor?-1:(b(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const n=typeof e.value_,s=typeof this.value_,i=xe.VALUE_TYPE_ORDER.indexOf(n),r=xe.VALUE_TYPE_ORDER.indexOf(s);return b(i>=0,"Unknown leaf type: "+n),b(r>=0,"Unknown leaf type: "+s),i===r?s==="object"?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const n=e;return this.value_===n.value_&&this.priorityNode_.equals(n.priorityNode_)}else return!1}}xe.VALUE_TYPE_ORDER=["object","boolean","number","string"];/**
904
+ */let Dh;class xe{static set __childrenNodeConstructor(e){Dh=e}static get __childrenNodeConstructor(){return Dh}constructor(e,n=xe.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=n,this.lazyHash_=null,b(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),cp(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new xe(this.value_,e)}getImmediateChild(e){return e===".priority"?this.priorityNode_:xe.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return H(e)?this:$(e)===".priority"?this.priorityNode_:xe.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,n){return null}updateImmediateChild(e,n){return e===".priority"?this.updatePriority(n):n.isEmpty()&&e!==".priority"?this:xe.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)}updateChild(e,n){const s=$(e);return s===null?n:n.isEmpty()&&s!==".priority"?this:(b(s!==".priority"||dn(e)===1,".priority must be the last token in a path"),this.updateImmediateChild(s,xe.__childrenNodeConstructor.EMPTY_NODE.updateChild(oe(e),n)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,n){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+ap(this.priorityNode_.val())+":");const n=typeof this.value_;e+=n+":",n==="number"?e+=Mf(this.value_):e+=this.value_,this.lazyHash_=Pf(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===xe.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof xe.__childrenNodeConstructor?-1:(b(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const n=typeof e.value_,s=typeof this.value_,i=xe.VALUE_TYPE_ORDER.indexOf(n),r=xe.VALUE_TYPE_ORDER.indexOf(s);return b(i>=0,"Unknown leaf type: "+n),b(r>=0,"Unknown leaf type: "+s),i===r?s==="object"?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const n=e;return this.value_===n.value_&&this.priorityNode_.equals(n.priorityNode_)}else return!1}}xe.VALUE_TYPE_ORDER=["object","boolean","number","string"];/**
905
905
  * @license
906
906
  * Copyright 2017 Google LLC
907
907
  *
@@ -916,7 +916,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
916
916
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
917
917
  * See the License for the specific language governing permissions and
918
918
  * limitations under the License.
919
- */let cp,lp;function E0(t){cp=t}function w0(t){lp=t}class b0 extends Xr{compare(e,n){const s=e.node.getPriority(),i=n.node.getPriority(),r=s.compareTo(i);return r===0?Ss(e.name,n.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,n){return!e.getPriority().equals(n.getPriority())}minPost(){return B.MIN}maxPost(){return new B(Ln,new xe("[PRIORITY-POST]",lp))}makePost(e,n){const s=cp(e);return new B(n,new xe("[PRIORITY-POST]",s))}toString(){return".priority"}}const ye=new b0;/**
919
+ */let lp,hp;function w0(t){lp=t}function b0(t){hp=t}class C0 extends Yr{compare(e,n){const s=e.node.getPriority(),i=n.node.getPriority(),r=s.compareTo(i);return r===0?Ss(e.name,n.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,n){return!e.getPriority().equals(n.getPriority())}minPost(){return B.MIN}maxPost(){return new B(Ln,new xe("[PRIORITY-POST]",hp))}makePost(e,n){const s=lp(e);return new B(n,new xe("[PRIORITY-POST]",s))}toString(){return".priority"}}const ye=new C0;/**
920
920
  * @license
921
921
  * Copyright 2017 Google LLC
922
922
  *
@@ -931,7 +931,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
931
931
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
932
932
  * See the License for the specific language governing permissions and
933
933
  * limitations under the License.
934
- */const C0=Math.log(2);class T0{constructor(e){const n=r=>parseInt(Math.log(r)/C0,10),s=r=>parseInt(Array(r+1).join("1"),2);this.count=n(e+1),this.current_=this.count-1;const i=s(this.count);this.bits_=e+1&i}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const br=function(t,e,n,s){t.sort(e);const i=function(c,l){const h=l-c;let u,d;if(h===0)return null;if(h===1)return u=t[c],d=n?n(u):u,new Fe(d,u.node,Fe.BLACK,null,null);{const p=parseInt(h/2,10)+c,m=i(c,p),y=i(p+1,l);return u=t[p],d=n?n(u):u,new Fe(d,u.node,Fe.BLACK,m,y)}},r=function(c){let l=null,h=null,u=t.length;const d=function(m,y){const w=u-m,k=u;u-=m;const E=i(w+1,k),T=t[w],P=n?n(T):T;p(new Fe(P,T.node,y,null,E))},p=function(m){l?(l.left=m,l=m):(h=m,l=m)};for(let m=0;m<c.count;++m){const y=c.nextBitIsOne(),w=Math.pow(2,c.count-(m+1));y?d(w,Fe.BLACK):(d(w,Fe.BLACK),d(w,Fe.RED))}return h},o=new T0(t.length),a=r(o);return new qe(s||e,a)};/**
934
+ */const T0=Math.log(2);class S0{constructor(e){const n=r=>parseInt(Math.log(r)/T0,10),s=r=>parseInt(Array(r+1).join("1"),2);this.count=n(e+1),this.current_=this.count-1;const i=s(this.count);this.bits_=e+1&i}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const br=function(t,e,n,s){t.sort(e);const i=function(c,l){const h=l-c;let u,d;if(h===0)return null;if(h===1)return u=t[c],d=n?n(u):u,new Ne(d,u.node,Ne.BLACK,null,null);{const p=parseInt(h/2,10)+c,m=i(c,p),y=i(p+1,l);return u=t[p],d=n?n(u):u,new Ne(d,u.node,Ne.BLACK,m,y)}},r=function(c){let l=null,h=null,u=t.length;const d=function(m,y){const w=u-m,k=u;u-=m;const E=i(w+1,k),T=t[w],P=n?n(T):T;p(new Ne(P,T.node,y,null,E))},p=function(m){l?(l.left=m,l=m):(h=m,l=m)};for(let m=0;m<c.count;++m){const y=c.nextBitIsOne(),w=Math.pow(2,c.count-(m+1));y?d(w,Ne.BLACK):(d(w,Ne.BLACK),d(w,Ne.RED))}return h},o=new S0(t.length),a=r(o);return new qe(s||e,a)};/**
935
935
  * @license
936
936
  * Copyright 2017 Google LLC
937
937
  *
@@ -946,7 +946,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
946
946
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
947
947
  * See the License for the specific language governing permissions and
948
948
  * limitations under the License.
949
- */let zo;const qn={};class Gt{static get Default(){return b(qn&&ye,"ChildrenNode.ts has not been loaded"),zo=zo||new Gt({".priority":qn},{".priority":ye}),zo}constructor(e,n){this.indexes_=e,this.indexSet_=n}get(e){const n=hs(this.indexes_,e);if(!n)throw new Error("No index defined for "+e);return n instanceof qe?n:null}hasIndex(e){return Zt(this.indexSet_,e.toString())}addIndex(e,n){b(e!==ns,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const s=[];let i=!1;const r=n.getIterator(B.Wrap);let o=r.getNext();for(;o;)i=i||e.isDefinedOn(o.node),s.push(o),o=r.getNext();let a;i?a=br(s,e.getCompare()):a=qn;const c=e.toString(),l=Object.assign({},this.indexSet_);l[c]=e;const h=Object.assign({},this.indexes_);return h[c]=a,new Gt(h,l)}addToIndexes(e,n){const s=gr(this.indexes_,(i,r)=>{const o=hs(this.indexSet_,r);if(b(o,"Missing index implementation for "+r),i===qn)if(o.isDefinedOn(e.node)){const a=[],c=n.getIterator(B.Wrap);let l=c.getNext();for(;l;)l.name!==e.name&&a.push(l),l=c.getNext();return a.push(e),br(a,o.getCompare())}else return qn;else{const a=n.get(e.name);let c=i;return a&&(c=c.remove(new B(e.name,a))),c.insert(e,e.node)}});return new Gt(s,this.indexSet_)}removeFromIndexes(e,n){const s=gr(this.indexes_,i=>{if(i===qn)return i;{const r=n.get(e.name);return r?i.remove(new B(e.name,r)):i}});return new Gt(s,this.indexSet_)}}/**
949
+ */let qo;const qn={};class Gt{static get Default(){return b(qn&&ye,"ChildrenNode.ts has not been loaded"),qo=qo||new Gt({".priority":qn},{".priority":ye}),qo}constructor(e,n){this.indexes_=e,this.indexSet_=n}get(e){const n=hs(this.indexes_,e);if(!n)throw new Error("No index defined for "+e);return n instanceof qe?n:null}hasIndex(e){return Zt(this.indexSet_,e.toString())}addIndex(e,n){b(e!==ns,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const s=[];let i=!1;const r=n.getIterator(B.Wrap);let o=r.getNext();for(;o;)i=i||e.isDefinedOn(o.node),s.push(o),o=r.getNext();let a;i?a=br(s,e.getCompare()):a=qn;const c=e.toString(),l=Object.assign({},this.indexSet_);l[c]=e;const h=Object.assign({},this.indexes_);return h[c]=a,new Gt(h,l)}addToIndexes(e,n){const s=gr(this.indexes_,(i,r)=>{const o=hs(this.indexSet_,r);if(b(o,"Missing index implementation for "+r),i===qn)if(o.isDefinedOn(e.node)){const a=[],c=n.getIterator(B.Wrap);let l=c.getNext();for(;l;)l.name!==e.name&&a.push(l),l=c.getNext();return a.push(e),br(a,o.getCompare())}else return qn;else{const a=n.get(e.name);let c=i;return a&&(c=c.remove(new B(e.name,a))),c.insert(e,e.node)}});return new Gt(s,this.indexSet_)}removeFromIndexes(e,n){const s=gr(this.indexes_,i=>{if(i===qn)return i;{const r=n.get(e.name);return r?i.remove(new B(e.name,r)):i}});return new Gt(s,this.indexSet_)}}/**
950
950
  * @license
951
951
  * Copyright 2017 Google LLC
952
952
  *
@@ -961,7 +961,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
961
961
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
962
962
  * See the License for the specific language governing permissions and
963
963
  * limitations under the License.
964
- */let Hs;class L{static get EMPTY_NODE(){return Hs||(Hs=new L(new qe(kc),null,Gt.Default))}constructor(e,n,s){this.children_=e,this.priorityNode_=n,this.indexMap_=s,this.lazyHash_=null,this.priorityNode_&&ap(this.priorityNode_),this.children_.isEmpty()&&b(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Hs}updatePriority(e){return this.children_.isEmpty()?this:new L(this.children_,e,this.indexMap_)}getImmediateChild(e){if(e===".priority")return this.getPriority();{const n=this.children_.get(e);return n===null?Hs:n}}getChild(e){const n=$(e);return n===null?this:this.getImmediateChild(n).getChild(oe(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,n){if(b(n,"We should always be passing snapshot nodes"),e===".priority")return this.updatePriority(n);{const s=new B(e,n);let i,r;n.isEmpty()?(i=this.children_.remove(e),r=this.indexMap_.removeFromIndexes(s,this.children_)):(i=this.children_.insert(e,n),r=this.indexMap_.addToIndexes(s,this.children_));const o=i.isEmpty()?Hs:this.priorityNode_;return new L(i,o,r)}}updateChild(e,n){const s=$(e);if(s===null)return n;{b($(e)!==".priority"||dn(e)===1,".priority must be the last token in a path");const i=this.getImmediateChild(s).updateChild(oe(e),n);return this.updateImmediateChild(s,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const n={};let s=0,i=0,r=!0;if(this.forEachChild(ye,(o,a)=>{n[o]=a.val(e),s++,r&&L.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):r=!1}),!e&&r&&i<2*s){const o=[];for(const a in n)o[a]=n[a];return o}else return e&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n}hash(){if(this.lazyHash_===null){let e="";this.getPriority().isEmpty()||(e+="priority:"+op(this.getPriority().val())+":"),this.forEachChild(ye,(n,s)=>{const i=s.hash();i!==""&&(e+=":"+n+":"+i)}),this.lazyHash_=e===""?"":Df(e)}return this.lazyHash_}getPredecessorChildName(e,n,s){const i=this.resolveIndex_(s);if(i){const r=i.getPredecessorKey(new B(e,n));return r?r.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){const n=this.resolveIndex_(e);if(n){const s=n.minKey();return s&&s.name}else return this.children_.minKey()}getFirstChild(e){const n=this.getFirstChildName(e);return n?new B(n,this.children_.get(n)):null}getLastChildName(e){const n=this.resolveIndex_(e);if(n){const s=n.maxKey();return s&&s.name}else return this.children_.maxKey()}getLastChild(e){const n=this.getLastChildName(e);return n?new B(n,this.children_.get(n)):null}forEachChild(e,n){const s=this.resolveIndex_(e);return s?s.inorderTraversal(i=>n(i.name,i.node)):this.children_.inorderTraversal(n)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,n){const s=this.resolveIndex_(n);if(s)return s.getIteratorFrom(e,i=>i);{const i=this.children_.getIteratorFrom(e.name,B.Wrap);let r=i.peek();for(;r!=null&&n.compare(r,e)<0;)i.getNext(),r=i.peek();return i}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,n){const s=this.resolveIndex_(n);if(s)return s.getReverseIteratorFrom(e,i=>i);{const i=this.children_.getReverseIteratorFrom(e.name,B.Wrap);let r=i.peek();for(;r!=null&&n.compare(r,e)>0;)i.getNext(),r=i.peek();return i}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Ai?-1:0}withIndex(e){if(e===ns||this.indexMap_.hasIndex(e))return this;{const n=this.indexMap_.addIndex(e,this.children_);return new L(this.children_,this.priorityNode_,n)}}isIndexed(e){return e===ns||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority()))if(this.children_.count()===n.children_.count()){const s=this.getIterator(ye),i=n.getIterator(ye);let r=s.getNext(),o=i.getNext();for(;r&&o;){if(r.name!==o.name||!r.node.equals(o.node))return!1;r=s.getNext(),o=i.getNext()}return r===null&&o===null}else return!1;else return!1}}resolveIndex_(e){return e===ns?null:this.indexMap_.get(e.toString())}}L.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class S0 extends L{constructor(){super(new qe(kc),L.EMPTY_NODE,Gt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return L.EMPTY_NODE}isEmpty(){return!1}}const Ai=new S0;Object.defineProperties(B,{MIN:{value:new B(us,L.EMPTY_NODE)},MAX:{value:new B(Ln,Ai)}});rp.__EMPTY_NODE=L.EMPTY_NODE;xe.__childrenNodeConstructor=L;v0(Ai);w0(Ai);/**
964
+ */let Hs;class O{static get EMPTY_NODE(){return Hs||(Hs=new O(new qe(kc),null,Gt.Default))}constructor(e,n,s){this.children_=e,this.priorityNode_=n,this.indexMap_=s,this.lazyHash_=null,this.priorityNode_&&cp(this.priorityNode_),this.children_.isEmpty()&&b(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Hs}updatePriority(e){return this.children_.isEmpty()?this:new O(this.children_,e,this.indexMap_)}getImmediateChild(e){if(e===".priority")return this.getPriority();{const n=this.children_.get(e);return n===null?Hs:n}}getChild(e){const n=$(e);return n===null?this:this.getImmediateChild(n).getChild(oe(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,n){if(b(n,"We should always be passing snapshot nodes"),e===".priority")return this.updatePriority(n);{const s=new B(e,n);let i,r;n.isEmpty()?(i=this.children_.remove(e),r=this.indexMap_.removeFromIndexes(s,this.children_)):(i=this.children_.insert(e,n),r=this.indexMap_.addToIndexes(s,this.children_));const o=i.isEmpty()?Hs:this.priorityNode_;return new O(i,o,r)}}updateChild(e,n){const s=$(e);if(s===null)return n;{b($(e)!==".priority"||dn(e)===1,".priority must be the last token in a path");const i=this.getImmediateChild(s).updateChild(oe(e),n);return this.updateImmediateChild(s,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const n={};let s=0,i=0,r=!0;if(this.forEachChild(ye,(o,a)=>{n[o]=a.val(e),s++,r&&O.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):r=!1}),!e&&r&&i<2*s){const o=[];for(const a in n)o[a]=n[a];return o}else return e&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n}hash(){if(this.lazyHash_===null){let e="";this.getPriority().isEmpty()||(e+="priority:"+ap(this.getPriority().val())+":"),this.forEachChild(ye,(n,s)=>{const i=s.hash();i!==""&&(e+=":"+n+":"+i)}),this.lazyHash_=e===""?"":Pf(e)}return this.lazyHash_}getPredecessorChildName(e,n,s){const i=this.resolveIndex_(s);if(i){const r=i.getPredecessorKey(new B(e,n));return r?r.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){const n=this.resolveIndex_(e);if(n){const s=n.minKey();return s&&s.name}else return this.children_.minKey()}getFirstChild(e){const n=this.getFirstChildName(e);return n?new B(n,this.children_.get(n)):null}getLastChildName(e){const n=this.resolveIndex_(e);if(n){const s=n.maxKey();return s&&s.name}else return this.children_.maxKey()}getLastChild(e){const n=this.getLastChildName(e);return n?new B(n,this.children_.get(n)):null}forEachChild(e,n){const s=this.resolveIndex_(e);return s?s.inorderTraversal(i=>n(i.name,i.node)):this.children_.inorderTraversal(n)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,n){const s=this.resolveIndex_(n);if(s)return s.getIteratorFrom(e,i=>i);{const i=this.children_.getIteratorFrom(e.name,B.Wrap);let r=i.peek();for(;r!=null&&n.compare(r,e)<0;)i.getNext(),r=i.peek();return i}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,n){const s=this.resolveIndex_(n);if(s)return s.getReverseIteratorFrom(e,i=>i);{const i=this.children_.getReverseIteratorFrom(e.name,B.Wrap);let r=i.peek();for(;r!=null&&n.compare(r,e)>0;)i.getNext(),r=i.peek();return i}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Ai?-1:0}withIndex(e){if(e===ns||this.indexMap_.hasIndex(e))return this;{const n=this.indexMap_.addIndex(e,this.children_);return new O(this.children_,this.priorityNode_,n)}}isIndexed(e){return e===ns||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority()))if(this.children_.count()===n.children_.count()){const s=this.getIterator(ye),i=n.getIterator(ye);let r=s.getNext(),o=i.getNext();for(;r&&o;){if(r.name!==o.name||!r.node.equals(o.node))return!1;r=s.getNext(),o=i.getNext()}return r===null&&o===null}else return!1;else return!1}}resolveIndex_(e){return e===ns?null:this.indexMap_.get(e.toString())}}O.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class k0 extends O{constructor(){super(new qe(kc),O.EMPTY_NODE,Gt.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return O.EMPTY_NODE}isEmpty(){return!1}}const Ai=new k0;Object.defineProperties(B,{MIN:{value:new B(us,O.EMPTY_NODE)},MAX:{value:new B(Ln,Ai)}});op.__EMPTY_NODE=O.EMPTY_NODE;xe.__childrenNodeConstructor=O;E0(Ai);b0(Ai);/**
965
965
  * @license
966
966
  * Copyright 2017 Google LLC
967
967
  *
@@ -976,7 +976,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
976
976
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
977
977
  * See the License for the specific language governing permissions and
978
978
  * limitations under the License.
979
- */const k0=!0;function Me(t,e=null){if(t===null)return L.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(e=t[".priority"]),b(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){const n=t;return new xe(n,Me(e))}if(!(t instanceof Array)&&k0){const n=[];let s=!1;if(Ye(t,(o,a)=>{if(o.substring(0,1)!=="."){const c=Me(a);c.isEmpty()||(s=s||!c.getPriority().isEmpty(),n.push(new B(o,c)))}}),n.length===0)return L.EMPTY_NODE;const r=br(n,y0,o=>o.name,kc);if(s){const o=br(n,ye.getCompare());return new L(r,Me(e),new Gt({".priority":o},{".priority":ye}))}else return new L(r,Me(e),Gt.Default)}else{let n=L.EMPTY_NODE;return Ye(t,(s,i)=>{if(Zt(t,s)&&s.substring(0,1)!=="."){const r=Me(i);(r.isLeafNode()||!r.isEmpty())&&(n=n.updateImmediateChild(s,r))}}),n.updatePriority(Me(e))}}E0(Me);/**
979
+ */const A0=!0;function Me(t,e=null){if(t===null)return O.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(e=t[".priority"]),b(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){const n=t;return new xe(n,Me(e))}if(!(t instanceof Array)&&A0){const n=[];let s=!1;if(Ye(t,(o,a)=>{if(o.substring(0,1)!=="."){const c=Me(a);c.isEmpty()||(s=s||!c.getPriority().isEmpty(),n.push(new B(o,c)))}}),n.length===0)return O.EMPTY_NODE;const r=br(n,v0,o=>o.name,kc);if(s){const o=br(n,ye.getCompare());return new O(r,Me(e),new Gt({".priority":o},{".priority":ye}))}else return new O(r,Me(e),Gt.Default)}else{let n=O.EMPTY_NODE;return Ye(t,(s,i)=>{if(Zt(t,s)&&s.substring(0,1)!=="."){const r=Me(i);(r.isLeafNode()||!r.isEmpty())&&(n=n.updateImmediateChild(s,r))}}),n.updatePriority(Me(e))}}w0(Me);/**
980
980
  * @license
981
981
  * Copyright 2017 Google LLC
982
982
  *
@@ -991,7 +991,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
991
991
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
992
992
  * See the License for the specific language governing permissions and
993
993
  * limitations under the License.
994
- */class A0 extends Xr{constructor(e){super(),this.indexPath_=e,b(!H(e)&&$(e)!==".priority","Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,n){const s=this.extractChild(e.node),i=this.extractChild(n.node),r=s.compareTo(i);return r===0?Ss(e.name,n.name):r}makePost(e,n){const s=Me(e),i=L.EMPTY_NODE.updateChild(this.indexPath_,s);return new B(n,i)}maxPost(){const e=L.EMPTY_NODE.updateChild(this.indexPath_,Ai);return new B(Ln,e)}toString(){return np(this.indexPath_,0).join("/")}}/**
994
+ */class R0 extends Yr{constructor(e){super(),this.indexPath_=e,b(!H(e)&&$(e)!==".priority","Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,n){const s=this.extractChild(e.node),i=this.extractChild(n.node),r=s.compareTo(i);return r===0?Ss(e.name,n.name):r}makePost(e,n){const s=Me(e),i=O.EMPTY_NODE.updateChild(this.indexPath_,s);return new B(n,i)}maxPost(){const e=O.EMPTY_NODE.updateChild(this.indexPath_,Ai);return new B(Ln,e)}toString(){return sp(this.indexPath_,0).join("/")}}/**
995
995
  * @license
996
996
  * Copyright 2017 Google LLC
997
997
  *
@@ -1006,7 +1006,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1006
1006
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1007
1007
  * See the License for the specific language governing permissions and
1008
1008
  * limitations under the License.
1009
- */class R0 extends Xr{compare(e,n){const s=e.node.compareTo(n.node);return s===0?Ss(e.name,n.name):s}isDefinedOn(e){return!0}indexedValueChanged(e,n){return!e.equals(n)}minPost(){return B.MIN}maxPost(){return B.MAX}makePost(e,n){const s=Me(e);return new B(n,s)}toString(){return".value"}}const I0=new R0;/**
1009
+ */class I0 extends Yr{compare(e,n){const s=e.node.compareTo(n.node);return s===0?Ss(e.name,n.name):s}isDefinedOn(e){return!0}indexedValueChanged(e,n){return!e.equals(n)}minPost(){return B.MIN}maxPost(){return B.MAX}makePost(e,n){const s=Me(e);return new B(n,s)}toString(){return".value"}}const x0=new I0;/**
1010
1010
  * @license
1011
1011
  * Copyright 2017 Google LLC
1012
1012
  *
@@ -1021,7 +1021,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1021
1021
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1022
1022
  * See the License for the specific language governing permissions and
1023
1023
  * limitations under the License.
1024
- */function hp(t){return{type:"value",snapshotNode:t}}function ds(t,e){return{type:"child_added",snapshotNode:e,childName:t}}function ui(t,e){return{type:"child_removed",snapshotNode:e,childName:t}}function di(t,e,n){return{type:"child_changed",snapshotNode:e,childName:t,oldSnap:n}}function x0(t,e){return{type:"child_moved",snapshotNode:e,childName:t}}/**
1024
+ */function up(t){return{type:"value",snapshotNode:t}}function ds(t,e){return{type:"child_added",snapshotNode:e,childName:t}}function ui(t,e){return{type:"child_removed",snapshotNode:e,childName:t}}function di(t,e,n){return{type:"child_changed",snapshotNode:e,childName:t,oldSnap:n}}function N0(t,e){return{type:"child_moved",snapshotNode:e,childName:t}}/**
1025
1025
  * @license
1026
1026
  * Copyright 2017 Google LLC
1027
1027
  *
@@ -1036,7 +1036,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1036
1036
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1037
1037
  * See the License for the specific language governing permissions and
1038
1038
  * limitations under the License.
1039
- */class Ac{constructor(e){this.index_=e}updateChild(e,n,s,i,r,o){b(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(n);return a.getChild(i).equals(s.getChild(i))&&a.isEmpty()===s.isEmpty()||(o!=null&&(s.isEmpty()?e.hasChild(n)?o.trackChildChange(ui(n,a)):b(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(ds(n,s)):o.trackChildChange(di(n,s,a))),e.isLeafNode()&&s.isEmpty())?e:e.updateImmediateChild(n,s).withIndex(this.index_)}updateFullNode(e,n,s){return s!=null&&(e.isLeafNode()||e.forEachChild(ye,(i,r)=>{n.hasChild(i)||s.trackChildChange(ui(i,r))}),n.isLeafNode()||n.forEachChild(ye,(i,r)=>{if(e.hasChild(i)){const o=e.getImmediateChild(i);o.equals(r)||s.trackChildChange(di(i,r,o))}else s.trackChildChange(ds(i,r))})),n.withIndex(this.index_)}updatePriority(e,n){return e.isEmpty()?L.EMPTY_NODE:e.updatePriority(n)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/**
1039
+ */class Ac{constructor(e){this.index_=e}updateChild(e,n,s,i,r,o){b(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(n);return a.getChild(i).equals(s.getChild(i))&&a.isEmpty()===s.isEmpty()||(o!=null&&(s.isEmpty()?e.hasChild(n)?o.trackChildChange(ui(n,a)):b(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(ds(n,s)):o.trackChildChange(di(n,s,a))),e.isLeafNode()&&s.isEmpty())?e:e.updateImmediateChild(n,s).withIndex(this.index_)}updateFullNode(e,n,s){return s!=null&&(e.isLeafNode()||e.forEachChild(ye,(i,r)=>{n.hasChild(i)||s.trackChildChange(ui(i,r))}),n.isLeafNode()||n.forEachChild(ye,(i,r)=>{if(e.hasChild(i)){const o=e.getImmediateChild(i);o.equals(r)||s.trackChildChange(di(i,r,o))}else s.trackChildChange(ds(i,r))})),n.withIndex(this.index_)}updatePriority(e,n){return e.isEmpty()?O.EMPTY_NODE:e.updatePriority(n)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/**
1040
1040
  * @license
1041
1041
  * Copyright 2017 Google LLC
1042
1042
  *
@@ -1051,7 +1051,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1051
1051
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1052
1052
  * See the License for the specific language governing permissions and
1053
1053
  * limitations under the License.
1054
- */class fi{constructor(e){this.indexedFilter_=new Ac(e.getIndex()),this.index_=e.getIndex(),this.startPost_=fi.getStartPost_(e),this.endPost_=fi.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const n=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,s=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return n&&s}updateChild(e,n,s,i,r,o){return this.matches(new B(n,s))||(s=L.EMPTY_NODE),this.indexedFilter_.updateChild(e,n,s,i,r,o)}updateFullNode(e,n,s){n.isLeafNode()&&(n=L.EMPTY_NODE);let i=n.withIndex(this.index_);i=i.updatePriority(L.EMPTY_NODE);const r=this;return n.forEachChild(ye,(o,a)=>{r.matches(new B(o,a))||(i=i.updateImmediateChild(o,L.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,s)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const n=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),n)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const n=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),n)}else return e.getIndex().maxPost()}}/**
1054
+ */class fi{constructor(e){this.indexedFilter_=new Ac(e.getIndex()),this.index_=e.getIndex(),this.startPost_=fi.getStartPost_(e),this.endPost_=fi.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const n=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,s=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return n&&s}updateChild(e,n,s,i,r,o){return this.matches(new B(n,s))||(s=O.EMPTY_NODE),this.indexedFilter_.updateChild(e,n,s,i,r,o)}updateFullNode(e,n,s){n.isLeafNode()&&(n=O.EMPTY_NODE);let i=n.withIndex(this.index_);i=i.updatePriority(O.EMPTY_NODE);const r=this;return n.forEachChild(ye,(o,a)=>{r.matches(new B(o,a))||(i=i.updateImmediateChild(o,O.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,s)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const n=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),n)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const n=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),n)}else return e.getIndex().maxPost()}}/**
1055
1055
  * @license
1056
1056
  * Copyright 2017 Google LLC
1057
1057
  *
@@ -1066,7 +1066,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1066
1066
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1067
1067
  * See the License for the specific language governing permissions and
1068
1068
  * limitations under the License.
1069
- */class F0{constructor(e){this.withinDirectionalStart=n=>this.reverse_?this.withinEndPost(n):this.withinStartPost(n),this.withinDirectionalEnd=n=>this.reverse_?this.withinStartPost(n):this.withinEndPost(n),this.withinStartPost=n=>{const s=this.index_.compare(this.rangedFilter_.getStartPost(),n);return this.startIsInclusive_?s<=0:s<0},this.withinEndPost=n=>{const s=this.index_.compare(n,this.rangedFilter_.getEndPost());return this.endIsInclusive_?s<=0:s<0},this.rangedFilter_=new fi(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,n,s,i,r,o){return this.rangedFilter_.matches(new B(n,s))||(s=L.EMPTY_NODE),e.getImmediateChild(n).equals(s)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,n,s,i,r,o):this.fullLimitUpdateChild_(e,n,s,r,o)}updateFullNode(e,n,s){let i;if(n.isLeafNode()||n.isEmpty())i=L.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<n.numChildren()&&n.isIndexed(this.index_)){i=L.EMPTY_NODE.withIndex(this.index_);let r;this.reverse_?r=n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):r=n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let o=0;for(;r.hasNext()&&o<this.limit_;){const a=r.getNext();if(this.withinDirectionalStart(a))if(this.withinDirectionalEnd(a))i=i.updateImmediateChild(a.name,a.node),o++;else break;else continue}}else{i=n.withIndex(this.index_),i=i.updatePriority(L.EMPTY_NODE);let r;this.reverse_?r=i.getReverseIterator(this.index_):r=i.getIterator(this.index_);let o=0;for(;r.hasNext();){const a=r.getNext();o<this.limit_&&this.withinDirectionalStart(a)&&this.withinDirectionalEnd(a)?o++:i=i.updateImmediateChild(a.name,L.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,s)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,n,s,i,r){let o;if(this.reverse_){const u=this.index_.getCompare();o=(d,p)=>u(p,d)}else o=this.index_.getCompare();const a=e;b(a.numChildren()===this.limit_,"");const c=new B(n,s),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(c);if(a.hasChild(n)){const u=a.getImmediateChild(n);let d=i.getChildAfterChild(this.index_,l,this.reverse_);for(;d!=null&&(d.name===n||a.hasChild(d.name));)d=i.getChildAfterChild(this.index_,d,this.reverse_);const p=d==null?1:o(d,c);if(h&&!s.isEmpty()&&p>=0)return r!=null&&r.trackChildChange(di(n,s,u)),a.updateImmediateChild(n,s);{r!=null&&r.trackChildChange(ui(n,u));const y=a.updateImmediateChild(n,L.EMPTY_NODE);return d!=null&&this.rangedFilter_.matches(d)?(r!=null&&r.trackChildChange(ds(d.name,d.node)),y.updateImmediateChild(d.name,d.node)):y}}else return s.isEmpty()?e:h&&o(l,c)>=0?(r!=null&&(r.trackChildChange(ui(l.name,l.node)),r.trackChildChange(ds(n,s))),a.updateImmediateChild(n,s).updateImmediateChild(l.name,L.EMPTY_NODE)):e}}/**
1069
+ */class F0{constructor(e){this.withinDirectionalStart=n=>this.reverse_?this.withinEndPost(n):this.withinStartPost(n),this.withinDirectionalEnd=n=>this.reverse_?this.withinStartPost(n):this.withinEndPost(n),this.withinStartPost=n=>{const s=this.index_.compare(this.rangedFilter_.getStartPost(),n);return this.startIsInclusive_?s<=0:s<0},this.withinEndPost=n=>{const s=this.index_.compare(n,this.rangedFilter_.getEndPost());return this.endIsInclusive_?s<=0:s<0},this.rangedFilter_=new fi(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,n,s,i,r,o){return this.rangedFilter_.matches(new B(n,s))||(s=O.EMPTY_NODE),e.getImmediateChild(n).equals(s)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,n,s,i,r,o):this.fullLimitUpdateChild_(e,n,s,r,o)}updateFullNode(e,n,s){let i;if(n.isLeafNode()||n.isEmpty())i=O.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<n.numChildren()&&n.isIndexed(this.index_)){i=O.EMPTY_NODE.withIndex(this.index_);let r;this.reverse_?r=n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):r=n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let o=0;for(;r.hasNext()&&o<this.limit_;){const a=r.getNext();if(this.withinDirectionalStart(a))if(this.withinDirectionalEnd(a))i=i.updateImmediateChild(a.name,a.node),o++;else break;else continue}}else{i=n.withIndex(this.index_),i=i.updatePriority(O.EMPTY_NODE);let r;this.reverse_?r=i.getReverseIterator(this.index_):r=i.getIterator(this.index_);let o=0;for(;r.hasNext();){const a=r.getNext();o<this.limit_&&this.withinDirectionalStart(a)&&this.withinDirectionalEnd(a)?o++:i=i.updateImmediateChild(a.name,O.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,s)}updatePriority(e,n){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,n,s,i,r){let o;if(this.reverse_){const u=this.index_.getCompare();o=(d,p)=>u(p,d)}else o=this.index_.getCompare();const a=e;b(a.numChildren()===this.limit_,"");const c=new B(n,s),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(c);if(a.hasChild(n)){const u=a.getImmediateChild(n);let d=i.getChildAfterChild(this.index_,l,this.reverse_);for(;d!=null&&(d.name===n||a.hasChild(d.name));)d=i.getChildAfterChild(this.index_,d,this.reverse_);const p=d==null?1:o(d,c);if(h&&!s.isEmpty()&&p>=0)return r!=null&&r.trackChildChange(di(n,s,u)),a.updateImmediateChild(n,s);{r!=null&&r.trackChildChange(ui(n,u));const y=a.updateImmediateChild(n,O.EMPTY_NODE);return d!=null&&this.rangedFilter_.matches(d)?(r!=null&&r.trackChildChange(ds(d.name,d.node)),y.updateImmediateChild(d.name,d.node)):y}}else return s.isEmpty()?e:h&&o(l,c)>=0?(r!=null&&(r.trackChildChange(ui(l.name,l.node)),r.trackChildChange(ds(n,s))),a.updateImmediateChild(n,s).updateImmediateChild(l.name,O.EMPTY_NODE)):e}}/**
1070
1070
  * @license
1071
1071
  * Copyright 2017 Google LLC
1072
1072
  *
@@ -1081,7 +1081,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1081
1081
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1082
1082
  * See the License for the specific language governing permissions and
1083
1083
  * limitations under the License.
1084
- */class Rc{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=ye}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return b(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return b(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:us}hasEnd(){return this.endSet_}getIndexEndValue(){return b(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return b(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Ln}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return b(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===ye}copy(){const e=new Rc;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function N0(t){return t.loadsAllData()?new Ac(t.getIndex()):t.hasLimit()?new F0(t):new fi(t)}function Ph(t){const e={};if(t.isDefault())return e;let n;if(t.index_===ye?n="$priority":t.index_===I0?n="$value":t.index_===ns?n="$key":(b(t.index_ instanceof A0,"Unrecognized index type!"),n=t.index_.toString()),e.orderBy=Ne(n),t.startSet_){const s=t.startAfterSet_?"startAfter":"startAt";e[s]=Ne(t.indexStartValue_),t.startNameSet_&&(e[s]+=","+Ne(t.indexStartName_))}if(t.endSet_){const s=t.endBeforeSet_?"endBefore":"endAt";e[s]=Ne(t.indexEndValue_),t.endNameSet_&&(e[s]+=","+Ne(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?e.limitToFirst=t.limit_:e.limitToLast=t.limit_),e}function Lh(t){const e={};if(t.startSet_&&(e.sp=t.indexStartValue_,t.startNameSet_&&(e.sn=t.indexStartName_),e.sin=!t.startAfterSet_),t.endSet_&&(e.ep=t.indexEndValue_,t.endNameSet_&&(e.en=t.indexEndName_),e.ein=!t.endBeforeSet_),t.limitSet_){e.l=t.limit_;let n=t.viewFrom_;n===""&&(t.isViewFromLeft()?n="l":n="r"),e.vf=n}return t.index_!==ye&&(e.i=t.index_.toString()),e}/**
1084
+ */class Rc{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=ye}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return b(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return b(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:us}hasEnd(){return this.endSet_}getIndexEndValue(){return b(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return b(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Ln}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return b(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===ye}copy(){const e=new Rc;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function D0(t){return t.loadsAllData()?new Ac(t.getIndex()):t.hasLimit()?new F0(t):new fi(t)}function Ph(t){const e={};if(t.isDefault())return e;let n;if(t.index_===ye?n="$priority":t.index_===x0?n="$value":t.index_===ns?n="$key":(b(t.index_ instanceof R0,"Unrecognized index type!"),n=t.index_.toString()),e.orderBy=Fe(n),t.startSet_){const s=t.startAfterSet_?"startAfter":"startAt";e[s]=Fe(t.indexStartValue_),t.startNameSet_&&(e[s]+=","+Fe(t.indexStartName_))}if(t.endSet_){const s=t.endBeforeSet_?"endBefore":"endAt";e[s]=Fe(t.indexEndValue_),t.endNameSet_&&(e[s]+=","+Fe(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?e.limitToFirst=t.limit_:e.limitToLast=t.limit_),e}function Lh(t){const e={};if(t.startSet_&&(e.sp=t.indexStartValue_,t.startNameSet_&&(e.sn=t.indexStartName_),e.sin=!t.startAfterSet_),t.endSet_&&(e.ep=t.indexEndValue_,t.endNameSet_&&(e.en=t.indexEndName_),e.ein=!t.endBeforeSet_),t.limitSet_){e.l=t.limit_;let n=t.viewFrom_;n===""&&(t.isViewFromLeft()?n="l":n="r"),e.vf=n}return t.index_!==ye&&(e.i=t.index_.toString()),e}/**
1085
1085
  * @license
1086
1086
  * Copyright 2017 Google LLC
1087
1087
  *
@@ -1096,7 +1096,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1096
1096
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1097
1097
  * See the License for the specific language governing permissions and
1098
1098
  * limitations under the License.
1099
- */class Cr extends Zf{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return n!==void 0?"tag$"+n:(b(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,n,s,i){super(),this.repoInfo_=e,this.onDataUpdate_=n,this.authTokenProvider_=s,this.appCheckTokenProvider_=i,this.log_=Si("p:rest:"),this.listens_={}}listen(e,n,s,i){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=Cr.getListenId_(e,s),a={};this.listens_[o]=a;const c=Ph(e._queryParams);this.restRequest_(r+".json",c,(l,h)=>{let u=h;if(l===404&&(u=null,l=null),l===null&&this.onDataUpdate_(r,u,!1,s),hs(this.listens_,o)===a){let d;l?l===401?d="permission_denied":d="rest_error:"+l:d="ok",i(d,null)}})}unlisten(e,n){const s=Cr.getListenId_(e,n);delete this.listens_[s]}get(e){const n=Ph(e._queryParams),s=e._path.toString(),i=new yc;return this.restRequest_(s+".json",n,(r,o)=>{let a=o;r===404&&(a=null,r=null),r===null?(this.onDataUpdate_(s,a,!1,null),i.resolve(a)):i.reject(new Error(a))}),i.promise}refreshAuthToken(e){}restRequest_(e,n={},s){return n.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,r])=>{i&&i.accessToken&&(n.auth=i.accessToken),r&&r.token&&(n.ac=r.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+r_(n);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=()=>{if(s&&a.readyState===4){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let c=null;if(a.status>=200&&a.status<300){try{c=ai(a.responseText)}catch{nt("Failed to parse JSON response for "+o+": "+a.responseText)}s(null,c)}else a.status!==401&&a.status!==404&&nt("Got unsuccessful REST response for "+o+" Status: "+a.status),s(a.status);s=null}},a.open("GET",o,!0),a.send()})}}/**
1099
+ */class Cr extends ep{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,n){return n!==void 0?"tag$"+n:(b(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,n,s,i){super(),this.repoInfo_=e,this.onDataUpdate_=n,this.authTokenProvider_=s,this.appCheckTokenProvider_=i,this.log_=Si("p:rest:"),this.listens_={}}listen(e,n,s,i){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=Cr.getListenId_(e,s),a={};this.listens_[o]=a;const c=Ph(e._queryParams);this.restRequest_(r+".json",c,(l,h)=>{let u=h;if(l===404&&(u=null,l=null),l===null&&this.onDataUpdate_(r,u,!1,s),hs(this.listens_,o)===a){let d;l?l===401?d="permission_denied":d="rest_error:"+l:d="ok",i(d,null)}})}unlisten(e,n){const s=Cr.getListenId_(e,n);delete this.listens_[s]}get(e){const n=Ph(e._queryParams),s=e._path.toString(),i=new yc;return this.restRequest_(s+".json",n,(r,o)=>{let a=o;r===404&&(a=null,r=null),r===null?(this.onDataUpdate_(s,a,!1,null),i.resolve(a)):i.reject(new Error(a))}),i.promise}refreshAuthToken(e){}restRequest_(e,n={},s){return n.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,r])=>{i&&i.accessToken&&(n.auth=i.accessToken),r&&r.token&&(n.ac=r.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+o_(n);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=()=>{if(s&&a.readyState===4){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let c=null;if(a.status>=200&&a.status<300){try{c=ai(a.responseText)}catch{nt("Failed to parse JSON response for "+o+": "+a.responseText)}s(null,c)}else a.status!==401&&a.status!==404&&nt("Got unsuccessful REST response for "+o+" Status: "+a.status),s(a.status);s=null}},a.open("GET",o,!0),a.send()})}}/**
1100
1100
  * @license
1101
1101
  * Copyright 2017 Google LLC
1102
1102
  *
@@ -1111,7 +1111,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1111
1111
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1112
1112
  * See the License for the specific language governing permissions and
1113
1113
  * limitations under the License.
1114
- */class D0{constructor(){this.rootNode_=L.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,n){this.rootNode_=this.rootNode_.updateChild(e,n)}}/**
1114
+ */class P0{constructor(){this.rootNode_=O.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,n){this.rootNode_=this.rootNode_.updateChild(e,n)}}/**
1115
1115
  * @license
1116
1116
  * Copyright 2017 Google LLC
1117
1117
  *
@@ -1126,7 +1126,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1126
1126
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1127
1127
  * See the License for the specific language governing permissions and
1128
1128
  * limitations under the License.
1129
- */function Tr(){return{value:null,children:new Map}}function up(t,e,n){if(H(e))t.value=n,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(e,n);else{const s=$(e);t.children.has(s)||t.children.set(s,Tr());const i=t.children.get(s);e=oe(e),up(i,e,n)}}function Fa(t,e,n){t.value!==null?n(e,t.value):P0(t,(s,i)=>{const r=new ie(e.toString()+"/"+s);Fa(i,r,n)})}function P0(t,e){t.children.forEach((n,s)=>{e(s,n)})}/**
1129
+ */function Tr(){return{value:null,children:new Map}}function dp(t,e,n){if(H(e))t.value=n,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(e,n);else{const s=$(e);t.children.has(s)||t.children.set(s,Tr());const i=t.children.get(s);e=oe(e),dp(i,e,n)}}function xa(t,e,n){t.value!==null?n(e,t.value):L0(t,(s,i)=>{const r=new ie(e.toString()+"/"+s);xa(i,r,n)})}function L0(t,e){t.children.forEach((n,s)=>{e(s,n)})}/**
1130
1130
  * @license
1131
1131
  * Copyright 2017 Google LLC
1132
1132
  *
@@ -1141,7 +1141,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1141
1141
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1142
1142
  * See the License for the specific language governing permissions and
1143
1143
  * limitations under the License.
1144
- */class L0{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),n=Object.assign({},e);return this.last_&&Ye(this.last_,(s,i)=>{n[s]=n[s]-i}),this.last_=e,n}}/**
1144
+ */class O0{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),n=Object.assign({},e);return this.last_&&Ye(this.last_,(s,i)=>{n[s]=n[s]-i}),this.last_=e,n}}/**
1145
1145
  * @license
1146
1146
  * Copyright 2017 Google LLC
1147
1147
  *
@@ -1156,7 +1156,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1156
1156
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1157
1157
  * See the License for the specific language governing permissions and
1158
1158
  * limitations under the License.
1159
- */const Oh=10*1e3,O0=30*1e3,M0=5*60*1e3;class B0{constructor(e,n){this.server_=n,this.statsToReport_={},this.statsListener_=new L0(e);const s=Oh+(O0-Oh)*Math.random();ei(this.reportStats_.bind(this),Math.floor(s))}reportStats_(){const e=this.statsListener_.get(),n={};let s=!1;Ye(e,(i,r)=>{r>0&&Zt(this.statsToReport_,i)&&(n[i]=r,s=!0)}),s&&this.server_.reportStats(n),ei(this.reportStats_.bind(this),Math.floor(Math.random()*2*M0))}}/**
1159
+ */const Oh=10*1e3,M0=30*1e3,B0=5*60*1e3;class U0{constructor(e,n){this.server_=n,this.statsToReport_={},this.statsListener_=new O0(e);const s=Oh+(M0-Oh)*Math.random();ei(this.reportStats_.bind(this),Math.floor(s))}reportStats_(){const e=this.statsListener_.get(),n={};let s=!1;Ye(e,(i,r)=>{r>0&&Zt(this.statsToReport_,i)&&(n[i]=r,s=!0)}),s&&this.server_.reportStats(n),ei(this.reportStats_.bind(this),Math.floor(Math.random()*2*B0))}}/**
1160
1160
  * @license
1161
1161
  * Copyright 2017 Google LLC
1162
1162
  *
@@ -1171,7 +1171,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1171
1171
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1172
1172
  * See the License for the specific language governing permissions and
1173
1173
  * limitations under the License.
1174
- */var Ct;(function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(Ct||(Ct={}));function dp(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Ic(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function xc(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}/**
1174
+ */var Ct;(function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(Ct||(Ct={}));function fp(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Ic(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function xc(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}/**
1175
1175
  * @license
1176
1176
  * Copyright 2017 Google LLC
1177
1177
  *
@@ -1186,7 +1186,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1186
1186
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1187
1187
  * See the License for the specific language governing permissions and
1188
1188
  * limitations under the License.
1189
- */class Sr{constructor(e,n,s){this.path=e,this.affectedTree=n,this.revert=s,this.type=Ct.ACK_USER_WRITE,this.source=dp()}operationForChild(e){if(H(this.path)){if(this.affectedTree.value!=null)return b(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const n=this.affectedTree.subtree(new ie(e));return new Sr(J(),n,this.revert)}}else return b($(this.path)===e,"operationForChild called for unrelated child."),new Sr(oe(this.path),this.affectedTree,this.revert)}}/**
1189
+ */class Sr{constructor(e,n,s){this.path=e,this.affectedTree=n,this.revert=s,this.type=Ct.ACK_USER_WRITE,this.source=fp()}operationForChild(e){if(H(this.path)){if(this.affectedTree.value!=null)return b(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const n=this.affectedTree.subtree(new ie(e));return new Sr(J(),n,this.revert)}}else return b($(this.path)===e,"operationForChild called for unrelated child."),new Sr(oe(this.path),this.affectedTree,this.revert)}}/**
1190
1190
  * @license
1191
1191
  * Copyright 2017 Google LLC
1192
1192
  *
@@ -1261,7 +1261,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1261
1261
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1262
1262
  * See the License for the specific language governing permissions and
1263
1263
  * limitations under the License.
1264
- */class U0{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function V0(t,e,n,s){const i=[],r=[];return e.forEach(o=>{o.type==="child_changed"&&t.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&r.push(x0(o.childName,o.snapshotNode))}),Ws(t,i,"child_removed",e,s,n),Ws(t,i,"child_added",e,s,n),Ws(t,i,"child_moved",r,s,n),Ws(t,i,"child_changed",e,s,n),Ws(t,i,"value",e,s,n),i}function Ws(t,e,n,s,i,r){const o=s.filter(a=>a.type===n);o.sort((a,c)=>H0(t,a,c)),o.forEach(a=>{const c=$0(t,a,r);i.forEach(l=>{l.respondsTo(a.type)&&e.push(l.createEvent(c,t.query_))})})}function $0(t,e,n){return e.type==="value"||e.type==="child_removed"||(e.prevName=n.getPredecessorChildName(e.childName,e.snapshotNode,t.index_)),e}function H0(t,e,n){if(e.childName==null||n.childName==null)throw Ts("Should only compare child_ events.");const s=new B(e.childName,e.snapshotNode),i=new B(n.childName,n.snapshotNode);return t.index_.compare(s,i)}/**
1264
+ */class V0{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function $0(t,e,n,s){const i=[],r=[];return e.forEach(o=>{o.type==="child_changed"&&t.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&r.push(N0(o.childName,o.snapshotNode))}),Ws(t,i,"child_removed",e,s,n),Ws(t,i,"child_added",e,s,n),Ws(t,i,"child_moved",r,s,n),Ws(t,i,"child_changed",e,s,n),Ws(t,i,"value",e,s,n),i}function Ws(t,e,n,s,i,r){const o=s.filter(a=>a.type===n);o.sort((a,c)=>W0(t,a,c)),o.forEach(a=>{const c=H0(t,a,r);i.forEach(l=>{l.respondsTo(a.type)&&e.push(l.createEvent(c,t.query_))})})}function H0(t,e,n){return e.type==="value"||e.type==="child_removed"||(e.prevName=n.getPredecessorChildName(e.childName,e.snapshotNode,t.index_)),e}function W0(t,e,n){if(e.childName==null||n.childName==null)throw Ts("Should only compare child_ events.");const s=new B(e.childName,e.snapshotNode),i=new B(n.childName,n.snapshotNode);return t.index_.compare(s,i)}/**
1265
1265
  * @license
1266
1266
  * Copyright 2017 Google LLC
1267
1267
  *
@@ -1276,7 +1276,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1276
1276
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1277
1277
  * See the License for the specific language governing permissions and
1278
1278
  * limitations under the License.
1279
- */function Qr(t,e){return{eventCache:t,serverCache:e}}function ti(t,e,n,s){return Qr(new Mn(e,n,s),t.serverCache)}function fp(t,e,n,s){return Qr(t.eventCache,new Mn(e,n,s))}function Na(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function Bn(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}/**
1279
+ */function Xr(t,e){return{eventCache:t,serverCache:e}}function ti(t,e,n,s){return Xr(new Mn(e,n,s),t.serverCache)}function pp(t,e,n,s){return Xr(t.eventCache,new Mn(e,n,s))}function Na(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function Bn(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}/**
1280
1280
  * @license
1281
1281
  * Copyright 2017 Google LLC
1282
1282
  *
@@ -1291,7 +1291,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1291
1291
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1292
1292
  * See the License for the specific language governing permissions and
1293
1293
  * limitations under the License.
1294
- */let Ko;const W0=()=>(Ko||(Ko=new qe(R2)),Ko);class he{static fromObject(e){let n=new he(null);return Ye(e,(s,i)=>{n=n.set(new ie(s),i)}),n}constructor(e,n=W0()){this.value=e,this.children=n}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,n){if(this.value!=null&&n(this.value))return{path:J(),value:this.value};if(H(e))return null;{const s=$(e),i=this.children.get(s);if(i!==null){const r=i.findRootMostMatchingPathAndValue(oe(e),n);return r!=null?{path:Re(new ie(s),r.path),value:r.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(H(e))return this;{const n=$(e),s=this.children.get(n);return s!==null?s.subtree(oe(e)):new he(null)}}set(e,n){if(H(e))return new he(n,this.children);{const s=$(e),r=(this.children.get(s)||new he(null)).set(oe(e),n),o=this.children.insert(s,r);return new he(this.value,o)}}remove(e){if(H(e))return this.children.isEmpty()?new he(null):new he(null,this.children);{const n=$(e),s=this.children.get(n);if(s){const i=s.remove(oe(e));let r;return i.isEmpty()?r=this.children.remove(n):r=this.children.insert(n,i),this.value===null&&r.isEmpty()?new he(null):new he(this.value,r)}else return this}}get(e){if(H(e))return this.value;{const n=$(e),s=this.children.get(n);return s?s.get(oe(e)):null}}setTree(e,n){if(H(e))return n;{const s=$(e),r=(this.children.get(s)||new he(null)).setTree(oe(e),n);let o;return r.isEmpty()?o=this.children.remove(s):o=this.children.insert(s,r),new he(this.value,o)}}fold(e){return this.fold_(J(),e)}fold_(e,n){const s={};return this.children.inorderTraversal((i,r)=>{s[i]=r.fold_(Re(e,i),n)}),n(e,this.value,s)}findOnPath(e,n){return this.findOnPath_(e,J(),n)}findOnPath_(e,n,s){const i=this.value?s(n,this.value):!1;if(i)return i;if(H(e))return null;{const r=$(e),o=this.children.get(r);return o?o.findOnPath_(oe(e),Re(n,r),s):null}}foreachOnPath(e,n){return this.foreachOnPath_(e,J(),n)}foreachOnPath_(e,n,s){if(H(e))return this;{this.value&&s(n,this.value);const i=$(e),r=this.children.get(i);return r?r.foreachOnPath_(oe(e),Re(n,i),s):new he(null)}}foreach(e){this.foreach_(J(),e)}foreach_(e,n){this.children.inorderTraversal((s,i)=>{i.foreach_(Re(e,s),n)}),this.value&&n(e,this.value)}foreachChild(e){this.children.inorderTraversal((n,s)=>{s.value&&e(n,s.value)})}}/**
1294
+ */let zo;const G0=()=>(zo||(zo=new qe(I2)),zo);class he{static fromObject(e){let n=new he(null);return Ye(e,(s,i)=>{n=n.set(new ie(s),i)}),n}constructor(e,n=G0()){this.value=e,this.children=n}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,n){if(this.value!=null&&n(this.value))return{path:J(),value:this.value};if(H(e))return null;{const s=$(e),i=this.children.get(s);if(i!==null){const r=i.findRootMostMatchingPathAndValue(oe(e),n);return r!=null?{path:Re(new ie(s),r.path),value:r.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(H(e))return this;{const n=$(e),s=this.children.get(n);return s!==null?s.subtree(oe(e)):new he(null)}}set(e,n){if(H(e))return new he(n,this.children);{const s=$(e),r=(this.children.get(s)||new he(null)).set(oe(e),n),o=this.children.insert(s,r);return new he(this.value,o)}}remove(e){if(H(e))return this.children.isEmpty()?new he(null):new he(null,this.children);{const n=$(e),s=this.children.get(n);if(s){const i=s.remove(oe(e));let r;return i.isEmpty()?r=this.children.remove(n):r=this.children.insert(n,i),this.value===null&&r.isEmpty()?new he(null):new he(this.value,r)}else return this}}get(e){if(H(e))return this.value;{const n=$(e),s=this.children.get(n);return s?s.get(oe(e)):null}}setTree(e,n){if(H(e))return n;{const s=$(e),r=(this.children.get(s)||new he(null)).setTree(oe(e),n);let o;return r.isEmpty()?o=this.children.remove(s):o=this.children.insert(s,r),new he(this.value,o)}}fold(e){return this.fold_(J(),e)}fold_(e,n){const s={};return this.children.inorderTraversal((i,r)=>{s[i]=r.fold_(Re(e,i),n)}),n(e,this.value,s)}findOnPath(e,n){return this.findOnPath_(e,J(),n)}findOnPath_(e,n,s){const i=this.value?s(n,this.value):!1;if(i)return i;if(H(e))return null;{const r=$(e),o=this.children.get(r);return o?o.findOnPath_(oe(e),Re(n,r),s):null}}foreachOnPath(e,n){return this.foreachOnPath_(e,J(),n)}foreachOnPath_(e,n,s){if(H(e))return this;{this.value&&s(n,this.value);const i=$(e),r=this.children.get(i);return r?r.foreachOnPath_(oe(e),Re(n,i),s):new he(null)}}foreach(e){this.foreach_(J(),e)}foreach_(e,n){this.children.inorderTraversal((s,i)=>{i.foreach_(Re(e,s),n)}),this.value&&n(e,this.value)}foreachChild(e){this.children.inorderTraversal((n,s)=>{s.value&&e(n,s.value)})}}/**
1295
1295
  * @license
1296
1296
  * Copyright 2017 Google LLC
1297
1297
  *
@@ -1306,7 +1306,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1306
1306
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1307
1307
  * See the License for the specific language governing permissions and
1308
1308
  * limitations under the License.
1309
- */class Tt{constructor(e){this.writeTree_=e}static empty(){return new Tt(new he(null))}}function ni(t,e,n){if(H(e))return new Tt(new he(n));{const s=t.writeTree_.findRootMostValueAndPath(e);if(s!=null){const i=s.path;let r=s.value;const o=je(i,e);return r=r.updateChild(o,n),new Tt(t.writeTree_.set(i,r))}else{const i=new he(n),r=t.writeTree_.setTree(e,i);return new Tt(r)}}}function Mh(t,e,n){let s=t;return Ye(n,(i,r)=>{s=ni(s,Re(e,i),r)}),s}function Bh(t,e){if(H(e))return Tt.empty();{const n=t.writeTree_.setTree(e,new he(null));return new Tt(n)}}function Da(t,e){return Hn(t,e)!=null}function Hn(t,e){const n=t.writeTree_.findRootMostValueAndPath(e);return n!=null?t.writeTree_.get(n.path).getChild(je(n.path,e)):null}function Uh(t){const e=[],n=t.writeTree_.value;return n!=null?n.isLeafNode()||n.forEachChild(ye,(s,i)=>{e.push(new B(s,i))}):t.writeTree_.children.inorderTraversal((s,i)=>{i.value!=null&&e.push(new B(s,i.value))}),e}function cn(t,e){if(H(e))return t;{const n=Hn(t,e);return n!=null?new Tt(new he(n)):new Tt(t.writeTree_.subtree(e))}}function Pa(t){return t.writeTree_.isEmpty()}function fs(t,e){return pp(J(),t.writeTree_,e)}function pp(t,e,n){if(e.value!=null)return n.updateChild(t,e.value);{let s=null;return e.children.inorderTraversal((i,r)=>{i===".priority"?(b(r.value!==null,"Priority writes must always be leaf nodes"),s=r.value):n=pp(Re(t,i),r,n)}),!n.getChild(t).isEmpty()&&s!==null&&(n=n.updateChild(Re(t,".priority"),s)),n}}/**
1309
+ */class Tt{constructor(e){this.writeTree_=e}static empty(){return new Tt(new he(null))}}function ni(t,e,n){if(H(e))return new Tt(new he(n));{const s=t.writeTree_.findRootMostValueAndPath(e);if(s!=null){const i=s.path;let r=s.value;const o=je(i,e);return r=r.updateChild(o,n),new Tt(t.writeTree_.set(i,r))}else{const i=new he(n),r=t.writeTree_.setTree(e,i);return new Tt(r)}}}function Mh(t,e,n){let s=t;return Ye(n,(i,r)=>{s=ni(s,Re(e,i),r)}),s}function Bh(t,e){if(H(e))return Tt.empty();{const n=t.writeTree_.setTree(e,new he(null));return new Tt(n)}}function Fa(t,e){return Hn(t,e)!=null}function Hn(t,e){const n=t.writeTree_.findRootMostValueAndPath(e);return n!=null?t.writeTree_.get(n.path).getChild(je(n.path,e)):null}function Uh(t){const e=[],n=t.writeTree_.value;return n!=null?n.isLeafNode()||n.forEachChild(ye,(s,i)=>{e.push(new B(s,i))}):t.writeTree_.children.inorderTraversal((s,i)=>{i.value!=null&&e.push(new B(s,i.value))}),e}function cn(t,e){if(H(e))return t;{const n=Hn(t,e);return n!=null?new Tt(new he(n)):new Tt(t.writeTree_.subtree(e))}}function Da(t){return t.writeTree_.isEmpty()}function fs(t,e){return mp(J(),t.writeTree_,e)}function mp(t,e,n){if(e.value!=null)return n.updateChild(t,e.value);{let s=null;return e.children.inorderTraversal((i,r)=>{i===".priority"?(b(r.value!==null,"Priority writes must always be leaf nodes"),s=r.value):n=mp(Re(t,i),r,n)}),!n.getChild(t).isEmpty()&&s!==null&&(n=n.updateChild(Re(t,".priority"),s)),n}}/**
1310
1310
  * @license
1311
1311
  * Copyright 2017 Google LLC
1312
1312
  *
@@ -1321,7 +1321,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1321
1321
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1322
1322
  * See the License for the specific language governing permissions and
1323
1323
  * limitations under the License.
1324
- */function Fc(t,e){return yp(e,t)}function G0(t,e,n,s,i){b(s>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:e,snap:n,writeId:s,visible:i}),i&&(t.visibleWrites=ni(t.visibleWrites,e,n)),t.lastWriteId=s}function j0(t,e){for(let n=0;n<t.allWrites.length;n++){const s=t.allWrites[n];if(s.writeId===e)return s}return null}function q0(t,e){const n=t.allWrites.findIndex(a=>a.writeId===e);b(n>=0,"removeWrite called with nonexistent writeId.");const s=t.allWrites[n];t.allWrites.splice(n,1);let i=s.visible,r=!1,o=t.allWrites.length-1;for(;i&&o>=0;){const a=t.allWrites[o];a.visible&&(o>=n&&z0(a,s.path)?i=!1:bt(s.path,a.path)&&(r=!0)),o--}if(i){if(r)return K0(t),!0;if(s.snap)t.visibleWrites=Bh(t.visibleWrites,s.path);else{const a=s.children;Ye(a,c=>{t.visibleWrites=Bh(t.visibleWrites,Re(s.path,c))})}return!0}else return!1}function z0(t,e){if(t.snap)return bt(t.path,e);for(const n in t.children)if(t.children.hasOwnProperty(n)&&bt(Re(t.path,n),e))return!0;return!1}function K0(t){t.visibleWrites=mp(t.allWrites,Y0,J()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function Y0(t){return t.visible}function mp(t,e,n){let s=Tt.empty();for(let i=0;i<t.length;++i){const r=t[i];if(e(r)){const o=r.path;let a;if(r.snap)bt(n,o)?(a=je(n,o),s=ni(s,a,r.snap)):bt(o,n)&&(a=je(o,n),s=ni(s,J(),r.snap.getChild(a)));else if(r.children){if(bt(n,o))a=je(n,o),s=Mh(s,a,r.children);else if(bt(o,n))if(a=je(o,n),H(a))s=Mh(s,J(),r.children);else{const c=hs(r.children,$(a));if(c){const l=c.getChild(oe(a));s=ni(s,J(),l)}}}else throw Ts("WriteRecord should have .snap or .children")}}return s}function gp(t,e,n,s,i){if(!s&&!i){const r=Hn(t.visibleWrites,e);if(r!=null)return r;{const o=cn(t.visibleWrites,e);if(Pa(o))return n;if(n==null&&!Da(o,J()))return null;{const a=n||L.EMPTY_NODE;return fs(o,a)}}}else{const r=cn(t.visibleWrites,e);if(!i&&Pa(r))return n;if(!i&&n==null&&!Da(r,J()))return null;{const o=function(l){return(l.visible||i)&&(!s||!~s.indexOf(l.writeId))&&(bt(l.path,e)||bt(e,l.path))},a=mp(t.allWrites,o,e),c=n||L.EMPTY_NODE;return fs(a,c)}}}function X0(t,e,n){let s=L.EMPTY_NODE;const i=Hn(t.visibleWrites,e);if(i)return i.isLeafNode()||i.forEachChild(ye,(r,o)=>{s=s.updateImmediateChild(r,o)}),s;if(n){const r=cn(t.visibleWrites,e);return n.forEachChild(ye,(o,a)=>{const c=fs(cn(r,new ie(o)),a);s=s.updateImmediateChild(o,c)}),Uh(r).forEach(o=>{s=s.updateImmediateChild(o.name,o.node)}),s}else{const r=cn(t.visibleWrites,e);return Uh(r).forEach(o=>{s=s.updateImmediateChild(o.name,o.node)}),s}}function Q0(t,e,n,s,i){b(s||i,"Either existingEventSnap or existingServerSnap must exist");const r=Re(e,n);if(Da(t.visibleWrites,r))return null;{const o=cn(t.visibleWrites,r);return Pa(o)?i.getChild(n):fs(o,i.getChild(n))}}function J0(t,e,n,s){const i=Re(e,n),r=Hn(t.visibleWrites,i);if(r!=null)return r;if(s.isCompleteForChild(n)){const o=cn(t.visibleWrites,i);return fs(o,s.getNode().getImmediateChild(n))}else return null}function Z0(t,e){return Hn(t.visibleWrites,e)}function ey(t,e,n,s,i,r,o){let a;const c=cn(t.visibleWrites,e),l=Hn(c,J());if(l!=null)a=l;else if(n!=null)a=fs(c,n);else return[];if(a=a.withIndex(o),!a.isEmpty()&&!a.isLeafNode()){const h=[],u=o.getCompare(),d=r?a.getReverseIteratorFrom(s,o):a.getIteratorFrom(s,o);let p=d.getNext();for(;p&&h.length<i;)u(p,s)!==0&&h.push(p),p=d.getNext();return h}else return[]}function ty(){return{visibleWrites:Tt.empty(),allWrites:[],lastWriteId:-1}}function kr(t,e,n,s){return gp(t.writeTree,t.treePath,e,n,s)}function Nc(t,e){return X0(t.writeTree,t.treePath,e)}function Vh(t,e,n,s){return Q0(t.writeTree,t.treePath,e,n,s)}function Ar(t,e){return Z0(t.writeTree,Re(t.treePath,e))}function ny(t,e,n,s,i,r){return ey(t.writeTree,t.treePath,e,n,s,i,r)}function Dc(t,e,n){return J0(t.writeTree,t.treePath,e,n)}function _p(t,e){return yp(Re(t.treePath,e),t.writeTree)}function yp(t,e){return{treePath:t,writeTree:e}}/**
1324
+ */function Nc(t,e){return vp(e,t)}function j0(t,e,n,s,i){b(s>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:e,snap:n,writeId:s,visible:i}),i&&(t.visibleWrites=ni(t.visibleWrites,e,n)),t.lastWriteId=s}function q0(t,e){for(let n=0;n<t.allWrites.length;n++){const s=t.allWrites[n];if(s.writeId===e)return s}return null}function z0(t,e){const n=t.allWrites.findIndex(a=>a.writeId===e);b(n>=0,"removeWrite called with nonexistent writeId.");const s=t.allWrites[n];t.allWrites.splice(n,1);let i=s.visible,r=!1,o=t.allWrites.length-1;for(;i&&o>=0;){const a=t.allWrites[o];a.visible&&(o>=n&&K0(a,s.path)?i=!1:bt(s.path,a.path)&&(r=!0)),o--}if(i){if(r)return Y0(t),!0;if(s.snap)t.visibleWrites=Bh(t.visibleWrites,s.path);else{const a=s.children;Ye(a,c=>{t.visibleWrites=Bh(t.visibleWrites,Re(s.path,c))})}return!0}else return!1}function K0(t,e){if(t.snap)return bt(t.path,e);for(const n in t.children)if(t.children.hasOwnProperty(n)&&bt(Re(t.path,n),e))return!0;return!1}function Y0(t){t.visibleWrites=gp(t.allWrites,X0,J()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function X0(t){return t.visible}function gp(t,e,n){let s=Tt.empty();for(let i=0;i<t.length;++i){const r=t[i];if(e(r)){const o=r.path;let a;if(r.snap)bt(n,o)?(a=je(n,o),s=ni(s,a,r.snap)):bt(o,n)&&(a=je(o,n),s=ni(s,J(),r.snap.getChild(a)));else if(r.children){if(bt(n,o))a=je(n,o),s=Mh(s,a,r.children);else if(bt(o,n))if(a=je(o,n),H(a))s=Mh(s,J(),r.children);else{const c=hs(r.children,$(a));if(c){const l=c.getChild(oe(a));s=ni(s,J(),l)}}}else throw Ts("WriteRecord should have .snap or .children")}}return s}function _p(t,e,n,s,i){if(!s&&!i){const r=Hn(t.visibleWrites,e);if(r!=null)return r;{const o=cn(t.visibleWrites,e);if(Da(o))return n;if(n==null&&!Fa(o,J()))return null;{const a=n||O.EMPTY_NODE;return fs(o,a)}}}else{const r=cn(t.visibleWrites,e);if(!i&&Da(r))return n;if(!i&&n==null&&!Fa(r,J()))return null;{const o=function(l){return(l.visible||i)&&(!s||!~s.indexOf(l.writeId))&&(bt(l.path,e)||bt(e,l.path))},a=gp(t.allWrites,o,e),c=n||O.EMPTY_NODE;return fs(a,c)}}}function Q0(t,e,n){let s=O.EMPTY_NODE;const i=Hn(t.visibleWrites,e);if(i)return i.isLeafNode()||i.forEachChild(ye,(r,o)=>{s=s.updateImmediateChild(r,o)}),s;if(n){const r=cn(t.visibleWrites,e);return n.forEachChild(ye,(o,a)=>{const c=fs(cn(r,new ie(o)),a);s=s.updateImmediateChild(o,c)}),Uh(r).forEach(o=>{s=s.updateImmediateChild(o.name,o.node)}),s}else{const r=cn(t.visibleWrites,e);return Uh(r).forEach(o=>{s=s.updateImmediateChild(o.name,o.node)}),s}}function J0(t,e,n,s,i){b(s||i,"Either existingEventSnap or existingServerSnap must exist");const r=Re(e,n);if(Fa(t.visibleWrites,r))return null;{const o=cn(t.visibleWrites,r);return Da(o)?i.getChild(n):fs(o,i.getChild(n))}}function Z0(t,e,n,s){const i=Re(e,n),r=Hn(t.visibleWrites,i);if(r!=null)return r;if(s.isCompleteForChild(n)){const o=cn(t.visibleWrites,i);return fs(o,s.getNode().getImmediateChild(n))}else return null}function ey(t,e){return Hn(t.visibleWrites,e)}function ty(t,e,n,s,i,r,o){let a;const c=cn(t.visibleWrites,e),l=Hn(c,J());if(l!=null)a=l;else if(n!=null)a=fs(c,n);else return[];if(a=a.withIndex(o),!a.isEmpty()&&!a.isLeafNode()){const h=[],u=o.getCompare(),d=r?a.getReverseIteratorFrom(s,o):a.getIteratorFrom(s,o);let p=d.getNext();for(;p&&h.length<i;)u(p,s)!==0&&h.push(p),p=d.getNext();return h}else return[]}function ny(){return{visibleWrites:Tt.empty(),allWrites:[],lastWriteId:-1}}function kr(t,e,n,s){return _p(t.writeTree,t.treePath,e,n,s)}function Fc(t,e){return Q0(t.writeTree,t.treePath,e)}function Vh(t,e,n,s){return J0(t.writeTree,t.treePath,e,n,s)}function Ar(t,e){return ey(t.writeTree,Re(t.treePath,e))}function sy(t,e,n,s,i,r){return ty(t.writeTree,t.treePath,e,n,s,i,r)}function Dc(t,e,n){return Z0(t.writeTree,t.treePath,e,n)}function yp(t,e){return vp(Re(t.treePath,e),t.writeTree)}function vp(t,e){return{treePath:t,writeTree:e}}/**
1325
1325
  * @license
1326
1326
  * Copyright 2017 Google LLC
1327
1327
  *
@@ -1336,7 +1336,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1336
1336
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1337
1337
  * See the License for the specific language governing permissions and
1338
1338
  * limitations under the License.
1339
- */class sy{constructor(){this.changeMap=new Map}trackChildChange(e){const n=e.type,s=e.childName;b(n==="child_added"||n==="child_changed"||n==="child_removed","Only child changes supported for tracking"),b(s!==".priority","Only non-priority child changes can be tracked.");const i=this.changeMap.get(s);if(i){const r=i.type;if(n==="child_added"&&r==="child_removed")this.changeMap.set(s,di(s,e.snapshotNode,i.snapshotNode));else if(n==="child_removed"&&r==="child_added")this.changeMap.delete(s);else if(n==="child_removed"&&r==="child_changed")this.changeMap.set(s,ui(s,i.oldSnap));else if(n==="child_changed"&&r==="child_added")this.changeMap.set(s,ds(s,e.snapshotNode));else if(n==="child_changed"&&r==="child_changed")this.changeMap.set(s,di(s,e.snapshotNode,i.oldSnap));else throw Ts("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(s,e)}getChanges(){return Array.from(this.changeMap.values())}}/**
1339
+ */class iy{constructor(){this.changeMap=new Map}trackChildChange(e){const n=e.type,s=e.childName;b(n==="child_added"||n==="child_changed"||n==="child_removed","Only child changes supported for tracking"),b(s!==".priority","Only non-priority child changes can be tracked.");const i=this.changeMap.get(s);if(i){const r=i.type;if(n==="child_added"&&r==="child_removed")this.changeMap.set(s,di(s,e.snapshotNode,i.snapshotNode));else if(n==="child_removed"&&r==="child_added")this.changeMap.delete(s);else if(n==="child_removed"&&r==="child_changed")this.changeMap.set(s,ui(s,i.oldSnap));else if(n==="child_changed"&&r==="child_added")this.changeMap.set(s,ds(s,e.snapshotNode));else if(n==="child_changed"&&r==="child_changed")this.changeMap.set(s,di(s,e.snapshotNode,i.oldSnap));else throw Ts("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(s,e)}getChanges(){return Array.from(this.changeMap.values())}}/**
1340
1340
  * @license
1341
1341
  * Copyright 2017 Google LLC
1342
1342
  *
@@ -1351,7 +1351,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1351
1351
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1352
1352
  * See the License for the specific language governing permissions and
1353
1353
  * limitations under the License.
1354
- */class iy{getCompleteChild(e){return null}getChildAfterChild(e,n,s){return null}}const vp=new iy;class Pc{constructor(e,n,s=null){this.writes_=e,this.viewCache_=n,this.optCompleteServerCache_=s}getCompleteChild(e){const n=this.viewCache_.eventCache;if(n.isCompleteForChild(e))return n.getNode().getImmediateChild(e);{const s=this.optCompleteServerCache_!=null?new Mn(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Dc(this.writes_,e,s)}}getChildAfterChild(e,n,s){const i=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:Bn(this.viewCache_),r=ny(this.writes_,i,n,1,s,e);return r.length===0?null:r[0]}}/**
1354
+ */class ry{getCompleteChild(e){return null}getChildAfterChild(e,n,s){return null}}const Ep=new ry;class Pc{constructor(e,n,s=null){this.writes_=e,this.viewCache_=n,this.optCompleteServerCache_=s}getCompleteChild(e){const n=this.viewCache_.eventCache;if(n.isCompleteForChild(e))return n.getNode().getImmediateChild(e);{const s=this.optCompleteServerCache_!=null?new Mn(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Dc(this.writes_,e,s)}}getChildAfterChild(e,n,s){const i=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:Bn(this.viewCache_),r=sy(this.writes_,i,n,1,s,e);return r.length===0?null:r[0]}}/**
1355
1355
  * @license
1356
1356
  * Copyright 2017 Google LLC
1357
1357
  *
@@ -1366,7 +1366,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1366
1366
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1367
1367
  * See the License for the specific language governing permissions and
1368
1368
  * limitations under the License.
1369
- */function ry(t){return{filter:t}}function oy(t,e){b(e.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),b(e.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed")}function ay(t,e,n,s,i){const r=new sy;let o,a;if(n.type===Ct.OVERWRITE){const l=n;l.source.fromUser?o=La(t,e,l.path,l.snap,s,i,r):(b(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered()&&!H(l.path),o=Rr(t,e,l.path,l.snap,s,i,a,r))}else if(n.type===Ct.MERGE){const l=n;l.source.fromUser?o=ly(t,e,l.path,l.children,s,i,r):(b(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered(),o=Oa(t,e,l.path,l.children,s,i,a,r))}else if(n.type===Ct.ACK_USER_WRITE){const l=n;l.revert?o=dy(t,e,l.path,s,i,r):o=hy(t,e,l.path,l.affectedTree,s,i,r)}else if(n.type===Ct.LISTEN_COMPLETE)o=uy(t,e,n.path,s,r);else throw Ts("Unknown operation type: "+n.type);const c=r.getChanges();return cy(e,o,c),{viewCache:o,changes:c}}function cy(t,e,n){const s=e.eventCache;if(s.isFullyInitialized()){const i=s.getNode().isLeafNode()||s.getNode().isEmpty(),r=Na(t);(n.length>0||!t.eventCache.isFullyInitialized()||i&&!s.getNode().equals(r)||!s.getNode().getPriority().equals(r.getPriority()))&&n.push(hp(Na(e)))}}function Ep(t,e,n,s,i,r){const o=e.eventCache;if(Ar(s,n)!=null)return e;{let a,c;if(H(n))if(b(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){const l=Bn(e),h=l instanceof L?l:L.EMPTY_NODE,u=Nc(s,h);a=t.filter.updateFullNode(e.eventCache.getNode(),u,r)}else{const l=kr(s,Bn(e));a=t.filter.updateFullNode(e.eventCache.getNode(),l,r)}else{const l=$(n);if(l===".priority"){b(dn(n)===1,"Can't have a priority with additional path components");const h=o.getNode();c=e.serverCache.getNode();const u=Vh(s,n,h,c);u!=null?a=t.filter.updatePriority(h,u):a=o.getNode()}else{const h=oe(n);let u;if(o.isCompleteForChild(l)){c=e.serverCache.getNode();const d=Vh(s,n,o.getNode(),c);d!=null?u=o.getNode().getImmediateChild(l).updateChild(h,d):u=o.getNode().getImmediateChild(l)}else u=Dc(s,l,e.serverCache);u!=null?a=t.filter.updateChild(o.getNode(),l,u,h,i,r):a=o.getNode()}}return ti(e,a,o.isFullyInitialized()||H(n),t.filter.filtersNodes())}}function Rr(t,e,n,s,i,r,o,a){const c=e.serverCache;let l;const h=o?t.filter:t.filter.getIndexedFilter();if(H(n))l=h.updateFullNode(c.getNode(),s,null);else if(h.filtersNodes()&&!c.isFiltered()){const p=c.getNode().updateChild(n,s);l=h.updateFullNode(c.getNode(),p,null)}else{const p=$(n);if(!c.isCompleteForPath(n)&&dn(n)>1)return e;const m=oe(n),w=c.getNode().getImmediateChild(p).updateChild(m,s);p===".priority"?l=h.updatePriority(c.getNode(),w):l=h.updateChild(c.getNode(),p,w,m,vp,null)}const u=fp(e,l,c.isFullyInitialized()||H(n),h.filtersNodes()),d=new Pc(i,u,r);return Ep(t,u,n,i,d,a)}function La(t,e,n,s,i,r,o){const a=e.eventCache;let c,l;const h=new Pc(i,e,r);if(H(n))l=t.filter.updateFullNode(e.eventCache.getNode(),s,o),c=ti(e,l,!0,t.filter.filtersNodes());else{const u=$(n);if(u===".priority")l=t.filter.updatePriority(e.eventCache.getNode(),s),c=ti(e,l,a.isFullyInitialized(),a.isFiltered());else{const d=oe(n),p=a.getNode().getImmediateChild(u);let m;if(H(d))m=s;else{const y=h.getCompleteChild(u);y!=null?tp(d)===".priority"&&y.getChild(sp(d)).isEmpty()?m=y:m=y.updateChild(d,s):m=L.EMPTY_NODE}if(p.equals(m))c=e;else{const y=t.filter.updateChild(a.getNode(),u,m,d,h,o);c=ti(e,y,a.isFullyInitialized(),t.filter.filtersNodes())}}}return c}function $h(t,e){return t.eventCache.isCompleteForChild(e)}function ly(t,e,n,s,i,r,o){let a=e;return s.foreach((c,l)=>{const h=Re(n,c);$h(e,$(h))&&(a=La(t,a,h,l,i,r,o))}),s.foreach((c,l)=>{const h=Re(n,c);$h(e,$(h))||(a=La(t,a,h,l,i,r,o))}),a}function Hh(t,e,n){return n.foreach((s,i)=>{e=e.updateChild(s,i)}),e}function Oa(t,e,n,s,i,r,o,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let c=e,l;H(n)?l=s:l=new he(null).setTree(n,s);const h=e.serverCache.getNode();return l.children.inorderTraversal((u,d)=>{if(h.hasChild(u)){const p=e.serverCache.getNode().getImmediateChild(u),m=Hh(t,p,d);c=Rr(t,c,new ie(u),m,i,r,o,a)}}),l.children.inorderTraversal((u,d)=>{const p=!e.serverCache.isCompleteForChild(u)&&d.value===null;if(!h.hasChild(u)&&!p){const m=e.serverCache.getNode().getImmediateChild(u),y=Hh(t,m,d);c=Rr(t,c,new ie(u),y,i,r,o,a)}}),c}function hy(t,e,n,s,i,r,o){if(Ar(i,n)!=null)return e;const a=e.serverCache.isFiltered(),c=e.serverCache;if(s.value!=null){if(H(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return Rr(t,e,n,c.getNode().getChild(n),i,r,a,o);if(H(n)){let l=new he(null);return c.getNode().forEachChild(ns,(h,u)=>{l=l.set(new ie(h),u)}),Oa(t,e,n,l,i,r,a,o)}else return e}else{let l=new he(null);return s.foreach((h,u)=>{const d=Re(n,h);c.isCompleteForPath(d)&&(l=l.set(h,c.getNode().getChild(d)))}),Oa(t,e,n,l,i,r,a,o)}}function uy(t,e,n,s,i){const r=e.serverCache,o=fp(e,r.getNode(),r.isFullyInitialized()||H(n),r.isFiltered());return Ep(t,o,n,s,vp,i)}function dy(t,e,n,s,i,r){let o;if(Ar(s,n)!=null)return e;{const a=new Pc(s,e,i),c=e.eventCache.getNode();let l;if(H(n)||$(n)===".priority"){let h;if(e.serverCache.isFullyInitialized())h=kr(s,Bn(e));else{const u=e.serverCache.getNode();b(u instanceof L,"serverChildren would be complete if leaf node"),h=Nc(s,u)}h=h,l=t.filter.updateFullNode(c,h,r)}else{const h=$(n);let u=Dc(s,h,e.serverCache);u==null&&e.serverCache.isCompleteForChild(h)&&(u=c.getImmediateChild(h)),u!=null?l=t.filter.updateChild(c,h,u,oe(n),a,r):e.eventCache.getNode().hasChild(h)?l=t.filter.updateChild(c,h,L.EMPTY_NODE,oe(n),a,r):l=c,l.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=kr(s,Bn(e)),o.isLeafNode()&&(l=t.filter.updateFullNode(l,o,r)))}return o=e.serverCache.isFullyInitialized()||Ar(s,J())!=null,ti(e,l,o,t.filter.filtersNodes())}}/**
1369
+ */function oy(t){return{filter:t}}function ay(t,e){b(e.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),b(e.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed")}function cy(t,e,n,s,i){const r=new iy;let o,a;if(n.type===Ct.OVERWRITE){const l=n;l.source.fromUser?o=Pa(t,e,l.path,l.snap,s,i,r):(b(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered()&&!H(l.path),o=Rr(t,e,l.path,l.snap,s,i,a,r))}else if(n.type===Ct.MERGE){const l=n;l.source.fromUser?o=hy(t,e,l.path,l.children,s,i,r):(b(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered(),o=La(t,e,l.path,l.children,s,i,a,r))}else if(n.type===Ct.ACK_USER_WRITE){const l=n;l.revert?o=fy(t,e,l.path,s,i,r):o=uy(t,e,l.path,l.affectedTree,s,i,r)}else if(n.type===Ct.LISTEN_COMPLETE)o=dy(t,e,n.path,s,r);else throw Ts("Unknown operation type: "+n.type);const c=r.getChanges();return ly(e,o,c),{viewCache:o,changes:c}}function ly(t,e,n){const s=e.eventCache;if(s.isFullyInitialized()){const i=s.getNode().isLeafNode()||s.getNode().isEmpty(),r=Na(t);(n.length>0||!t.eventCache.isFullyInitialized()||i&&!s.getNode().equals(r)||!s.getNode().getPriority().equals(r.getPriority()))&&n.push(up(Na(e)))}}function wp(t,e,n,s,i,r){const o=e.eventCache;if(Ar(s,n)!=null)return e;{let a,c;if(H(n))if(b(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){const l=Bn(e),h=l instanceof O?l:O.EMPTY_NODE,u=Fc(s,h);a=t.filter.updateFullNode(e.eventCache.getNode(),u,r)}else{const l=kr(s,Bn(e));a=t.filter.updateFullNode(e.eventCache.getNode(),l,r)}else{const l=$(n);if(l===".priority"){b(dn(n)===1,"Can't have a priority with additional path components");const h=o.getNode();c=e.serverCache.getNode();const u=Vh(s,n,h,c);u!=null?a=t.filter.updatePriority(h,u):a=o.getNode()}else{const h=oe(n);let u;if(o.isCompleteForChild(l)){c=e.serverCache.getNode();const d=Vh(s,n,o.getNode(),c);d!=null?u=o.getNode().getImmediateChild(l).updateChild(h,d):u=o.getNode().getImmediateChild(l)}else u=Dc(s,l,e.serverCache);u!=null?a=t.filter.updateChild(o.getNode(),l,u,h,i,r):a=o.getNode()}}return ti(e,a,o.isFullyInitialized()||H(n),t.filter.filtersNodes())}}function Rr(t,e,n,s,i,r,o,a){const c=e.serverCache;let l;const h=o?t.filter:t.filter.getIndexedFilter();if(H(n))l=h.updateFullNode(c.getNode(),s,null);else if(h.filtersNodes()&&!c.isFiltered()){const p=c.getNode().updateChild(n,s);l=h.updateFullNode(c.getNode(),p,null)}else{const p=$(n);if(!c.isCompleteForPath(n)&&dn(n)>1)return e;const m=oe(n),w=c.getNode().getImmediateChild(p).updateChild(m,s);p===".priority"?l=h.updatePriority(c.getNode(),w):l=h.updateChild(c.getNode(),p,w,m,Ep,null)}const u=pp(e,l,c.isFullyInitialized()||H(n),h.filtersNodes()),d=new Pc(i,u,r);return wp(t,u,n,i,d,a)}function Pa(t,e,n,s,i,r,o){const a=e.eventCache;let c,l;const h=new Pc(i,e,r);if(H(n))l=t.filter.updateFullNode(e.eventCache.getNode(),s,o),c=ti(e,l,!0,t.filter.filtersNodes());else{const u=$(n);if(u===".priority")l=t.filter.updatePriority(e.eventCache.getNode(),s),c=ti(e,l,a.isFullyInitialized(),a.isFiltered());else{const d=oe(n),p=a.getNode().getImmediateChild(u);let m;if(H(d))m=s;else{const y=h.getCompleteChild(u);y!=null?np(d)===".priority"&&y.getChild(ip(d)).isEmpty()?m=y:m=y.updateChild(d,s):m=O.EMPTY_NODE}if(p.equals(m))c=e;else{const y=t.filter.updateChild(a.getNode(),u,m,d,h,o);c=ti(e,y,a.isFullyInitialized(),t.filter.filtersNodes())}}}return c}function $h(t,e){return t.eventCache.isCompleteForChild(e)}function hy(t,e,n,s,i,r,o){let a=e;return s.foreach((c,l)=>{const h=Re(n,c);$h(e,$(h))&&(a=Pa(t,a,h,l,i,r,o))}),s.foreach((c,l)=>{const h=Re(n,c);$h(e,$(h))||(a=Pa(t,a,h,l,i,r,o))}),a}function Hh(t,e,n){return n.foreach((s,i)=>{e=e.updateChild(s,i)}),e}function La(t,e,n,s,i,r,o,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let c=e,l;H(n)?l=s:l=new he(null).setTree(n,s);const h=e.serverCache.getNode();return l.children.inorderTraversal((u,d)=>{if(h.hasChild(u)){const p=e.serverCache.getNode().getImmediateChild(u),m=Hh(t,p,d);c=Rr(t,c,new ie(u),m,i,r,o,a)}}),l.children.inorderTraversal((u,d)=>{const p=!e.serverCache.isCompleteForChild(u)&&d.value===null;if(!h.hasChild(u)&&!p){const m=e.serverCache.getNode().getImmediateChild(u),y=Hh(t,m,d);c=Rr(t,c,new ie(u),y,i,r,o,a)}}),c}function uy(t,e,n,s,i,r,o){if(Ar(i,n)!=null)return e;const a=e.serverCache.isFiltered(),c=e.serverCache;if(s.value!=null){if(H(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return Rr(t,e,n,c.getNode().getChild(n),i,r,a,o);if(H(n)){let l=new he(null);return c.getNode().forEachChild(ns,(h,u)=>{l=l.set(new ie(h),u)}),La(t,e,n,l,i,r,a,o)}else return e}else{let l=new he(null);return s.foreach((h,u)=>{const d=Re(n,h);c.isCompleteForPath(d)&&(l=l.set(h,c.getNode().getChild(d)))}),La(t,e,n,l,i,r,a,o)}}function dy(t,e,n,s,i){const r=e.serverCache,o=pp(e,r.getNode(),r.isFullyInitialized()||H(n),r.isFiltered());return wp(t,o,n,s,Ep,i)}function fy(t,e,n,s,i,r){let o;if(Ar(s,n)!=null)return e;{const a=new Pc(s,e,i),c=e.eventCache.getNode();let l;if(H(n)||$(n)===".priority"){let h;if(e.serverCache.isFullyInitialized())h=kr(s,Bn(e));else{const u=e.serverCache.getNode();b(u instanceof O,"serverChildren would be complete if leaf node"),h=Fc(s,u)}h=h,l=t.filter.updateFullNode(c,h,r)}else{const h=$(n);let u=Dc(s,h,e.serverCache);u==null&&e.serverCache.isCompleteForChild(h)&&(u=c.getImmediateChild(h)),u!=null?l=t.filter.updateChild(c,h,u,oe(n),a,r):e.eventCache.getNode().hasChild(h)?l=t.filter.updateChild(c,h,O.EMPTY_NODE,oe(n),a,r):l=c,l.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=kr(s,Bn(e)),o.isLeafNode()&&(l=t.filter.updateFullNode(l,o,r)))}return o=e.serverCache.isFullyInitialized()||Ar(s,J())!=null,ti(e,l,o,t.filter.filtersNodes())}}/**
1370
1370
  * @license
1371
1371
  * Copyright 2017 Google LLC
1372
1372
  *
@@ -1381,7 +1381,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1381
1381
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1382
1382
  * See the License for the specific language governing permissions and
1383
1383
  * limitations under the License.
1384
- */class fy{constructor(e,n){this.query_=e,this.eventRegistrations_=[];const s=this.query_._queryParams,i=new Ac(s.getIndex()),r=N0(s);this.processor_=ry(r);const o=n.serverCache,a=n.eventCache,c=i.updateFullNode(L.EMPTY_NODE,o.getNode(),null),l=r.updateFullNode(L.EMPTY_NODE,a.getNode(),null),h=new Mn(c,o.isFullyInitialized(),i.filtersNodes()),u=new Mn(l,a.isFullyInitialized(),r.filtersNodes());this.viewCache_=Qr(u,h),this.eventGenerator_=new U0(this.query_)}get query(){return this.query_}}function py(t){return t.viewCache_.serverCache.getNode()}function my(t,e){const n=Bn(t.viewCache_);return n&&(t.query._queryParams.loadsAllData()||!H(e)&&!n.getImmediateChild($(e)).isEmpty())?n.getChild(e):null}function Wh(t){return t.eventRegistrations_.length===0}function gy(t,e){t.eventRegistrations_.push(e)}function Gh(t,e,n){const s=[];if(n){b(e==null,"A cancel should cancel all event registrations.");const i=t.query._path;t.eventRegistrations_.forEach(r=>{const o=r.createCancelEvent(n,i);o&&s.push(o)})}if(e){let i=[];for(let r=0;r<t.eventRegistrations_.length;++r){const o=t.eventRegistrations_[r];if(!o.matches(e))i.push(o);else if(e.hasAnyCallback()){i=i.concat(t.eventRegistrations_.slice(r+1));break}}t.eventRegistrations_=i}else t.eventRegistrations_=[];return s}function jh(t,e,n,s){e.type===Ct.MERGE&&e.source.queryId!==null&&(b(Bn(t.viewCache_),"We should always have a full cache before handling merges"),b(Na(t.viewCache_),"Missing event cache, even though we have a server cache"));const i=t.viewCache_,r=ay(t.processor_,i,e,n,s);return oy(t.processor_,r.viewCache),b(r.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),t.viewCache_=r.viewCache,wp(t,r.changes,r.viewCache.eventCache.getNode(),null)}function _y(t,e){const n=t.viewCache_.eventCache,s=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(ye,(r,o)=>{s.push(ds(r,o))}),n.isFullyInitialized()&&s.push(hp(n.getNode())),wp(t,s,n.getNode(),e)}function wp(t,e,n,s){const i=s?[s]:t.eventRegistrations_;return V0(t.eventGenerator_,e,n,i)}/**
1384
+ */class py{constructor(e,n){this.query_=e,this.eventRegistrations_=[];const s=this.query_._queryParams,i=new Ac(s.getIndex()),r=D0(s);this.processor_=oy(r);const o=n.serverCache,a=n.eventCache,c=i.updateFullNode(O.EMPTY_NODE,o.getNode(),null),l=r.updateFullNode(O.EMPTY_NODE,a.getNode(),null),h=new Mn(c,o.isFullyInitialized(),i.filtersNodes()),u=new Mn(l,a.isFullyInitialized(),r.filtersNodes());this.viewCache_=Xr(u,h),this.eventGenerator_=new V0(this.query_)}get query(){return this.query_}}function my(t){return t.viewCache_.serverCache.getNode()}function gy(t,e){const n=Bn(t.viewCache_);return n&&(t.query._queryParams.loadsAllData()||!H(e)&&!n.getImmediateChild($(e)).isEmpty())?n.getChild(e):null}function Wh(t){return t.eventRegistrations_.length===0}function _y(t,e){t.eventRegistrations_.push(e)}function Gh(t,e,n){const s=[];if(n){b(e==null,"A cancel should cancel all event registrations.");const i=t.query._path;t.eventRegistrations_.forEach(r=>{const o=r.createCancelEvent(n,i);o&&s.push(o)})}if(e){let i=[];for(let r=0;r<t.eventRegistrations_.length;++r){const o=t.eventRegistrations_[r];if(!o.matches(e))i.push(o);else if(e.hasAnyCallback()){i=i.concat(t.eventRegistrations_.slice(r+1));break}}t.eventRegistrations_=i}else t.eventRegistrations_=[];return s}function jh(t,e,n,s){e.type===Ct.MERGE&&e.source.queryId!==null&&(b(Bn(t.viewCache_),"We should always have a full cache before handling merges"),b(Na(t.viewCache_),"Missing event cache, even though we have a server cache"));const i=t.viewCache_,r=cy(t.processor_,i,e,n,s);return ay(t.processor_,r.viewCache),b(r.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),t.viewCache_=r.viewCache,bp(t,r.changes,r.viewCache.eventCache.getNode(),null)}function yy(t,e){const n=t.viewCache_.eventCache,s=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(ye,(r,o)=>{s.push(ds(r,o))}),n.isFullyInitialized()&&s.push(up(n.getNode())),bp(t,s,n.getNode(),e)}function bp(t,e,n,s){const i=s?[s]:t.eventRegistrations_;return $0(t.eventGenerator_,e,n,i)}/**
1385
1385
  * @license
1386
1386
  * Copyright 2017 Google LLC
1387
1387
  *
@@ -1396,7 +1396,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1396
1396
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1397
1397
  * See the License for the specific language governing permissions and
1398
1398
  * limitations under the License.
1399
- */let Ir;class yy{constructor(){this.views=new Map}}function vy(t){b(!Ir,"__referenceConstructor has already been defined"),Ir=t}function Ey(){return b(Ir,"Reference.ts has not been loaded"),Ir}function wy(t){return t.views.size===0}function Lc(t,e,n,s){const i=e.source.queryId;if(i!==null){const r=t.views.get(i);return b(r!=null,"SyncTree gave us an op for an invalid query."),jh(r,e,n,s)}else{let r=[];for(const o of t.views.values())r=r.concat(jh(o,e,n,s));return r}}function by(t,e,n,s,i){const r=e._queryIdentifier,o=t.views.get(r);if(!o){let a=kr(n,i?s:null),c=!1;a?c=!0:s instanceof L?(a=Nc(n,s),c=!1):(a=L.EMPTY_NODE,c=!1);const l=Qr(new Mn(a,c,!1),new Mn(s,i,!1));return new fy(e,l)}return o}function Cy(t,e,n,s,i,r){const o=by(t,e,s,i,r);return t.views.has(e._queryIdentifier)||t.views.set(e._queryIdentifier,o),gy(o,n),_y(o,n)}function Ty(t,e,n,s){const i=e._queryIdentifier,r=[];let o=[];const a=fn(t);if(i==="default")for(const[c,l]of t.views.entries())o=o.concat(Gh(l,n,s)),Wh(l)&&(t.views.delete(c),l.query._queryParams.loadsAllData()||r.push(l.query));else{const c=t.views.get(i);c&&(o=o.concat(Gh(c,n,s)),Wh(c)&&(t.views.delete(i),c.query._queryParams.loadsAllData()||r.push(c.query)))}return a&&!fn(t)&&r.push(new(Ey())(e._repo,e._path)),{removed:r,events:o}}function bp(t){const e=[];for(const n of t.views.values())n.query._queryParams.loadsAllData()||e.push(n);return e}function ss(t,e){let n=null;for(const s of t.views.values())n=n||my(s,e);return n}function Cp(t,e){if(e._queryParams.loadsAllData())return Jr(t);{const s=e._queryIdentifier;return t.views.get(s)}}function Tp(t,e){return Cp(t,e)!=null}function fn(t){return Jr(t)!=null}function Jr(t){for(const e of t.views.values())if(e.query._queryParams.loadsAllData())return e;return null}/**
1399
+ */let Ir;class vy{constructor(){this.views=new Map}}function Ey(t){b(!Ir,"__referenceConstructor has already been defined"),Ir=t}function wy(){return b(Ir,"Reference.ts has not been loaded"),Ir}function by(t){return t.views.size===0}function Lc(t,e,n,s){const i=e.source.queryId;if(i!==null){const r=t.views.get(i);return b(r!=null,"SyncTree gave us an op for an invalid query."),jh(r,e,n,s)}else{let r=[];for(const o of t.views.values())r=r.concat(jh(o,e,n,s));return r}}function Cy(t,e,n,s,i){const r=e._queryIdentifier,o=t.views.get(r);if(!o){let a=kr(n,i?s:null),c=!1;a?c=!0:s instanceof O?(a=Fc(n,s),c=!1):(a=O.EMPTY_NODE,c=!1);const l=Xr(new Mn(a,c,!1),new Mn(s,i,!1));return new py(e,l)}return o}function Ty(t,e,n,s,i,r){const o=Cy(t,e,s,i,r);return t.views.has(e._queryIdentifier)||t.views.set(e._queryIdentifier,o),_y(o,n),yy(o,n)}function Sy(t,e,n,s){const i=e._queryIdentifier,r=[];let o=[];const a=fn(t);if(i==="default")for(const[c,l]of t.views.entries())o=o.concat(Gh(l,n,s)),Wh(l)&&(t.views.delete(c),l.query._queryParams.loadsAllData()||r.push(l.query));else{const c=t.views.get(i);c&&(o=o.concat(Gh(c,n,s)),Wh(c)&&(t.views.delete(i),c.query._queryParams.loadsAllData()||r.push(c.query)))}return a&&!fn(t)&&r.push(new(wy())(e._repo,e._path)),{removed:r,events:o}}function Cp(t){const e=[];for(const n of t.views.values())n.query._queryParams.loadsAllData()||e.push(n);return e}function ss(t,e){let n=null;for(const s of t.views.values())n=n||gy(s,e);return n}function Tp(t,e){if(e._queryParams.loadsAllData())return Qr(t);{const s=e._queryIdentifier;return t.views.get(s)}}function Sp(t,e){return Tp(t,e)!=null}function fn(t){return Qr(t)!=null}function Qr(t){for(const e of t.views.values())if(e.query._queryParams.loadsAllData())return e;return null}/**
1400
1400
  * @license
1401
1401
  * Copyright 2017 Google LLC
1402
1402
  *
@@ -1411,7 +1411,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1411
1411
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1412
1412
  * See the License for the specific language governing permissions and
1413
1413
  * limitations under the License.
1414
- */let xr;function Sy(t){b(!xr,"__referenceConstructor has already been defined"),xr=t}function ky(){return b(xr,"Reference.ts has not been loaded"),xr}let Ay=1;class qh{constructor(e){this.listenProvider_=e,this.syncPointTree_=new he(null),this.pendingWriteTree_=ty(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ry(t,e,n,s,i){return G0(t.pendingWriteTree_,e,n,s,i),i?Ri(t,new On(dp(),e,n)):[]}function Xn(t,e,n=!1){const s=j0(t.pendingWriteTree_,e);if(q0(t.pendingWriteTree_,e)){let r=new he(null);return s.snap!=null?r=r.set(J(),!0):Ye(s.children,o=>{r=r.set(new ie(o),!0)}),Ri(t,new Sr(s.path,r,n))}else return[]}function Zr(t,e,n){return Ri(t,new On(Ic(),e,n))}function Iy(t,e,n){const s=he.fromObject(n);return Ri(t,new mi(Ic(),e,s))}function xy(t,e){return Ri(t,new pi(Ic(),e))}function Fy(t,e,n){const s=Oc(t,n);if(s){const i=Mc(s),r=i.path,o=i.queryId,a=je(r,e),c=new pi(xc(o),a);return Bc(t,r,c)}else return[]}function Ma(t,e,n,s,i=!1){const r=e._path,o=t.syncPointTree_.get(r);let a=[];if(o&&(e._queryIdentifier==="default"||Tp(o,e))){const c=Ty(o,e,n,s);wy(o)&&(t.syncPointTree_=t.syncPointTree_.remove(r));const l=c.removed;if(a=c.events,!i){const h=l.findIndex(d=>d._queryParams.loadsAllData())!==-1,u=t.syncPointTree_.findOnPath(r,(d,p)=>fn(p));if(h&&!u){const d=t.syncPointTree_.subtree(r);if(!d.isEmpty()){const p=Py(d);for(let m=0;m<p.length;++m){const y=p[m],w=y.query,k=Rp(t,y);t.listenProvider_.startListening(si(w),Fr(t,w),k.hashFn,k.onComplete)}}}!u&&l.length>0&&!s&&(h?t.listenProvider_.stopListening(si(e),null):l.forEach(d=>{const p=t.queryToTagMap.get(eo(d));t.listenProvider_.stopListening(si(d),p)}))}Ly(t,l)}return a}function Ny(t,e,n,s){const i=Oc(t,s);if(i!=null){const r=Mc(i),o=r.path,a=r.queryId,c=je(o,e),l=new On(xc(a),c,n);return Bc(t,o,l)}else return[]}function Dy(t,e,n,s){const i=Oc(t,s);if(i){const r=Mc(i),o=r.path,a=r.queryId,c=je(o,e),l=he.fromObject(n),h=new mi(xc(a),c,l);return Bc(t,o,h)}else return[]}function zh(t,e,n,s=!1){const i=e._path;let r=null,o=!1;t.syncPointTree_.foreachOnPath(i,(d,p)=>{const m=je(d,i);r=r||ss(p,m),o=o||fn(p)});let a=t.syncPointTree_.get(i);a?(o=o||fn(a),r=r||ss(a,J())):(a=new yy,t.syncPointTree_=t.syncPointTree_.set(i,a));let c;r!=null?c=!0:(c=!1,r=L.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((p,m)=>{const y=ss(m,J());y&&(r=r.updateImmediateChild(p,y))}));const l=Tp(a,e);if(!l&&!e._queryParams.loadsAllData()){const d=eo(e);b(!t.queryToTagMap.has(d),"View does not exist, but we have a tag");const p=Oy();t.queryToTagMap.set(d,p),t.tagToQueryMap.set(p,d)}const h=Fc(t.pendingWriteTree_,i);let u=Cy(a,e,n,h,r,c);if(!l&&!o&&!s){const d=Cp(a,e);u=u.concat(My(t,e,d))}return u}function Sp(t,e,n){const i=t.pendingWriteTree_,r=t.syncPointTree_.findOnPath(e,(o,a)=>{const c=je(o,e),l=ss(a,c);if(l)return l});return gp(i,e,r,n,!0)}function Ri(t,e){return kp(e,t.syncPointTree_,null,Fc(t.pendingWriteTree_,J()))}function kp(t,e,n,s){if(H(t.path))return Ap(t,e,n,s);{const i=e.get(J());n==null&&i!=null&&(n=ss(i,J()));let r=[];const o=$(t.path),a=t.operationForChild(o),c=e.children.get(o);if(c&&a){const l=n?n.getImmediateChild(o):null,h=_p(s,o);r=r.concat(kp(a,c,l,h))}return i&&(r=r.concat(Lc(i,t,s,n))),r}}function Ap(t,e,n,s){const i=e.get(J());n==null&&i!=null&&(n=ss(i,J()));let r=[];return e.children.inorderTraversal((o,a)=>{const c=n?n.getImmediateChild(o):null,l=_p(s,o),h=t.operationForChild(o);h&&(r=r.concat(Ap(h,a,c,l)))}),i&&(r=r.concat(Lc(i,t,s,n))),r}function Rp(t,e){const n=e.query,s=Fr(t,n);return{hashFn:()=>(py(e)||L.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return s?Fy(t,n._path,s):xy(t,n._path);{const r=F2(i,n);return Ma(t,n,null,r)}}}}function Fr(t,e){const n=eo(e);return t.queryToTagMap.get(n)}function eo(t){return t._path.toString()+"$"+t._queryIdentifier}function Oc(t,e){return t.tagToQueryMap.get(e)}function Mc(t){const e=t.indexOf("$");return b(e!==-1&&e<t.length-1,"Bad queryKey."),{queryId:t.substr(e+1),path:new ie(t.substr(0,e))}}function Bc(t,e,n){const s=t.syncPointTree_.get(e);b(s,"Missing sync point for query tag that we're tracking");const i=Fc(t.pendingWriteTree_,e);return Lc(s,n,i,null)}function Py(t){return t.fold((e,n,s)=>{if(n&&fn(n))return[Jr(n)];{let i=[];return n&&(i=bp(n)),Ye(s,(r,o)=>{i=i.concat(o)}),i}})}function si(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(ky())(t._repo,t._path):t}function Ly(t,e){for(let n=0;n<e.length;++n){const s=e[n];if(!s._queryParams.loadsAllData()){const i=eo(s),r=t.queryToTagMap.get(i);t.queryToTagMap.delete(i),t.tagToQueryMap.delete(r)}}}function Oy(){return Ay++}function My(t,e,n){const s=e._path,i=Fr(t,e),r=Rp(t,n),o=t.listenProvider_.startListening(si(e),i,r.hashFn,r.onComplete),a=t.syncPointTree_.subtree(s);if(i)b(!fn(a.value),"If we're adding a query, it shouldn't be shadowed");else{const c=a.fold((l,h,u)=>{if(!H(l)&&h&&fn(h))return[Jr(h).query];{let d=[];return h&&(d=d.concat(bp(h).map(p=>p.query))),Ye(u,(p,m)=>{d=d.concat(m)}),d}});for(let l=0;l<c.length;++l){const h=c[l];t.listenProvider_.stopListening(si(h),Fr(t,h))}}return o}/**
1414
+ */let xr;function ky(t){b(!xr,"__referenceConstructor has already been defined"),xr=t}function Ay(){return b(xr,"Reference.ts has not been loaded"),xr}let Ry=1;class qh{constructor(e){this.listenProvider_=e,this.syncPointTree_=new he(null),this.pendingWriteTree_=ny(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Iy(t,e,n,s,i){return j0(t.pendingWriteTree_,e,n,s,i),i?Ri(t,new On(fp(),e,n)):[]}function Xn(t,e,n=!1){const s=q0(t.pendingWriteTree_,e);if(z0(t.pendingWriteTree_,e)){let r=new he(null);return s.snap!=null?r=r.set(J(),!0):Ye(s.children,o=>{r=r.set(new ie(o),!0)}),Ri(t,new Sr(s.path,r,n))}else return[]}function Jr(t,e,n){return Ri(t,new On(Ic(),e,n))}function xy(t,e,n){const s=he.fromObject(n);return Ri(t,new mi(Ic(),e,s))}function Ny(t,e){return Ri(t,new pi(Ic(),e))}function Fy(t,e,n){const s=Oc(t,n);if(s){const i=Mc(s),r=i.path,o=i.queryId,a=je(r,e),c=new pi(xc(o),a);return Bc(t,r,c)}else return[]}function Oa(t,e,n,s,i=!1){const r=e._path,o=t.syncPointTree_.get(r);let a=[];if(o&&(e._queryIdentifier==="default"||Sp(o,e))){const c=Sy(o,e,n,s);by(o)&&(t.syncPointTree_=t.syncPointTree_.remove(r));const l=c.removed;if(a=c.events,!i){const h=l.findIndex(d=>d._queryParams.loadsAllData())!==-1,u=t.syncPointTree_.findOnPath(r,(d,p)=>fn(p));if(h&&!u){const d=t.syncPointTree_.subtree(r);if(!d.isEmpty()){const p=Ly(d);for(let m=0;m<p.length;++m){const y=p[m],w=y.query,k=Ip(t,y);t.listenProvider_.startListening(si(w),Nr(t,w),k.hashFn,k.onComplete)}}}!u&&l.length>0&&!s&&(h?t.listenProvider_.stopListening(si(e),null):l.forEach(d=>{const p=t.queryToTagMap.get(Zr(d));t.listenProvider_.stopListening(si(d),p)}))}Oy(t,l)}return a}function Dy(t,e,n,s){const i=Oc(t,s);if(i!=null){const r=Mc(i),o=r.path,a=r.queryId,c=je(o,e),l=new On(xc(a),c,n);return Bc(t,o,l)}else return[]}function Py(t,e,n,s){const i=Oc(t,s);if(i){const r=Mc(i),o=r.path,a=r.queryId,c=je(o,e),l=he.fromObject(n),h=new mi(xc(a),c,l);return Bc(t,o,h)}else return[]}function zh(t,e,n,s=!1){const i=e._path;let r=null,o=!1;t.syncPointTree_.foreachOnPath(i,(d,p)=>{const m=je(d,i);r=r||ss(p,m),o=o||fn(p)});let a=t.syncPointTree_.get(i);a?(o=o||fn(a),r=r||ss(a,J())):(a=new vy,t.syncPointTree_=t.syncPointTree_.set(i,a));let c;r!=null?c=!0:(c=!1,r=O.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((p,m)=>{const y=ss(m,J());y&&(r=r.updateImmediateChild(p,y))}));const l=Sp(a,e);if(!l&&!e._queryParams.loadsAllData()){const d=Zr(e);b(!t.queryToTagMap.has(d),"View does not exist, but we have a tag");const p=My();t.queryToTagMap.set(d,p),t.tagToQueryMap.set(p,d)}const h=Nc(t.pendingWriteTree_,i);let u=Ty(a,e,n,h,r,c);if(!l&&!o&&!s){const d=Tp(a,e);u=u.concat(By(t,e,d))}return u}function kp(t,e,n){const i=t.pendingWriteTree_,r=t.syncPointTree_.findOnPath(e,(o,a)=>{const c=je(o,e),l=ss(a,c);if(l)return l});return _p(i,e,r,n,!0)}function Ri(t,e){return Ap(e,t.syncPointTree_,null,Nc(t.pendingWriteTree_,J()))}function Ap(t,e,n,s){if(H(t.path))return Rp(t,e,n,s);{const i=e.get(J());n==null&&i!=null&&(n=ss(i,J()));let r=[];const o=$(t.path),a=t.operationForChild(o),c=e.children.get(o);if(c&&a){const l=n?n.getImmediateChild(o):null,h=yp(s,o);r=r.concat(Ap(a,c,l,h))}return i&&(r=r.concat(Lc(i,t,s,n))),r}}function Rp(t,e,n,s){const i=e.get(J());n==null&&i!=null&&(n=ss(i,J()));let r=[];return e.children.inorderTraversal((o,a)=>{const c=n?n.getImmediateChild(o):null,l=yp(s,o),h=t.operationForChild(o);h&&(r=r.concat(Rp(h,a,c,l)))}),i&&(r=r.concat(Lc(i,t,s,n))),r}function Ip(t,e){const n=e.query,s=Nr(t,n);return{hashFn:()=>(my(e)||O.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return s?Fy(t,n._path,s):Ny(t,n._path);{const r=F2(i,n);return Oa(t,n,null,r)}}}}function Nr(t,e){const n=Zr(e);return t.queryToTagMap.get(n)}function Zr(t){return t._path.toString()+"$"+t._queryIdentifier}function Oc(t,e){return t.tagToQueryMap.get(e)}function Mc(t){const e=t.indexOf("$");return b(e!==-1&&e<t.length-1,"Bad queryKey."),{queryId:t.substr(e+1),path:new ie(t.substr(0,e))}}function Bc(t,e,n){const s=t.syncPointTree_.get(e);b(s,"Missing sync point for query tag that we're tracking");const i=Nc(t.pendingWriteTree_,e);return Lc(s,n,i,null)}function Ly(t){return t.fold((e,n,s)=>{if(n&&fn(n))return[Qr(n)];{let i=[];return n&&(i=Cp(n)),Ye(s,(r,o)=>{i=i.concat(o)}),i}})}function si(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(Ay())(t._repo,t._path):t}function Oy(t,e){for(let n=0;n<e.length;++n){const s=e[n];if(!s._queryParams.loadsAllData()){const i=Zr(s),r=t.queryToTagMap.get(i);t.queryToTagMap.delete(i),t.tagToQueryMap.delete(r)}}}function My(){return Ry++}function By(t,e,n){const s=e._path,i=Nr(t,e),r=Ip(t,n),o=t.listenProvider_.startListening(si(e),i,r.hashFn,r.onComplete),a=t.syncPointTree_.subtree(s);if(i)b(!fn(a.value),"If we're adding a query, it shouldn't be shadowed");else{const c=a.fold((l,h,u)=>{if(!H(l)&&h&&fn(h))return[Qr(h).query];{let d=[];return h&&(d=d.concat(Cp(h).map(p=>p.query))),Ye(u,(p,m)=>{d=d.concat(m)}),d}});for(let l=0;l<c.length;++l){const h=c[l];t.listenProvider_.stopListening(si(h),Nr(t,h))}}return o}/**
1415
1415
  * @license
1416
1416
  * Copyright 2017 Google LLC
1417
1417
  *
@@ -1426,7 +1426,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1426
1426
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1427
1427
  * See the License for the specific language governing permissions and
1428
1428
  * limitations under the License.
1429
- */class Uc{constructor(e){this.node_=e}getImmediateChild(e){const n=this.node_.getImmediateChild(e);return new Uc(n)}node(){return this.node_}}class Vc{constructor(e,n){this.syncTree_=e,this.path_=n}getImmediateChild(e){const n=Re(this.path_,e);return new Vc(this.syncTree_,n)}node(){return Sp(this.syncTree_,this.path_)}}const By=function(t){return t=t||{},t.timestamp=t.timestamp||new Date().getTime(),t},Kh=function(t,e,n){if(!t||typeof t!="object")return t;if(b(".sv"in t,"Unexpected leaf node or priority contents"),typeof t[".sv"]=="string")return Uy(t[".sv"],e,n);if(typeof t[".sv"]=="object")return Vy(t[".sv"],e);b(!1,"Unexpected server value: "+JSON.stringify(t,null,2))},Uy=function(t,e,n){switch(t){case"timestamp":return n.timestamp;default:b(!1,"Unexpected server value: "+t)}},Vy=function(t,e,n){t.hasOwnProperty("increment")||b(!1,"Unexpected server value: "+JSON.stringify(t,null,2));const s=t.increment;typeof s!="number"&&b(!1,"Unexpected increment value: "+s);const i=e.node();if(b(i!==null&&typeof i<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return s;const o=i.getValue();return typeof o!="number"?s:o+s},$y=function(t,e,n,s){return $c(e,new Vc(n,t),s)},Hy=function(t,e,n){return $c(t,new Uc(e),n)};function $c(t,e,n){const s=t.getPriority().val(),i=Kh(s,e.getImmediateChild(".priority"),n);let r;if(t.isLeafNode()){const o=t,a=Kh(o.getValue(),e,n);return a!==o.getValue()||i!==o.getPriority().val()?new xe(a,Me(i)):t}else{const o=t;return r=o,i!==o.getPriority().val()&&(r=r.updatePriority(new xe(i))),o.forEachChild(ye,(a,c)=>{const l=$c(c,e.getImmediateChild(a),n);l!==c&&(r=r.updateImmediateChild(a,l))}),r}}/**
1429
+ */class Uc{constructor(e){this.node_=e}getImmediateChild(e){const n=this.node_.getImmediateChild(e);return new Uc(n)}node(){return this.node_}}class Vc{constructor(e,n){this.syncTree_=e,this.path_=n}getImmediateChild(e){const n=Re(this.path_,e);return new Vc(this.syncTree_,n)}node(){return kp(this.syncTree_,this.path_)}}const Uy=function(t){return t=t||{},t.timestamp=t.timestamp||new Date().getTime(),t},Kh=function(t,e,n){if(!t||typeof t!="object")return t;if(b(".sv"in t,"Unexpected leaf node or priority contents"),typeof t[".sv"]=="string")return Vy(t[".sv"],e,n);if(typeof t[".sv"]=="object")return $y(t[".sv"],e);b(!1,"Unexpected server value: "+JSON.stringify(t,null,2))},Vy=function(t,e,n){switch(t){case"timestamp":return n.timestamp;default:b(!1,"Unexpected server value: "+t)}},$y=function(t,e,n){t.hasOwnProperty("increment")||b(!1,"Unexpected server value: "+JSON.stringify(t,null,2));const s=t.increment;typeof s!="number"&&b(!1,"Unexpected increment value: "+s);const i=e.node();if(b(i!==null&&typeof i<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return s;const o=i.getValue();return typeof o!="number"?s:o+s},Hy=function(t,e,n,s){return $c(e,new Vc(n,t),s)},Wy=function(t,e,n){return $c(t,new Uc(e),n)};function $c(t,e,n){const s=t.getPriority().val(),i=Kh(s,e.getImmediateChild(".priority"),n);let r;if(t.isLeafNode()){const o=t,a=Kh(o.getValue(),e,n);return a!==o.getValue()||i!==o.getPriority().val()?new xe(a,Me(i)):t}else{const o=t;return r=o,i!==o.getPriority().val()&&(r=r.updatePriority(new xe(i))),o.forEachChild(ye,(a,c)=>{const l=$c(c,e.getImmediateChild(a),n);l!==c&&(r=r.updateImmediateChild(a,l))}),r}}/**
1430
1430
  * @license
1431
1431
  * Copyright 2017 Google LLC
1432
1432
  *
@@ -1441,7 +1441,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1441
1441
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1442
1442
  * See the License for the specific language governing permissions and
1443
1443
  * limitations under the License.
1444
- */class Hc{constructor(e="",n=null,s={children:{},childCount:0}){this.name=e,this.parent=n,this.node=s}}function Wc(t,e){let n=e instanceof ie?e:new ie(e),s=t,i=$(n);for(;i!==null;){const r=hs(s.node.children,i)||{children:{},childCount:0};s=new Hc(i,s,r),n=oe(n),i=$(n)}return s}function ks(t){return t.node.value}function Ip(t,e){t.node.value=e,Ba(t)}function xp(t){return t.node.childCount>0}function Wy(t){return ks(t)===void 0&&!xp(t)}function to(t,e){Ye(t.node.children,(n,s)=>{e(new Hc(n,t,s))})}function Fp(t,e,n,s){n&&e(t),to(t,i=>{Fp(i,e,!0)})}function Gy(t,e,n){let s=t.parent;for(;s!==null;){if(e(s))return!0;s=s.parent}return!1}function Ii(t){return new ie(t.parent===null?t.name:Ii(t.parent)+"/"+t.name)}function Ba(t){t.parent!==null&&jy(t.parent,t.name,t)}function jy(t,e,n){const s=Wy(n),i=Zt(t.node.children,e);s&&i?(delete t.node.children[e],t.node.childCount--,Ba(t)):!s&&!i&&(t.node.children[e]=n.node,t.node.childCount++,Ba(t))}/**
1444
+ */class Hc{constructor(e="",n=null,s={children:{},childCount:0}){this.name=e,this.parent=n,this.node=s}}function Wc(t,e){let n=e instanceof ie?e:new ie(e),s=t,i=$(n);for(;i!==null;){const r=hs(s.node.children,i)||{children:{},childCount:0};s=new Hc(i,s,r),n=oe(n),i=$(n)}return s}function ks(t){return t.node.value}function xp(t,e){t.node.value=e,Ma(t)}function Np(t){return t.node.childCount>0}function Gy(t){return ks(t)===void 0&&!Np(t)}function eo(t,e){Ye(t.node.children,(n,s)=>{e(new Hc(n,t,s))})}function Fp(t,e,n,s){n&&e(t),eo(t,i=>{Fp(i,e,!0)})}function jy(t,e,n){let s=t.parent;for(;s!==null;){if(e(s))return!0;s=s.parent}return!1}function Ii(t){return new ie(t.parent===null?t.name:Ii(t.parent)+"/"+t.name)}function Ma(t){t.parent!==null&&qy(t.parent,t.name,t)}function qy(t,e,n){const s=Gy(n),i=Zt(t.node.children,e);s&&i?(delete t.node.children[e],t.node.childCount--,Ma(t)):!s&&!i&&(t.node.children[e]=n.node,t.node.childCount++,Ma(t))}/**
1445
1445
  * @license
1446
1446
  * Copyright 2017 Google LLC
1447
1447
  *
@@ -1456,7 +1456,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1456
1456
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1457
1457
  * See the License for the specific language governing permissions and
1458
1458
  * limitations under the License.
1459
- */const qy=/[\[\].#$\/\u0000-\u001F\u007F]/,zy=/[\[\].#$\u0000-\u001F\u007F]/,Yo=10*1024*1024,Np=function(t){return typeof t=="string"&&t.length!==0&&!qy.test(t)},Dp=function(t){return typeof t=="string"&&t.length!==0&&!zy.test(t)},Ky=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),Dp(t)},Pp=function(t,e,n){const s=n instanceof ie?new h0(n,t):n;if(e===void 0)throw new Error(t+"contains undefined "+Tn(s));if(typeof e=="function")throw new Error(t+"contains a function "+Tn(s)+" with contents = "+e.toString());if(Pf(e))throw new Error(t+"contains "+e.toString()+" "+Tn(s));if(typeof e=="string"&&e.length>Yo/3&&Kr(e)>Yo)throw new Error(t+"contains a string greater than "+Yo+" utf8 bytes "+Tn(s)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,r=!1;if(Ye(e,(o,a)=>{if(o===".value")i=!0;else if(o!==".priority"&&o!==".sv"&&(r=!0,!Np(o)))throw new Error(t+" contains an invalid key ("+o+") "+Tn(s)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);u0(s,o),Pp(t,a,s),d0(s)}),i&&r)throw new Error(t+' contains ".value" child '+Tn(s)+" in addition to actual children.")}},Lp=function(t,e,n,s){if(!Dp(n))throw new Error(Tf(t,e)+'was an invalid path = "'+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Yy=function(t,e,n,s){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Lp(t,e,n)},Xy=function(t,e){const n=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!Np(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!Ky(n))throw new Error(Tf(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};/**
1459
+ */const zy=/[\[\].#$\/\u0000-\u001F\u007F]/,Ky=/[\[\].#$\u0000-\u001F\u007F]/,Ko=10*1024*1024,Dp=function(t){return typeof t=="string"&&t.length!==0&&!zy.test(t)},Pp=function(t){return typeof t=="string"&&t.length!==0&&!Ky.test(t)},Yy=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),Pp(t)},Lp=function(t,e,n){const s=n instanceof ie?new u0(n,t):n;if(e===void 0)throw new Error(t+"contains undefined "+Tn(s));if(typeof e=="function")throw new Error(t+"contains a function "+Tn(s)+" with contents = "+e.toString());if(Lf(e))throw new Error(t+"contains "+e.toString()+" "+Tn(s));if(typeof e=="string"&&e.length>Ko/3&&zr(e)>Ko)throw new Error(t+"contains a string greater than "+Ko+" utf8 bytes "+Tn(s)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,r=!1;if(Ye(e,(o,a)=>{if(o===".value")i=!0;else if(o!==".priority"&&o!==".sv"&&(r=!0,!Dp(o)))throw new Error(t+" contains an invalid key ("+o+") "+Tn(s)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);d0(s,o),Lp(t,a,s),f0(s)}),i&&r)throw new Error(t+' contains ".value" child '+Tn(s)+" in addition to actual children.")}},Op=function(t,e,n,s){if(!Pp(n))throw new Error(Sf(t,e)+'was an invalid path = "'+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Xy=function(t,e,n,s){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Op(t,e,n)},Qy=function(t,e){const n=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!Dp(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!Yy(n))throw new Error(Sf(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};/**
1460
1460
  * @license
1461
1461
  * Copyright 2017 Google LLC
1462
1462
  *
@@ -1471,7 +1471,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1471
1471
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1472
1472
  * See the License for the specific language governing permissions and
1473
1473
  * limitations under the License.
1474
- */class Qy{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Op(t,e){let n=null;for(let s=0;s<e.length;s++){const i=e[s],r=i.getPath();n!==null&&!Tc(r,n.path)&&(t.eventLists_.push(n),n=null),n===null&&(n={events:[],path:r}),n.events.push(i)}n&&t.eventLists_.push(n)}function Mp(t,e,n){Op(t,n),Bp(t,s=>Tc(s,e))}function Wn(t,e,n){Op(t,n),Bp(t,s=>bt(s,e)||bt(e,s))}function Bp(t,e){t.recursionDepth_++;let n=!0;for(let s=0;s<t.eventLists_.length;s++){const i=t.eventLists_[s];if(i){const r=i.path;e(r)?(Jy(t.eventLists_[s]),t.eventLists_[s]=null):n=!1}}n&&(t.eventLists_=[]),t.recursionDepth_--}function Jy(t){for(let e=0;e<t.events.length;e++){const n=t.events[e];if(n!==null){t.events[e]=null;const s=n.getEventRunner();Zs&&Oe("event: "+n.toString()),ki(s)}}}/**
1474
+ */class Jy{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Mp(t,e){let n=null;for(let s=0;s<e.length;s++){const i=e[s],r=i.getPath();n!==null&&!Tc(r,n.path)&&(t.eventLists_.push(n),n=null),n===null&&(n={events:[],path:r}),n.events.push(i)}n&&t.eventLists_.push(n)}function Bp(t,e,n){Mp(t,n),Up(t,s=>Tc(s,e))}function Wn(t,e,n){Mp(t,n),Up(t,s=>bt(s,e)||bt(e,s))}function Up(t,e){t.recursionDepth_++;let n=!0;for(let s=0;s<t.eventLists_.length;s++){const i=t.eventLists_[s];if(i){const r=i.path;e(r)?(Zy(t.eventLists_[s]),t.eventLists_[s]=null):n=!1}}n&&(t.eventLists_=[]),t.recursionDepth_--}function Zy(t){for(let e=0;e<t.events.length;e++){const n=t.events[e];if(n!==null){t.events[e]=null;const s=n.getEventRunner();Zs&&Oe("event: "+n.toString()),ki(s)}}}/**
1475
1475
  * @license
1476
1476
  * Copyright 2017 Google LLC
1477
1477
  *
@@ -1486,7 +1486,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1486
1486
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1487
1487
  * See the License for the specific language governing permissions and
1488
1488
  * limitations under the License.
1489
- */const Zy="repo_interrupt",e3=25;class t3{constructor(e,n,s,i){this.repoInfo_=e,this.forceRestClient_=n,this.authTokenProvider_=s,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Qy,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=Tr(),this.transactionQueueTree_=new Hc,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function n3(t,e,n){if(t.stats_=bc(t.repoInfo_),t.forceRestClient_||L2())t.server_=new Cr(t.repoInfo_,(s,i,r,o)=>{Yh(t,s,i,r,o)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>Xh(t,!0),0);else{if(typeof n<"u"&&n!==null){if(typeof n!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Ne(n)}catch(s){throw new Error("Invalid authOverride provided: "+s)}}t.persistentConnection_=new qt(t.repoInfo_,e,(s,i,r,o)=>{Yh(t,s,i,r,o)},s=>{Xh(t,s)},s=>{i3(t,s)},t.authTokenProvider_,t.appCheckProvider_,n),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(s=>{t.server_.refreshAuthToken(s)}),t.appCheckProvider_.addTokenChangeListener(s=>{t.server_.refreshAppCheckToken(s.token)}),t.statsReporter_=V2(t.repoInfo_,()=>new B0(t.stats_,t.server_)),t.infoData_=new D0,t.infoSyncTree_=new qh({startListening:(s,i,r,o)=>{let a=[];const c=t.infoData_.getNode(s._path);return c.isEmpty()||(a=Zr(t.infoSyncTree_,s._path,c),setTimeout(()=>{o("ok")},0)),a},stopListening:()=>{}}),Gc(t,"connected",!1),t.serverSyncTree_=new qh({startListening:(s,i,r,o)=>(t.server_.listen(s,r,i,(a,c)=>{const l=o(a,c);Wn(t.eventQueue_,s._path,l)}),[]),stopListening:(s,i)=>{t.server_.unlisten(s,i)}})}function s3(t){const n=t.infoData_.getNode(new ie(".info/serverTimeOffset")).val()||0;return new Date().getTime()+n}function Up(t){return By({timestamp:s3(t)})}function Yh(t,e,n,s,i){t.dataUpdateCount++;const r=new ie(e);n=t.interceptServerDataCallback_?t.interceptServerDataCallback_(e,n):n;let o=[];if(i)if(s){const c=gr(n,l=>Me(l));o=Dy(t.serverSyncTree_,r,c,i)}else{const c=Me(n);o=Ny(t.serverSyncTree_,r,c,i)}else if(s){const c=gr(n,l=>Me(l));o=Iy(t.serverSyncTree_,r,c)}else{const c=Me(n);o=Zr(t.serverSyncTree_,r,c)}let a=r;o.length>0&&(a=qc(t,r)),Wn(t.eventQueue_,a,o)}function Xh(t,e){Gc(t,"connected",e),e===!1&&o3(t)}function i3(t,e){Ye(e,(n,s)=>{Gc(t,n,s)})}function Gc(t,e,n){const s=new ie("/.info/"+e),i=Me(n);t.infoData_.updateSnapshot(s,i);const r=Zr(t.infoSyncTree_,s,i);Wn(t.eventQueue_,s,r)}function r3(t){return t.nextWriteId_++}function o3(t){Vp(t,"onDisconnectEvents");const e=Up(t),n=Tr();Fa(t.onDisconnect_,J(),(i,r)=>{const o=$y(i,r,t.serverSyncTree_,e);up(n,i,o)});let s=[];Fa(n,J(),(i,r)=>{s=s.concat(Zr(t.serverSyncTree_,i,r));const o=d3(t,i);qc(t,o)}),t.onDisconnect_=Tr(),Wn(t.eventQueue_,J(),s)}function a3(t,e,n){let s;$(e._path)===".info"?s=zh(t.infoSyncTree_,e,n):s=zh(t.serverSyncTree_,e,n),Mp(t.eventQueue_,e._path,s)}function c3(t,e,n){let s;$(e._path)===".info"?s=Ma(t.infoSyncTree_,e,n):s=Ma(t.serverSyncTree_,e,n),Mp(t.eventQueue_,e._path,s)}function l3(t){t.persistentConnection_&&t.persistentConnection_.interrupt(Zy)}function Vp(t,...e){let n="";t.persistentConnection_&&(n=t.persistentConnection_.id+":"),Oe(n,...e)}function $p(t,e,n){return Sp(t.serverSyncTree_,e,n)||L.EMPTY_NODE}function jc(t,e=t.transactionQueueTree_){if(e||no(t,e),ks(e)){const n=Wp(t,e);b(n.length>0,"Sending zero length transaction queue"),n.every(i=>i.status===0)&&h3(t,Ii(e),n)}else xp(e)&&to(e,n=>{jc(t,n)})}function h3(t,e,n){const s=n.map(l=>l.currentWriteId),i=$p(t,e,s);let r=i;const o=i.hash();for(let l=0;l<n.length;l++){const h=n[l];b(h.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;const u=je(e,h.path);r=r.updateChild(u,h.currentOutputSnapshotRaw)}const a=r.val(!0),c=e;t.server_.put(c.toString(),a,l=>{Vp(t,"transaction put response",{path:c.toString(),status:l});let h=[];if(l==="ok"){const u=[];for(let d=0;d<n.length;d++)n[d].status=2,h=h.concat(Xn(t.serverSyncTree_,n[d].currentWriteId)),n[d].onComplete&&u.push(()=>n[d].onComplete(null,!0,n[d].currentOutputSnapshotResolved)),n[d].unwatcher();no(t,Wc(t.transactionQueueTree_,e)),jc(t,t.transactionQueueTree_),Wn(t.eventQueue_,e,h);for(let d=0;d<u.length;d++)ki(u[d])}else{if(l==="datastale")for(let u=0;u<n.length;u++)n[u].status===3?n[u].status=4:n[u].status=0;else{nt("transaction at "+c.toString()+" failed: "+l);for(let u=0;u<n.length;u++)n[u].status=4,n[u].abortReason=l}qc(t,e)}},o)}function qc(t,e){const n=Hp(t,e),s=Ii(n),i=Wp(t,n);return u3(t,i,s),s}function u3(t,e,n){if(e.length===0)return;const s=[];let i=[];const o=e.filter(a=>a.status===0).map(a=>a.currentWriteId);for(let a=0;a<e.length;a++){const c=e[a],l=je(n,c.path);let h=!1,u;if(b(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),c.status===4)h=!0,u=c.abortReason,i=i.concat(Xn(t.serverSyncTree_,c.currentWriteId,!0));else if(c.status===0)if(c.retryCount>=e3)h=!0,u="maxretry",i=i.concat(Xn(t.serverSyncTree_,c.currentWriteId,!0));else{const d=$p(t,c.path,o);c.currentInputSnapshot=d;const p=e[a].update(d.val());if(p!==void 0){Pp("transaction failed: Data returned ",p,c.path);let m=Me(p);typeof p=="object"&&p!=null&&Zt(p,".priority")||(m=m.updatePriority(d.getPriority()));const w=c.currentWriteId,k=Up(t),E=Hy(m,d,k);c.currentOutputSnapshotRaw=m,c.currentOutputSnapshotResolved=E,c.currentWriteId=r3(t),o.splice(o.indexOf(w),1),i=i.concat(Ry(t.serverSyncTree_,c.path,E,c.currentWriteId,c.applyLocally)),i=i.concat(Xn(t.serverSyncTree_,w,!0))}else h=!0,u="nodata",i=i.concat(Xn(t.serverSyncTree_,c.currentWriteId,!0))}Wn(t.eventQueue_,n,i),i=[],h&&(e[a].status=2,function(d){setTimeout(d,Math.floor(0))}(e[a].unwatcher),e[a].onComplete&&(u==="nodata"?s.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):s.push(()=>e[a].onComplete(new Error(u),!1,null))))}no(t,t.transactionQueueTree_);for(let a=0;a<s.length;a++)ki(s[a]);jc(t,t.transactionQueueTree_)}function Hp(t,e){let n,s=t.transactionQueueTree_;for(n=$(e);n!==null&&ks(s)===void 0;)s=Wc(s,n),e=oe(e),n=$(e);return s}function Wp(t,e){const n=[];return Gp(t,e,n),n.sort((s,i)=>s.order-i.order),n}function Gp(t,e,n){const s=ks(e);if(s)for(let i=0;i<s.length;i++)n.push(s[i]);to(e,i=>{Gp(t,i,n)})}function no(t,e){const n=ks(e);if(n){let s=0;for(let i=0;i<n.length;i++)n[i].status!==2&&(n[s]=n[i],s++);n.length=s,Ip(e,n.length>0?n:void 0)}to(e,s=>{no(t,s)})}function d3(t,e){const n=Ii(Hp(t,e)),s=Wc(t.transactionQueueTree_,e);return Gy(s,i=>{Xo(t,i)}),Xo(t,s),Fp(s,i=>{Xo(t,i)}),n}function Xo(t,e){const n=ks(e);if(n){const s=[];let i=[],r=-1;for(let o=0;o<n.length;o++)n[o].status===3||(n[o].status===1?(b(r===o-1,"All SENT items should be at beginning of queue."),r=o,n[o].status=3,n[o].abortReason="set"):(b(n[o].status===0,"Unexpected transaction status in abort"),n[o].unwatcher(),i=i.concat(Xn(t.serverSyncTree_,n[o].currentWriteId,!0)),n[o].onComplete&&s.push(n[o].onComplete.bind(null,new Error("set"),!1,null))));r===-1?Ip(e,void 0):n.length=r+1,Wn(t.eventQueue_,Ii(e),i);for(let o=0;o<s.length;o++)ki(s[o])}}/**
1489
+ */const e3="repo_interrupt",t3=25;class n3{constructor(e,n,s,i){this.repoInfo_=e,this.forceRestClient_=n,this.authTokenProvider_=s,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Jy,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=Tr(),this.transactionQueueTree_=new Hc,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function s3(t,e,n){if(t.stats_=bc(t.repoInfo_),t.forceRestClient_||O2())t.server_=new Cr(t.repoInfo_,(s,i,r,o)=>{Yh(t,s,i,r,o)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>Xh(t,!0),0);else{if(typeof n<"u"&&n!==null){if(typeof n!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Fe(n)}catch(s){throw new Error("Invalid authOverride provided: "+s)}}t.persistentConnection_=new qt(t.repoInfo_,e,(s,i,r,o)=>{Yh(t,s,i,r,o)},s=>{Xh(t,s)},s=>{r3(t,s)},t.authTokenProvider_,t.appCheckProvider_,n),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(s=>{t.server_.refreshAuthToken(s)}),t.appCheckProvider_.addTokenChangeListener(s=>{t.server_.refreshAppCheckToken(s.token)}),t.statsReporter_=$2(t.repoInfo_,()=>new U0(t.stats_,t.server_)),t.infoData_=new P0,t.infoSyncTree_=new qh({startListening:(s,i,r,o)=>{let a=[];const c=t.infoData_.getNode(s._path);return c.isEmpty()||(a=Jr(t.infoSyncTree_,s._path,c),setTimeout(()=>{o("ok")},0)),a},stopListening:()=>{}}),Gc(t,"connected",!1),t.serverSyncTree_=new qh({startListening:(s,i,r,o)=>(t.server_.listen(s,r,i,(a,c)=>{const l=o(a,c);Wn(t.eventQueue_,s._path,l)}),[]),stopListening:(s,i)=>{t.server_.unlisten(s,i)}})}function i3(t){const n=t.infoData_.getNode(new ie(".info/serverTimeOffset")).val()||0;return new Date().getTime()+n}function Vp(t){return Uy({timestamp:i3(t)})}function Yh(t,e,n,s,i){t.dataUpdateCount++;const r=new ie(e);n=t.interceptServerDataCallback_?t.interceptServerDataCallback_(e,n):n;let o=[];if(i)if(s){const c=gr(n,l=>Me(l));o=Py(t.serverSyncTree_,r,c,i)}else{const c=Me(n);o=Dy(t.serverSyncTree_,r,c,i)}else if(s){const c=gr(n,l=>Me(l));o=xy(t.serverSyncTree_,r,c)}else{const c=Me(n);o=Jr(t.serverSyncTree_,r,c)}let a=r;o.length>0&&(a=qc(t,r)),Wn(t.eventQueue_,a,o)}function Xh(t,e){Gc(t,"connected",e),e===!1&&a3(t)}function r3(t,e){Ye(e,(n,s)=>{Gc(t,n,s)})}function Gc(t,e,n){const s=new ie("/.info/"+e),i=Me(n);t.infoData_.updateSnapshot(s,i);const r=Jr(t.infoSyncTree_,s,i);Wn(t.eventQueue_,s,r)}function o3(t){return t.nextWriteId_++}function a3(t){$p(t,"onDisconnectEvents");const e=Vp(t),n=Tr();xa(t.onDisconnect_,J(),(i,r)=>{const o=Hy(i,r,t.serverSyncTree_,e);dp(n,i,o)});let s=[];xa(n,J(),(i,r)=>{s=s.concat(Jr(t.serverSyncTree_,i,r));const o=f3(t,i);qc(t,o)}),t.onDisconnect_=Tr(),Wn(t.eventQueue_,J(),s)}function c3(t,e,n){let s;$(e._path)===".info"?s=zh(t.infoSyncTree_,e,n):s=zh(t.serverSyncTree_,e,n),Bp(t.eventQueue_,e._path,s)}function l3(t,e,n){let s;$(e._path)===".info"?s=Oa(t.infoSyncTree_,e,n):s=Oa(t.serverSyncTree_,e,n),Bp(t.eventQueue_,e._path,s)}function h3(t){t.persistentConnection_&&t.persistentConnection_.interrupt(e3)}function $p(t,...e){let n="";t.persistentConnection_&&(n=t.persistentConnection_.id+":"),Oe(n,...e)}function Hp(t,e,n){return kp(t.serverSyncTree_,e,n)||O.EMPTY_NODE}function jc(t,e=t.transactionQueueTree_){if(e||to(t,e),ks(e)){const n=Gp(t,e);b(n.length>0,"Sending zero length transaction queue"),n.every(i=>i.status===0)&&u3(t,Ii(e),n)}else Np(e)&&eo(e,n=>{jc(t,n)})}function u3(t,e,n){const s=n.map(l=>l.currentWriteId),i=Hp(t,e,s);let r=i;const o=i.hash();for(let l=0;l<n.length;l++){const h=n[l];b(h.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;const u=je(e,h.path);r=r.updateChild(u,h.currentOutputSnapshotRaw)}const a=r.val(!0),c=e;t.server_.put(c.toString(),a,l=>{$p(t,"transaction put response",{path:c.toString(),status:l});let h=[];if(l==="ok"){const u=[];for(let d=0;d<n.length;d++)n[d].status=2,h=h.concat(Xn(t.serverSyncTree_,n[d].currentWriteId)),n[d].onComplete&&u.push(()=>n[d].onComplete(null,!0,n[d].currentOutputSnapshotResolved)),n[d].unwatcher();to(t,Wc(t.transactionQueueTree_,e)),jc(t,t.transactionQueueTree_),Wn(t.eventQueue_,e,h);for(let d=0;d<u.length;d++)ki(u[d])}else{if(l==="datastale")for(let u=0;u<n.length;u++)n[u].status===3?n[u].status=4:n[u].status=0;else{nt("transaction at "+c.toString()+" failed: "+l);for(let u=0;u<n.length;u++)n[u].status=4,n[u].abortReason=l}qc(t,e)}},o)}function qc(t,e){const n=Wp(t,e),s=Ii(n),i=Gp(t,n);return d3(t,i,s),s}function d3(t,e,n){if(e.length===0)return;const s=[];let i=[];const o=e.filter(a=>a.status===0).map(a=>a.currentWriteId);for(let a=0;a<e.length;a++){const c=e[a],l=je(n,c.path);let h=!1,u;if(b(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),c.status===4)h=!0,u=c.abortReason,i=i.concat(Xn(t.serverSyncTree_,c.currentWriteId,!0));else if(c.status===0)if(c.retryCount>=t3)h=!0,u="maxretry",i=i.concat(Xn(t.serverSyncTree_,c.currentWriteId,!0));else{const d=Hp(t,c.path,o);c.currentInputSnapshot=d;const p=e[a].update(d.val());if(p!==void 0){Lp("transaction failed: Data returned ",p,c.path);let m=Me(p);typeof p=="object"&&p!=null&&Zt(p,".priority")||(m=m.updatePriority(d.getPriority()));const w=c.currentWriteId,k=Vp(t),E=Wy(m,d,k);c.currentOutputSnapshotRaw=m,c.currentOutputSnapshotResolved=E,c.currentWriteId=o3(t),o.splice(o.indexOf(w),1),i=i.concat(Iy(t.serverSyncTree_,c.path,E,c.currentWriteId,c.applyLocally)),i=i.concat(Xn(t.serverSyncTree_,w,!0))}else h=!0,u="nodata",i=i.concat(Xn(t.serverSyncTree_,c.currentWriteId,!0))}Wn(t.eventQueue_,n,i),i=[],h&&(e[a].status=2,function(d){setTimeout(d,Math.floor(0))}(e[a].unwatcher),e[a].onComplete&&(u==="nodata"?s.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):s.push(()=>e[a].onComplete(new Error(u),!1,null))))}to(t,t.transactionQueueTree_);for(let a=0;a<s.length;a++)ki(s[a]);jc(t,t.transactionQueueTree_)}function Wp(t,e){let n,s=t.transactionQueueTree_;for(n=$(e);n!==null&&ks(s)===void 0;)s=Wc(s,n),e=oe(e),n=$(e);return s}function Gp(t,e){const n=[];return jp(t,e,n),n.sort((s,i)=>s.order-i.order),n}function jp(t,e,n){const s=ks(e);if(s)for(let i=0;i<s.length;i++)n.push(s[i]);eo(e,i=>{jp(t,i,n)})}function to(t,e){const n=ks(e);if(n){let s=0;for(let i=0;i<n.length;i++)n[i].status!==2&&(n[s]=n[i],s++);n.length=s,xp(e,n.length>0?n:void 0)}eo(e,s=>{to(t,s)})}function f3(t,e){const n=Ii(Wp(t,e)),s=Wc(t.transactionQueueTree_,e);return jy(s,i=>{Yo(t,i)}),Yo(t,s),Fp(s,i=>{Yo(t,i)}),n}function Yo(t,e){const n=ks(e);if(n){const s=[];let i=[],r=-1;for(let o=0;o<n.length;o++)n[o].status===3||(n[o].status===1?(b(r===o-1,"All SENT items should be at beginning of queue."),r=o,n[o].status=3,n[o].abortReason="set"):(b(n[o].status===0,"Unexpected transaction status in abort"),n[o].unwatcher(),i=i.concat(Xn(t.serverSyncTree_,n[o].currentWriteId,!0)),n[o].onComplete&&s.push(n[o].onComplete.bind(null,new Error("set"),!1,null))));r===-1?xp(e,void 0):n.length=r+1,Wn(t.eventQueue_,Ii(e),i);for(let o=0;o<s.length;o++)ki(s[o])}}/**
1490
1490
  * @license
1491
1491
  * Copyright 2017 Google LLC
1492
1492
  *
@@ -1501,7 +1501,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1501
1501
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1502
1502
  * See the License for the specific language governing permissions and
1503
1503
  * limitations under the License.
1504
- */function f3(t){let e="";const n=t.split("/");for(let s=0;s<n.length;s++)if(n[s].length>0){let i=n[s];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function p3(t){const e={};t.charAt(0)==="?"&&(t=t.substring(1));for(const n of t.split("&")){if(n.length===0)continue;const s=n.split("=");s.length===2?e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]):nt(`Invalid query segment '${n}' in query '${t}'`)}return e}const Qh=function(t,e){const n=m3(t),s=n.namespace;n.domain==="firebase.com"&&Xt(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!s||s==="undefined")&&n.domain!=="localhost"&&Xt("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||k2();const i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new qf(n.host,n.secure,s,i,e,"",s!==n.subdomain),path:new ie(n.pathString)}},m3=function(t){let e="",n="",s="",i="",r="",o=!0,a="https",c=443;if(typeof t=="string"){let l=t.indexOf("//");l>=0&&(a=t.substring(0,l-1),t=t.substring(l+2));let h=t.indexOf("/");h===-1&&(h=t.length);let u=t.indexOf("?");u===-1&&(u=t.length),e=t.substring(0,Math.min(h,u)),h<u&&(i=f3(t.substring(h,u)));const d=p3(t.substring(Math.min(t.length,u)));l=e.indexOf(":"),l>=0?(o=a==="https"||a==="wss",c=parseInt(e.substring(l+1),10)):l=e.length;const p=e.slice(0,l);if(p.toLowerCase()==="localhost")n="localhost";else if(p.split(".").length<=2)n=p;else{const m=e.indexOf(".");s=e.substring(0,m).toLowerCase(),n=e.substring(m+1),r=s}"ns"in d&&(r=d.ns)}return{host:e,port:c,domain:n,subdomain:s,secure:o,scheme:a,pathString:i,namespace:r}};/**
1504
+ */function p3(t){let e="";const n=t.split("/");for(let s=0;s<n.length;s++)if(n[s].length>0){let i=n[s];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function m3(t){const e={};t.charAt(0)==="?"&&(t=t.substring(1));for(const n of t.split("&")){if(n.length===0)continue;const s=n.split("=");s.length===2?e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]):nt(`Invalid query segment '${n}' in query '${t}'`)}return e}const Qh=function(t,e){const n=g3(t),s=n.namespace;n.domain==="firebase.com"&&Xt(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!s||s==="undefined")&&n.domain!=="localhost"&&Xt("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||A2();const i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new zf(n.host,n.secure,s,i,e,"",s!==n.subdomain),path:new ie(n.pathString)}},g3=function(t){let e="",n="",s="",i="",r="",o=!0,a="https",c=443;if(typeof t=="string"){let l=t.indexOf("//");l>=0&&(a=t.substring(0,l-1),t=t.substring(l+2));let h=t.indexOf("/");h===-1&&(h=t.length);let u=t.indexOf("?");u===-1&&(u=t.length),e=t.substring(0,Math.min(h,u)),h<u&&(i=p3(t.substring(h,u)));const d=m3(t.substring(Math.min(t.length,u)));l=e.indexOf(":"),l>=0?(o=a==="https"||a==="wss",c=parseInt(e.substring(l+1),10)):l=e.length;const p=e.slice(0,l);if(p.toLowerCase()==="localhost")n="localhost";else if(p.split(".").length<=2)n=p;else{const m=e.indexOf(".");s=e.substring(0,m).toLowerCase(),n=e.substring(m+1),r=s}"ns"in d&&(r=d.ns)}return{host:e,port:c,domain:n,subdomain:s,secure:o,scheme:a,pathString:i,namespace:r}};/**
1505
1505
  * @license
1506
1506
  * Copyright 2017 Google LLC
1507
1507
  *
@@ -1516,7 +1516,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1516
1516
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1517
1517
  * See the License for the specific language governing permissions and
1518
1518
  * limitations under the License.
1519
- */class jp{constructor(e,n,s,i){this.eventType=e,this.eventRegistration=n,this.snapshot=s,this.prevName=i}getPath(){const e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Ne(this.snapshot.exportVal())}}class qp{constructor(e,n,s){this.eventRegistration=e,this.error=n,this.path=s}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/**
1519
+ */class qp{constructor(e,n,s,i){this.eventType=e,this.eventRegistration=n,this.snapshot=s,this.prevName=i}getPath(){const e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Fe(this.snapshot.exportVal())}}class zp{constructor(e,n,s){this.eventRegistration=e,this.error=n,this.path=s}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/**
1520
1520
  * @license
1521
1521
  * Copyright 2017 Google LLC
1522
1522
  *
@@ -1531,7 +1531,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1531
1531
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1532
1532
  * See the License for the specific language governing permissions and
1533
1533
  * limitations under the License.
1534
- */class g3{constructor(e,n){this.snapshotCallback=e,this.cancelCallback=n}onValue(e,n){this.snapshotCallback.call(null,e,n)}onCancel(e){return b(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}/**
1534
+ */class _3{constructor(e,n){this.snapshotCallback=e,this.cancelCallback=n}onValue(e,n){this.snapshotCallback.call(null,e,n)}onCancel(e){return b(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}/**
1535
1535
  * @license
1536
1536
  * Copyright 2020 Google LLC
1537
1537
  *
@@ -1546,7 +1546,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1546
1546
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1547
1547
  * See the License for the specific language governing permissions and
1548
1548
  * limitations under the License.
1549
- */class zc{constructor(e,n,s,i){this._repo=e,this._path=n,this._queryParams=s,this._orderByCalled=i}get key(){return H(this._path)?null:tp(this._path)}get ref(){return new en(this._repo,this._path)}get _queryIdentifier(){const e=Lh(this._queryParams),n=Ec(e);return n==="{}"?"default":n}get _queryObject(){return Lh(this._queryParams)}isEqual(e){if(e=Yr(e),!(e instanceof zc))return!1;const n=this._repo===e._repo,s=Tc(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return n&&s&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+l0(this._path)}}class en extends zc{constructor(e,n){super(e,n,new Rc,!1)}get parent(){const e=sp(this._path);return e===null?null:new en(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}}class gi{constructor(e,n,s){this._node=e,this.ref=n,this._index=s}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const n=new ie(e),s=Nr(this.ref,e);return new gi(this._node.getChild(n),s,ye)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(s,i)=>e(new gi(i,Nr(this.ref,s),ye)))}hasChild(e){const n=new ie(e);return!this._node.getChild(n).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Ys(t,e){return t=Yr(t),t._checkNotDeleted("ref"),e!==void 0?Nr(t._root,e):t._root}function Nr(t,e){return t=Yr(t),$(t._path)===null?Yy("child","path",e):Lp("child","path",e),new en(t._repo,Re(t._path,e))}class Kc{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,n){const s=n._queryParams.getIndex();return new jp("value",this,new gi(e.snapshotNode,new en(n._repo,n._path),s))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new qp(this,e,n):null}matches(e){return e instanceof Kc?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}class Yc{constructor(e,n){this.eventType=e,this.callbackContext=n}respondsTo(e){let n=e==="children_added"?"child_added":e;return n=n==="children_removed"?"child_removed":n,this.eventType===n}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new qp(this,e,n):null}createEvent(e,n){b(e.childName!=null,"Child events should have a childName.");const s=Nr(new en(n._repo,n._path),e.childName),i=n._queryParams.getIndex();return new jp(e.type,this,new gi(e.snapshotNode,s,i),e.prevName)}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Yc?this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}}function zp(t,e,n,s,i){const r=new g3(n,void 0),o=e==="value"?new Kc(r):new Yc(e,r);return a3(t._repo,t,o),()=>c3(t._repo,t,o)}function Zi(t,e,n,s){return zp(t,"value",e)}function _3(t,e,n,s){return zp(t,"child_added",e)}vy(en);Sy(en);/**
1549
+ */class zc{constructor(e,n,s,i){this._repo=e,this._path=n,this._queryParams=s,this._orderByCalled=i}get key(){return H(this._path)?null:np(this._path)}get ref(){return new en(this._repo,this._path)}get _queryIdentifier(){const e=Lh(this._queryParams),n=Ec(e);return n==="{}"?"default":n}get _queryObject(){return Lh(this._queryParams)}isEqual(e){if(e=Kr(e),!(e instanceof zc))return!1;const n=this._repo===e._repo,s=Tc(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return n&&s&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+h0(this._path)}}class en extends zc{constructor(e,n){super(e,n,new Rc,!1)}get parent(){const e=ip(this._path);return e===null?null:new en(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}}class gi{constructor(e,n,s){this._node=e,this.ref=n,this._index=s}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const n=new ie(e),s=Fr(this.ref,e);return new gi(this._node.getChild(n),s,ye)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(s,i)=>e(new gi(i,Fr(this.ref,s),ye)))}hasChild(e){const n=new ie(e);return!this._node.getChild(n).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Ys(t,e){return t=Kr(t),t._checkNotDeleted("ref"),e!==void 0?Fr(t._root,e):t._root}function Fr(t,e){return t=Kr(t),$(t._path)===null?Xy("child","path",e):Op("child","path",e),new en(t._repo,Re(t._path,e))}class Kc{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,n){const s=n._queryParams.getIndex();return new qp("value",this,new gi(e.snapshotNode,new en(n._repo,n._path),s))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new zp(this,e,n):null}matches(e){return e instanceof Kc?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}class Yc{constructor(e,n){this.eventType=e,this.callbackContext=n}respondsTo(e){let n=e==="children_added"?"child_added":e;return n=n==="children_removed"?"child_removed":n,this.eventType===n}createCancelEvent(e,n){return this.callbackContext.hasCancelCallback?new zp(this,e,n):null}createEvent(e,n){b(e.childName!=null,"Child events should have a childName.");const s=Fr(new en(n._repo,n._path),e.childName),i=n._queryParams.getIndex();return new qp(e.type,this,new gi(e.snapshotNode,s,i),e.prevName)}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Yc?this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}}function Kp(t,e,n,s,i){const r=new _3(n,void 0),o=e==="value"?new Kc(r):new Yc(e,r);return c3(t._repo,t,o),()=>l3(t._repo,t,o)}function Zi(t,e,n,s){return Kp(t,"value",e)}function y3(t,e,n,s){return Kp(t,"child_added",e)}Ey(en);ky(en);/**
1550
1550
  * @license
1551
1551
  * Copyright 2020 Google LLC
1552
1552
  *
@@ -1561,7 +1561,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1561
1561
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1562
1562
  * See the License for the specific language governing permissions and
1563
1563
  * limitations under the License.
1564
- */const y3="FIREBASE_DATABASE_EMULATOR_HOST",Ua={};let v3=!1;function E3(t,e,n,s){t.repoInfo_=new qf(e,!1,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0,n),s&&(t.authTokenProvider_=s)}function w3(t,e,n,s,i){let r=s||t.options.databaseURL;r===void 0&&(t.options.projectId||Xt("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Oe("Using default host for project ",t.options.projectId),r=`${t.options.projectId}-default-rtdb.firebaseio.com`);let o=Qh(r,i),a=o.repoInfo,c;typeof process<"u"&&process.env&&(c=process.env[y3]),c?(r=`http://${c}?ns=${a.namespace}`,o=Qh(r,i),a=o.repoInfo):o.repoInfo.secure;const l=new M2(t.name,t.options,e);Xy("Invalid Firebase Database URL",o),H(o.path)||Xt("Database URL must point to the root of a Firebase Database (not including a child path).");const h=C3(a,t,l,new O2(t,n));return new T3(h,t)}function b3(t,e){const n=Ua[e];(!n||n[t.key]!==t)&&Xt(`Database ${e}(${t.repoInfo_}) has already been deleted.`),l3(t),delete n[t.key]}function C3(t,e,n,s){let i=Ua[e.name];i||(i={},Ua[e.name]=i);let r=i[t.toURLString()];return r&&Xt("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new t3(t,v3,n,s),i[t.toURLString()]=r,r}class T3{constructor(e,n){this._repoInternal=e,this.app=n,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(n3(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new en(this._repo,J())),this._rootInternal}_delete(){return this._rootInternal!==null&&(b3(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&Xt("Cannot call "+e+" on a deleted database.")}}function er(t=l2(),e){const n=i2(t,"database").getImmediate({identifier:e});if(!n._instanceStarted){const s=z1("database");s&&S3(n,...s)}return n}function S3(t,e,n,s={}){t=Yr(t),t._checkNotDeleted("useEmulator");const i=`${e}:${n}`,r=t._repoInternal;if(t._instanceStarted){if(i===t._repoInternal.repoInfo_.host&&_r(s,r.repoInfo_.emulatorOptions))return;Xt("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o;if(r.repoInfo_.nodeAdmin)s.mockUserToken&&Xt('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Ji(Ji.OWNER);else if(s.mockUserToken){const a=typeof s.mockUserToken=="string"?s.mockUserToken:K1(s.mockUserToken,t.app.options.projectId);o=new Ji(a)}E3(r,i,s,o)}/**
1564
+ */const v3="FIREBASE_DATABASE_EMULATOR_HOST",Ba={};let E3=!1;function w3(t,e,n,s){t.repoInfo_=new zf(e,!1,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0,n),s&&(t.authTokenProvider_=s)}function b3(t,e,n,s,i){let r=s||t.options.databaseURL;r===void 0&&(t.options.projectId||Xt("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Oe("Using default host for project ",t.options.projectId),r=`${t.options.projectId}-default-rtdb.firebaseio.com`);let o=Qh(r,i),a=o.repoInfo,c;typeof process<"u"&&process.env&&(c=process.env[v3]),c?(r=`http://${c}?ns=${a.namespace}`,o=Qh(r,i),a=o.repoInfo):o.repoInfo.secure;const l=new B2(t.name,t.options,e);Qy("Invalid Firebase Database URL",o),H(o.path)||Xt("Database URL must point to the root of a Firebase Database (not including a child path).");const h=T3(a,t,l,new M2(t,n));return new S3(h,t)}function C3(t,e){const n=Ba[e];(!n||n[t.key]!==t)&&Xt(`Database ${e}(${t.repoInfo_}) has already been deleted.`),h3(t),delete n[t.key]}function T3(t,e,n,s){let i=Ba[e.name];i||(i={},Ba[e.name]=i);let r=i[t.toURLString()];return r&&Xt("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new n3(t,E3,n,s),i[t.toURLString()]=r,r}class S3{constructor(e,n){this._repoInternal=e,this.app=n,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(s3(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new en(this._repo,J())),this._rootInternal}_delete(){return this._rootInternal!==null&&(C3(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&Xt("Cannot call "+e+" on a deleted database.")}}function er(t=h2(),e){const n=r2(t,"database").getImmediate({identifier:e});if(!n._instanceStarted){const s=K1("database");s&&k3(n,...s)}return n}function k3(t,e,n,s={}){t=Kr(t),t._checkNotDeleted("useEmulator");const i=`${e}:${n}`,r=t._repoInternal;if(t._instanceStarted){if(i===t._repoInternal.repoInfo_.host&&_r(s,r.repoInfo_.emulatorOptions))return;Xt("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o;if(r.repoInfo_.nodeAdmin)s.mockUserToken&&Xt('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Ji(Ji.OWNER);else if(s.mockUserToken){const a=typeof s.mockUserToken=="string"?s.mockUserToken:Y1(s.mockUserToken,t.app.options.projectId);o=new Ji(a)}w3(r,i,s,o)}/**
1565
1565
  * @license
1566
1566
  * Copyright 2021 Google LLC
1567
1567
  *
@@ -1576,7 +1576,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1576
1576
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1577
1577
  * See the License for the specific language governing permissions and
1578
1578
  * limitations under the License.
1579
- */function k3(t){E2(c2),vr(new ci("database",(e,{instanceIdentifier:n})=>{const s=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return w3(s,i,r,n)},"PUBLIC").setMultipleInstances(!0)),es(yh,vh,t),es(yh,vh,"esm2017")}qt.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)};qt.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};k3();var A3="firebase",R3="11.6.1";/**
1579
+ */function A3(t){w2(l2),vr(new ci("database",(e,{instanceIdentifier:n})=>{const s=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return b3(s,i,r,n)},"PUBLIC").setMultipleInstances(!0)),es(yh,vh,t),es(yh,vh,"esm2017")}qt.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)};qt.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};A3();var R3="firebase",I3="11.6.1";/**
1580
1580
  * @license
1581
1581
  * Copyright 2020 Google LLC
1582
1582
  *
@@ -1591,7 +1591,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1591
1591
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1592
1592
  * See the License for the specific language governing permissions and
1593
1593
  * limitations under the License.
1594
- */es(A3,R3,"app");var Un=typeof self<"u"?self:{};function En(){throw Error("Invalid UTF8")}function Jh(t,e){return e=String.fromCharCode.apply(null,e),t==null?e:t+e}let Hi,Qo;const I3=typeof TextDecoder<"u";let x3;const F3=typeof TextEncoder<"u";function Kp(t){if(F3)t=(x3||(x3=new TextEncoder)).encode(t);else{let n=0;const s=new Uint8Array(3*t.length);for(let i=0;i<t.length;i++){var e=t.charCodeAt(i);if(e<128)s[n++]=e;else{if(e<2048)s[n++]=e>>6|192;else{if(e>=55296&&e<=57343){if(e<=56319&&i<t.length){const r=t.charCodeAt(++i);if(r>=56320&&r<=57343){e=1024*(e-55296)+r-56320+65536,s[n++]=e>>18|240,s[n++]=e>>12&63|128,s[n++]=e>>6&63|128,s[n++]=63&e|128;continue}i--}e=65533}s[n++]=e>>12|224,s[n++]=e>>6&63|128}s[n++]=63&e|128}}t=n===s.length?s:s.subarray(0,n)}return t}var Xc,Dr;e:{for(var Zh=["CLOSURE_FLAGS"],Jo=Un,Zo=0;Zo<Zh.length;Zo++)if((Jo=Jo[Zh[Zo]])==null){Dr=null;break e}Dr=Jo}var _i,eu=Dr&&Dr[610401301];Xc=eu!=null&&eu;const tu=Un.navigator;function Va(t){return!!Xc&&!!_i&&_i.brands.some(({brand:e})=>e&&e.indexOf(t)!=-1)}function dt(t){var e;return(e=Un.navigator)&&(e=e.userAgent)||(e=""),e.indexOf(t)!=-1}function sn(){return!!Xc&&!!_i&&_i.brands.length>0}function ea(){return sn()?Va("Chromium"):(dt("Chrome")||dt("CriOS"))&&!(!sn()&&dt("Edge"))||dt("Silk")}function Qc(t){return Qc[" "](t),t}_i=tu&&tu.userAgentData||null,Qc[" "]=function(){};var N3=!sn()&&(dt("Trident")||dt("MSIE"));!dt("Android")||ea(),ea(),dt("Safari")&&(ea()||!sn()&&dt("Coast")||!sn()&&dt("Opera")||!sn()&&dt("Edge")||(sn()?Va("Microsoft Edge"):dt("Edg/"))||sn()&&Va("Opera"));var Yp={},Xs=null;function D3(t){const e=t.length;let n=3*e/4;n%3?n=Math.floor(n):"=.".indexOf(t[e-1])!=-1&&(n="=.".indexOf(t[e-2])!=-1?n-2:n-1);const s=new Uint8Array(n);let i=0;return function(r,o){function a(l){for(;c<r.length;){const h=r.charAt(c++),u=Xs[h];if(u!=null)return u;if(!/^[\s\xa0]*$/.test(h))throw Error("Unknown base64 encoding at char: "+h)}return l}Xp();let c=0;for(;;){const l=a(-1),h=a(0),u=a(64),d=a(64);if(d===64&&l===-1)break;o(l<<2|h>>4),u!=64&&(o(h<<4&240|u>>2),d!=64&&o(u<<6&192|d))}}(t,function(r){s[i++]=r}),i!==n?s.subarray(0,i):s}function Xp(){if(!Xs){Xs={};var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),e=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const s=t.concat(e[n].split(""));Yp[n]=s;for(let i=0;i<s.length;i++){const r=s[i];Xs[r]===void 0&&(Xs[r]=i)}}}}var Qp=typeof Uint8Array<"u",Jp=!N3&&typeof btoa=="function";function nu(t){if(!Jp){var e;e===void 0&&(e=0),Xp(),e=Yp[e];var n=Array(Math.floor(t.length/3)),s=e[64]||"";let c=0,l=0;for(;c<t.length-2;c+=3){var i=t[c],r=t[c+1],o=t[c+2],a=e[i>>2];i=e[(3&i)<<4|r>>4],r=e[(15&r)<<2|o>>6],o=e[63&o],n[l++]=a+i+r+o}switch(a=0,o=s,t.length-c){case 2:o=e[(15&(a=t[c+1]))<<2]||s;case 1:t=t[c],n[l]=e[t>>2]+e[(3&t)<<4|a>>4]+o+s}return n.join("")}for(e="",n=0,s=t.length-10240;n<s;)e+=String.fromCharCode.apply(null,t.subarray(n,n+=10240));return e+=String.fromCharCode.apply(null,n?t.subarray(n):t),btoa(e)}const su=/[-_.]/g,P3={"-":"+",_:"/",".":"="};function L3(t){return P3[t]||""}function Zp(t){if(!Jp)return D3(t);su.test(t)&&(t=t.replace(su,L3)),t=atob(t);const e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}function xi(t){return Qp&&t!=null&&t instanceof Uint8Array}var ps={};function Vn(){return O3||(O3=new zt(null,ps))}function Jc(t){em(ps);var e=t.g;return(e=e==null||xi(e)?e:typeof e=="string"?Zp(e):null)==null?e:t.g=e}var zt=class{h(){return new Uint8Array(Jc(this)||0)}constructor(t,e){if(em(e),this.g=t,t!=null&&t.length===0)throw Error("ByteString should be constructed with non-empty values")}};let O3,M3;function em(t){if(t!==ps)throw Error("illegal external caller")}function tm(t,e){t.__closure__error__context__984382||(t.__closure__error__context__984382={}),t.__closure__error__context__984382.severity=e}function $a(t){return tm(t=Error(t),"warning"),t}var so=typeof Symbol=="function"&&typeof Symbol()=="symbol",B3=new Set;function Fi(t,e,n=!1,s=!1){return t=typeof Symbol=="function"&&typeof Symbol()=="symbol"?s&&Symbol.for&&t?Symbol.for(t):t!=null?Symbol(t):Symbol():e,n&&B3.add(t),t}var U3=Fi("jas",void 0,!0,!0),iu=Fi(void 0,"0di"),ta=Fi(void 0,"2ex"),Gs=Fi(void 0,"1oa",!0),ms=Fi(void 0,Symbol(),!0);const F=so?U3:"Ga",nm={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},sm=Object.defineProperties;function io(t,e){so||F in t||sm(t,nm),t[F]|=e}function be(t,e){so||F in t||sm(t,nm),t[F]=e}function As(t){return io(t,34),t}function V3(t,e){be(e,-30975&(0|t))}function Ha(t,e){be(e,-30941&(34|t))}function Zc(){return typeof BigInt=="function"}function ze(t){return Array.prototype.slice.call(t)}var el,Ni={},im={};function ru(t){return!(!t||typeof t!="object"||t.Ia!==im)}function tl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&t.constructor===Object}function nl(t,e){if(t!=null){if(typeof t=="string")t=t?new zt(t,ps):Vn();else if(t.constructor!==zt)if(xi(t))t=t.length?new zt(new Uint8Array(t),ps):Vn();else{if(!e)throw Error();t=void 0}}return t}function Pr(t){return!(!Array.isArray(t)||t.length)&&!!(1&(0|t[F]))}const ou=[];function _n(t){if(2&t)throw Error()}be(ou,55),el=Object.freeze(ou);class Lr{constructor(e,n,s){this.l=0,this.g=e,this.h=n,this.m=s}next(){if(this.l<this.g.length){const e=this.g[this.l++];return{done:!1,value:this.h?this.h.call(this.m,e):e}}return{done:!0,value:void 0}}[Symbol.iterator](){return new Lr(this.g,this.h,this.m)}}function sl(t){return ms?t[ms]:void 0}var $3=Object.freeze({});function ro(t){return t.Qa=!0,t}var H3=ro(t=>typeof t=="number"),au=ro(t=>typeof t=="string"),W3=ro(t=>typeof t=="boolean"),oo=typeof Un.BigInt=="function"&&typeof Un.BigInt(0)=="bigint",Wa=ro(t=>oo?t>=j3&&t<=z3:t[0]==="-"?cu(t,G3):cu(t,q3));const G3=Number.MIN_SAFE_INTEGER.toString(),j3=oo?BigInt(Number.MIN_SAFE_INTEGER):void 0,q3=Number.MAX_SAFE_INTEGER.toString(),z3=oo?BigInt(Number.MAX_SAFE_INTEGER):void 0;function cu(t,e){if(t.length>e.length)return!1;if(t.length<e.length||t===e)return!0;for(let n=0;n<t.length;n++){const s=t[n],i=e[n];if(s>i)return!1;if(s<i)return!0}}const K3=typeof Uint8Array.prototype.slice=="function";let rm,se=0,_e=0;function lu(t){const e=t>>>0;se=e,_e=(t-e)/4294967296>>>0}function gs(t){if(t<0){lu(-t);const[e,n]=al(se,_e);se=e>>>0,_e=n>>>0}else lu(t)}function il(t){const e=rm||(rm=new DataView(new ArrayBuffer(8)));e.setFloat32(0,+t,!0),_e=0,se=e.getUint32(0,!0)}function rl(t,e){const n=4294967296*e+(t>>>0);return Number.isSafeInteger(n)?n:yi(t,e)}function ol(t,e){const n=2147483648&e;return n&&(e=~e>>>0,(t=1+~t>>>0)==0&&(e=e+1>>>0)),typeof(t=rl(t,e))=="number"?n?-t:t:n?"-"+t:t}function yi(t,e){if(t>>>=0,(e>>>=0)<=2097151)var n=""+(4294967296*e+t);else Zc()?n=""+(BigInt(e)<<BigInt(32)|BigInt(t)):(t=(16777215&t)+6777216*(n=16777215&(t>>>24|e<<8))+6710656*(e=e>>16&65535),n+=8147497*e,e*=2,t>=1e7&&(n+=t/1e7>>>0,t%=1e7),n>=1e7&&(e+=n/1e7>>>0,n%=1e7),n=e+hu(n)+hu(t));return n}function hu(t){return t=String(t),"0000000".slice(t.length)+t}function ao(t){if(t.length<16)gs(Number(t));else if(Zc())t=BigInt(t),se=Number(t&BigInt(4294967295))>>>0,_e=Number(t>>BigInt(32)&BigInt(4294967295));else{const e=+(t[0]==="-");_e=se=0;const n=t.length;for(let s=e,i=(n-e)%6+e;i<=n;s=i,i+=6){const r=Number(t.slice(s,i));_e*=1e6,se=1e6*se+r,se>=4294967296&&(_e+=Math.trunc(se/4294967296),_e>>>=0,se>>>=0)}if(e){const[s,i]=al(se,_e);se=s,_e=i}}}function al(t,e){return e=~e,t?t=1+~t:e+=1,[t,e]}const cl=typeof BigInt=="function"?BigInt.asIntN:void 0,Y3=typeof BigInt=="function"?BigInt.asUintN:void 0,is=Number.isSafeInteger,co=Number.isFinite,Or=Math.trunc;function yn(t){return t==null||typeof t=="number"?t:t==="NaN"||t==="Infinity"||t==="-Infinity"?Number(t):void 0}function om(t){return t==null||typeof t=="boolean"?t:typeof t=="number"?!!t:void 0}const X3=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function lo(t){switch(typeof t){case"bigint":return!0;case"number":return co(t);case"string":return X3.test(t);default:return!1}}function Rs(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return co(t)?0|t:void 0}function am(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return co(t)?t>>>0:void 0}function uu(t){if(t[0]==="-")return!1;const e=t.length;return e<20||e===20&&Number(t.substring(0,6))<184467}function ll(t){return t=Or(t),is(t)||(gs(t),t=ol(se,_e)),t}function hl(t){var e=Or(Number(t));if(is(e))return String(e);if((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),e=t.length,!(t[0]==="-"?e<20||e===20&&Number(t.substring(0,7))>-922337:e<19||e===19&&Number(t.substring(0,6))<922337))if(ao(t),t=se,2147483648&(e=_e))if(Zc())t=""+(BigInt(0|e)<<BigInt(32)|BigInt(t>>>0));else{const[n,s]=al(t,e);t="-"+yi(n,s)}else t=yi(t,e);return t}function Mr(t){return t==null?t:typeof t=="bigint"?(Wa(t)?t=Number(t):(t=cl(64,t),t=Wa(t)?Number(t):String(t)),t):lo(t)?typeof t=="number"?ll(t):hl(t):void 0}function Q3(t){if(t==null)return t;var e=typeof t;if(e==="bigint")return String(Y3(64,t));if(lo(t)){if(e==="string")return e=Or(Number(t)),is(e)&&e>=0?t=String(e):((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),uu(t)||(ao(t),t=yi(se,_e))),t;if(e==="number")return(t=Or(t))>=0&&is(t)?t:function(n){if(n<0){gs(n);var s=yi(se,_e);return n=Number(s),is(n)?n:s}return uu(s=String(n))?s:(gs(n),rl(se,_e))}(t)}}function cm(t){if(typeof t!="string")throw Error();return t}function Is(t){if(t!=null&&typeof t!="string")throw Error();return t}function _s(t){return t==null||typeof t=="string"?t:void 0}function ul(t,e,n,s){if(t!=null&&typeof t=="object"&&t.W===Ni)return t;if(!Array.isArray(t))return n?2&s?((t=e[iu])||(As((t=new e).u),t=e[iu]=t),e=t):e=new e:e=void 0,e;let i=n=0|t[F];return i===0&&(i|=32&s),i|=2&s,i!==n&&be(t,i),new e(t)}function J3(t,e,n){if(e)e:{if(!lo(e=t))throw $a("int64");switch(typeof e){case"string":e=hl(e);break e;case"bigint":if(t=e=cl(64,e),au(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(H3(t)&&!Number.isSafeInteger(t))throw Error(String(t));e=oo?BigInt(e):W3(e)?e?"1":"0":au(e)?e.trim()||"0":String(e);break e;default:e=ll(e)}}else e=Mr(t);return typeof(n=(t=e)==null?n?0:void 0:t)=="string"&&is(e=+n)?e:n}const Z3={};let ev=function(){try{return Qc(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class na{constructor(){this.g=new Map}get(e){return this.g.get(e)}set(e,n){return this.g.set(e,n),this.size=this.g.size,this}delete(e){return e=this.g.delete(e),this.size=this.g.size,e}clear(){this.g.clear(),this.size=this.g.size}has(e){return this.g.has(e)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(e,n){return this.g.forEach(e,n)}[Symbol.iterator](){return this.entries()}}const tv=ev?(Object.setPrototypeOf(na.prototype,Map.prototype),Object.defineProperties(na.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),na):class extends Map{constructor(){super()}};function du(t){return t}function sa(t){if(2&t.L)throw Error("Cannot mutate an immutable Map")}var mt=class extends tv{constructor(t,e,n=du,s=du){super();let i=0|t[F];i|=64,be(t,i),this.L=i,this.S=e,this.R=n,this.Y=this.S?nv:s;for(let r=0;r<t.length;r++){const o=t[r],a=n(o[0],!1,!0);let c=o[1];e?c===void 0&&(c=null):c=s(o[1],!1,!0,void 0,void 0,i),super.set(a,c)}}na(t=fu){if(this.size!==0)return this.X(t)}X(t=fu){const e=[],n=super.entries();for(var s;!(s=n.next()).done;)(s=s.value)[0]=t(s[0]),s[1]=t(s[1]),e.push(s);return e}clear(){sa(this),super.clear()}delete(t){return sa(this),super.delete(this.R(t,!0,!1))}entries(){var t=this.ma();return new Lr(t,sv,this)}keys(){return this.Ha()}values(){var t=this.ma();return new Lr(t,mt.prototype.get,this)}forEach(t,e){super.forEach((n,s)=>{t.call(e,this.get(s),s,this)})}set(t,e){return sa(this),(t=this.R(t,!0,!1))==null?this:e==null?(super.delete(t),this):super.set(t,this.Y(e,!0,!0,this.S,!1,this.L))}Na(t){const e=this.R(t[0],!1,!0);t=t[1],t=this.S?t===void 0?null:t:this.Y(t,!1,!0,void 0,!1,this.L),super.set(e,t)}has(t){return super.has(this.R(t,!1,!1))}get(t){t=this.R(t,!1,!1);const e=super.get(t);if(e!==void 0){var n=this.S;return n?((n=this.Y(e,!1,!0,n,this.ra,this.L))!==e&&super.set(t,n),n):e}}ma(){return Array.from(super.keys())}Ha(){return super.keys()}[Symbol.iterator](){return this.entries()}};function nv(t,e,n,s,i,r){return t=ul(t,s,n,r),i&&(t=uo(t)),t}function fu(t){return t}function sv(t){return[t,this.get(t)]}let iv,lm,rv;function pu(){return iv||(iv=new mt(As([]),void 0,void 0,void 0,Z3))}function dl(t,e,n,s,i){if(t!=null){if(Array.isArray(t))t=Pr(t)?void 0:i&&2&(0|t[F])?t:fl(t,e,n,s!==void 0,i);else if(tl(t)){const r={};for(let o in t)r[o]=dl(t[o],e,n,s,i);t=r}else t=e(t,s);return t}}function fl(t,e,n,s,i){const r=s||n?0|t[F]:0,o=s?!!(32&r):void 0;s=ze(t);for(let a=0;a<s.length;a++)s[a]=dl(s[a],e,n,o,i);return n&&((t=sl(t))&&(s[ms]=ze(t)),n(r,s)),s}function ov(t){return dl(t,hm,void 0,void 0,!1)}function hm(t){return t.W===Ni?t.toJSON():t instanceof mt?t.na(ov):function(e){switch(typeof e){case"number":return isFinite(e)?e:String(e);case"bigint":return Wa(e)?Number(e):String(e);case"boolean":return e?1:0;case"object":if(e)if(Array.isArray(e)){if(Pr(e))return}else{if(xi(e))return nu(e);if(e instanceof zt){const n=e.g;return n==null?"":typeof n=="string"?n:e.g=nu(n)}if(e instanceof mt)return e.na()}}return e}(t)}function um(t){return fl(t,hm,void 0,void 0,!1)}function ln(t,e,n){return t=dm(t,e[0],e[1],n?1:2),e!==lm&&n&&io(t,16384),t}function dm(t,e,n,s){if(t==null){var i=96;n?(t=[n],i|=512):t=[],e&&(i=-33521665&i|(1023&e)<<15)}else{if(!Array.isArray(t))throw Error("narr");if(2048&(i=0|t[F]))throw Error("farr");if(64&i)return t;if(s===1||s===2||(i|=64),n&&(i|=512,n!==t[0]))throw Error("mid");e:{if(s=(n=t).length){const r=s-1;if(tl(n[r])){if((e=r-(512&(i|=256)?0:-1))>=1024)throw Error("pvtlmt");i=-33521665&i|(1023&e)<<15;break e}}if(e){if((e=Math.max(e,s-(512&i?0:-1)))>1024)throw Error("spvt");i=-33521665&i|(1023&e)<<15}}}return be(t,i),t}function Ga(t,e,n=Ha){if(t!=null){if(Qp&&t instanceof Uint8Array)return e?t:new Uint8Array(t);if(Array.isArray(t)){var s=0|t[F];return 2&s?t:(e&&(e=s===0||!!(32&s)&&!(64&s||!(16&s))),e?(be(t,-12293&(34|s)),t):fl(t,Ga,4&s?Ha:n,!0,!0))}return t.W===Ni?t=2&(s=0|(n=t.u)[F])?t:new t.constructor(ho(n,s,!0)):t instanceof mt&&!(2&t.L)&&(n=As(t.X(Ga)),t=new mt(n,t.S,t.R,t.Y)),t}}function ho(t,e,n){const s=n||2&e?Ha:V3,i=!!(32&e);return t=function(r,o,a){const c=ze(r);var l=c.length;const h=256&o?c[l-1]:void 0;for(l+=h?-1:0,o=512&o?1:0;o<l;o++)c[o]=a(c[o]);if(h){o=c[o]={};for(const u in h)o[u]=a(h[u])}return(r=sl(r))&&(c[ms]=ze(r)),c}(t,e,r=>Ga(r,i,s)),io(t,32|(n?2:0)),t}function uo(t){const e=t.u,n=0|e[F];return 2&n?new t.constructor(ho(e,n,!1)):t}function ys(t,e){return tn(t=t.u,0|t[F],e)}function tn(t,e,n,s){if(n===-1)return null;var i=n+(512&e?0:-1);const r=t.length-1;return i>=r&&256&e?t[r][n]:s&&256&e&&(e=t[r][n])!=null?(t[i]!=null&&ta!=null&&((i=(t=M3??(M3={}))[ta]||0)>=4||(t[ta]=i+1,tm(t=Error(),"incident"),function(o){Un.setTimeout(()=>{throw o},0)}(t))),e):i<=r?t[i]:void 0}function ae(t,e,n){const s=t.u;let i=0|s[F];return _n(i),ge(s,i,e,n),t}function ge(t,e,n,s){const i=512&e?0:-1,r=n+i;var o=t.length-1;return r>=o&&256&e?(t[o][n]=s,e):r<=o?(t[r]=s,256&e&&n in(t=t[o])&&delete t[n],e):(s!==void 0&&(n>=(o=e>>15&1023||536870912)?s!=null&&(t[o+i]={[n]:s},be(t,e|=256)):t[r]=s),e)}function tr(t,e){let n=0|(t=t.u)[F];const s=tn(t,n,e),i=yn(s);return i!=null&&i!==s&&ge(t,n,e,i),i}function fm(t){let e=0|(t=t.u)[F];const n=tn(t,e,1),s=nl(n,!0);return s!=null&&s!==n&&ge(t,e,1,s),s}function xn(){return $3===void 0?2:4}function Fn(t,e,n,s,i){const r=t.u,o=2&(t=0|r[F])?1:s;i=!!i;let a=0|(s=pl(r,t,e))[F];if(!(4&a)){4&a&&(s=ze(s),a=Kt(a,t),t=ge(r,t,e,s));let c=0,l=0;for(;c<s.length;c++){const h=n(s[c]);h!=null&&(s[l++]=h)}l<c&&(s.length=l),a=ml(a,t),n=-4097&(20|a),a=n&=-8193,be(s,a),2&a&&Object.freeze(s)}return o===1||o===4&&32&a?jt(a)||(i=a,a|=2,a!==i&&be(s,a),Object.freeze(s)):(o===2&&jt(a)&&(s=ze(s),a=Kt(a,t),a=hn(a,t,i),be(s,a),t=ge(r,t,e,s)),jt(a)||(e=a,a=hn(a,t,i),a!==e&&be(s,a))),s}function pl(t,e,n,s){return t=tn(t,e,n,s),Array.isArray(t)?t:el}function ml(t,e){return t===0&&(t=Kt(t,e)),1|t}function jt(t){return!!(2&t)&&!!(4&t)||!!(2048&t)}function pm(t){t=ze(t);for(let e=0;e<t.length;e++){const n=t[e]=ze(t[e]);Array.isArray(n[1])&&(n[1]=As(n[1]))}return t}function ja(t,e,n,s){let i=0|(t=t.u)[F];_n(i),ge(t,i,e,(s==="0"?Number(n)===0:n===s)?void 0:n)}function xs(t,e,n,s,i){_n(e);var r=!(!(64&e)&&16384&e);const o=(i=pl(t,e,n,i))!==el;if(r||!o){let a=r=o?0|i[F]:0;(!o||2&a||jt(a)||4&a&&!(32&a))&&(i=ze(i),a=Kt(a,e),e=ge(t,e,n,i)),a=-13&ml(a,e),a=hn(s?-17&a:16|a,e,!0),a!==r&&be(i,a)}return i}function ia(t,e){var n=sg;return _l(gl(t=t.u),t,0|t[F],n)===e?e:-1}function gl(t){if(so)return t[Gs]??(t[Gs]=new Map);if(Gs in t)return t[Gs];const e=new Map;return Object.defineProperty(t,Gs,{value:e}),e}function mm(t,e,n,s){const i=gl(t),r=_l(i,t,e,n);return r!==s&&(r&&(e=ge(t,e,r)),i.set(n,s)),e}function _l(t,e,n,s){let i=t.get(s);if(i!=null)return i;i=0;for(let r=0;r<s.length;r++){const o=s[r];tn(e,n,o)!=null&&(i!==0&&(n=ge(e,n,i)),i=o)}return t.set(s,i),i}function yl(t,e,n,s){let i,r=0|t[F];if((s=tn(t,r,n,s))!=null&&s.W===Ni)return(e=uo(s))!==s&&ge(t,r,n,e),e.u;if(Array.isArray(s)){const o=0|s[F];i=2&o?ln(ho(s,o,!1),e,!0):64&o?s:ln(i,e,!0)}else i=ln(void 0,e,!0);return i!==s&&ge(t,r,n,i),i}function gm(t,e,n,s){let i=0|(t=t.u)[F];return(e=ul(s=tn(t,i,n,s),e,!1,i))!==s&&e!=null&&ge(t,i,n,e),e}function z(t,e,n,s=!1){if((e=gm(t,e,n,s))==null)return e;if(!(2&(s=0|(t=t.u)[F]))){const i=uo(e);i!==e&&ge(t,s,n,e=i)}return e}function _m(t,e,n,s,i,r,o){t=t.u;var a=!!(2&e);const c=a?1:i;r=!!r,o&&(o=!a);var l=0|(i=pl(t,e,s))[F];if(!(a=!!(4&l))){var h=i,u=e;const d=!!(2&(l=ml(l,e)));d&&(u|=2);let p=!d,m=!0,y=0,w=0;for(;y<h.length;y++){const k=ul(h[y],n,!1,u);if(k instanceof n){if(!d){const E=!!(2&(0|k.u[F]));p&&(p=!E),m&&(m=E)}h[w++]=k}}w<y&&(h.length=w),l|=4,l=m?16|l:-17&l,be(h,l=p?8|l:-9&l),d&&Object.freeze(h)}if(o&&!(8&l||!i.length&&(c===1||c===4&&32&l))){for(jt(l)&&(i=ze(i),l=Kt(l,e),e=ge(t,e,s,i)),n=i,o=l,h=0;h<n.length;h++)(l=n[h])!==(u=uo(l))&&(n[h]=u);o|=8,be(n,o=n.length?-17&o:16|o),l=o}return c===1||c===4&&32&l?jt(l)||(e=l,(l|=!i.length||16&l&&(!a||32&l)?2:2048)!==e&&be(i,l),Object.freeze(i)):(c===2&&jt(l)&&(be(i=ze(i),l=hn(l=Kt(l,e),e,r)),e=ge(t,e,s,i)),jt(l)||(s=l,(l=hn(l,e,r))!==s&&be(i,l))),i}function Qt(t,e,n){const s=0|t.u[F];return _m(t,s,e,n,xn(),!1,!(2&s))}function N(t,e,n,s){return s==null&&(s=void 0),ae(t,n,s)}function ii(t,e,n,s){s==null&&(s=void 0);e:{let i=0|(t=t.u)[F];if(_n(i),s==null){const r=gl(t);if(_l(r,t,i,n)!==e)break e;r.set(n,0)}else i=mm(t,i,n,e);ge(t,i,e,s)}}function Kt(t,e){return-2049&(t=32|(2&e?2|t:-3&t))}function hn(t,e,n){return 32&e&&n||(t&=-33),t}function Br(t,e,n,s){const i=0|t.u[F];_n(i),t=_m(t,i,n,e,2,!0),s=s??new n,t.push(s),t[F]=2&(0|s.u[F])?-9&t[F]:-17&t[F]}function pt(t,e){return Rs(ys(t,e))}function gt(t,e){return _s(ys(t,e))}function Ee(t,e){return tr(t,e)??0}function vi(t,e,n){if(n!=null&&typeof n!="boolean")throw t=typeof n,Error(`Expected boolean but got ${t!="object"?t:n?Array.isArray(n)?"array":t:"null"}: ${n}`);ae(t,e,n)}function Mt(t,e,n){if(n!=null){if(typeof n!="number"||!co(n))throw $a("int32");n|=0}ae(t,e,n)}function I(t,e,n){if(n!=null&&typeof n!="number")throw Error(`Value of float/double field must be a number, found ${typeof n}: ${n}`);ae(t,e,n)}function Ur(t,e,n){{const o=t.u;let a=0|o[F];if(_n(a),n==null)ge(o,a,e);else{var s=t=0|n[F],i=jt(t),r=i||Object.isFrozen(n);for(i||(t=0),r||(n=ze(n),s=0,t=hn(t=Kt(t,a),a,!0),r=!1),t|=21,i=0;i<n.length;i++){const c=n[i],l=cm(c);Object.is(c,l)||(r&&(n=ze(n),s=0,t=hn(t=Kt(t,a),a,!0),r=!1),n[i]=l)}t!==s&&(r&&(n=ze(n),t=hn(t=Kt(t,a),a,!0)),be(n,t)),ge(o,a,e,n)}}}function fo(t,e,n){_n(0|t.u[F]),Fn(t,e,_s,2,!0).push(cm(n))}function ym(t,e){return Error(`Invalid wire type: ${t} (at position ${e})`)}function vl(){return Error("Failed to read varint, encoding is invalid.")}function vm(t,e){return Error(`Tried to read past the end of the data ${e} > ${t}`)}function El(t){if(typeof t=="string")return{buffer:Zp(t),N:!1};if(Array.isArray(t))return{buffer:new Uint8Array(t),N:!1};if(t.constructor===Uint8Array)return{buffer:t,N:!1};if(t.constructor===ArrayBuffer)return{buffer:new Uint8Array(t),N:!1};if(t.constructor===zt)return{buffer:Jc(t)||new Uint8Array(0),N:!0};if(t instanceof Uint8Array)return{buffer:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),N:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}function wl(t,e){let n,s=0,i=0,r=0;const o=t.h;let a=t.g;do n=o[a++],s|=(127&n)<<r,r+=7;while(r<32&&128&n);for(r>32&&(i|=(127&n)>>4),r=3;r<32&&128&n;r+=7)n=o[a++],i|=(127&n)<<r;if(Dn(t,a),n<128)return e(s>>>0,i>>>0);throw vl()}function bl(t){let e=0,n=t.g;const s=n+10,i=t.h;for(;n<s;){const r=i[n++];if(e|=r,(128&r)==0)return Dn(t,n),!!(127&e)}throw vl()}function pn(t){const e=t.h;let n=t.g,s=e[n++],i=127&s;if(128&s&&(s=e[n++],i|=(127&s)<<7,128&s&&(s=e[n++],i|=(127&s)<<14,128&s&&(s=e[n++],i|=(127&s)<<21,128&s&&(s=e[n++],i|=s<<28,128&s&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++])))))throw vl();return Dn(t,n),i}function Jt(t){return pn(t)>>>0}function qa(t){var e=t.h;const n=t.g,s=e[n],i=e[n+1],r=e[n+2];return e=e[n+3],Dn(t,t.g+4),(s<<0|i<<8|r<<16|e<<24)>>>0}function za(t){var e=qa(t);t=2*(e>>31)+1;const n=e>>>23&255;return e&=8388607,n==255?e?NaN:t*(1/0):n==0?1401298464324817e-60*t*e:t*Math.pow(2,n-150)*(e+8388608)}function av(t){return pn(t)}function ra(t,e,{ba:n=!1}={}){t.ba=n,e&&(e=El(e),t.h=e.buffer,t.m=e.N,t.j=0,t.l=t.h.length,t.g=t.j)}function Dn(t,e){if(t.g=e,e>t.l)throw vm(t.l,e)}function Em(t,e){if(e<0)throw Error(`Tried to read a negative byte length: ${e}`);const n=t.g,s=n+e;if(s>t.l)throw vm(e,t.l-n);return t.g=s,n}function wm(t,e){if(e==0)return Vn();var n=Em(t,e);return t.ba&&t.m?n=t.h.subarray(n,n+e):(t=t.h,n=n===(e=n+e)?new Uint8Array(0):K3?t.slice(n,e):new Uint8Array(t.subarray(n,e))),n.length==0?Vn():new zt(n,ps)}mt.prototype.toJSON=void 0,mt.prototype.Ia=im;var mu=[];function bm(t){var e=t.g;if(e.g==e.l)return!1;t.l=t.g.g;var n=Jt(t.g);if(e=n>>>3,!((n&=7)>=0&&n<=5))throw ym(n,t.l);if(e<1)throw Error(`Invalid field number: ${e} (at position ${t.l})`);return t.m=e,t.h=n,!0}function nr(t){switch(t.h){case 0:t.h!=0?nr(t):bl(t.g);break;case 1:Dn(t=t.g,t.g+8);break;case 2:if(t.h!=2)nr(t);else{var e=Jt(t.g);Dn(t=t.g,t.g+e)}break;case 5:Dn(t=t.g,t.g+4);break;case 3:for(e=t.m;;){if(!bm(t))throw Error("Unmatched start-group tag: stream EOF");if(t.h==4){if(t.m!=e)throw Error("Unmatched end-group tag");break}nr(t)}break;default:throw ym(t.h,t.l)}}function Di(t,e,n){const s=t.g.l,i=Jt(t.g),r=t.g.g+i;let o=r-s;if(o<=0&&(t.g.l=r,n(e,t,void 0,void 0,void 0),o=r-t.g.g),o)throw Error(`Message parsing ended unexpectedly. Expected to read ${i} bytes, instead read ${i-o} bytes, either the data ended unexpectedly or the message misreported its own length`);return t.g.g=r,t.g.l=s,e}function Cl(t){var e=Jt(t.g),n=Em(t=t.g,e);if(t=t.h,I3){var s,i=t;(s=Qo)||(s=Qo=new TextDecoder("utf-8",{fatal:!0})),e=n+e,i=n===0&&e===i.length?i:i.subarray(n,e);try{var r=s.decode(i)}catch(a){if(Hi===void 0){try{s.decode(new Uint8Array([128]))}catch{}try{s.decode(new Uint8Array([97])),Hi=!0}catch{Hi=!1}}throw!Hi&&(Qo=void 0),a}}else{e=(r=n)+e,n=[];let a,c=null;for(;r<e;){var o=t[r++];o<128?n.push(o):o<224?r>=e?En():(a=t[r++],o<194||(192&a)!=128?(r--,En()):n.push((31&o)<<6|63&a)):o<240?r>=e-1?En():(a=t[r++],(192&a)!=128||o===224&&a<160||o===237&&a>=160||(192&(s=t[r++]))!=128?(r--,En()):n.push((15&o)<<12|(63&a)<<6|63&s)):o<=244?r>=e-2?En():(a=t[r++],(192&a)!=128||a-144+(o<<28)>>30!=0||(192&(s=t[r++]))!=128||(192&(i=t[r++]))!=128?(r--,En()):(o=(7&o)<<18|(63&a)<<12|(63&s)<<6|63&i,o-=65536,n.push(55296+(o>>10&1023),56320+(1023&o)))):En(),n.length>=8192&&(c=Jh(c,n),n.length=0)}r=Jh(c,n)}return r}function Cm(t){const e=Jt(t.g);return wm(t.g,e)}function po(t,e,n){var s=Jt(t.g);for(s=t.g.g+s;t.g.g<s;)n.push(e(t.g))}var Wi=[];function cv(t){return t}let rs;function St(t,e,n){e.g?e.m(t,e.g,e.h,n):e.m(t,e.h,n)}var A=class{constructor(t,e){this.u=dm(t,e)}toJSON(){const t=!rs;try{return t&&(rs=um),Tm(this)}finally{t&&(rs=void 0)}}l(){var t=Gv;return t.g?t.l(this,t.g,t.h,!0):t.l(this,t.h,t.defaultValue,!0)}clone(){const t=this.u;return new this.constructor(ho(t,0|t[F],!1))}N(){return!!(2&(0|this.u[F]))}};function Tm(t){var e=t.u;{e=(t=rs(e))!==e;let l=t.length;if(l){var n=t[l-1],s=tl(n);s?l--:n=void 0;var i=t;if(s){e:{var r,o=n,a=!1;if(o)for(let h in o)isNaN(+h)?(r??(r={}))[h]=o[h]:(s=o[h],Array.isArray(s)&&(Pr(s)||ru(s)&&s.size===0)&&(s=null),s==null&&(a=!0),s!=null&&((r??(r={}))[h]=s));if(a||(r=o),r)for(let h in r){a=r;break e}a=null}o=a==null?n!=null:a!==n}for(;l>0&&((r=i[l-1])==null||Pr(r)||ru(r)&&r.size===0);l--)var c=!0;(i!==t||o||c)&&(e?(c||o||a)&&(i.length=l):i=Array.prototype.slice.call(i,0,l),a&&i.push(a)),c=i}else c=t}return c}function gu(t){return t?/^\d+$/.test(t)?(ao(t),new Ka(se,_e)):null:lv||(lv=new Ka(0,0))}A.prototype.W=Ni,A.prototype.toString=function(){try{return rs=cv,Tm(this).toString()}finally{rs=void 0}};var Ka=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let lv;function _u(t){return t?/^-?\d+$/.test(t)?(ao(t),new Ya(se,_e)):null:hv||(hv=new Ya(0,0))}var Ya=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let hv;function os(t,e,n){for(;n>0||e>127;)t.g.push(127&e|128),e=(e>>>7|n<<25)>>>0,n>>>=7;t.g.push(e)}function Fs(t,e){for(;e>127;)t.g.push(127&e|128),e>>>=7;t.g.push(e)}function mo(t,e){if(e>=0)Fs(t,e);else{for(let n=0;n<9;n++)t.g.push(127&e|128),e>>=7;t.g.push(1)}}function Ei(t,e){t.g.push(e>>>0&255),t.g.push(e>>>8&255),t.g.push(e>>>16&255),t.g.push(e>>>24&255)}function vs(t,e){e.length!==0&&(t.l.push(e),t.h+=e.length)}function rt(t,e,n){Fs(t.g,8*e+n)}function Tl(t,e){return rt(t,e,2),e=t.g.end(),vs(t,e),e.push(t.h),e}function Sl(t,e){var n=e.pop();for(n=t.h+t.g.length()-n;n>127;)e.push(127&n|128),n>>>=7,t.h++;e.push(n),t.h++}function go(t,e,n){rt(t,e,2),Fs(t.g,n.length),vs(t,t.g.end()),vs(t,n)}function Vr(t,e,n,s){n!=null&&(e=Tl(t,e),s(n,t),Sl(t,e))}function kt(){const t=class{constructor(){throw Error()}};return Object.setPrototypeOf(t,t.prototype),t}var kl=kt(),Sm=kt(),Al=kt(),Rl=kt(),km=kt(),Am=kt(),Il=kt(),Rm=kt(),Im=kt(),Ns=class{constructor(t,e,n){this.g=t,this.h=e,t=kl,this.l=!!t&&n===t||!1}};function _o(t,e){return new Ns(t,e,kl)}function xm(t,e,n,s,i){Vr(t,n,Pm(e,s),i)}const uv=_o(function(t,e,n,s,i){return t.h===2&&(Di(t,yl(e,s,n),i),!0)},xm),dv=_o(function(t,e,n,s,i){return t.h===2&&(Di(t,yl(e,s,n,!0),i),!0)},xm);var yo=Symbol(),xl=Symbol(),yu=Symbol(),vu=Symbol();let Fm,Nm;function Gn(t,e,n,s){var i=s[t];if(i)return i;(i={}).Pa=s,i.V=function(u){switch(typeof u){case"boolean":return lm||(lm=[0,void 0,!0]);case"number":return u>0?void 0:u===0?rv||(rv=[0,void 0]):[-u,void 0];case"string":return[0,u];case"object":return u}}(s[0]);var r=s[1];let o=1;r&&r.constructor===Object&&(i.ga=r,typeof(r=s[++o])=="function"&&(i.la=!0,Fm??(Fm=r),Nm??(Nm=s[o+1]),r=s[o+=2]));const a={};for(;r&&Array.isArray(r)&&r.length&&typeof r[0]=="number"&&r[0]>0;){for(var c=0;c<r.length;c++)a[r[c]]=r;r=s[++o]}for(c=1;r!==void 0;){let u;typeof r=="number"&&(c+=r,r=s[++o]);var l=void 0;if(r instanceof Ns?u=r:(u=uv,o--),u==null?void 0:u.l){r=s[++o],l=s;var h=o;typeof r=="function"&&(r=r(),l[h]=r),l=r}for(h=c+1,typeof(r=s[++o])=="number"&&r<0&&(h-=r,r=s[++o]);c<h;c++){const d=a[c];l?n(i,c,u,l,d):e(i,c,u,d)}}return s[t]=i}function Dm(t){return Array.isArray(t)?t[0]instanceof Ns?t:[dv,t]:[t,void 0]}function Pm(t,e){return t instanceof A?t.u:Array.isArray(t)?ln(t,e,!1):void 0}function Fl(t,e,n,s){const i=n.g;t[e]=s?(r,o,a)=>i(r,o,a,s):i}function Nl(t,e,n,s,i){const r=n.g;let o,a;t[e]=(c,l,h)=>r(c,l,h,a||(a=Gn(xl,Fl,Nl,s).V),o||(o=Dl(s)),i)}function Dl(t){let e=t[yu];if(e!=null)return e;const n=Gn(xl,Fl,Nl,t);return e=n.la?(s,i)=>Fm(s,i,n):(s,i)=>{const r=0|s[F];for(;bm(i)&&i.h!=4;){var o=i.m,a=n[o];if(a==null){var c=n.ga;c&&(c=c[o])&&(c=fv(c))!=null&&(a=n[o]=c)}a!=null&&a(i,s,o)||(o=(a=i).l,nr(a),a.fa?a=void 0:(c=a.g.g-o,a.g.g=o,a=wm(a.g,c)),o=s,a&&((c=o[ms])?c.push(a):o[ms]=[a]))}return 16384&r&&As(s),!0},t[yu]=e}function fv(t){const e=(t=Dm(t))[0].g;if(t=t[1]){const n=Dl(t),s=Gn(xl,Fl,Nl,t).V;return(i,r,o)=>e(i,r,o,s,n)}return e}function vo(t,e,n){t[e]=n.h}function Eo(t,e,n,s){let i,r;const o=n.h;t[e]=(a,c,l)=>o(a,c,l,r||(r=Gn(yo,vo,Eo,s).V),i||(i=Lm(s)))}function Lm(t){let e=t[vu];if(!e){const n=Gn(yo,vo,Eo,t);e=(s,i)=>Om(s,i,n),t[vu]=e}return e}function Om(t,e,n){for(var s=0|t[F],i=512&s?0:-1,r=t.length,o=512&s?1:0,a=r+(256&s?-1:0);o<a;o++){const c=t[o];if(c==null)continue;const l=o-i,h=Eu(n,l);h&&h(e,c,l)}if(256&s){s=t[r-1];for(const c in s)i=+c,Number.isNaN(i)||(r=s[i])!=null&&(a=Eu(n,i))&&a(e,r,i)}if(t=sl(t))for(vs(e,e.g.end()),n=0;n<t.length;n++)vs(e,Jc(t[n])||new Uint8Array(0))}function Eu(t,e){var n=t[e];if(n)return n;if((n=t.ga)&&(n=n[e])){var s=(n=Dm(n))[0].h;if(n=n[1]){const i=Lm(n),r=Gn(yo,vo,Eo,n).V;n=t.la?Nm(r,i):(o,a,c)=>s(o,a,c,r,i)}else n=s;return t[e]=n}}function Ds(t,e){if(Array.isArray(e)){var n=0|e[F];if(4&n)return e;for(var s=0,i=0;s<e.length;s++){const r=t(e[s]);r!=null&&(e[i++]=r)}return i<s&&(e.length=i),be(e,-12289&(5|n)),2&n&&Object.freeze(e),e}}function He(t,e,n){return new Ns(t,e,n)}function Ps(t,e,n){return new Ns(t,e,n)}function We(t,e,n){ge(t,0|t[F],e,n)}var pv=_o(function(t,e,n,s,i){return t.h===2&&(t=Di(t,ln([void 0,void 0],s,!0),i),_n(s=0|e[F]),(i=tn(e,s,n))instanceof mt?(2&i.L)!=0?((i=i.X()).push(t),ge(e,s,n,i)):i.Na(t):Array.isArray(i)?(2&(0|i[F])&&ge(e,s,n,i=pm(i)),i.push(t)):ge(e,s,n,[t]),!0)},function(t,e,n,s,i){if(e instanceof mt)e.forEach((r,o)=>{Vr(t,n,ln([o,r],s,!1),i)});else if(Array.isArray(e))for(let r=0;r<e.length;r++){const o=e[r];Array.isArray(o)&&Vr(t,n,ln(o,s,!1),i)}});function Mm(t,e,n){if(e=function(s){if(s==null)return s;const i=typeof s;if(i==="bigint")return String(cl(64,s));if(lo(s)){if(i==="string")return hl(s);if(i==="number")return ll(s)}}(e),e!=null&&(typeof e=="string"&&_u(e),e!=null))switch(rt(t,n,0),typeof e){case"number":t=t.g,gs(e),os(t,se,_e);break;case"bigint":n=BigInt.asUintN(64,e),n=new Ya(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),os(t.g,n.h,n.g);break;default:n=_u(e),os(t.g,n.h,n.g)}}function Bm(t,e,n){(e=Rs(e))!=null&&e!=null&&(rt(t,n,0),mo(t.g,e))}function Um(t,e,n){(e=om(e))!=null&&(rt(t,n,0),t.g.g.push(e?1:0))}function Vm(t,e,n){(e=_s(e))!=null&&go(t,n,Kp(e))}function $m(t,e,n,s,i){Vr(t,n,Pm(e,s),i)}function Hm(t,e,n){(e=e==null||typeof e=="string"||xi(e)||e instanceof zt?e:void 0)!=null&&go(t,n,El(e).buffer)}function Wm(t,e,n){return(t.h===5||t.h===2)&&(e=xs(e,0|e[F],n,!1,!1),t.h==2?po(t,za,e):e.push(za(t.g)),!0)}var Ht=He(function(t,e,n){if(t.h!==1)return!1;var s=t.g;t=qa(s);const i=qa(s);s=2*(i>>31)+1;const r=i>>>20&2047;return t=4294967296*(1048575&i)+t,We(e,n,r==2047?t?NaN:s*(1/0):r==0?5e-324*s*t:s*Math.pow(2,r-1075)*(t+4503599627370496)),!0},function(t,e,n){(e=yn(e))!=null&&(rt(t,n,1),t=t.g,(n=rm||(rm=new DataView(new ArrayBuffer(8)))).setFloat64(0,+e,!0),se=n.getUint32(0,!0),_e=n.getUint32(4,!0),Ei(t,se),Ei(t,_e))},kt()),Ce=He(function(t,e,n){return t.h===5&&(We(e,n,za(t.g)),!0)},function(t,e,n){(e=yn(e))!=null&&(rt(t,n,5),t=t.g,il(e),Ei(t,se))},Il),mv=Ps(Wm,function(t,e,n){if((e=Ds(yn,e))!=null)for(let o=0;o<e.length;o++){var s=t,i=n,r=e[o];r!=null&&(rt(s,i,5),s=s.g,il(r),Ei(s,se))}},Il),Pl=Ps(Wm,function(t,e,n){if((e=Ds(yn,e))!=null&&e.length){rt(t,n,2),Fs(t.g,4*e.length);for(let s=0;s<e.length;s++)n=t.g,il(e[s]),Ei(n,se)}},Il),mn=He(function(t,e,n){return t.h===0&&(We(e,n,wl(t.g,ol)),!0)},Mm,Am),oa=He(function(t,e,n){return t.h===0&&(We(e,n,(t=wl(t.g,ol))===0?void 0:t),!0)},Mm,Am),gv=He(function(t,e,n){return t.h===0&&(We(e,n,wl(t.g,rl)),!0)},function(t,e,n){if((e=Q3(e))!=null&&(typeof e=="string"&&gu(e),e!=null))switch(rt(t,n,0),typeof e){case"number":t=t.g,gs(e),os(t,se,_e);break;case"bigint":n=BigInt.asUintN(64,e),n=new Ka(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),os(t.g,n.h,n.g);break;default:n=gu(e),os(t.g,n.h,n.g)}},kt()),ve=He(function(t,e,n){return t.h===0&&(We(e,n,pn(t.g)),!0)},Bm,Rl),wo=Ps(function(t,e,n){return(t.h===0||t.h===2)&&(e=xs(e,0|e[F],n,!1,!1),t.h==2?po(t,pn,e):e.push(pn(t.g)),!0)},function(t,e,n){if((e=Ds(Rs,e))!=null&&e.length){n=Tl(t,n);for(let s=0;s<e.length;s++)mo(t.g,e[s]);Sl(t,n)}},Rl),Qn=He(function(t,e,n){return t.h===0&&(We(e,n,(t=pn(t.g))===0?void 0:t),!0)},Bm,Rl),fe=He(function(t,e,n){return t.h===0&&(We(e,n,bl(t.g)),!0)},Um,Sm),as=He(function(t,e,n){return t.h===0&&(We(e,n,(t=bl(t.g))===!1?void 0:t),!0)},Um,Sm),Le=Ps(function(t,e,n){return t.h===2&&(t=Cl(t),xs(e,0|e[F],n,!1).push(t),!0)},function(t,e,n){if((e=Ds(_s,e))!=null)for(let o=0;o<e.length;o++){var s=t,i=n,r=e[o];r!=null&&go(s,i,Kp(r))}},Al),rn=He(function(t,e,n){return t.h===2&&(We(e,n,(t=Cl(t))===""?void 0:t),!0)},Vm,Al),Z=He(function(t,e,n){return t.h===2&&(We(e,n,Cl(t)),!0)},Vm,Al),Ae=function(t,e,n=kl){return new Ns(t,e,n)}(function(t,e,n,s,i){return t.h===2&&(s=ln(void 0,s,!0),xs(e,0|e[F],n,!0).push(s),Di(t,s,i),!0)},function(t,e,n,s,i){if(Array.isArray(e))for(let r=0;r<e.length;r++)$m(t,e[r],n,s,i)}),ee=_o(function(t,e,n,s,i,r){return t.h===2&&(mm(e,0|e[F],r,n),Di(t,e=yl(e,s,n),i),!0)},$m),Gm=He(function(t,e,n){return t.h===2&&(We(e,n,Cm(t)),!0)},Hm,Rm),_v=Ps(function(t,e,n){return(t.h===0||t.h===2)&&(e=xs(e,0|e[F],n,!1,!1),t.h==2?po(t,Jt,e):e.push(Jt(t.g)),!0)},function(t,e,n){if((e=Ds(am,e))!=null)for(let o=0;o<e.length;o++){var s=t,i=n,r=e[o];r!=null&&(rt(s,i,0),Fs(s.g,r))}},km),yv=He(function(t,e,n){return t.h===0&&(We(e,n,(t=Jt(t.g))===0?void 0:t),!0)},function(t,e,n){(e=am(e))!=null&&e!=null&&(rt(t,n,0),Fs(t.g,e))},km),_t=He(function(t,e,n){return t.h===0&&(We(e,n,pn(t.g)),!0)},function(t,e,n){(e=Rs(e))!=null&&(e=parseInt(e,10),rt(t,n,0),mo(t.g,e))},Im);class vv{constructor(e,n){this.h=e,this.g=n,this.l=z,this.m=N,this.defaultValue=void 0}}function At(t,e){return new vv(t,e)}function vn(t,e){return(n,s)=>{if(Wi.length){const r=Wi.pop();r.o(s),ra(r.g,n,s),n=r}else n=new class{constructor(r,o){if(mu.length){const a=mu.pop();ra(a,r,o),r=a}else r=new class{constructor(a,c){this.h=null,this.m=!1,this.g=this.l=this.j=0,ra(this,a,c)}clear(){this.h=null,this.m=!1,this.g=this.l=this.j=0,this.ba=!1}}(r,o);this.g=r,this.l=this.g.g,this.h=this.m=-1,this.o(o)}o({fa:r=!1}={}){this.fa=r}}(n,s);try{const r=new t,o=r.u;Dl(e)(o,n);var i=r}finally{n.g.clear(),n.m=-1,n.h=-1,Wi.length<100&&Wi.push(n)}return i}}function bo(t){return function(){const e=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const o=this.g;return this.g=[],o}}}};Om(this.u,e,Gn(yo,vo,Eo,t)),vs(e,e.g.end());const n=new Uint8Array(e.h),s=e.l,i=s.length;let r=0;for(let o=0;o<i;o++){const a=s[o];n.set(a,r),r+=a.length}return e.l=[n],n}}var wu=class extends A{constructor(t){super(t)}},bu=[0,rn,He(function(t,e,n){return t.h===2&&(We(e,n,(t=Cm(t))===Vn()?void 0:t),!0)},function(t,e,n){if(e!=null){if(e instanceof A){const s=e.Ra;return void(s&&(e=s(e),e!=null&&go(t,n,El(e).buffer)))}if(Array.isArray(e))return}Hm(t,e,n)},Rm)];let aa,Cu=globalThis.trustedTypes;function Tu(t){aa===void 0&&(aa=function(){let n=null;if(!Cu)return n;try{const s=i=>i;n=Cu.createPolicy("goog#html",{createHTML:s,createScript:s,createScriptURL:s})}catch{}return n}());var e=aa;return new class{constructor(n){this.g=n}toString(){return this.g+""}}(e?e.createScriptURL(t):t)}function Ev(t,...e){if(e.length===0)return Tu(t[0]);let n=t[0];for(let s=0;s<e.length;s++)n+=encodeURIComponent(e[s])+t[s+1];return Tu(n)}var jm=[0,ve,_t,fe,-1,wo,_t,-1],wv=class extends A{constructor(t){super(t)}},qm=[0,fe,Z,fe,_t,-1,Ps(function(t,e,n){return(t.h===0||t.h===2)&&(e=xs(e,0|e[F],n,!1,!1),t.h==2?po(t,av,e):e.push(pn(t.g)),!0)},function(t,e,n){if((e=Ds(Rs,e))!=null&&e.length){n=Tl(t,n);for(let s=0;s<e.length;s++)mo(t.g,e[s]);Sl(t,n)}},Im),Z,-1,[0,fe,-1],_t,fe,-1],zm=[0,Z,-2],Su=class extends A{constructor(t){super(t)}},Km=[0],Ym=[0,ve,fe,1,fe,-3],it=class extends A{constructor(t){super(t,2)}},Se={};Se[336783863]=[0,Z,fe,-1,ve,[0,[1,2,3,4,5,6,7,8],ee,Km,ee,qm,ee,zm,ee,Ym,ee,jm,ee,[0,Z,-2],ee,[0,Z,_t],ee,[0,_t,Z]],[0,Z],fe,[0,[1,3],[2,4],ee,[0,wo],-1,ee,[0,Le],-1,Ae,[0,Z,-1]],Z];var ku=[0,oa,-1,as,-3,oa,wo,rn,Qn,oa,-1,as,Qn,as,-2,rn];function ot(t,e){ja(t,2,Is(e),"")}function ce(t,e){fo(t,3,e)}function j(t,e){fo(t,4,e)}var $e=class extends A{constructor(t){super(t,500)}o(t){return N(this,0,7,t)}},ri=[-1,{}],Au=[0,Z,1,ri],Ru=[0,Z,Le,ri];function at(t,e){Br(t,1,$e,e)}function ue(t,e){fo(t,10,e)}function Q(t,e){fo(t,15,e)}var Qe=class extends A{constructor(t){super(t,500)}o(t){return N(this,0,1001,t)}},Xm=[-500,Ae,[-500,rn,-1,Le,-3,[-2,Se,fe],Ae,bu,Qn,-1,Au,Ru,Ae,[0,rn,as],rn,ku,Qn,Le,987,Le],4,Ae,[-500,Z,-1,[-1,{}],998,Z],Ae,[-500,Z,Le,-1,[-2,{},fe],997,Le,-1],Qn,Ae,[-500,Z,Le,ri,998,Le],Le,Qn,Au,Ru,Ae,[0,rn,-1,ri],Le,-2,ku,rn,-1,as,[0,as,yv],978,ri,Ae,bu];Qe.prototype.g=bo(Xm);var bv=vn(Qe,Xm),Cv=class extends A{constructor(t){super(t)}},Qm=class extends A{constructor(t){super(t)}g(){return Qt(this,Cv,1)}},Jm=[0,Ae,[0,ve,Ce,Z,-1]],Co=vn(Qm,Jm),Tv=class extends A{constructor(t){super(t)}},Sv=class extends A{constructor(t){super(t)}},ca=class extends A{constructor(t){super(t)}h(){return z(this,Tv,2)}g(){return Qt(this,Sv,5)}},Zm=vn(class extends A{constructor(t){super(t)}},[0,Le,wo,Pl,[0,_t,[0,ve,-3],[0,Ce,-3],[0,ve,-1,[0,Ae,[0,ve,-2]]],Ae,[0,Ce,-1,Z,Ce]],Z,-1,mn,Ae,[0,ve,Ce],Le,mn]),eg=class extends A{constructor(t){super(t)}},cs=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,Ce,-4]]),tg=class extends A{constructor(t){super(t)}},Pi=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,Ce,-4]]),kv=class extends A{constructor(t){super(t)}},Av=[0,ve,-1,Pl,_t],ng=class extends A{constructor(t){super(t)}};ng.prototype.g=bo([0,Ce,-4,mn]);var Rv=class extends A{constructor(t){super(t)}},Iv=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,1,ve,Z,Jm],mn]),Iu=class extends A{constructor(t){super(t)}},xv=class extends A{constructor(t){super(t)}oa(){const t=fm(this);return t??Vn()}},Fv=class extends A{constructor(t){super(t)}},sg=[1,2],Nv=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,sg,ee,[0,Pl],ee,[0,Gm],ve,Z],mn]),Ll=class extends A{constructor(t){super(t)}},ig=[0,Z,ve,Ce,Le,-1],xu=class extends A{constructor(t){super(t)}},Dv=[0,fe,-1],Fu=class extends A{constructor(t){super(t)}},sr=[1,2,3,4,5],$r=class extends A{constructor(t){super(t)}g(){return fm(this)!=null}h(){return gt(this,2)!=null}},pe=class extends A{constructor(t){super(t)}g(){return om(ys(this,2))??!1}},rg=[0,Gm,Z,[0,ve,mn,-1],[0,gv,mn]],we=[0,rg,fe,[0,sr,ee,Ym,ee,qm,ee,jm,ee,Km,ee,zm],_t],To=class extends A{constructor(t){super(t)}},Ol=[0,we,Ce,-1,ve],Pv=At(502141897,To);Se[502141897]=Ol;var Lv=vn(class extends A{constructor(t){super(t)}},[0,[0,_t,-1,mv,_v],Av]),og=class extends A{constructor(t){super(t)}},ag=class extends A{constructor(t){super(t)}},Ml=[0,we,Ce,[0,we],fe],cg=[0,we,Ol,Ml,Ce,[0,[0,rg]]],Ov=At(508968150,ag);Se[508968150]=cg,Se[508968149]=Ml;var lg=class extends A{constructor(t){super(t)}},Mv=At(513916220,lg);Se[513916220]=[0,we,cg,ve];var zn=class extends A{constructor(t){super(t)}h(){return z(this,Ll,2)}g(){ae(this,2)}},hg=[0,we,ig];Se[478825465]=hg;var Bv=class extends A{constructor(t){super(t)}},ug=class extends A{constructor(t){super(t)}},Bl=class extends A{constructor(t){super(t)}},Ul=class extends A{constructor(t){super(t)}},dg=class extends A{constructor(t){super(t)}},Nu=[0,we,[0,we],hg,-1],fg=[0,we,Ce,ve],Vl=[0,we,Ce],pg=[0,we,fg,Vl,Ce],Uv=At(479097054,dg);Se[479097054]=[0,we,pg,Nu],Se[463370452]=Nu,Se[464864288]=fg;var Vv=At(462713202,Ul);Se[462713202]=pg,Se[474472470]=Vl;var $v=class extends A{constructor(t){super(t)}},mg=class extends A{constructor(t){super(t)}},gg=class extends A{constructor(t){super(t)}},_g=class extends A{constructor(t){super(t)}},$l=[0,we,Ce,-1,ve],Xa=[0,we,Ce,fe];_g.prototype.g=bo([0,we,Vl,[0,we],Ol,Ml,$l,Xa]);var yg=class extends A{constructor(t){super(t)}},Hv=At(456383383,yg);Se[456383383]=[0,we,ig];var vg=class extends A{constructor(t){super(t)}},Wv=At(476348187,vg);Se[476348187]=[0,we,Dv];var Eg=class extends A{constructor(t){super(t)}},Du=class extends A{constructor(t){super(t)}},wg=[0,_t,-1],Gv=At(458105876,class extends A{constructor(t){super(t)}g(){var t=this.u;const e=0|t[F],n=2&e;return t=function(s,i,r){var o=Du;const a=2&i;let c=!1;if(r==null){if(a)return pu();r=[]}else if(r.constructor===mt){if((2&r.L)==0||a)return r;r=r.X()}else Array.isArray(r)?c=!!(2&(0|r[F])):r=[];if(a){if(!r.length)return pu();c||(c=!0,As(r))}else c&&(c=!1,r=pm(r));return c||(64&(0|r[F])?r[F]&=-33:32&i&&io(r,32)),ge(s,i,2,o=new mt(r,o,J3,void 0)),o}(t,e,tn(t,e,2)),!n&&Du&&(t.ra=!0),t}});Se[458105876]=[0,wg,pv,[!0,mn,[0,Z,-1,Le]]];var Hl=class extends A{constructor(t){super(t)}},bg=At(458105758,Hl);Se[458105758]=[0,we,Z,wg];var Cg=class extends A{constructor(t){super(t)}},jv=At(443442058,Cg);Se[443442058]=[0,we,Z,ve,Ce,Le,-1,fe,Ce],Se[514774813]=$l;var Tg=class extends A{constructor(t){super(t)}},qv=At(516587230,Tg);function Qa(t,e){return e=e?e.clone():new Ll,t.displayNamesLocale!==void 0?ae(e,1,Is(t.displayNamesLocale)):t.displayNamesLocale===void 0&&ae(e,1),t.maxResults!==void 0?Mt(e,2,t.maxResults):"maxResults"in t&&ae(e,2),t.scoreThreshold!==void 0?I(e,3,t.scoreThreshold):"scoreThreshold"in t&&ae(e,3),t.categoryAllowlist!==void 0?Ur(e,4,t.categoryAllowlist):"categoryAllowlist"in t&&ae(e,4),t.categoryDenylist!==void 0?Ur(e,5,t.categoryDenylist):"categoryDenylist"in t&&ae(e,5),e}function Wl(t,e=-1,n=""){return{categories:t.map(s=>({index:pt(s,1)??0??-1,score:Ee(s,2)??0,categoryName:gt(s,3)??""??"",displayName:gt(s,4)??""??""})),headIndex:e,headName:n}}function Sg(t){var o,a;var e=Fn(t,3,yn,xn()),n=Fn(t,2,Rs,xn()),s=Fn(t,1,_s,xn()),i=Fn(t,9,_s,xn());const r={categories:[],keypoints:[]};for(let c=0;c<e.length;c++)r.categories.push({score:e[c],index:n[c]??-1,categoryName:s[c]??"",displayName:i[c]??""});if((e=(o=z(t,ca,4))==null?void 0:o.h())&&(r.boundingBox={originX:pt(e,1)??0,originY:pt(e,2)??0,width:pt(e,3)??0,height:pt(e,4)??0,angle:0}),(a=z(t,ca,4))==null?void 0:a.g().length)for(const c of z(t,ca,4).g())r.keypoints.push({x:tr(c,1)??0,y:tr(c,2)??0,score:tr(c,4)??0,label:gt(c,3)??""});return r}function So(t){const e=[];for(const n of Qt(t,tg,1))e.push({x:Ee(n,1)??0,y:Ee(n,2)??0,z:Ee(n,3)??0,visibility:Ee(n,4)??0});return e}function oi(t){const e=[];for(const n of Qt(t,eg,1))e.push({x:Ee(n,1)??0,y:Ee(n,2)??0,z:Ee(n,3)??0,visibility:Ee(n,4)??0});return e}function Pu(t){return Array.from(t,e=>e>127?e-256:e)}function Lu(t,e){if(t.length!==e.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${t.length} vs. ${e.length}).`);let n=0,s=0,i=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r],s+=t[r]*t[r],i+=e[r]*e[r];if(s<=0||i<=0)throw Error("Cannot compute cosine similarity on embedding with 0 norm.");return n/Math.sqrt(s*i)}let Gi;Se[516587230]=[0,we,$l,Xa,Ce],Se[518928384]=Xa;const zv=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);async function kg(){if(Gi===void 0)try{await WebAssembly.instantiate(zv),Gi=!0}catch{Gi=!1}return Gi}async function js(t,e=Ev``){const n=await kg()?"wasm_internal":"wasm_nosimd_internal";return{wasmLoaderPath:`${e}/${t}_${n}.js`,wasmBinaryPath:`${e}/${t}_${n}.wasm`}}var Sn=class{};function Ag(){var t=navigator;return typeof OffscreenCanvas<"u"&&(!function(e=navigator){return(e=e.userAgent).includes("Safari")&&!e.includes("Chrome")}(t)||!!((t=t.userAgent.match(/Version\/([\d]+).*Safari/))&&t.length>=1&&Number(t[1])>=17))}async function Ou(t){if(typeof importScripts!="function"){const e=document.createElement("script");return e.src=t.toString(),e.crossOrigin="anonymous",new Promise((n,s)=>{e.addEventListener("load",()=>{n()},!1),e.addEventListener("error",i=>{s(i)},!1),document.body.appendChild(e)})}importScripts(t.toString())}function Rg(t){return t.videoWidth!==void 0?[t.videoWidth,t.videoHeight]:t.naturalWidth!==void 0?[t.naturalWidth,t.naturalHeight]:t.displayWidth!==void 0?[t.displayWidth,t.displayHeight]:[t.width,t.height]}function x(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(e=t.i.stringToNewUTF8(e)),t.i._free(e)}function Mu(t,e,n){if(!t.i.canvas)throw Error("No OpenGL canvas configured.");if(n?t.i._bindTextureToStream(n):t.i._bindTextureToCanvas(),!(n=t.i.canvas.getContext("webgl2")||t.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[s,i]=Rg(e);return!t.l||s===t.i.canvas.width&&i===t.i.canvas.height||(t.i.canvas.width=s,t.i.canvas.height=i),[s,i]}function Bu(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const s=new Uint32Array(e.length);for(let i=0;i<e.length;i++)s[i]=t.i.stringToNewUTF8(e[i]);e=t.i._malloc(4*s.length),t.i.HEAPU32.set(s,e>>2),n(e);for(const i of s)t.i._free(i);t.i._free(e)}function Ft(t,e,n){t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=n}function nn(t,e,n){let s=[];t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=(i,r,o)=>{r?(n(s,o),s=[]):s.push(i)}}Sn.forVisionTasks=function(t){return js("vision",t)},Sn.forTextTasks=function(t){return js("text",t)},Sn.forGenAiExperimentalTasks=function(t){return js("genai_experimental",t)},Sn.forGenAiTasks=function(t){return js("genai",t)},Sn.forAudioTasks=function(t){return js("audio",t)},Sn.isSimdSupported=function(){return kg()};async function Kv(t,e,n,s){return t=await(async(i,r,o,a,c)=>{if(r&&await Ou(r),!self.ModuleFactory||o&&(await Ou(o),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((r=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(r.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new i(c,a)})(t,n.wasmLoaderPath,n.assetLoaderPath,e,{locateFile:i=>i.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&i.endsWith(".data")?n.assetBinaryPath.toString():i}),await t.o(s),t}function la(t,e){const n=z(t.baseOptions,$r,1)||new $r;typeof e=="string"?(ae(n,2,Is(e)),ae(n,1)):e instanceof Uint8Array&&(ae(n,1,nl(e,!1)),ae(n,2)),N(t.baseOptions,0,1,n)}function Uu(t){try{const e=t.G.length;if(e===1)throw Error(t.G[0].message);if(e>1)throw Error("Encountered multiple errors: "+t.G.map(n=>n.message).join(", "))}finally{t.G=[]}}function S(t,e){t.B=Math.max(t.B,e)}function ko(t,e){t.A=new $e,ot(t.A,"PassThroughCalculator"),ce(t.A,"free_memory"),j(t.A,"free_memory_unused_out"),ue(e,"free_memory"),at(e,t.A)}function Es(t,e){ce(t.A,e),j(t.A,e+"_unused_out")}function Ao(t){t.g.addBoolToStream(!0,"free_memory",t.B)}var ir=class{constructor(t){this.g=t,this.G=[],this.B=0,this.g.setAutoRenderToScreen(!1)}l(t,e=!0){var n,s,i,r,o,a;if(e){const c=t.baseOptions||{};if((n=t.baseOptions)!=null&&n.modelAssetBuffer&&((s=t.baseOptions)!=null&&s.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((i=z(this.baseOptions,$r,1))!=null&&i.g()||(r=z(this.baseOptions,$r,1))!=null&&r.h()||(o=t.baseOptions)!=null&&o.modelAssetBuffer||(a=t.baseOptions)!=null&&a.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(l,h){let u=z(l.baseOptions,Fu,3);if(!u){var d=u=new Fu,p=new Su;ii(d,4,sr,p)}"delegate"in h&&(h.delegate==="GPU"?(h=u,d=new wv,ii(h,2,sr,d)):(h=u,d=new Su,ii(h,4,sr,d))),N(l.baseOptions,0,3,u)}(this,c),c.modelAssetPath)return fetch(c.modelAssetPath.toString()).then(l=>{if(l.ok)return l.arrayBuffer();throw Error(`Failed to fetch model: ${c.modelAssetPath} (${l.status})`)}).then(l=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(l),!0,!1,!1),la(this,"/model.dat"),this.m(),this.I()});if(c.modelAssetBuffer instanceof Uint8Array)la(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(l){const h=[];for(var u=0;;){const{done:d,value:p}=await l.read();if(d)break;h.push(p),u+=p.length}if(h.length===0)return new Uint8Array(0);if(h.length===1)return h[0];l=new Uint8Array(u),u=0;for(const d of h)l.set(d,u),u+=d.length;return l}(c.modelAssetBuffer).then(l=>{la(this,l),this.m(),this.I()})}return this.m(),this.I(),Promise.resolve()}I(){}da(){let t;if(this.g.da(e=>{t=bv(e)}),!t)throw Error("Failed to retrieve CalculatorGraphConfig");return t}setGraph(t,e){this.g.attachErrorListener((n,s)=>{this.G.push(Error(s))}),this.g.La(),this.g.setGraph(t,e),this.A=void 0,Uu(this)}finishProcessing(){this.g.finishProcessing(),Uu(this)}close(){this.A=void 0,this.g.closeGraph()}};function Ve(t,e){if(!t)throw Error(`Unable to obtain required WebGL resource: ${e}`);return t}ir.prototype.close=ir.prototype.close,function(t,e){t=t.split(".");var n,s=Un;for((t[0]in s)||s.execScript===void 0||s.execScript("var "+t[0]);t.length&&(n=t.shift());)t.length||e===void 0?s=s[n]&&s[n]!==Object.prototype[n]?s[n]:s[n]={}:s[n]=e}("TaskRunner",ir);class Yv{constructor(e,n,s,i){this.g=e,this.h=n,this.m=s,this.l=i}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function Vu(t,e,n){const s=t.g;if(n=Ve(s.createShader(n),"Failed to create WebGL shader"),s.shaderSource(n,e),s.compileShader(n),!s.getShaderParameter(n,s.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${s.getShaderInfoLog(n)}`);return s.attachShader(t.h,n),n}function $u(t,e){const n=t.g,s=Ve(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(s);const i=Ve(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(t.O),n.vertexAttribPointer(t.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const r=Ve(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,r),n.enableVertexAttribArray(t.I),n.vertexAttribPointer(t.I,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(e?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new Yv(n,s,i,r)}function Gl(t,e){if(t.g){if(e!==t.g)throw Error("Cannot change GL context once initialized")}else t.g=e}function Li(t,e,n,s){return Gl(t,e),t.h||(t.m(),t.C()),n?(t.s||(t.s=$u(t,!0)),n=t.s):(t.v||(t.v=$u(t,!1)),n=t.v),e.useProgram(t.h),n.bind(),t.l(),t=s(),n.g.bindVertexArray(null),t}function gn(t,e,n){return Gl(t,e),t=Ve(e.createTexture(),"Failed to create texture"),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n??e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,n??e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),t}function Ro(t,e,n){Gl(t,e),t.A||(t.A=Ve(e.createFramebuffer(),"Failed to create framebuffe.")),e.bindFramebuffer(e.FRAMEBUFFER,t.A),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}function jl(t){var e;(e=t.g)==null||e.bindFramebuffer(t.g.FRAMEBUFFER,null)}var Ls=class{G(){return`
1594
+ */es(R3,I3,"app");var Un=typeof self<"u"?self:{};function En(){throw Error("Invalid UTF8")}function Jh(t,e){return e=String.fromCharCode.apply(null,e),t==null?e:t+e}let Hi,Xo;const x3=typeof TextDecoder<"u";let N3;const F3=typeof TextEncoder<"u";function Yp(t){if(F3)t=(N3||(N3=new TextEncoder)).encode(t);else{let n=0;const s=new Uint8Array(3*t.length);for(let i=0;i<t.length;i++){var e=t.charCodeAt(i);if(e<128)s[n++]=e;else{if(e<2048)s[n++]=e>>6|192;else{if(e>=55296&&e<=57343){if(e<=56319&&i<t.length){const r=t.charCodeAt(++i);if(r>=56320&&r<=57343){e=1024*(e-55296)+r-56320+65536,s[n++]=e>>18|240,s[n++]=e>>12&63|128,s[n++]=e>>6&63|128,s[n++]=63&e|128;continue}i--}e=65533}s[n++]=e>>12|224,s[n++]=e>>6&63|128}s[n++]=63&e|128}}t=n===s.length?s:s.subarray(0,n)}return t}var Xc,Dr;e:{for(var Zh=["CLOSURE_FLAGS"],Qo=Un,Jo=0;Jo<Zh.length;Jo++)if((Qo=Qo[Zh[Jo]])==null){Dr=null;break e}Dr=Qo}var _i,eu=Dr&&Dr[610401301];Xc=eu!=null&&eu;const tu=Un.navigator;function Ua(t){return!!Xc&&!!_i&&_i.brands.some(({brand:e})=>e&&e.indexOf(t)!=-1)}function dt(t){var e;return(e=Un.navigator)&&(e=e.userAgent)||(e=""),e.indexOf(t)!=-1}function sn(){return!!Xc&&!!_i&&_i.brands.length>0}function Zo(){return sn()?Ua("Chromium"):(dt("Chrome")||dt("CriOS"))&&!(!sn()&&dt("Edge"))||dt("Silk")}function Qc(t){return Qc[" "](t),t}_i=tu&&tu.userAgentData||null,Qc[" "]=function(){};var D3=!sn()&&(dt("Trident")||dt("MSIE"));!dt("Android")||Zo(),Zo(),dt("Safari")&&(Zo()||!sn()&&dt("Coast")||!sn()&&dt("Opera")||!sn()&&dt("Edge")||(sn()?Ua("Microsoft Edge"):dt("Edg/"))||sn()&&Ua("Opera"));var Xp={},Xs=null;function P3(t){const e=t.length;let n=3*e/4;n%3?n=Math.floor(n):"=.".indexOf(t[e-1])!=-1&&(n="=.".indexOf(t[e-2])!=-1?n-2:n-1);const s=new Uint8Array(n);let i=0;return function(r,o){function a(l){for(;c<r.length;){const h=r.charAt(c++),u=Xs[h];if(u!=null)return u;if(!/^[\s\xa0]*$/.test(h))throw Error("Unknown base64 encoding at char: "+h)}return l}Qp();let c=0;for(;;){const l=a(-1),h=a(0),u=a(64),d=a(64);if(d===64&&l===-1)break;o(l<<2|h>>4),u!=64&&(o(h<<4&240|u>>2),d!=64&&o(u<<6&192|d))}}(t,function(r){s[i++]=r}),i!==n?s.subarray(0,i):s}function Qp(){if(!Xs){Xs={};var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),e=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const s=t.concat(e[n].split(""));Xp[n]=s;for(let i=0;i<s.length;i++){const r=s[i];Xs[r]===void 0&&(Xs[r]=i)}}}}var Jp=typeof Uint8Array<"u",Zp=!D3&&typeof btoa=="function";function nu(t){if(!Zp){var e;e===void 0&&(e=0),Qp(),e=Xp[e];var n=Array(Math.floor(t.length/3)),s=e[64]||"";let c=0,l=0;for(;c<t.length-2;c+=3){var i=t[c],r=t[c+1],o=t[c+2],a=e[i>>2];i=e[(3&i)<<4|r>>4],r=e[(15&r)<<2|o>>6],o=e[63&o],n[l++]=a+i+r+o}switch(a=0,o=s,t.length-c){case 2:o=e[(15&(a=t[c+1]))<<2]||s;case 1:t=t[c],n[l]=e[t>>2]+e[(3&t)<<4|a>>4]+o+s}return n.join("")}for(e="",n=0,s=t.length-10240;n<s;)e+=String.fromCharCode.apply(null,t.subarray(n,n+=10240));return e+=String.fromCharCode.apply(null,n?t.subarray(n):t),btoa(e)}const su=/[-_.]/g,L3={"-":"+",_:"/",".":"="};function O3(t){return L3[t]||""}function em(t){if(!Zp)return P3(t);su.test(t)&&(t=t.replace(su,O3)),t=atob(t);const e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}function xi(t){return Jp&&t!=null&&t instanceof Uint8Array}var ps={};function Vn(){return M3||(M3=new zt(null,ps))}function Jc(t){tm(ps);var e=t.g;return(e=e==null||xi(e)?e:typeof e=="string"?em(e):null)==null?e:t.g=e}var zt=class{h(){return new Uint8Array(Jc(this)||0)}constructor(t,e){if(tm(e),this.g=t,t!=null&&t.length===0)throw Error("ByteString should be constructed with non-empty values")}};let M3,B3;function tm(t){if(t!==ps)throw Error("illegal external caller")}function nm(t,e){t.__closure__error__context__984382||(t.__closure__error__context__984382={}),t.__closure__error__context__984382.severity=e}function Va(t){return nm(t=Error(t),"warning"),t}var no=typeof Symbol=="function"&&typeof Symbol()=="symbol",U3=new Set;function Ni(t,e,n=!1,s=!1){return t=typeof Symbol=="function"&&typeof Symbol()=="symbol"?s&&Symbol.for&&t?Symbol.for(t):t!=null?Symbol(t):Symbol():e,n&&U3.add(t),t}var V3=Ni("jas",void 0,!0,!0),iu=Ni(void 0,"0di"),ea=Ni(void 0,"2ex"),Gs=Ni(void 0,"1oa",!0),ms=Ni(void 0,Symbol(),!0);const N=no?V3:"Ga",sm={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},im=Object.defineProperties;function so(t,e){no||N in t||im(t,sm),t[N]|=e}function be(t,e){no||N in t||im(t,sm),t[N]=e}function As(t){return so(t,34),t}function $3(t,e){be(e,-30975&(0|t))}function $a(t,e){be(e,-30941&(34|t))}function Zc(){return typeof BigInt=="function"}function ze(t){return Array.prototype.slice.call(t)}var el,Fi={},rm={};function ru(t){return!(!t||typeof t!="object"||t.Ia!==rm)}function tl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&t.constructor===Object}function nl(t,e){if(t!=null){if(typeof t=="string")t=t?new zt(t,ps):Vn();else if(t.constructor!==zt)if(xi(t))t=t.length?new zt(new Uint8Array(t),ps):Vn();else{if(!e)throw Error();t=void 0}}return t}function Pr(t){return!(!Array.isArray(t)||t.length)&&!!(1&(0|t[N]))}const ou=[];function _n(t){if(2&t)throw Error()}be(ou,55),el=Object.freeze(ou);class Lr{constructor(e,n,s){this.l=0,this.g=e,this.h=n,this.m=s}next(){if(this.l<this.g.length){const e=this.g[this.l++];return{done:!1,value:this.h?this.h.call(this.m,e):e}}return{done:!0,value:void 0}}[Symbol.iterator](){return new Lr(this.g,this.h,this.m)}}function sl(t){return ms?t[ms]:void 0}var H3=Object.freeze({});function io(t){return t.Qa=!0,t}var W3=io(t=>typeof t=="number"),au=io(t=>typeof t=="string"),G3=io(t=>typeof t=="boolean"),ro=typeof Un.BigInt=="function"&&typeof Un.BigInt(0)=="bigint",Ha=io(t=>ro?t>=q3&&t<=K3:t[0]==="-"?cu(t,j3):cu(t,z3));const j3=Number.MIN_SAFE_INTEGER.toString(),q3=ro?BigInt(Number.MIN_SAFE_INTEGER):void 0,z3=Number.MAX_SAFE_INTEGER.toString(),K3=ro?BigInt(Number.MAX_SAFE_INTEGER):void 0;function cu(t,e){if(t.length>e.length)return!1;if(t.length<e.length||t===e)return!0;for(let n=0;n<t.length;n++){const s=t[n],i=e[n];if(s>i)return!1;if(s<i)return!0}}const Y3=typeof Uint8Array.prototype.slice=="function";let om,se=0,_e=0;function lu(t){const e=t>>>0;se=e,_e=(t-e)/4294967296>>>0}function gs(t){if(t<0){lu(-t);const[e,n]=al(se,_e);se=e>>>0,_e=n>>>0}else lu(t)}function il(t){const e=om||(om=new DataView(new ArrayBuffer(8)));e.setFloat32(0,+t,!0),_e=0,se=e.getUint32(0,!0)}function rl(t,e){const n=4294967296*e+(t>>>0);return Number.isSafeInteger(n)?n:yi(t,e)}function ol(t,e){const n=2147483648&e;return n&&(e=~e>>>0,(t=1+~t>>>0)==0&&(e=e+1>>>0)),typeof(t=rl(t,e))=="number"?n?-t:t:n?"-"+t:t}function yi(t,e){if(t>>>=0,(e>>>=0)<=2097151)var n=""+(4294967296*e+t);else Zc()?n=""+(BigInt(e)<<BigInt(32)|BigInt(t)):(t=(16777215&t)+6777216*(n=16777215&(t>>>24|e<<8))+6710656*(e=e>>16&65535),n+=8147497*e,e*=2,t>=1e7&&(n+=t/1e7>>>0,t%=1e7),n>=1e7&&(e+=n/1e7>>>0,n%=1e7),n=e+hu(n)+hu(t));return n}function hu(t){return t=String(t),"0000000".slice(t.length)+t}function oo(t){if(t.length<16)gs(Number(t));else if(Zc())t=BigInt(t),se=Number(t&BigInt(4294967295))>>>0,_e=Number(t>>BigInt(32)&BigInt(4294967295));else{const e=+(t[0]==="-");_e=se=0;const n=t.length;for(let s=e,i=(n-e)%6+e;i<=n;s=i,i+=6){const r=Number(t.slice(s,i));_e*=1e6,se=1e6*se+r,se>=4294967296&&(_e+=Math.trunc(se/4294967296),_e>>>=0,se>>>=0)}if(e){const[s,i]=al(se,_e);se=s,_e=i}}}function al(t,e){return e=~e,t?t=1+~t:e+=1,[t,e]}const cl=typeof BigInt=="function"?BigInt.asIntN:void 0,X3=typeof BigInt=="function"?BigInt.asUintN:void 0,is=Number.isSafeInteger,ao=Number.isFinite,Or=Math.trunc;function yn(t){return t==null||typeof t=="number"?t:t==="NaN"||t==="Infinity"||t==="-Infinity"?Number(t):void 0}function am(t){return t==null||typeof t=="boolean"?t:typeof t=="number"?!!t:void 0}const Q3=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function co(t){switch(typeof t){case"bigint":return!0;case"number":return ao(t);case"string":return Q3.test(t);default:return!1}}function Rs(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return ao(t)?0|t:void 0}function cm(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return ao(t)?t>>>0:void 0}function uu(t){if(t[0]==="-")return!1;const e=t.length;return e<20||e===20&&Number(t.substring(0,6))<184467}function ll(t){return t=Or(t),is(t)||(gs(t),t=ol(se,_e)),t}function hl(t){var e=Or(Number(t));if(is(e))return String(e);if((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),e=t.length,!(t[0]==="-"?e<20||e===20&&Number(t.substring(0,7))>-922337:e<19||e===19&&Number(t.substring(0,6))<922337))if(oo(t),t=se,2147483648&(e=_e))if(Zc())t=""+(BigInt(0|e)<<BigInt(32)|BigInt(t>>>0));else{const[n,s]=al(t,e);t="-"+yi(n,s)}else t=yi(t,e);return t}function Mr(t){return t==null?t:typeof t=="bigint"?(Ha(t)?t=Number(t):(t=cl(64,t),t=Ha(t)?Number(t):String(t)),t):co(t)?typeof t=="number"?ll(t):hl(t):void 0}function J3(t){if(t==null)return t;var e=typeof t;if(e==="bigint")return String(X3(64,t));if(co(t)){if(e==="string")return e=Or(Number(t)),is(e)&&e>=0?t=String(e):((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),uu(t)||(oo(t),t=yi(se,_e))),t;if(e==="number")return(t=Or(t))>=0&&is(t)?t:function(n){if(n<0){gs(n);var s=yi(se,_e);return n=Number(s),is(n)?n:s}return uu(s=String(n))?s:(gs(n),rl(se,_e))}(t)}}function lm(t){if(typeof t!="string")throw Error();return t}function Is(t){if(t!=null&&typeof t!="string")throw Error();return t}function _s(t){return t==null||typeof t=="string"?t:void 0}function ul(t,e,n,s){if(t!=null&&typeof t=="object"&&t.W===Fi)return t;if(!Array.isArray(t))return n?2&s?((t=e[iu])||(As((t=new e).u),t=e[iu]=t),e=t):e=new e:e=void 0,e;let i=n=0|t[N];return i===0&&(i|=32&s),i|=2&s,i!==n&&be(t,i),new e(t)}function Z3(t,e,n){if(e)e:{if(!co(e=t))throw Va("int64");switch(typeof e){case"string":e=hl(e);break e;case"bigint":if(t=e=cl(64,e),au(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(W3(t)&&!Number.isSafeInteger(t))throw Error(String(t));e=ro?BigInt(e):G3(e)?e?"1":"0":au(e)?e.trim()||"0":String(e);break e;default:e=ll(e)}}else e=Mr(t);return typeof(n=(t=e)==null?n?0:void 0:t)=="string"&&is(e=+n)?e:n}const ev={};let tv=function(){try{return Qc(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class ta{constructor(){this.g=new Map}get(e){return this.g.get(e)}set(e,n){return this.g.set(e,n),this.size=this.g.size,this}delete(e){return e=this.g.delete(e),this.size=this.g.size,e}clear(){this.g.clear(),this.size=this.g.size}has(e){return this.g.has(e)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(e,n){return this.g.forEach(e,n)}[Symbol.iterator](){return this.entries()}}const nv=tv?(Object.setPrototypeOf(ta.prototype,Map.prototype),Object.defineProperties(ta.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),ta):class extends Map{constructor(){super()}};function du(t){return t}function na(t){if(2&t.L)throw Error("Cannot mutate an immutable Map")}var mt=class extends nv{constructor(t,e,n=du,s=du){super();let i=0|t[N];i|=64,be(t,i),this.L=i,this.S=e,this.R=n,this.Y=this.S?sv:s;for(let r=0;r<t.length;r++){const o=t[r],a=n(o[0],!1,!0);let c=o[1];e?c===void 0&&(c=null):c=s(o[1],!1,!0,void 0,void 0,i),super.set(a,c)}}na(t=fu){if(this.size!==0)return this.X(t)}X(t=fu){const e=[],n=super.entries();for(var s;!(s=n.next()).done;)(s=s.value)[0]=t(s[0]),s[1]=t(s[1]),e.push(s);return e}clear(){na(this),super.clear()}delete(t){return na(this),super.delete(this.R(t,!0,!1))}entries(){var t=this.ma();return new Lr(t,iv,this)}keys(){return this.Ha()}values(){var t=this.ma();return new Lr(t,mt.prototype.get,this)}forEach(t,e){super.forEach((n,s)=>{t.call(e,this.get(s),s,this)})}set(t,e){return na(this),(t=this.R(t,!0,!1))==null?this:e==null?(super.delete(t),this):super.set(t,this.Y(e,!0,!0,this.S,!1,this.L))}Na(t){const e=this.R(t[0],!1,!0);t=t[1],t=this.S?t===void 0?null:t:this.Y(t,!1,!0,void 0,!1,this.L),super.set(e,t)}has(t){return super.has(this.R(t,!1,!1))}get(t){t=this.R(t,!1,!1);const e=super.get(t);if(e!==void 0){var n=this.S;return n?((n=this.Y(e,!1,!0,n,this.ra,this.L))!==e&&super.set(t,n),n):e}}ma(){return Array.from(super.keys())}Ha(){return super.keys()}[Symbol.iterator](){return this.entries()}};function sv(t,e,n,s,i,r){return t=ul(t,s,n,r),i&&(t=ho(t)),t}function fu(t){return t}function iv(t){return[t,this.get(t)]}let rv,hm,ov;function pu(){return rv||(rv=new mt(As([]),void 0,void 0,void 0,ev))}function dl(t,e,n,s,i){if(t!=null){if(Array.isArray(t))t=Pr(t)?void 0:i&&2&(0|t[N])?t:fl(t,e,n,s!==void 0,i);else if(tl(t)){const r={};for(let o in t)r[o]=dl(t[o],e,n,s,i);t=r}else t=e(t,s);return t}}function fl(t,e,n,s,i){const r=s||n?0|t[N]:0,o=s?!!(32&r):void 0;s=ze(t);for(let a=0;a<s.length;a++)s[a]=dl(s[a],e,n,o,i);return n&&((t=sl(t))&&(s[ms]=ze(t)),n(r,s)),s}function av(t){return dl(t,um,void 0,void 0,!1)}function um(t){return t.W===Fi?t.toJSON():t instanceof mt?t.na(av):function(e){switch(typeof e){case"number":return isFinite(e)?e:String(e);case"bigint":return Ha(e)?Number(e):String(e);case"boolean":return e?1:0;case"object":if(e)if(Array.isArray(e)){if(Pr(e))return}else{if(xi(e))return nu(e);if(e instanceof zt){const n=e.g;return n==null?"":typeof n=="string"?n:e.g=nu(n)}if(e instanceof mt)return e.na()}}return e}(t)}function dm(t){return fl(t,um,void 0,void 0,!1)}function ln(t,e,n){return t=fm(t,e[0],e[1],n?1:2),e!==hm&&n&&so(t,16384),t}function fm(t,e,n,s){if(t==null){var i=96;n?(t=[n],i|=512):t=[],e&&(i=-33521665&i|(1023&e)<<15)}else{if(!Array.isArray(t))throw Error("narr");if(2048&(i=0|t[N]))throw Error("farr");if(64&i)return t;if(s===1||s===2||(i|=64),n&&(i|=512,n!==t[0]))throw Error("mid");e:{if(s=(n=t).length){const r=s-1;if(tl(n[r])){if((e=r-(512&(i|=256)?0:-1))>=1024)throw Error("pvtlmt");i=-33521665&i|(1023&e)<<15;break e}}if(e){if((e=Math.max(e,s-(512&i?0:-1)))>1024)throw Error("spvt");i=-33521665&i|(1023&e)<<15}}}return be(t,i),t}function Wa(t,e,n=$a){if(t!=null){if(Jp&&t instanceof Uint8Array)return e?t:new Uint8Array(t);if(Array.isArray(t)){var s=0|t[N];return 2&s?t:(e&&(e=s===0||!!(32&s)&&!(64&s||!(16&s))),e?(be(t,-12293&(34|s)),t):fl(t,Wa,4&s?$a:n,!0,!0))}return t.W===Fi?t=2&(s=0|(n=t.u)[N])?t:new t.constructor(lo(n,s,!0)):t instanceof mt&&!(2&t.L)&&(n=As(t.X(Wa)),t=new mt(n,t.S,t.R,t.Y)),t}}function lo(t,e,n){const s=n||2&e?$a:$3,i=!!(32&e);return t=function(r,o,a){const c=ze(r);var l=c.length;const h=256&o?c[l-1]:void 0;for(l+=h?-1:0,o=512&o?1:0;o<l;o++)c[o]=a(c[o]);if(h){o=c[o]={};for(const u in h)o[u]=a(h[u])}return(r=sl(r))&&(c[ms]=ze(r)),c}(t,e,r=>Wa(r,i,s)),so(t,32|(n?2:0)),t}function ho(t){const e=t.u,n=0|e[N];return 2&n?new t.constructor(lo(e,n,!1)):t}function ys(t,e){return tn(t=t.u,0|t[N],e)}function tn(t,e,n,s){if(n===-1)return null;var i=n+(512&e?0:-1);const r=t.length-1;return i>=r&&256&e?t[r][n]:s&&256&e&&(e=t[r][n])!=null?(t[i]!=null&&ea!=null&&((i=(t=B3??(B3={}))[ea]||0)>=4||(t[ea]=i+1,nm(t=Error(),"incident"),function(o){Un.setTimeout(()=>{throw o},0)}(t))),e):i<=r?t[i]:void 0}function ae(t,e,n){const s=t.u;let i=0|s[N];return _n(i),ge(s,i,e,n),t}function ge(t,e,n,s){const i=512&e?0:-1,r=n+i;var o=t.length-1;return r>=o&&256&e?(t[o][n]=s,e):r<=o?(t[r]=s,256&e&&n in(t=t[o])&&delete t[n],e):(s!==void 0&&(n>=(o=e>>15&1023||536870912)?s!=null&&(t[o+i]={[n]:s},be(t,e|=256)):t[r]=s),e)}function tr(t,e){let n=0|(t=t.u)[N];const s=tn(t,n,e),i=yn(s);return i!=null&&i!==s&&ge(t,n,e,i),i}function pm(t){let e=0|(t=t.u)[N];const n=tn(t,e,1),s=nl(n,!0);return s!=null&&s!==n&&ge(t,e,1,s),s}function xn(){return H3===void 0?2:4}function Nn(t,e,n,s,i){const r=t.u,o=2&(t=0|r[N])?1:s;i=!!i;let a=0|(s=pl(r,t,e))[N];if(!(4&a)){4&a&&(s=ze(s),a=Kt(a,t),t=ge(r,t,e,s));let c=0,l=0;for(;c<s.length;c++){const h=n(s[c]);h!=null&&(s[l++]=h)}l<c&&(s.length=l),a=ml(a,t),n=-4097&(20|a),a=n&=-8193,be(s,a),2&a&&Object.freeze(s)}return o===1||o===4&&32&a?jt(a)||(i=a,a|=2,a!==i&&be(s,a),Object.freeze(s)):(o===2&&jt(a)&&(s=ze(s),a=Kt(a,t),a=hn(a,t,i),be(s,a),t=ge(r,t,e,s)),jt(a)||(e=a,a=hn(a,t,i),a!==e&&be(s,a))),s}function pl(t,e,n,s){return t=tn(t,e,n,s),Array.isArray(t)?t:el}function ml(t,e){return t===0&&(t=Kt(t,e)),1|t}function jt(t){return!!(2&t)&&!!(4&t)||!!(2048&t)}function mm(t){t=ze(t);for(let e=0;e<t.length;e++){const n=t[e]=ze(t[e]);Array.isArray(n[1])&&(n[1]=As(n[1]))}return t}function Ga(t,e,n,s){let i=0|(t=t.u)[N];_n(i),ge(t,i,e,(s==="0"?Number(n)===0:n===s)?void 0:n)}function xs(t,e,n,s,i){_n(e);var r=!(!(64&e)&&16384&e);const o=(i=pl(t,e,n,i))!==el;if(r||!o){let a=r=o?0|i[N]:0;(!o||2&a||jt(a)||4&a&&!(32&a))&&(i=ze(i),a=Kt(a,e),e=ge(t,e,n,i)),a=-13&ml(a,e),a=hn(s?-17&a:16|a,e,!0),a!==r&&be(i,a)}return i}function sa(t,e){var n=ig;return _l(gl(t=t.u),t,0|t[N],n)===e?e:-1}function gl(t){if(no)return t[Gs]??(t[Gs]=new Map);if(Gs in t)return t[Gs];const e=new Map;return Object.defineProperty(t,Gs,{value:e}),e}function gm(t,e,n,s){const i=gl(t),r=_l(i,t,e,n);return r!==s&&(r&&(e=ge(t,e,r)),i.set(n,s)),e}function _l(t,e,n,s){let i=t.get(s);if(i!=null)return i;i=0;for(let r=0;r<s.length;r++){const o=s[r];tn(e,n,o)!=null&&(i!==0&&(n=ge(e,n,i)),i=o)}return t.set(s,i),i}function yl(t,e,n,s){let i,r=0|t[N];if((s=tn(t,r,n,s))!=null&&s.W===Fi)return(e=ho(s))!==s&&ge(t,r,n,e),e.u;if(Array.isArray(s)){const o=0|s[N];i=2&o?ln(lo(s,o,!1),e,!0):64&o?s:ln(i,e,!0)}else i=ln(void 0,e,!0);return i!==s&&ge(t,r,n,i),i}function _m(t,e,n,s){let i=0|(t=t.u)[N];return(e=ul(s=tn(t,i,n,s),e,!1,i))!==s&&e!=null&&ge(t,i,n,e),e}function Y(t,e,n,s=!1){if((e=_m(t,e,n,s))==null)return e;if(!(2&(s=0|(t=t.u)[N]))){const i=ho(e);i!==e&&ge(t,s,n,e=i)}return e}function ym(t,e,n,s,i,r,o){t=t.u;var a=!!(2&e);const c=a?1:i;r=!!r,o&&(o=!a);var l=0|(i=pl(t,e,s))[N];if(!(a=!!(4&l))){var h=i,u=e;const d=!!(2&(l=ml(l,e)));d&&(u|=2);let p=!d,m=!0,y=0,w=0;for(;y<h.length;y++){const k=ul(h[y],n,!1,u);if(k instanceof n){if(!d){const E=!!(2&(0|k.u[N]));p&&(p=!E),m&&(m=E)}h[w++]=k}}w<y&&(h.length=w),l|=4,l=m?16|l:-17&l,be(h,l=p?8|l:-9&l),d&&Object.freeze(h)}if(o&&!(8&l||!i.length&&(c===1||c===4&&32&l))){for(jt(l)&&(i=ze(i),l=Kt(l,e),e=ge(t,e,s,i)),n=i,o=l,h=0;h<n.length;h++)(l=n[h])!==(u=ho(l))&&(n[h]=u);o|=8,be(n,o=n.length?-17&o:16|o),l=o}return c===1||c===4&&32&l?jt(l)||(e=l,(l|=!i.length||16&l&&(!a||32&l)?2:2048)!==e&&be(i,l),Object.freeze(i)):(c===2&&jt(l)&&(be(i=ze(i),l=hn(l=Kt(l,e),e,r)),e=ge(t,e,s,i)),jt(l)||(s=l,(l=hn(l,e,r))!==s&&be(i,l))),i}function Qt(t,e,n){const s=0|t.u[N];return ym(t,s,e,n,xn(),!1,!(2&s))}function F(t,e,n,s){return s==null&&(s=void 0),ae(t,n,s)}function ii(t,e,n,s){s==null&&(s=void 0);e:{let i=0|(t=t.u)[N];if(_n(i),s==null){const r=gl(t);if(_l(r,t,i,n)!==e)break e;r.set(n,0)}else i=gm(t,i,n,e);ge(t,i,e,s)}}function Kt(t,e){return-2049&(t=32|(2&e?2|t:-3&t))}function hn(t,e,n){return 32&e&&n||(t&=-33),t}function Br(t,e,n,s){const i=0|t.u[N];_n(i),t=ym(t,i,n,e,2,!0),s=s??new n,t.push(s),t[N]=2&(0|s.u[N])?-9&t[N]:-17&t[N]}function pt(t,e){return Rs(ys(t,e))}function gt(t,e){return _s(ys(t,e))}function Ee(t,e){return tr(t,e)??0}function vi(t,e,n){if(n!=null&&typeof n!="boolean")throw t=typeof n,Error(`Expected boolean but got ${t!="object"?t:n?Array.isArray(n)?"array":t:"null"}: ${n}`);ae(t,e,n)}function Mt(t,e,n){if(n!=null){if(typeof n!="number"||!ao(n))throw Va("int32");n|=0}ae(t,e,n)}function I(t,e,n){if(n!=null&&typeof n!="number")throw Error(`Value of float/double field must be a number, found ${typeof n}: ${n}`);ae(t,e,n)}function Ur(t,e,n){{const o=t.u;let a=0|o[N];if(_n(a),n==null)ge(o,a,e);else{var s=t=0|n[N],i=jt(t),r=i||Object.isFrozen(n);for(i||(t=0),r||(n=ze(n),s=0,t=hn(t=Kt(t,a),a,!0),r=!1),t|=21,i=0;i<n.length;i++){const c=n[i],l=lm(c);Object.is(c,l)||(r&&(n=ze(n),s=0,t=hn(t=Kt(t,a),a,!0),r=!1),n[i]=l)}t!==s&&(r&&(n=ze(n),t=hn(t=Kt(t,a),a,!0)),be(n,t)),ge(o,a,e,n)}}}function uo(t,e,n){_n(0|t.u[N]),Nn(t,e,_s,2,!0).push(lm(n))}function vm(t,e){return Error(`Invalid wire type: ${t} (at position ${e})`)}function vl(){return Error("Failed to read varint, encoding is invalid.")}function Em(t,e){return Error(`Tried to read past the end of the data ${e} > ${t}`)}function El(t){if(typeof t=="string")return{buffer:em(t),N:!1};if(Array.isArray(t))return{buffer:new Uint8Array(t),N:!1};if(t.constructor===Uint8Array)return{buffer:t,N:!1};if(t.constructor===ArrayBuffer)return{buffer:new Uint8Array(t),N:!1};if(t.constructor===zt)return{buffer:Jc(t)||new Uint8Array(0),N:!0};if(t instanceof Uint8Array)return{buffer:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),N:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}function wl(t,e){let n,s=0,i=0,r=0;const o=t.h;let a=t.g;do n=o[a++],s|=(127&n)<<r,r+=7;while(r<32&&128&n);for(r>32&&(i|=(127&n)>>4),r=3;r<32&&128&n;r+=7)n=o[a++],i|=(127&n)<<r;if(Dn(t,a),n<128)return e(s>>>0,i>>>0);throw vl()}function bl(t){let e=0,n=t.g;const s=n+10,i=t.h;for(;n<s;){const r=i[n++];if(e|=r,(128&r)==0)return Dn(t,n),!!(127&e)}throw vl()}function pn(t){const e=t.h;let n=t.g,s=e[n++],i=127&s;if(128&s&&(s=e[n++],i|=(127&s)<<7,128&s&&(s=e[n++],i|=(127&s)<<14,128&s&&(s=e[n++],i|=(127&s)<<21,128&s&&(s=e[n++],i|=s<<28,128&s&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++])))))throw vl();return Dn(t,n),i}function Jt(t){return pn(t)>>>0}function ja(t){var e=t.h;const n=t.g,s=e[n],i=e[n+1],r=e[n+2];return e=e[n+3],Dn(t,t.g+4),(s<<0|i<<8|r<<16|e<<24)>>>0}function qa(t){var e=ja(t);t=2*(e>>31)+1;const n=e>>>23&255;return e&=8388607,n==255?e?NaN:t*(1/0):n==0?1401298464324817e-60*t*e:t*Math.pow(2,n-150)*(e+8388608)}function cv(t){return pn(t)}function ia(t,e,{ba:n=!1}={}){t.ba=n,e&&(e=El(e),t.h=e.buffer,t.m=e.N,t.j=0,t.l=t.h.length,t.g=t.j)}function Dn(t,e){if(t.g=e,e>t.l)throw Em(t.l,e)}function wm(t,e){if(e<0)throw Error(`Tried to read a negative byte length: ${e}`);const n=t.g,s=n+e;if(s>t.l)throw Em(e,t.l-n);return t.g=s,n}function bm(t,e){if(e==0)return Vn();var n=wm(t,e);return t.ba&&t.m?n=t.h.subarray(n,n+e):(t=t.h,n=n===(e=n+e)?new Uint8Array(0):Y3?t.slice(n,e):new Uint8Array(t.subarray(n,e))),n.length==0?Vn():new zt(n,ps)}mt.prototype.toJSON=void 0,mt.prototype.Ia=rm;var mu=[];function Cm(t){var e=t.g;if(e.g==e.l)return!1;t.l=t.g.g;var n=Jt(t.g);if(e=n>>>3,!((n&=7)>=0&&n<=5))throw vm(n,t.l);if(e<1)throw Error(`Invalid field number: ${e} (at position ${t.l})`);return t.m=e,t.h=n,!0}function nr(t){switch(t.h){case 0:t.h!=0?nr(t):bl(t.g);break;case 1:Dn(t=t.g,t.g+8);break;case 2:if(t.h!=2)nr(t);else{var e=Jt(t.g);Dn(t=t.g,t.g+e)}break;case 5:Dn(t=t.g,t.g+4);break;case 3:for(e=t.m;;){if(!Cm(t))throw Error("Unmatched start-group tag: stream EOF");if(t.h==4){if(t.m!=e)throw Error("Unmatched end-group tag");break}nr(t)}break;default:throw vm(t.h,t.l)}}function Di(t,e,n){const s=t.g.l,i=Jt(t.g),r=t.g.g+i;let o=r-s;if(o<=0&&(t.g.l=r,n(e,t,void 0,void 0,void 0),o=r-t.g.g),o)throw Error(`Message parsing ended unexpectedly. Expected to read ${i} bytes, instead read ${i-o} bytes, either the data ended unexpectedly or the message misreported its own length`);return t.g.g=r,t.g.l=s,e}function Cl(t){var e=Jt(t.g),n=wm(t=t.g,e);if(t=t.h,x3){var s,i=t;(s=Xo)||(s=Xo=new TextDecoder("utf-8",{fatal:!0})),e=n+e,i=n===0&&e===i.length?i:i.subarray(n,e);try{var r=s.decode(i)}catch(a){if(Hi===void 0){try{s.decode(new Uint8Array([128]))}catch{}try{s.decode(new Uint8Array([97])),Hi=!0}catch{Hi=!1}}throw!Hi&&(Xo=void 0),a}}else{e=(r=n)+e,n=[];let a,c=null;for(;r<e;){var o=t[r++];o<128?n.push(o):o<224?r>=e?En():(a=t[r++],o<194||(192&a)!=128?(r--,En()):n.push((31&o)<<6|63&a)):o<240?r>=e-1?En():(a=t[r++],(192&a)!=128||o===224&&a<160||o===237&&a>=160||(192&(s=t[r++]))!=128?(r--,En()):n.push((15&o)<<12|(63&a)<<6|63&s)):o<=244?r>=e-2?En():(a=t[r++],(192&a)!=128||a-144+(o<<28)>>30!=0||(192&(s=t[r++]))!=128||(192&(i=t[r++]))!=128?(r--,En()):(o=(7&o)<<18|(63&a)<<12|(63&s)<<6|63&i,o-=65536,n.push(55296+(o>>10&1023),56320+(1023&o)))):En(),n.length>=8192&&(c=Jh(c,n),n.length=0)}r=Jh(c,n)}return r}function Tm(t){const e=Jt(t.g);return bm(t.g,e)}function fo(t,e,n){var s=Jt(t.g);for(s=t.g.g+s;t.g.g<s;)n.push(e(t.g))}var Wi=[];function lv(t){return t}let rs;function St(t,e,n){e.g?e.m(t,e.g,e.h,n):e.m(t,e.h,n)}var A=class{constructor(t,e){this.u=fm(t,e)}toJSON(){const t=!rs;try{return t&&(rs=dm),Sm(this)}finally{t&&(rs=void 0)}}l(){var t=jv;return t.g?t.l(this,t.g,t.h,!0):t.l(this,t.h,t.defaultValue,!0)}clone(){const t=this.u;return new this.constructor(lo(t,0|t[N],!1))}N(){return!!(2&(0|this.u[N]))}};function Sm(t){var e=t.u;{e=(t=rs(e))!==e;let l=t.length;if(l){var n=t[l-1],s=tl(n);s?l--:n=void 0;var i=t;if(s){e:{var r,o=n,a=!1;if(o)for(let h in o)isNaN(+h)?(r??(r={}))[h]=o[h]:(s=o[h],Array.isArray(s)&&(Pr(s)||ru(s)&&s.size===0)&&(s=null),s==null&&(a=!0),s!=null&&((r??(r={}))[h]=s));if(a||(r=o),r)for(let h in r){a=r;break e}a=null}o=a==null?n!=null:a!==n}for(;l>0&&((r=i[l-1])==null||Pr(r)||ru(r)&&r.size===0);l--)var c=!0;(i!==t||o||c)&&(e?(c||o||a)&&(i.length=l):i=Array.prototype.slice.call(i,0,l),a&&i.push(a)),c=i}else c=t}return c}function gu(t){return t?/^\d+$/.test(t)?(oo(t),new za(se,_e)):null:hv||(hv=new za(0,0))}A.prototype.W=Fi,A.prototype.toString=function(){try{return rs=lv,Sm(this).toString()}finally{rs=void 0}};var za=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let hv;function _u(t){return t?/^-?\d+$/.test(t)?(oo(t),new Ka(se,_e)):null:uv||(uv=new Ka(0,0))}var Ka=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let uv;function os(t,e,n){for(;n>0||e>127;)t.g.push(127&e|128),e=(e>>>7|n<<25)>>>0,n>>>=7;t.g.push(e)}function Ns(t,e){for(;e>127;)t.g.push(127&e|128),e>>>=7;t.g.push(e)}function po(t,e){if(e>=0)Ns(t,e);else{for(let n=0;n<9;n++)t.g.push(127&e|128),e>>=7;t.g.push(1)}}function Ei(t,e){t.g.push(e>>>0&255),t.g.push(e>>>8&255),t.g.push(e>>>16&255),t.g.push(e>>>24&255)}function vs(t,e){e.length!==0&&(t.l.push(e),t.h+=e.length)}function rt(t,e,n){Ns(t.g,8*e+n)}function Tl(t,e){return rt(t,e,2),e=t.g.end(),vs(t,e),e.push(t.h),e}function Sl(t,e){var n=e.pop();for(n=t.h+t.g.length()-n;n>127;)e.push(127&n|128),n>>>=7,t.h++;e.push(n),t.h++}function mo(t,e,n){rt(t,e,2),Ns(t.g,n.length),vs(t,t.g.end()),vs(t,n)}function Vr(t,e,n,s){n!=null&&(e=Tl(t,e),s(n,t),Sl(t,e))}function kt(){const t=class{constructor(){throw Error()}};return Object.setPrototypeOf(t,t.prototype),t}var kl=kt(),km=kt(),Al=kt(),Rl=kt(),Am=kt(),Rm=kt(),Il=kt(),Im=kt(),xm=kt(),Fs=class{constructor(t,e,n){this.g=t,this.h=e,t=kl,this.l=!!t&&n===t||!1}};function go(t,e){return new Fs(t,e,kl)}function Nm(t,e,n,s,i){Vr(t,n,Lm(e,s),i)}const dv=go(function(t,e,n,s,i){return t.h===2&&(Di(t,yl(e,s,n),i),!0)},Nm),fv=go(function(t,e,n,s,i){return t.h===2&&(Di(t,yl(e,s,n,!0),i),!0)},Nm);var _o=Symbol(),xl=Symbol(),yu=Symbol(),vu=Symbol();let Fm,Dm;function Gn(t,e,n,s){var i=s[t];if(i)return i;(i={}).Pa=s,i.V=function(u){switch(typeof u){case"boolean":return hm||(hm=[0,void 0,!0]);case"number":return u>0?void 0:u===0?ov||(ov=[0,void 0]):[-u,void 0];case"string":return[0,u];case"object":return u}}(s[0]);var r=s[1];let o=1;r&&r.constructor===Object&&(i.ga=r,typeof(r=s[++o])=="function"&&(i.la=!0,Fm??(Fm=r),Dm??(Dm=s[o+1]),r=s[o+=2]));const a={};for(;r&&Array.isArray(r)&&r.length&&typeof r[0]=="number"&&r[0]>0;){for(var c=0;c<r.length;c++)a[r[c]]=r;r=s[++o]}for(c=1;r!==void 0;){let u;typeof r=="number"&&(c+=r,r=s[++o]);var l=void 0;if(r instanceof Fs?u=r:(u=dv,o--),u==null?void 0:u.l){r=s[++o],l=s;var h=o;typeof r=="function"&&(r=r(),l[h]=r),l=r}for(h=c+1,typeof(r=s[++o])=="number"&&r<0&&(h-=r,r=s[++o]);c<h;c++){const d=a[c];l?n(i,c,u,l,d):e(i,c,u,d)}}return s[t]=i}function Pm(t){return Array.isArray(t)?t[0]instanceof Fs?t:[fv,t]:[t,void 0]}function Lm(t,e){return t instanceof A?t.u:Array.isArray(t)?ln(t,e,!1):void 0}function Nl(t,e,n,s){const i=n.g;t[e]=s?(r,o,a)=>i(r,o,a,s):i}function Fl(t,e,n,s,i){const r=n.g;let o,a;t[e]=(c,l,h)=>r(c,l,h,a||(a=Gn(xl,Nl,Fl,s).V),o||(o=Dl(s)),i)}function Dl(t){let e=t[yu];if(e!=null)return e;const n=Gn(xl,Nl,Fl,t);return e=n.la?(s,i)=>Fm(s,i,n):(s,i)=>{const r=0|s[N];for(;Cm(i)&&i.h!=4;){var o=i.m,a=n[o];if(a==null){var c=n.ga;c&&(c=c[o])&&(c=pv(c))!=null&&(a=n[o]=c)}a!=null&&a(i,s,o)||(o=(a=i).l,nr(a),a.fa?a=void 0:(c=a.g.g-o,a.g.g=o,a=bm(a.g,c)),o=s,a&&((c=o[ms])?c.push(a):o[ms]=[a]))}return 16384&r&&As(s),!0},t[yu]=e}function pv(t){const e=(t=Pm(t))[0].g;if(t=t[1]){const n=Dl(t),s=Gn(xl,Nl,Fl,t).V;return(i,r,o)=>e(i,r,o,s,n)}return e}function yo(t,e,n){t[e]=n.h}function vo(t,e,n,s){let i,r;const o=n.h;t[e]=(a,c,l)=>o(a,c,l,r||(r=Gn(_o,yo,vo,s).V),i||(i=Om(s)))}function Om(t){let e=t[vu];if(!e){const n=Gn(_o,yo,vo,t);e=(s,i)=>Mm(s,i,n),t[vu]=e}return e}function Mm(t,e,n){for(var s=0|t[N],i=512&s?0:-1,r=t.length,o=512&s?1:0,a=r+(256&s?-1:0);o<a;o++){const c=t[o];if(c==null)continue;const l=o-i,h=Eu(n,l);h&&h(e,c,l)}if(256&s){s=t[r-1];for(const c in s)i=+c,Number.isNaN(i)||(r=s[i])!=null&&(a=Eu(n,i))&&a(e,r,i)}if(t=sl(t))for(vs(e,e.g.end()),n=0;n<t.length;n++)vs(e,Jc(t[n])||new Uint8Array(0))}function Eu(t,e){var n=t[e];if(n)return n;if((n=t.ga)&&(n=n[e])){var s=(n=Pm(n))[0].h;if(n=n[1]){const i=Om(n),r=Gn(_o,yo,vo,n).V;n=t.la?Dm(r,i):(o,a,c)=>s(o,a,c,r,i)}else n=s;return t[e]=n}}function Ds(t,e){if(Array.isArray(e)){var n=0|e[N];if(4&n)return e;for(var s=0,i=0;s<e.length;s++){const r=t(e[s]);r!=null&&(e[i++]=r)}return i<s&&(e.length=i),be(e,-12289&(5|n)),2&n&&Object.freeze(e),e}}function He(t,e,n){return new Fs(t,e,n)}function Ps(t,e,n){return new Fs(t,e,n)}function We(t,e,n){ge(t,0|t[N],e,n)}var mv=go(function(t,e,n,s,i){return t.h===2&&(t=Di(t,ln([void 0,void 0],s,!0),i),_n(s=0|e[N]),(i=tn(e,s,n))instanceof mt?(2&i.L)!=0?((i=i.X()).push(t),ge(e,s,n,i)):i.Na(t):Array.isArray(i)?(2&(0|i[N])&&ge(e,s,n,i=mm(i)),i.push(t)):ge(e,s,n,[t]),!0)},function(t,e,n,s,i){if(e instanceof mt)e.forEach((r,o)=>{Vr(t,n,ln([o,r],s,!1),i)});else if(Array.isArray(e))for(let r=0;r<e.length;r++){const o=e[r];Array.isArray(o)&&Vr(t,n,ln(o,s,!1),i)}});function Bm(t,e,n){if(e=function(s){if(s==null)return s;const i=typeof s;if(i==="bigint")return String(cl(64,s));if(co(s)){if(i==="string")return hl(s);if(i==="number")return ll(s)}}(e),e!=null&&(typeof e=="string"&&_u(e),e!=null))switch(rt(t,n,0),typeof e){case"number":t=t.g,gs(e),os(t,se,_e);break;case"bigint":n=BigInt.asUintN(64,e),n=new Ka(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),os(t.g,n.h,n.g);break;default:n=_u(e),os(t.g,n.h,n.g)}}function Um(t,e,n){(e=Rs(e))!=null&&e!=null&&(rt(t,n,0),po(t.g,e))}function Vm(t,e,n){(e=am(e))!=null&&(rt(t,n,0),t.g.g.push(e?1:0))}function $m(t,e,n){(e=_s(e))!=null&&mo(t,n,Yp(e))}function Hm(t,e,n,s,i){Vr(t,n,Lm(e,s),i)}function Wm(t,e,n){(e=e==null||typeof e=="string"||xi(e)||e instanceof zt?e:void 0)!=null&&mo(t,n,El(e).buffer)}function Gm(t,e,n){return(t.h===5||t.h===2)&&(e=xs(e,0|e[N],n,!1,!1),t.h==2?fo(t,qa,e):e.push(qa(t.g)),!0)}var Ht=He(function(t,e,n){if(t.h!==1)return!1;var s=t.g;t=ja(s);const i=ja(s);s=2*(i>>31)+1;const r=i>>>20&2047;return t=4294967296*(1048575&i)+t,We(e,n,r==2047?t?NaN:s*(1/0):r==0?5e-324*s*t:s*Math.pow(2,r-1075)*(t+4503599627370496)),!0},function(t,e,n){(e=yn(e))!=null&&(rt(t,n,1),t=t.g,(n=om||(om=new DataView(new ArrayBuffer(8)))).setFloat64(0,+e,!0),se=n.getUint32(0,!0),_e=n.getUint32(4,!0),Ei(t,se),Ei(t,_e))},kt()),Ce=He(function(t,e,n){return t.h===5&&(We(e,n,qa(t.g)),!0)},function(t,e,n){(e=yn(e))!=null&&(rt(t,n,5),t=t.g,il(e),Ei(t,se))},Il),gv=Ps(Gm,function(t,e,n){if((e=Ds(yn,e))!=null)for(let o=0;o<e.length;o++){var s=t,i=n,r=e[o];r!=null&&(rt(s,i,5),s=s.g,il(r),Ei(s,se))}},Il),Pl=Ps(Gm,function(t,e,n){if((e=Ds(yn,e))!=null&&e.length){rt(t,n,2),Ns(t.g,4*e.length);for(let s=0;s<e.length;s++)n=t.g,il(e[s]),Ei(n,se)}},Il),mn=He(function(t,e,n){return t.h===0&&(We(e,n,wl(t.g,ol)),!0)},Bm,Rm),ra=He(function(t,e,n){return t.h===0&&(We(e,n,(t=wl(t.g,ol))===0?void 0:t),!0)},Bm,Rm),_v=He(function(t,e,n){return t.h===0&&(We(e,n,wl(t.g,rl)),!0)},function(t,e,n){if((e=J3(e))!=null&&(typeof e=="string"&&gu(e),e!=null))switch(rt(t,n,0),typeof e){case"number":t=t.g,gs(e),os(t,se,_e);break;case"bigint":n=BigInt.asUintN(64,e),n=new za(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),os(t.g,n.h,n.g);break;default:n=gu(e),os(t.g,n.h,n.g)}},kt()),ve=He(function(t,e,n){return t.h===0&&(We(e,n,pn(t.g)),!0)},Um,Rl),Eo=Ps(function(t,e,n){return(t.h===0||t.h===2)&&(e=xs(e,0|e[N],n,!1,!1),t.h==2?fo(t,pn,e):e.push(pn(t.g)),!0)},function(t,e,n){if((e=Ds(Rs,e))!=null&&e.length){n=Tl(t,n);for(let s=0;s<e.length;s++)po(t.g,e[s]);Sl(t,n)}},Rl),Qn=He(function(t,e,n){return t.h===0&&(We(e,n,(t=pn(t.g))===0?void 0:t),!0)},Um,Rl),fe=He(function(t,e,n){return t.h===0&&(We(e,n,bl(t.g)),!0)},Vm,km),as=He(function(t,e,n){return t.h===0&&(We(e,n,(t=bl(t.g))===!1?void 0:t),!0)},Vm,km),Le=Ps(function(t,e,n){return t.h===2&&(t=Cl(t),xs(e,0|e[N],n,!1).push(t),!0)},function(t,e,n){if((e=Ds(_s,e))!=null)for(let o=0;o<e.length;o++){var s=t,i=n,r=e[o];r!=null&&mo(s,i,Yp(r))}},Al),rn=He(function(t,e,n){return t.h===2&&(We(e,n,(t=Cl(t))===""?void 0:t),!0)},$m,Al),Z=He(function(t,e,n){return t.h===2&&(We(e,n,Cl(t)),!0)},$m,Al),Ae=function(t,e,n=kl){return new Fs(t,e,n)}(function(t,e,n,s,i){return t.h===2&&(s=ln(void 0,s,!0),xs(e,0|e[N],n,!0).push(s),Di(t,s,i),!0)},function(t,e,n,s,i){if(Array.isArray(e))for(let r=0;r<e.length;r++)Hm(t,e[r],n,s,i)}),ee=go(function(t,e,n,s,i,r){return t.h===2&&(gm(e,0|e[N],r,n),Di(t,e=yl(e,s,n),i),!0)},Hm),jm=He(function(t,e,n){return t.h===2&&(We(e,n,Tm(t)),!0)},Wm,Im),yv=Ps(function(t,e,n){return(t.h===0||t.h===2)&&(e=xs(e,0|e[N],n,!1,!1),t.h==2?fo(t,Jt,e):e.push(Jt(t.g)),!0)},function(t,e,n){if((e=Ds(cm,e))!=null)for(let o=0;o<e.length;o++){var s=t,i=n,r=e[o];r!=null&&(rt(s,i,0),Ns(s.g,r))}},Am),vv=He(function(t,e,n){return t.h===0&&(We(e,n,(t=Jt(t.g))===0?void 0:t),!0)},function(t,e,n){(e=cm(e))!=null&&e!=null&&(rt(t,n,0),Ns(t.g,e))},Am),_t=He(function(t,e,n){return t.h===0&&(We(e,n,pn(t.g)),!0)},function(t,e,n){(e=Rs(e))!=null&&(e=parseInt(e,10),rt(t,n,0),po(t.g,e))},xm);class Ev{constructor(e,n){this.h=e,this.g=n,this.l=Y,this.m=F,this.defaultValue=void 0}}function At(t,e){return new Ev(t,e)}function vn(t,e){return(n,s)=>{if(Wi.length){const r=Wi.pop();r.o(s),ia(r.g,n,s),n=r}else n=new class{constructor(r,o){if(mu.length){const a=mu.pop();ia(a,r,o),r=a}else r=new class{constructor(a,c){this.h=null,this.m=!1,this.g=this.l=this.j=0,ia(this,a,c)}clear(){this.h=null,this.m=!1,this.g=this.l=this.j=0,this.ba=!1}}(r,o);this.g=r,this.l=this.g.g,this.h=this.m=-1,this.o(o)}o({fa:r=!1}={}){this.fa=r}}(n,s);try{const r=new t,o=r.u;Dl(e)(o,n);var i=r}finally{n.g.clear(),n.m=-1,n.h=-1,Wi.length<100&&Wi.push(n)}return i}}function wo(t){return function(){const e=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const o=this.g;return this.g=[],o}}}};Mm(this.u,e,Gn(_o,yo,vo,t)),vs(e,e.g.end());const n=new Uint8Array(e.h),s=e.l,i=s.length;let r=0;for(let o=0;o<i;o++){const a=s[o];n.set(a,r),r+=a.length}return e.l=[n],n}}var wu=class extends A{constructor(t){super(t)}},bu=[0,rn,He(function(t,e,n){return t.h===2&&(We(e,n,(t=Tm(t))===Vn()?void 0:t),!0)},function(t,e,n){if(e!=null){if(e instanceof A){const s=e.Ra;return void(s&&(e=s(e),e!=null&&mo(t,n,El(e).buffer)))}if(Array.isArray(e))return}Wm(t,e,n)},Im)];let oa,Cu=globalThis.trustedTypes;function Tu(t){oa===void 0&&(oa=function(){let n=null;if(!Cu)return n;try{const s=i=>i;n=Cu.createPolicy("goog#html",{createHTML:s,createScript:s,createScriptURL:s})}catch{}return n}());var e=oa;return new class{constructor(n){this.g=n}toString(){return this.g+""}}(e?e.createScriptURL(t):t)}function wv(t,...e){if(e.length===0)return Tu(t[0]);let n=t[0];for(let s=0;s<e.length;s++)n+=encodeURIComponent(e[s])+t[s+1];return Tu(n)}var qm=[0,ve,_t,fe,-1,Eo,_t,-1],bv=class extends A{constructor(t){super(t)}},zm=[0,fe,Z,fe,_t,-1,Ps(function(t,e,n){return(t.h===0||t.h===2)&&(e=xs(e,0|e[N],n,!1,!1),t.h==2?fo(t,cv,e):e.push(pn(t.g)),!0)},function(t,e,n){if((e=Ds(Rs,e))!=null&&e.length){n=Tl(t,n);for(let s=0;s<e.length;s++)po(t.g,e[s]);Sl(t,n)}},xm),Z,-1,[0,fe,-1],_t,fe,-1],Km=[0,Z,-2],Su=class extends A{constructor(t){super(t)}},Ym=[0],Xm=[0,ve,fe,1,fe,-3],it=class extends A{constructor(t){super(t,2)}},Se={};Se[336783863]=[0,Z,fe,-1,ve,[0,[1,2,3,4,5,6,7,8],ee,Ym,ee,zm,ee,Km,ee,Xm,ee,qm,ee,[0,Z,-2],ee,[0,Z,_t],ee,[0,_t,Z]],[0,Z],fe,[0,[1,3],[2,4],ee,[0,Eo],-1,ee,[0,Le],-1,Ae,[0,Z,-1]],Z];var ku=[0,ra,-1,as,-3,ra,Eo,rn,Qn,ra,-1,as,Qn,as,-2,rn];function ot(t,e){Ga(t,2,Is(e),"")}function ce(t,e){uo(t,3,e)}function q(t,e){uo(t,4,e)}var $e=class extends A{constructor(t){super(t,500)}o(t){return F(this,0,7,t)}},ri=[-1,{}],Au=[0,Z,1,ri],Ru=[0,Z,Le,ri];function at(t,e){Br(t,1,$e,e)}function ue(t,e){uo(t,10,e)}function Q(t,e){uo(t,15,e)}var Qe=class extends A{constructor(t){super(t,500)}o(t){return F(this,0,1001,t)}},Qm=[-500,Ae,[-500,rn,-1,Le,-3,[-2,Se,fe],Ae,bu,Qn,-1,Au,Ru,Ae,[0,rn,as],rn,ku,Qn,Le,987,Le],4,Ae,[-500,Z,-1,[-1,{}],998,Z],Ae,[-500,Z,Le,-1,[-2,{},fe],997,Le,-1],Qn,Ae,[-500,Z,Le,ri,998,Le],Le,Qn,Au,Ru,Ae,[0,rn,-1,ri],Le,-2,ku,rn,-1,as,[0,as,vv],978,ri,Ae,bu];Qe.prototype.g=wo(Qm);var Cv=vn(Qe,Qm),Tv=class extends A{constructor(t){super(t)}},Jm=class extends A{constructor(t){super(t)}g(){return Qt(this,Tv,1)}},Zm=[0,Ae,[0,ve,Ce,Z,-1]],bo=vn(Jm,Zm),Sv=class extends A{constructor(t){super(t)}},kv=class extends A{constructor(t){super(t)}},aa=class extends A{constructor(t){super(t)}h(){return Y(this,Sv,2)}g(){return Qt(this,kv,5)}},eg=vn(class extends A{constructor(t){super(t)}},[0,Le,Eo,Pl,[0,_t,[0,ve,-3],[0,Ce,-3],[0,ve,-1,[0,Ae,[0,ve,-2]]],Ae,[0,Ce,-1,Z,Ce]],Z,-1,mn,Ae,[0,ve,Ce],Le,mn]),tg=class extends A{constructor(t){super(t)}},cs=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,Ce,-4]]),ng=class extends A{constructor(t){super(t)}},Pi=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,Ce,-4]]),Av=class extends A{constructor(t){super(t)}},Rv=[0,ve,-1,Pl,_t],sg=class extends A{constructor(t){super(t)}};sg.prototype.g=wo([0,Ce,-4,mn]);var Iv=class extends A{constructor(t){super(t)}},xv=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,1,ve,Z,Zm],mn]),Iu=class extends A{constructor(t){super(t)}},Nv=class extends A{constructor(t){super(t)}oa(){const t=pm(this);return t??Vn()}},Fv=class extends A{constructor(t){super(t)}},ig=[1,2],Dv=vn(class extends A{constructor(t){super(t)}},[0,Ae,[0,ig,ee,[0,Pl],ee,[0,jm],ve,Z],mn]),Ll=class extends A{constructor(t){super(t)}},rg=[0,Z,ve,Ce,Le,-1],xu=class extends A{constructor(t){super(t)}},Pv=[0,fe,-1],Nu=class extends A{constructor(t){super(t)}},sr=[1,2,3,4,5],$r=class extends A{constructor(t){super(t)}g(){return pm(this)!=null}h(){return gt(this,2)!=null}},pe=class extends A{constructor(t){super(t)}g(){return am(ys(this,2))??!1}},og=[0,jm,Z,[0,ve,mn,-1],[0,_v,mn]],we=[0,og,fe,[0,sr,ee,Xm,ee,zm,ee,qm,ee,Ym,ee,Km],_t],Co=class extends A{constructor(t){super(t)}},Ol=[0,we,Ce,-1,ve],Lv=At(502141897,Co);Se[502141897]=Ol;var Ov=vn(class extends A{constructor(t){super(t)}},[0,[0,_t,-1,gv,yv],Rv]),ag=class extends A{constructor(t){super(t)}},cg=class extends A{constructor(t){super(t)}},Ml=[0,we,Ce,[0,we],fe],lg=[0,we,Ol,Ml,Ce,[0,[0,og]]],Mv=At(508968150,cg);Se[508968150]=lg,Se[508968149]=Ml;var hg=class extends A{constructor(t){super(t)}},Bv=At(513916220,hg);Se[513916220]=[0,we,lg,ve];var zn=class extends A{constructor(t){super(t)}h(){return Y(this,Ll,2)}g(){ae(this,2)}},ug=[0,we,rg];Se[478825465]=ug;var Uv=class extends A{constructor(t){super(t)}},dg=class extends A{constructor(t){super(t)}},Bl=class extends A{constructor(t){super(t)}},Ul=class extends A{constructor(t){super(t)}},fg=class extends A{constructor(t){super(t)}},Fu=[0,we,[0,we],ug,-1],pg=[0,we,Ce,ve],Vl=[0,we,Ce],mg=[0,we,pg,Vl,Ce],Vv=At(479097054,fg);Se[479097054]=[0,we,mg,Fu],Se[463370452]=Fu,Se[464864288]=pg;var $v=At(462713202,Ul);Se[462713202]=mg,Se[474472470]=Vl;var Hv=class extends A{constructor(t){super(t)}},gg=class extends A{constructor(t){super(t)}},_g=class extends A{constructor(t){super(t)}},yg=class extends A{constructor(t){super(t)}},$l=[0,we,Ce,-1,ve],Ya=[0,we,Ce,fe];yg.prototype.g=wo([0,we,Vl,[0,we],Ol,Ml,$l,Ya]);var vg=class extends A{constructor(t){super(t)}},Wv=At(456383383,vg);Se[456383383]=[0,we,rg];var Eg=class extends A{constructor(t){super(t)}},Gv=At(476348187,Eg);Se[476348187]=[0,we,Pv];var wg=class extends A{constructor(t){super(t)}},Du=class extends A{constructor(t){super(t)}},bg=[0,_t,-1],jv=At(458105876,class extends A{constructor(t){super(t)}g(){var t=this.u;const e=0|t[N],n=2&e;return t=function(s,i,r){var o=Du;const a=2&i;let c=!1;if(r==null){if(a)return pu();r=[]}else if(r.constructor===mt){if((2&r.L)==0||a)return r;r=r.X()}else Array.isArray(r)?c=!!(2&(0|r[N])):r=[];if(a){if(!r.length)return pu();c||(c=!0,As(r))}else c&&(c=!1,r=mm(r));return c||(64&(0|r[N])?r[N]&=-33:32&i&&so(r,32)),ge(s,i,2,o=new mt(r,o,Z3,void 0)),o}(t,e,tn(t,e,2)),!n&&Du&&(t.ra=!0),t}});Se[458105876]=[0,bg,mv,[!0,mn,[0,Z,-1,Le]]];var Hl=class extends A{constructor(t){super(t)}},Cg=At(458105758,Hl);Se[458105758]=[0,we,Z,bg];var Tg=class extends A{constructor(t){super(t)}},qv=At(443442058,Tg);Se[443442058]=[0,we,Z,ve,Ce,Le,-1,fe,Ce],Se[514774813]=$l;var Sg=class extends A{constructor(t){super(t)}},zv=At(516587230,Sg);function Xa(t,e){return e=e?e.clone():new Ll,t.displayNamesLocale!==void 0?ae(e,1,Is(t.displayNamesLocale)):t.displayNamesLocale===void 0&&ae(e,1),t.maxResults!==void 0?Mt(e,2,t.maxResults):"maxResults"in t&&ae(e,2),t.scoreThreshold!==void 0?I(e,3,t.scoreThreshold):"scoreThreshold"in t&&ae(e,3),t.categoryAllowlist!==void 0?Ur(e,4,t.categoryAllowlist):"categoryAllowlist"in t&&ae(e,4),t.categoryDenylist!==void 0?Ur(e,5,t.categoryDenylist):"categoryDenylist"in t&&ae(e,5),e}function Wl(t,e=-1,n=""){return{categories:t.map(s=>({index:pt(s,1)??0??-1,score:Ee(s,2)??0,categoryName:gt(s,3)??""??"",displayName:gt(s,4)??""??""})),headIndex:e,headName:n}}function kg(t){var o,a;var e=Nn(t,3,yn,xn()),n=Nn(t,2,Rs,xn()),s=Nn(t,1,_s,xn()),i=Nn(t,9,_s,xn());const r={categories:[],keypoints:[]};for(let c=0;c<e.length;c++)r.categories.push({score:e[c],index:n[c]??-1,categoryName:s[c]??"",displayName:i[c]??""});if((e=(o=Y(t,aa,4))==null?void 0:o.h())&&(r.boundingBox={originX:pt(e,1)??0,originY:pt(e,2)??0,width:pt(e,3)??0,height:pt(e,4)??0,angle:0}),(a=Y(t,aa,4))==null?void 0:a.g().length)for(const c of Y(t,aa,4).g())r.keypoints.push({x:tr(c,1)??0,y:tr(c,2)??0,score:tr(c,4)??0,label:gt(c,3)??""});return r}function To(t){const e=[];for(const n of Qt(t,ng,1))e.push({x:Ee(n,1)??0,y:Ee(n,2)??0,z:Ee(n,3)??0,visibility:Ee(n,4)??0});return e}function oi(t){const e=[];for(const n of Qt(t,tg,1))e.push({x:Ee(n,1)??0,y:Ee(n,2)??0,z:Ee(n,3)??0,visibility:Ee(n,4)??0});return e}function Pu(t){return Array.from(t,e=>e>127?e-256:e)}function Lu(t,e){if(t.length!==e.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${t.length} vs. ${e.length}).`);let n=0,s=0,i=0;for(let r=0;r<t.length;r++)n+=t[r]*e[r],s+=t[r]*t[r],i+=e[r]*e[r];if(s<=0||i<=0)throw Error("Cannot compute cosine similarity on embedding with 0 norm.");return n/Math.sqrt(s*i)}let Gi;Se[516587230]=[0,we,$l,Ya,Ce],Se[518928384]=Ya;const Kv=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);async function Ag(){if(Gi===void 0)try{await WebAssembly.instantiate(Kv),Gi=!0}catch{Gi=!1}return Gi}async function js(t,e=wv``){const n=await Ag()?"wasm_internal":"wasm_nosimd_internal";return{wasmLoaderPath:`${e}/${t}_${n}.js`,wasmBinaryPath:`${e}/${t}_${n}.wasm`}}var Sn=class{};function Rg(){var t=navigator;return typeof OffscreenCanvas<"u"&&(!function(e=navigator){return(e=e.userAgent).includes("Safari")&&!e.includes("Chrome")}(t)||!!((t=t.userAgent.match(/Version\/([\d]+).*Safari/))&&t.length>=1&&Number(t[1])>=17))}async function Ou(t){if(typeof importScripts!="function"){const e=document.createElement("script");return e.src=t.toString(),e.crossOrigin="anonymous",new Promise((n,s)=>{e.addEventListener("load",()=>{n()},!1),e.addEventListener("error",i=>{s(i)},!1),document.body.appendChild(e)})}importScripts(t.toString())}function Ig(t){return t.videoWidth!==void 0?[t.videoWidth,t.videoHeight]:t.naturalWidth!==void 0?[t.naturalWidth,t.naturalHeight]:t.displayWidth!==void 0?[t.displayWidth,t.displayHeight]:[t.width,t.height]}function x(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(e=t.i.stringToNewUTF8(e)),t.i._free(e)}function Mu(t,e,n){if(!t.i.canvas)throw Error("No OpenGL canvas configured.");if(n?t.i._bindTextureToStream(n):t.i._bindTextureToCanvas(),!(n=t.i.canvas.getContext("webgl2")||t.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[s,i]=Ig(e);return!t.l||s===t.i.canvas.width&&i===t.i.canvas.height||(t.i.canvas.width=s,t.i.canvas.height=i),[s,i]}function Bu(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const s=new Uint32Array(e.length);for(let i=0;i<e.length;i++)s[i]=t.i.stringToNewUTF8(e[i]);e=t.i._malloc(4*s.length),t.i.HEAPU32.set(s,e>>2),n(e);for(const i of s)t.i._free(i);t.i._free(e)}function Nt(t,e,n){t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=n}function nn(t,e,n){let s=[];t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=(i,r,o)=>{r?(n(s,o),s=[]):s.push(i)}}Sn.forVisionTasks=function(t){return js("vision",t)},Sn.forTextTasks=function(t){return js("text",t)},Sn.forGenAiExperimentalTasks=function(t){return js("genai_experimental",t)},Sn.forGenAiTasks=function(t){return js("genai",t)},Sn.forAudioTasks=function(t){return js("audio",t)},Sn.isSimdSupported=function(){return Ag()};async function Yv(t,e,n,s){return t=await(async(i,r,o,a,c)=>{if(r&&await Ou(r),!self.ModuleFactory||o&&(await Ou(o),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((r=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(r.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new i(c,a)})(t,n.wasmLoaderPath,n.assetLoaderPath,e,{locateFile:i=>i.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&i.endsWith(".data")?n.assetBinaryPath.toString():i}),await t.o(s),t}function ca(t,e){const n=Y(t.baseOptions,$r,1)||new $r;typeof e=="string"?(ae(n,2,Is(e)),ae(n,1)):e instanceof Uint8Array&&(ae(n,1,nl(e,!1)),ae(n,2)),F(t.baseOptions,0,1,n)}function Uu(t){try{const e=t.G.length;if(e===1)throw Error(t.G[0].message);if(e>1)throw Error("Encountered multiple errors: "+t.G.map(n=>n.message).join(", "))}finally{t.G=[]}}function S(t,e){t.B=Math.max(t.B,e)}function So(t,e){t.A=new $e,ot(t.A,"PassThroughCalculator"),ce(t.A,"free_memory"),q(t.A,"free_memory_unused_out"),ue(e,"free_memory"),at(e,t.A)}function Es(t,e){ce(t.A,e),q(t.A,e+"_unused_out")}function ko(t){t.g.addBoolToStream(!0,"free_memory",t.B)}var ir=class{constructor(t){this.g=t,this.G=[],this.B=0,this.g.setAutoRenderToScreen(!1)}l(t,e=!0){var n,s,i,r,o,a;if(e){const c=t.baseOptions||{};if((n=t.baseOptions)!=null&&n.modelAssetBuffer&&((s=t.baseOptions)!=null&&s.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((i=Y(this.baseOptions,$r,1))!=null&&i.g()||(r=Y(this.baseOptions,$r,1))!=null&&r.h()||(o=t.baseOptions)!=null&&o.modelAssetBuffer||(a=t.baseOptions)!=null&&a.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(l,h){let u=Y(l.baseOptions,Nu,3);if(!u){var d=u=new Nu,p=new Su;ii(d,4,sr,p)}"delegate"in h&&(h.delegate==="GPU"?(h=u,d=new bv,ii(h,2,sr,d)):(h=u,d=new Su,ii(h,4,sr,d))),F(l.baseOptions,0,3,u)}(this,c),c.modelAssetPath)return fetch(c.modelAssetPath.toString()).then(l=>{if(l.ok)return l.arrayBuffer();throw Error(`Failed to fetch model: ${c.modelAssetPath} (${l.status})`)}).then(l=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(l),!0,!1,!1),ca(this,"/model.dat"),this.m(),this.I()});if(c.modelAssetBuffer instanceof Uint8Array)ca(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(l){const h=[];for(var u=0;;){const{done:d,value:p}=await l.read();if(d)break;h.push(p),u+=p.length}if(h.length===0)return new Uint8Array(0);if(h.length===1)return h[0];l=new Uint8Array(u),u=0;for(const d of h)l.set(d,u),u+=d.length;return l}(c.modelAssetBuffer).then(l=>{ca(this,l),this.m(),this.I()})}return this.m(),this.I(),Promise.resolve()}I(){}da(){let t;if(this.g.da(e=>{t=Cv(e)}),!t)throw Error("Failed to retrieve CalculatorGraphConfig");return t}setGraph(t,e){this.g.attachErrorListener((n,s)=>{this.G.push(Error(s))}),this.g.La(),this.g.setGraph(t,e),this.A=void 0,Uu(this)}finishProcessing(){this.g.finishProcessing(),Uu(this)}close(){this.A=void 0,this.g.closeGraph()}};function Ve(t,e){if(!t)throw Error(`Unable to obtain required WebGL resource: ${e}`);return t}ir.prototype.close=ir.prototype.close,function(t,e){t=t.split(".");var n,s=Un;for((t[0]in s)||s.execScript===void 0||s.execScript("var "+t[0]);t.length&&(n=t.shift());)t.length||e===void 0?s=s[n]&&s[n]!==Object.prototype[n]?s[n]:s[n]={}:s[n]=e}("TaskRunner",ir);class Xv{constructor(e,n,s,i){this.g=e,this.h=n,this.m=s,this.l=i}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function Vu(t,e,n){const s=t.g;if(n=Ve(s.createShader(n),"Failed to create WebGL shader"),s.shaderSource(n,e),s.compileShader(n),!s.getShaderParameter(n,s.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${s.getShaderInfoLog(n)}`);return s.attachShader(t.h,n),n}function $u(t,e){const n=t.g,s=Ve(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(s);const i=Ve(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(t.O),n.vertexAttribPointer(t.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const r=Ve(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,r),n.enableVertexAttribArray(t.I),n.vertexAttribPointer(t.I,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(e?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new Xv(n,s,i,r)}function Gl(t,e){if(t.g){if(e!==t.g)throw Error("Cannot change GL context once initialized")}else t.g=e}function Li(t,e,n,s){return Gl(t,e),t.h||(t.m(),t.C()),n?(t.s||(t.s=$u(t,!0)),n=t.s):(t.v||(t.v=$u(t,!1)),n=t.v),e.useProgram(t.h),n.bind(),t.l(),t=s(),n.g.bindVertexArray(null),t}function gn(t,e,n){return Gl(t,e),t=Ve(e.createTexture(),"Failed to create texture"),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n??e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,n??e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),t}function Ao(t,e,n){Gl(t,e),t.A||(t.A=Ve(e.createFramebuffer(),"Failed to create framebuffe.")),e.bindFramebuffer(e.FRAMEBUFFER,t.A),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}function jl(t){var e;(e=t.g)==null||e.bindFramebuffer(t.g.FRAMEBUFFER,null)}var Ls=class{G(){return`
1595
1595
  precision mediump float;
1596
1596
  varying vec2 vTex;
1597
1597
  uniform sampler2D inputTexture;
@@ -1605,7 +1605,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1605
1605
  void main(void) {
1606
1606
  gl_Position = vec4(aVertex, 0.0, 1.0);
1607
1607
  vTex = aTex;
1608
- }`,t.VERTEX_SHADER),this.Z=Vu(this,this.G(),t.FRAGMENT_SHADER),t.linkProgram(this.h),!t.getProgramParameter(this.h,t.LINK_STATUS))throw Error(`Error during program linking: ${t.getProgramInfoLog(this.h)}`);this.O=t.getAttribLocation(this.h,"aVertex"),this.I=t.getAttribLocation(this.h,"aTex")}C(){}l(){}close(){if(this.h){const t=this.g;t.deleteProgram(this.h),t.deleteShader(this.aa),t.deleteShader(this.Z)}this.A&&this.g.deleteFramebuffer(this.A),this.v&&this.v.close(),this.s&&this.s.close()}},Xv=class extends Ls{G(){return`
1608
+ }`,t.VERTEX_SHADER),this.Z=Vu(this,this.G(),t.FRAGMENT_SHADER),t.linkProgram(this.h),!t.getProgramParameter(this.h,t.LINK_STATUS))throw Error(`Error during program linking: ${t.getProgramInfoLog(this.h)}`);this.O=t.getAttribLocation(this.h,"aVertex"),this.I=t.getAttribLocation(this.h,"aTex")}C(){}l(){}close(){if(this.h){const t=this.g;t.deleteProgram(this.h),t.deleteShader(this.aa),t.deleteShader(this.Z)}this.A&&this.g.deleteFramebuffer(this.A),this.v&&this.v.close(),this.s&&this.s.close()}},Qv=class extends Ls{G(){return`
1609
1609
  precision mediump float;
1610
1610
  uniform sampler2D backgroundTexture;
1611
1611
  uniform sampler2D maskTexture;
@@ -1617,7 +1617,7 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1617
1617
  vec4 categoryColor = texture2D(colorMappingTexture, vec2(category, 0.0));
1618
1618
  gl_FragColor = mix(backgroundColor, categoryColor, categoryColor.a);
1619
1619
  }
1620
- `}C(){const t=this.g;t.activeTexture(t.TEXTURE1),this.B=gn(this,t,t.LINEAR),t.activeTexture(t.TEXTURE2),this.j=gn(this,t,t.NEAREST)}m(){super.m();const t=this.g;this.K=Ve(t.getUniformLocation(this.h,"backgroundTexture"),"Uniform location"),this.T=Ve(t.getUniformLocation(this.h,"colorMappingTexture"),"Uniform location"),this.J=Ve(t.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const t=this.g;t.uniform1i(this.J,0),t.uniform1i(this.K,1),t.uniform1i(this.T,2)}close(){this.B&&this.g.deleteTexture(this.B),this.j&&this.g.deleteTexture(this.j),super.close()}},Qv=class extends Ls{G(){return`
1620
+ `}C(){const t=this.g;t.activeTexture(t.TEXTURE1),this.B=gn(this,t,t.LINEAR),t.activeTexture(t.TEXTURE2),this.j=gn(this,t,t.NEAREST)}m(){super.m();const t=this.g;this.K=Ve(t.getUniformLocation(this.h,"backgroundTexture"),"Uniform location"),this.T=Ve(t.getUniformLocation(this.h,"colorMappingTexture"),"Uniform location"),this.J=Ve(t.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const t=this.g;t.uniform1i(this.J,0),t.uniform1i(this.K,1),t.uniform1i(this.T,2)}close(){this.B&&this.g.deleteTexture(this.B),this.j&&this.g.deleteTexture(this.j),super.close()}},Jv=class extends Ls{G(){return`
1621
1621
  precision mediump float;
1622
1622
  uniform sampler2D maskTexture;
1623
1623
  uniform sampler2D defaultTexture;
@@ -1631,9 +1631,9 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1631
1631
  overlayColor = mix(defaultColor, overlayColor, overlayColor.a);
1632
1632
  gl_FragColor = mix(defaultColor, overlayColor, confidence);
1633
1633
  }
1634
- `}C(){const t=this.g;t.activeTexture(t.TEXTURE1),this.j=gn(this,t),t.activeTexture(t.TEXTURE2),this.B=gn(this,t)}m(){super.m();const t=this.g;this.J=Ve(t.getUniformLocation(this.h,"defaultTexture"),"Uniform location"),this.K=Ve(t.getUniformLocation(this.h,"overlayTexture"),"Uniform location"),this.H=Ve(t.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const t=this.g;t.uniform1i(this.H,0),t.uniform1i(this.J,1),t.uniform1i(this.K,2)}close(){this.j&&this.g.deleteTexture(this.j),this.B&&this.g.deleteTexture(this.B),super.close()}};function Wt(t,e){switch(e){case 0:return t.g.find(n=>n instanceof Uint8Array);case 1:return t.g.find(n=>n instanceof Float32Array);case 2:return t.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${e}`)}}function Ja(t){var e=Wt(t,1);if(!e){if(e=Wt(t,0))e=new Float32Array(e).map(s=>s/255);else{e=new Float32Array(t.width*t.height);const s=ws(t);var n=ql(t);if(Ro(n,s,Ig(t)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){n=new Float32Array(t.width*t.height*4),s.readPixels(0,0,t.width,t.height,s.RGBA,s.FLOAT,n);for(let i=0,r=0;i<e.length;++i,r+=4)e[i]=n[r]}else s.readPixels(0,0,t.width,t.height,s.RED,s.FLOAT,e)}t.g.push(e)}return e}function Ig(t){let e=Wt(t,2);if(!e){const n=ws(t);e=Fg(t);const s=Ja(t),i=xg(t);n.texImage2D(n.TEXTURE_2D,0,i,t.width,t.height,0,n.RED,n.FLOAT,s),Za(t)}return e}function ws(t){if(!t.canvas)throw Error("Conversion to different image formats require that a canvas is passed when initializing the image.");return t.h||(t.h=Ve(t.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),t.h}function xg(t){if(t=ws(t),!ji)if(t.getExtension("EXT_color_buffer_float")&&t.getExtension("OES_texture_float_linear")&&t.getExtension("EXT_float_blend"))ji=t.R32F;else{if(!t.getExtension("EXT_color_buffer_half_float"))throw Error("GPU does not fully support 4-channel float32 or float16 formats");ji=t.R16F}return ji}function ql(t){return t.l||(t.l=new Ls),t.l}function Fg(t){const e=ws(t);e.viewport(0,0,t.width,t.height),e.activeTexture(e.TEXTURE0);let n=Wt(t,2);return n||(n=gn(ql(t),e,t.m?e.LINEAR:e.NEAREST),t.g.push(n),t.j=!0),e.bindTexture(e.TEXTURE_2D,n),n}function Za(t){t.h.bindTexture(t.h.TEXTURE_2D,null)}var ji,ke=class{constructor(t,e,n,s,i,r,o){this.g=t,this.m=e,this.j=n,this.canvas=s,this.l=i,this.width=r,this.height=o,this.j&&--Hu===0&&console.error("You seem to be creating MPMask instances without invoking .close(). This leaks resources.")}Fa(){return!!Wt(this,0)}ja(){return!!Wt(this,1)}P(){return!!Wt(this,2)}ia(){return(e=Wt(t=this,0))||(e=Ja(t),e=new Uint8Array(e.map(n=>255*n)),t.g.push(e)),e;var t,e}ha(){return Ja(this)}M(){return Ig(this)}clone(){const t=[];for(const e of this.g){let n;if(e instanceof Uint8Array)n=new Uint8Array(e);else if(e instanceof Float32Array)n=new Float32Array(e);else{if(!(e instanceof WebGLTexture))throw Error(`Type is not supported: ${e}`);{const s=ws(this),i=ql(this);s.activeTexture(s.TEXTURE1),n=gn(i,s,this.m?s.LINEAR:s.NEAREST),s.bindTexture(s.TEXTURE_2D,n);const r=xg(this);s.texImage2D(s.TEXTURE_2D,0,r,this.width,this.height,0,s.RED,s.FLOAT,null),s.bindTexture(s.TEXTURE_2D,null),Ro(i,s,n),Li(i,s,!1,()=>{Fg(this),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.drawArrays(s.TRIANGLE_FAN,0,4),Za(this)}),jl(i),Za(this)}}t.push(n)}return new ke(t,this.m,this.P(),this.canvas,this.l,this.width,this.height)}close(){this.j&&ws(this).deleteTexture(Wt(this,2)),Hu=-1}};ke.prototype.close=ke.prototype.close,ke.prototype.clone=ke.prototype.clone,ke.prototype.getAsWebGLTexture=ke.prototype.M,ke.prototype.getAsFloat32Array=ke.prototype.ha,ke.prototype.getAsUint8Array=ke.prototype.ia,ke.prototype.hasWebGLTexture=ke.prototype.P,ke.prototype.hasFloat32Array=ke.prototype.ja,ke.prototype.hasUint8Array=ke.prototype.Fa;var Hu=250;const Jv={color:"white",lineWidth:4,radius:6};function ha(t){return{...Jv,fillColor:(t=t||{}).color,...t}}function Vt(t,e){return t instanceof Function?t(e):t}function Wu(t,e,n){return Math.max(Math.min(e,n),Math.min(Math.max(e,n),t))}function qs(t){if(!t.l)throw Error("CPU rendering requested but CanvasRenderingContext2D not provided.");return t.l}function wi(t){if(!t.j)throw Error("GPU rendering requested but WebGL2RenderingContext not provided.");return t.j}function Gu(t,e,n){if(e.P())n(e.M());else{const s=e.ja()?e.ha():e.ia();t.m=t.m??new Ls;const i=wi(t);n((t=new ke([s],e.m,!1,i.canvas,t.m,e.width,e.height)).M()),t.close()}}function ju(t,e,n,s){const i=function(a){return a.g||(a.g=new Xv),a.g}(t),r=wi(t),o=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n;Li(i,r,!0,()=>{(function(c,l,h,u){const d=c.g;if(d.activeTexture(d.TEXTURE0),d.bindTexture(d.TEXTURE_2D,l),d.activeTexture(d.TEXTURE1),d.bindTexture(d.TEXTURE_2D,c.B),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,h),c.H&&function(p,m){if(p!==m)return!1;p=p.entries(),m=m.entries();for(const[w,k]of p){p=w;const E=k;var y=m.next();if(y.done)return!1;const[T,P]=y.value;if(y=P,p!==T||E[0]!==y[0]||E[1]!==y[1]||E[2]!==y[2]||E[3]!==y[3])return!1}return!!m.next().done}(c.H,u))d.activeTexture(d.TEXTURE2),d.bindTexture(d.TEXTURE_2D,c.j);else{c.H=u;const p=Array(1024).fill(0);u.forEach((m,y)=>{if(m.length!==4)throw Error(`Color at index ${y} is not a four-channel value.`);p[4*y]=m[0],p[4*y+1]=m[1],p[4*y+2]=m[2],p[4*y+3]=m[3]}),d.activeTexture(d.TEXTURE2),d.bindTexture(d.TEXTURE_2D,c.j),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,256,1,0,d.RGBA,d.UNSIGNED_BYTE,new Uint8Array(p))}})(i,e,o,s),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4);const a=i.g;a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,null),a.activeTexture(a.TEXTURE1),a.bindTexture(a.TEXTURE_2D,null),a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,null)})}function qu(t,e,n,s){const i=wi(t),r=function(c){return c.h||(c.h=new Qv),c.h}(t),o=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n,a=Array.isArray(s)?new ImageData(new Uint8ClampedArray(s),1,1):s;Li(r,i,!0,()=>{var c=r.g;c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,e),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,r.j),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,o),c.activeTexture(c.TEXTURE2),c.bindTexture(c.TEXTURE_2D,r.B),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,a),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLE_FAN,0,4),i.bindTexture(i.TEXTURE_2D,null),(c=r.g).activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,null),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,null),c.activeTexture(c.TEXTURE2),c.bindTexture(c.TEXTURE_2D,null)})}var Pe=class{constructor(t,e){t instanceof CanvasRenderingContext2D||t instanceof OffscreenCanvasRenderingContext2D?(this.l=t,this.j=e):this.j=t}ya(t,e){if(t){var n=qs(this);e=ha(e),n.save();var s=n.canvas,i=0;for(const r of t)n.fillStyle=Vt(e.fillColor,{index:i,from:r}),n.strokeStyle=Vt(e.color,{index:i,from:r}),n.lineWidth=Vt(e.lineWidth,{index:i,from:r}),(t=new Path2D).arc(r.x*s.width,r.y*s.height,Vt(e.radius,{index:i,from:r}),0,2*Math.PI),n.fill(t),n.stroke(t),++i;n.restore()}}xa(t,e,n){if(t&&e){var s=qs(this);n=ha(n),s.save();var i=s.canvas,r=0;for(const o of e){s.beginPath(),e=t[o.start];const a=t[o.end];e&&a&&(s.strokeStyle=Vt(n.color,{index:r,from:e,to:a}),s.lineWidth=Vt(n.lineWidth,{index:r,from:e,to:a}),s.moveTo(e.x*i.width,e.y*i.height),s.lineTo(a.x*i.width,a.y*i.height)),++r,s.stroke()}s.restore()}}ua(t,e){const n=qs(this);e=ha(e),n.save(),n.beginPath(),n.lineWidth=Vt(e.lineWidth,{}),n.strokeStyle=Vt(e.color,{}),n.fillStyle=Vt(e.fillColor,{}),n.moveTo(t.originX,t.originY),n.lineTo(t.originX+t.width,t.originY),n.lineTo(t.originX+t.width,t.originY+t.height),n.lineTo(t.originX,t.originY+t.height),n.lineTo(t.originX,t.originY),n.stroke(),n.fill(),n.restore()}va(t,e,n=[0,0,0,255]){this.l?function(s,i,r,o){const a=wi(s);Gu(s,i,c=>{ju(s,c,r,o),(c=qs(s)).drawImage(a.canvas,0,0,c.canvas.width,c.canvas.height)})}(this,t,n,e):ju(this,t.M(),n,e)}wa(t,e,n){this.l?function(s,i,r,o){const a=wi(s);Gu(s,i,c=>{qu(s,c,r,o),(c=qs(s)).drawImage(a.canvas,0,0,c.canvas.width,c.canvas.height)})}(this,t,e,n):qu(this,t.M(),e,n)}close(){var t,e,n;(t=this.g)==null||t.close(),this.g=void 0,(e=this.h)==null||e.close(),this.h=void 0,(n=this.m)==null||n.close(),this.m=void 0}};function Ot(t,e){switch(e){case 0:return t.g.find(n=>n instanceof ImageData);case 1:return t.g.find(n=>typeof ImageBitmap<"u"&&n instanceof ImageBitmap);case 2:return t.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${e}`)}}function Ng(t){var e=Ot(t,0);if(!e){e=bs(t);const n=Io(t),s=new Uint8Array(t.width*t.height*4);Ro(n,e,rr(t)),e.readPixels(0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,s),jl(n),e=new ImageData(new Uint8ClampedArray(s.buffer),t.width,t.height),t.g.push(e)}return e}function rr(t){let e=Ot(t,2);if(!e){const n=bs(t);e=or(t);const s=Ot(t,1)||Ng(t);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,s),Qs(t)}return e}function bs(t){if(!t.canvas)throw Error("Conversion to different image formats require that a canvas is passed when initializing the image.");return t.h||(t.h=Ve(t.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),t.h}function Io(t){return t.l||(t.l=new Ls),t.l}function or(t){const e=bs(t);e.viewport(0,0,t.width,t.height),e.activeTexture(e.TEXTURE0);let n=Ot(t,2);return n||(n=gn(Io(t),e),t.g.push(n),t.m=!0),e.bindTexture(e.TEXTURE_2D,n),n}function Qs(t){t.h.bindTexture(t.h.TEXTURE_2D,null)}function zu(t){const e=bs(t);return Li(Io(t),e,!0,()=>function(n,s){const i=n.canvas;if(i.width===n.width&&i.height===n.height)return s();const r=i.width,o=i.height;return i.width=n.width,i.height=n.height,n=s(),i.width=r,i.height=o,n}(t,()=>{if(e.bindFramebuffer(e.FRAMEBUFFER,null),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_FAN,0,4),!(t.canvas instanceof OffscreenCanvas))throw Error("Conversion to ImageBitmap requires that the MediaPipe Tasks is initialized with an OffscreenCanvas");return t.canvas.transferToImageBitmap()}))}Pe.prototype.close=Pe.prototype.close,Pe.prototype.drawConfidenceMask=Pe.prototype.wa,Pe.prototype.drawCategoryMask=Pe.prototype.va,Pe.prototype.drawBoundingBox=Pe.prototype.ua,Pe.prototype.drawConnectors=Pe.prototype.xa,Pe.prototype.drawLandmarks=Pe.prototype.ya,Pe.lerp=function(t,e,n,s,i){return Wu(s*(1-(t-e)/(n-e))+i*(1-(n-t)/(n-e)),s,i)},Pe.clamp=Wu;var Ie=class{constructor(t,e,n,s,i,r,o){this.g=t,this.j=e,this.m=n,this.canvas=s,this.l=i,this.width=r,this.height=o,(this.j||this.m)&&--Ku===0&&console.error("You seem to be creating MPImage instances without invoking .close(). This leaks resources.")}Ea(){return!!Ot(this,0)}ka(){return!!Ot(this,1)}P(){return!!Ot(this,2)}Ca(){return Ng(this)}Ba(){var t=Ot(this,1);return t||(rr(this),or(this),t=zu(this),Qs(this),this.g.push(t),this.j=!0),t}M(){return rr(this)}clone(){const t=[];for(const e of this.g){let n;if(e instanceof ImageData)n=new ImageData(e.data,this.width,this.height);else if(e instanceof WebGLTexture){const s=bs(this),i=Io(this);s.activeTexture(s.TEXTURE1),n=gn(i,s),s.bindTexture(s.TEXTURE_2D,n),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.bindTexture(s.TEXTURE_2D,null),Ro(i,s,n),Li(i,s,!1,()=>{or(this),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.drawArrays(s.TRIANGLE_FAN,0,4),Qs(this)}),jl(i),Qs(this)}else{if(!(e instanceof ImageBitmap))throw Error(`Type is not supported: ${e}`);rr(this),or(this),n=zu(this),Qs(this)}t.push(n)}return new Ie(t,this.ka(),this.P(),this.canvas,this.l,this.width,this.height)}close(){this.j&&Ot(this,1).close(),this.m&&bs(this).deleteTexture(Ot(this,2)),Ku=-1}};Ie.prototype.close=Ie.prototype.close,Ie.prototype.clone=Ie.prototype.clone,Ie.prototype.getAsWebGLTexture=Ie.prototype.M,Ie.prototype.getAsImageBitmap=Ie.prototype.Ba,Ie.prototype.getAsImageData=Ie.prototype.Ca,Ie.prototype.hasWebGLTexture=Ie.prototype.P,Ie.prototype.hasImageBitmap=Ie.prototype.ka,Ie.prototype.hasImageData=Ie.prototype.Ea;var Ku=250;function Rt(...t){return t.map(([e,n])=>({start:e,end:n}))}const Zv=function(t){return class extends t{La(){this.i._registerModelResourcesGraphService()}}}((Yu=class{constructor(t,e){this.l=!0,this.i=t,this.g=null,this.h=0,this.m=typeof this.i._addIntToInputStream=="function",e!==void 0?this.i.canvas=e:Ag()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(t){const e=await(await fetch(t)).arrayBuffer();t=!(t.endsWith(".pbtxt")||t.endsWith(".textproto")),this.setGraph(new Uint8Array(e),t)}setGraphFromString(t){this.setGraph(new TextEncoder().encode(t),!1)}setGraph(t,e){const n=t.length,s=this.i._malloc(n);this.i.HEAPU8.set(t,s),e?this.i._changeBinaryGraph(n,s):this.i._changeTextGraph(n,s),this.i._free(s)}configureAudio(t,e,n,s,i){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),x(this,s||"input_audio",r=>{x(this,i=i||"audio_header",o=>{this.i._configureAudio(r,o,t,e??0,n)})})}setAutoResizeCanvas(t){this.l=t}setAutoRenderToScreen(t){this.i._setAutoRenderToScreen(t)}setGpuBufferVerticalFlip(t){this.i.gpuOriginForWebTexturesIsBottomLeft=t}da(t){Ft(this,"__graph_config__",e=>{t(e)}),x(this,"__graph_config__",e=>{this.i._getGraphConfig(e,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(t){this.i.errorListener=t}attachEmptyPacketListener(t,e){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[t]=e}addAudioToStream(t,e,n){this.addAudioToStreamWithShape(t,0,0,e,n)}addAudioToStreamWithShape(t,e,n,s,i){const r=4*t.length;this.h!==r&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(r),this.h=r),this.i.HEAPF32.set(t,this.g/4),x(this,s,o=>{this.i._addAudioToInputStream(this.g,e,n,o,i)})}addGpuBufferToStream(t,e,n){x(this,e,s=>{const[i,r]=Mu(this,t,s);this.i._addBoundTextureToStream(s,i,r,n)})}addBoolToStream(t,e,n){x(this,e,s=>{this.i._addBoolToInputStream(t,s,n)})}addDoubleToStream(t,e,n){x(this,e,s=>{this.i._addDoubleToInputStream(t,s,n)})}addFloatToStream(t,e,n){x(this,e,s=>{this.i._addFloatToInputStream(t,s,n)})}addIntToStream(t,e,n){x(this,e,s=>{this.i._addIntToInputStream(t,s,n)})}addUintToStream(t,e,n){x(this,e,s=>{this.i._addUintToInputStream(t,s,n)})}addStringToStream(t,e,n){x(this,e,s=>{x(this,t,i=>{this.i._addStringToInputStream(i,s,n)})})}addStringRecordToStream(t,e,n){x(this,e,s=>{Bu(this,Object.keys(t),i=>{Bu(this,Object.values(t),r=>{this.i._addFlatHashMapToInputStream(i,r,Object.keys(t).length,s,n)})})})}addProtoToStream(t,e,n,s){x(this,n,i=>{x(this,e,r=>{const o=this.i._malloc(t.length);this.i.HEAPU8.set(t,o),this.i._addProtoToInputStream(o,t.length,r,i,s),this.i._free(o)})})}addEmptyPacketToStream(t,e){x(this,t,n=>{this.i._addEmptyPacketToInputStream(n,e)})}addBoolVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateBoolVector(t.length);if(!i)throw Error("Unable to allocate new bool vector on heap.");for(const r of t)this.i._addBoolVectorEntry(i,r);this.i._addBoolVectorToInputStream(i,s,n)})}addDoubleVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateDoubleVector(t.length);if(!i)throw Error("Unable to allocate new double vector on heap.");for(const r of t)this.i._addDoubleVectorEntry(i,r);this.i._addDoubleVectorToInputStream(i,s,n)})}addFloatVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateFloatVector(t.length);if(!i)throw Error("Unable to allocate new float vector on heap.");for(const r of t)this.i._addFloatVectorEntry(i,r);this.i._addFloatVectorToInputStream(i,s,n)})}addIntVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateIntVector(t.length);if(!i)throw Error("Unable to allocate new int vector on heap.");for(const r of t)this.i._addIntVectorEntry(i,r);this.i._addIntVectorToInputStream(i,s,n)})}addUintVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateUintVector(t.length);if(!i)throw Error("Unable to allocate new unsigned int vector on heap.");for(const r of t)this.i._addUintVectorEntry(i,r);this.i._addUintVectorToInputStream(i,s,n)})}addStringVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateStringVector(t.length);if(!i)throw Error("Unable to allocate new string vector on heap.");for(const r of t)x(this,r,o=>{this.i._addStringVectorEntry(i,o)});this.i._addStringVectorToInputStream(i,s,n)})}addBoolToInputSidePacket(t,e){x(this,e,n=>{this.i._addBoolToInputSidePacket(t,n)})}addDoubleToInputSidePacket(t,e){x(this,e,n=>{this.i._addDoubleToInputSidePacket(t,n)})}addFloatToInputSidePacket(t,e){x(this,e,n=>{this.i._addFloatToInputSidePacket(t,n)})}addIntToInputSidePacket(t,e){x(this,e,n=>{this.i._addIntToInputSidePacket(t,n)})}addUintToInputSidePacket(t,e){x(this,e,n=>{this.i._addUintToInputSidePacket(t,n)})}addStringToInputSidePacket(t,e){x(this,e,n=>{x(this,t,s=>{this.i._addStringToInputSidePacket(s,n)})})}addProtoToInputSidePacket(t,e,n){x(this,n,s=>{x(this,e,i=>{const r=this.i._malloc(t.length);this.i.HEAPU8.set(t,r),this.i._addProtoToInputSidePacket(r,t.length,i,s),this.i._free(r)})})}addBoolVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateBoolVector(t.length);if(!s)throw Error("Unable to allocate new bool vector on heap.");for(const i of t)this.i._addBoolVectorEntry(s,i);this.i._addBoolVectorToInputSidePacket(s,n)})}addDoubleVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateDoubleVector(t.length);if(!s)throw Error("Unable to allocate new double vector on heap.");for(const i of t)this.i._addDoubleVectorEntry(s,i);this.i._addDoubleVectorToInputSidePacket(s,n)})}addFloatVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateFloatVector(t.length);if(!s)throw Error("Unable to allocate new float vector on heap.");for(const i of t)this.i._addFloatVectorEntry(s,i);this.i._addFloatVectorToInputSidePacket(s,n)})}addIntVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateIntVector(t.length);if(!s)throw Error("Unable to allocate new int vector on heap.");for(const i of t)this.i._addIntVectorEntry(s,i);this.i._addIntVectorToInputSidePacket(s,n)})}addUintVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateUintVector(t.length);if(!s)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of t)this.i._addUintVectorEntry(s,i);this.i._addUintVectorToInputSidePacket(s,n)})}addStringVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateStringVector(t.length);if(!s)throw Error("Unable to allocate new string vector on heap.");for(const i of t)x(this,i,r=>{this.i._addStringVectorEntry(s,r)});this.i._addStringVectorToInputSidePacket(s,n)})}attachBoolListener(t,e){Ft(this,t,e),x(this,t,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(t,e){Ft(this,t,e),x(this,t,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(t,e){Ft(this,t,e),x(this,t,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(t,e){Ft(this,t,e),x(this,t,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(t,e){Ft(this,t,e),x(this,t,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(t,e){Ft(this,t,e),x(this,t,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(t,e,n){Ft(this,t,e),x(this,t,s=>{this.i._attachProtoListener(s,n||!1)})}attachProtoVectorListener(t,e,n){nn(this,t,e),x(this,t,s=>{this.i._attachProtoVectorListener(s,n||!1)})}attachAudioListener(t,e,n){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),Ft(this,t,(s,i)=>{s=new Float32Array(s.buffer,s.byteOffset,s.length/4),e(s,i)}),x(this,t,s=>{this.i._attachAudioListener(s,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends Yu{get ea(){return this.i}qa(t,e,n){x(this,e,s=>{const[i,r]=Mu(this,t,s);this.ea._addBoundTextureAsImageToStream(s,i,r,n)})}U(t,e){Ft(this,t,e),x(this,t,n=>{this.ea._attachImageListener(n)})}ca(t,e){nn(this,t,e),x(this,t,n=>{this.ea._attachImageVectorListener(n)})}}));var Yu,yt=class extends Zv{};async function W(t,e,n){return async function(s,i,r,o){return Kv(s,i,r,o)}(t,n.canvas??(Ag()?void 0:document.createElement("canvas")),e,n)}function Dg(t,e,n,s){if(t.T){const r=new ng;if(n!=null&&n.regionOfInterest){if(!t.pa)throw Error("This task doesn't support region-of-interest.");var i=n.regionOfInterest;if(i.left>=i.right||i.top>=i.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(i.left<0||i.top<0||i.right>1||i.bottom>1)throw Error("Expected RectF values to be in [0,1].");I(r,1,(i.left+i.right)/2),I(r,2,(i.top+i.bottom)/2),I(r,4,i.right-i.left),I(r,3,i.bottom-i.top)}else I(r,1,.5),I(r,2,.5),I(r,4,1),I(r,3,1);if(n!=null&&n.rotationDegrees){if((n==null?void 0:n.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(I(r,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[o,a]=Rg(e);n=Ee(r,3)*a/o,i=Ee(r,4)*o/a,I(r,4,n),I(r,3,i)}}t.g.addProtoToStream(r.g(),"mediapipe.NormalizedRect",t.T,s)}t.g.qa(e,t.aa,s??performance.now()),t.finishProcessing()}function vt(t,e,n){var s;if((s=t.baseOptions)!=null&&s.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");Dg(t,e,n,t.B+1)}function Ut(t,e,n,s){var i;if(!((i=t.baseOptions)!=null&&i.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");Dg(t,e,n,s)}function Cs(t,e,n,s){var i=e.data;const r=e.width,o=r*(e=e.height);if((i instanceof Uint8Array||i instanceof Float32Array)&&i.length!==o)throw Error("Unsupported channel count: "+i.length/o);return t=new ke([i],n,!1,t.g.i.canvas,t.O,r,e),s?t.clone():t}var Xe=class extends ir{constructor(t,e,n,s){super(t),this.g=t,this.aa=e,this.T=n,this.pa=s,this.O=new Ls}l(t,e=!0){if("runningMode"in t&&vi(this.baseOptions,2,!!t.runningMode&&t.runningMode!=="IMAGE"),t.canvas!==void 0&&this.g.i.canvas!==t.canvas)throw Error("You must create a new task to reset the canvas.");return super.l(t,e)}close(){this.O.close(),super.close()}};Xe.prototype.close=Xe.prototype.close;var lt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect_in",!1),this.j={detections:[]},N(t=this.h=new To,0,1,e=new pe),I(this.h,2,.5),I(this.h,3,.3)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return"minDetectionConfidence"in t&&I(this.h,2,t.minDetectionConfidence??.5),"minSuppressionThreshold"in t&&I(this.h,3,t.minSuppressionThreshold??.3),this.l(t)}D(t,e){return this.j={detections:[]},vt(this,t,e),this.j}F(t,e,n){return this.j={detections:[]},Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect_in"),Q(t,"detections");const e=new it;St(e,Pv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect_in"),j(n,"DETECTIONS:detections"),n.o(e),at(t,n),this.g.attachProtoVectorListener("detections",(s,i)=>{for(const r of s)s=Zm(r),this.j.detections.push(Sg(s));S(this,i)}),this.g.attachEmptyPacketListener("detections",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};lt.prototype.detectForVideo=lt.prototype.F,lt.prototype.detect=lt.prototype.D,lt.prototype.setOptions=lt.prototype.o,lt.createFromModelPath=async function(t,e){return W(lt,t,{baseOptions:{modelAssetPath:e}})},lt.createFromModelBuffer=function(t,e){return W(lt,t,{baseOptions:{modelAssetBuffer:e}})},lt.createFromOptions=function(t,e){return W(lt,t,e)};var zl=Rt([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),Kl=Rt([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),Yl=Rt([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),Pg=Rt([474,475],[475,476],[476,477],[477,474]),Xl=Rt([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),Ql=Rt([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),Lg=Rt([469,470],[470,471],[471,472],[472,469]),Jl=Rt([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),Og=[...zl,...Kl,...Yl,...Xl,...Ql,...Jl],Mg=Rt([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function Xu(t){t.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var X=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,N(t=this.h=new ag,0,1,e=new pe),this.v=new og,N(this.h,0,3,this.v),this.s=new To,N(this.h,0,2,this.s),Mt(this.s,4,1),I(this.s,2,.5),I(this.v,2,.5),I(this.h,4,.5)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return"numFaces"in t&&Mt(this.s,4,t.numFaces??1),"minFaceDetectionConfidence"in t&&I(this.s,2,t.minFaceDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.h,4,t.minTrackingConfidence??.5),"minFacePresenceConfidence"in t&&I(this.v,2,t.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in t&&(this.outputFaceBlendshapes=!!t.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in t&&(this.outputFacialTransformationMatrixes=!!t.outputFacialTransformationMatrixes),this.l(t)}D(t,e){return Xu(this),vt(this,t,e),this.j}F(t,e,n){return Xu(this),Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"face_landmarks");const e=new it;St(e,Ov,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),j(n,"NORM_LANDMARKS:face_landmarks"),n.o(e),at(t,n),this.g.attachProtoVectorListener("face_landmarks",(s,i)=>{for(const r of s)s=Pi(r),this.j.faceLandmarks.push(So(s));S(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",s=>{S(this,s)}),this.outputFaceBlendshapes&&(Q(t,"blendshapes"),j(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(s,i)=>{if(this.outputFaceBlendshapes)for(const r of s)s=Co(r),this.j.faceBlendshapes.push(Wl(s.g()??[]));S(this,i)}),this.g.attachEmptyPacketListener("blendshapes",s=>{S(this,s)})),this.outputFacialTransformationMatrixes&&(Q(t,"face_geometry"),j(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(s,i)=>{if(this.outputFacialTransformationMatrixes)for(const r of s)(s=z(Lv(r),kv,2))&&this.j.facialTransformationMatrixes.push({rows:pt(s,1)??0??0,columns:pt(s,2)??0??0,data:Fn(s,3,yn,xn()).slice()??[]});S(this,i)}),this.g.attachEmptyPacketListener("face_geometry",s=>{S(this,s)})),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};X.prototype.detectForVideo=X.prototype.F,X.prototype.detect=X.prototype.D,X.prototype.setOptions=X.prototype.o,X.createFromModelPath=function(t,e){return W(X,t,{baseOptions:{modelAssetPath:e}})},X.createFromModelBuffer=function(t,e){return W(X,t,{baseOptions:{modelAssetBuffer:e}})},X.createFromOptions=function(t,e){return W(X,t,e)},X.FACE_LANDMARKS_LIPS=zl,X.FACE_LANDMARKS_LEFT_EYE=Kl,X.FACE_LANDMARKS_LEFT_EYEBROW=Yl,X.FACE_LANDMARKS_LEFT_IRIS=Pg,X.FACE_LANDMARKS_RIGHT_EYE=Xl,X.FACE_LANDMARKS_RIGHT_EYEBROW=Ql,X.FACE_LANDMARKS_RIGHT_IRIS=Lg,X.FACE_LANDMARKS_FACE_OVAL=Jl,X.FACE_LANDMARKS_CONTOURS=Og,X.FACE_LANDMARKS_TESSELATION=Mg;var Nt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!0),N(t=this.j=new lg,0,1,e=new pe)}get baseOptions(){return z(this.j,pe,1)}set baseOptions(t){N(this.j,0,1,t)}o(t){return super.l(t)}Oa(t,e,n){const s=typeof e!="function"?e:{};if(this.h=typeof e=="function"?e:n,vt(this,t,s??{}),!this.h)return this.s}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"stylized_image");const e=new it;St(e,Mv,this.j);const n=new $e;ot(n,"mediapipe.tasks.vision.face_stylizer.FaceStylizerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),j(n,"STYLIZED_IMAGE:stylized_image"),n.o(e),at(t,n),this.g.U("stylized_image",(s,i)=>{var r=!this.h,o=s.data,a=s.width;const c=a*(s=s.height);if(o instanceof Uint8Array)if(o.length===3*c){const l=new Uint8ClampedArray(4*c);for(let h=0;h<c;++h)l[4*h]=o[3*h],l[4*h+1]=o[3*h+1],l[4*h+2]=o[3*h+2],l[4*h+3]=255;o=new ImageData(l,a,s)}else{if(o.length!==4*c)throw Error("Unsupported channel count: "+o.length/c);o=new ImageData(new Uint8ClampedArray(o.buffer,o.byteOffset,o.length),a,s)}else if(!(o instanceof WebGLTexture))throw Error(`Unsupported format: ${o.constructor.name}`);a=new Ie([o],!1,!1,this.g.i.canvas,this.O,a,s),this.s=r=r?a.clone():a,this.h&&this.h(r),S(this,i)}),this.g.attachEmptyPacketListener("stylized_image",s=>{this.s=null,this.h&&this.h(null),S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Nt.prototype.stylize=Nt.prototype.Oa,Nt.prototype.setOptions=Nt.prototype.o,Nt.createFromModelPath=function(t,e){return W(Nt,t,{baseOptions:{modelAssetPath:e}})},Nt.createFromModelBuffer=function(t,e){return W(Nt,t,{baseOptions:{modelAssetBuffer:e}})},Nt.createFromOptions=function(t,e){return W(Nt,t,e)};var Zl=Rt([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function Qu(t){t.gestures=[],t.landmarks=[],t.worldLandmarks=[],t.handedness=[]}function Ju(t){return t.gestures.length===0?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:t.gestures,landmarks:t.landmarks,worldLandmarks:t.worldLandmarks,handedness:t.handedness,handednesses:t.handedness}}function Zu(t,e=!0){const n=[];for(const i of t){var s=Co(i);t=[];for(const r of s.g())s=e&&pt(r,1)!=null?pt(r,1)??0:-1,t.push({score:Ee(r,2)??0,index:s,categoryName:gt(r,3)??""??"",displayName:gt(r,4)??""??""});n.push(t)}return n}var Je=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],N(t=this.j=new dg,0,1,e=new pe),this.s=new Ul,N(this.j,0,2,this.s),this.C=new Bl,N(this.s,0,3,this.C),this.v=new ug,N(this.s,0,2,this.v),this.h=new Bv,N(this.j,0,3,this.h),I(this.v,2,.5),I(this.s,4,.5),I(this.C,2,.5)}get baseOptions(){return z(this.j,pe,1)}set baseOptions(t){N(this.j,0,1,t)}o(t){var i,r,o,a;if(Mt(this.v,3,t.numHands??1),"minHandDetectionConfidence"in t&&I(this.v,2,t.minHandDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.s,4,t.minTrackingConfidence??.5),"minHandPresenceConfidence"in t&&I(this.C,2,t.minHandPresenceConfidence??.5),t.cannedGesturesClassifierOptions){var e=new zn,n=e,s=Qa(t.cannedGesturesClassifierOptions,(i=z(this.h,zn,3))==null?void 0:i.h());N(n,0,2,s),N(this.h,0,3,e)}else t.cannedGesturesClassifierOptions===void 0&&((r=z(this.h,zn,3))==null||r.g());return t.customGesturesClassifierOptions?(N(n=e=new zn,0,2,s=Qa(t.customGesturesClassifierOptions,(o=z(this.h,zn,4))==null?void 0:o.h())),N(this.h,0,4,e)):t.customGesturesClassifierOptions===void 0&&((a=z(this.h,zn,4))==null||a.g()),this.l(t)}Ja(t,e){return Qu(this),vt(this,t,e),Ju(this)}Ka(t,e,n){return Qu(this),Ut(this,t,n,e),Ju(this)}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"hand_gestures"),Q(t,"hand_landmarks"),Q(t,"world_hand_landmarks"),Q(t,"handedness");const e=new it;St(e,Uv,this.j);const n=new $e;ot(n,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),j(n,"HAND_GESTURES:hand_gestures"),j(n,"LANDMARKS:hand_landmarks"),j(n,"WORLD_LANDMARKS:world_hand_landmarks"),j(n,"HANDEDNESS:handedness"),n.o(e),at(t,n),this.g.attachProtoVectorListener("hand_landmarks",(s,i)=>{for(const r of s){s=Pi(r);const o=[];for(const a of Qt(s,tg,1))o.push({x:Ee(a,1)??0,y:Ee(a,2)??0,z:Ee(a,3)??0,visibility:Ee(a,4)??0});this.landmarks.push(o)}S(this,i)}),this.g.attachEmptyPacketListener("hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("world_hand_landmarks",(s,i)=>{for(const r of s){s=cs(r);const o=[];for(const a of Qt(s,eg,1))o.push({x:Ee(a,1)??0,y:Ee(a,2)??0,z:Ee(a,3)??0,visibility:Ee(a,4)??0});this.worldLandmarks.push(o)}S(this,i)}),this.g.attachEmptyPacketListener("world_hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("hand_gestures",(s,i)=>{this.gestures.push(...Zu(s,!1)),S(this,i)}),this.g.attachEmptyPacketListener("hand_gestures",s=>{S(this,s)}),this.g.attachProtoVectorListener("handedness",(s,i)=>{this.handedness.push(...Zu(s)),S(this,i)}),this.g.attachEmptyPacketListener("handedness",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};function ed(t){return{landmarks:t.landmarks,worldLandmarks:t.worldLandmarks,handednesses:t.handedness,handedness:t.handedness}}Je.prototype.recognizeForVideo=Je.prototype.Ka,Je.prototype.recognize=Je.prototype.Ja,Je.prototype.setOptions=Je.prototype.o,Je.createFromModelPath=function(t,e){return W(Je,t,{baseOptions:{modelAssetPath:e}})},Je.createFromModelBuffer=function(t,e){return W(Je,t,{baseOptions:{modelAssetBuffer:e}})},Je.createFromOptions=function(t,e){return W(Je,t,e)},Je.HAND_CONNECTIONS=Zl;var Ze=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],N(t=this.h=new Ul,0,1,e=new pe),this.s=new Bl,N(this.h,0,3,this.s),this.j=new ug,N(this.h,0,2,this.j),Mt(this.j,3,1),I(this.j,2,.5),I(this.s,2,.5),I(this.h,4,.5)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return"numHands"in t&&Mt(this.j,3,t.numHands??1),"minHandDetectionConfidence"in t&&I(this.j,2,t.minHandDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.h,4,t.minTrackingConfidence??.5),"minHandPresenceConfidence"in t&&I(this.s,2,t.minHandPresenceConfidence??.5),this.l(t)}D(t,e){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],vt(this,t,e),ed(this)}F(t,e,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Ut(this,t,n,e),ed(this)}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"hand_landmarks"),Q(t,"world_hand_landmarks"),Q(t,"handedness");const e=new it;St(e,Vv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),j(n,"LANDMARKS:hand_landmarks"),j(n,"WORLD_LANDMARKS:world_hand_landmarks"),j(n,"HANDEDNESS:handedness"),n.o(e),at(t,n),this.g.attachProtoVectorListener("hand_landmarks",(s,i)=>{for(const r of s)s=Pi(r),this.landmarks.push(So(s));S(this,i)}),this.g.attachEmptyPacketListener("hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("world_hand_landmarks",(s,i)=>{for(const r of s)s=cs(r),this.worldLandmarks.push(oi(s));S(this,i)}),this.g.attachEmptyPacketListener("world_hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("handedness",(s,i)=>{var r=this.handedness,o=r.push;const a=[];for(const c of s){s=Co(c);const l=[];for(const h of s.g())l.push({score:Ee(h,2)??0,index:pt(h,1)??0??-1,categoryName:gt(h,3)??""??"",displayName:gt(h,4)??""??""});a.push(l)}o.call(r,...a),S(this,i)}),this.g.attachEmptyPacketListener("handedness",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Ze.prototype.detectForVideo=Ze.prototype.F,Ze.prototype.detect=Ze.prototype.D,Ze.prototype.setOptions=Ze.prototype.o,Ze.createFromModelPath=function(t,e){return W(Ze,t,{baseOptions:{modelAssetPath:e}})},Ze.createFromModelBuffer=function(t,e){return W(Ze,t,{baseOptions:{modelAssetBuffer:e}})},Ze.createFromOptions=function(t,e){return W(Ze,t,e)},Ze.HAND_CONNECTIONS=Zl;var Bg=Rt([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function td(t){t.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function nd(t){try{if(!t.C)return t.h;t.C(t.h)}finally{Ao(t)}}function qi(t,e){t=Pi(t),e.push(So(t))}var de=class extends Xe{constructor(t,e){super(new yt(t,e),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,N(t=this.j=new _g,0,1,e=new pe),this.J=new Bl,N(this.j,0,2,this.J),this.Z=new $v,N(this.j,0,3,this.Z),this.s=new To,N(this.j,0,4,this.s),this.H=new og,N(this.j,0,5,this.H),this.v=new mg,N(this.j,0,6,this.v),this.K=new gg,N(this.j,0,7,this.K),I(this.s,2,.5),I(this.s,3,.3),I(this.H,2,.5),I(this.v,2,.5),I(this.v,3,.3),I(this.K,2,.5),I(this.J,2,.5)}get baseOptions(){return z(this.j,pe,1)}set baseOptions(t){N(this.j,0,1,t)}o(t){return"minFaceDetectionConfidence"in t&&I(this.s,2,t.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in t&&I(this.s,3,t.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in t&&I(this.H,2,t.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in t&&(this.outputFaceBlendshapes=!!t.outputFaceBlendshapes),"minPoseDetectionConfidence"in t&&I(this.v,2,t.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in t&&I(this.v,3,t.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in t&&I(this.K,2,t.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in t&&(this.outputPoseSegmentationMasks=!!t.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in t&&I(this.J,2,t.minHandLandmarksConfidence??.5),this.l(t)}D(t,e,n){const s=typeof e!="function"?e:{};return this.C=typeof e=="function"?e:n,td(this),vt(this,t,s),nd(this)}F(t,e,n,s){const i=typeof n!="function"?n:{};return this.C=typeof n=="function"?n:s,td(this),Ut(this,t,i,e),nd(this)}m(){var t=new Qe;ue(t,"input_frames_image"),Q(t,"pose_landmarks"),Q(t,"pose_world_landmarks"),Q(t,"face_landmarks"),Q(t,"left_hand_landmarks"),Q(t,"left_hand_world_landmarks"),Q(t,"right_hand_landmarks"),Q(t,"right_hand_world_landmarks");const e=new it,n=new wu;ja(n,1,Is("type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),""),function(i,r){if(r!=null)if(Array.isArray(r))ae(i,2,um(r));else{if(!(typeof r=="string"||r instanceof zt||xi(r)))throw Error("invalid value in Any.value field: "+r+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");ja(i,2,nl(r,!1),Vn())}}(n,this.j.g());const s=new $e;ot(s,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Br(s,8,wu,n),ce(s,"IMAGE:input_frames_image"),j(s,"POSE_LANDMARKS:pose_landmarks"),j(s,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),j(s,"FACE_LANDMARKS:face_landmarks"),j(s,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),j(s,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),j(s,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),j(s,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),s.o(e),at(t,s),ko(this,t),this.g.attachProtoListener("pose_landmarks",(i,r)=>{qi(i,this.h.poseLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("pose_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("pose_world_landmarks",(i,r)=>{var o=this.h.poseWorldLandmarks;i=cs(i),o.push(oi(i)),S(this,r)}),this.g.attachEmptyPacketListener("pose_world_landmarks",i=>{S(this,i)}),this.outputPoseSegmentationMasks&&(j(s,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),Es(this,"pose_segmentation_mask"),this.g.U("pose_segmentation_mask",(i,r)=>{this.h.poseSegmentationMasks=[Cs(this,i,!0,!this.C)],S(this,r)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",i=>{this.h.poseSegmentationMasks=[],S(this,i)})),this.g.attachProtoListener("face_landmarks",(i,r)=>{qi(i,this.h.faceLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("face_landmarks",i=>{S(this,i)}),this.outputFaceBlendshapes&&(Q(t,"extra_blendshapes"),j(s,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(i,r)=>{var o=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(i=Co(i),o.push(Wl(i.g()??[]))),S(this,r)}),this.g.attachEmptyPacketListener("extra_blendshapes",i=>{S(this,i)})),this.g.attachProtoListener("left_hand_landmarks",(i,r)=>{qi(i,this.h.leftHandLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("left_hand_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("left_hand_world_landmarks",(i,r)=>{var o=this.h.leftHandWorldLandmarks;i=cs(i),o.push(oi(i)),S(this,r)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("right_hand_landmarks",(i,r)=>{qi(i,this.h.rightHandLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("right_hand_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("right_hand_world_landmarks",(i,r)=>{var o=this.h.rightHandWorldLandmarks;i=cs(i),o.push(oi(i)),S(this,r)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",i=>{S(this,i)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};de.prototype.detectForVideo=de.prototype.F,de.prototype.detect=de.prototype.D,de.prototype.setOptions=de.prototype.o,de.createFromModelPath=function(t,e){return W(de,t,{baseOptions:{modelAssetPath:e}})},de.createFromModelBuffer=function(t,e){return W(de,t,{baseOptions:{modelAssetBuffer:e}})},de.createFromOptions=function(t,e){return W(de,t,e)},de.HAND_CONNECTIONS=Zl,de.POSE_CONNECTIONS=Bg,de.FACE_LANDMARKS_LIPS=zl,de.FACE_LANDMARKS_LEFT_EYE=Kl,de.FACE_LANDMARKS_LEFT_EYEBROW=Yl,de.FACE_LANDMARKS_LEFT_IRIS=Pg,de.FACE_LANDMARKS_RIGHT_EYE=Xl,de.FACE_LANDMARKS_RIGHT_EYEBROW=Ql,de.FACE_LANDMARKS_RIGHT_IRIS=Lg,de.FACE_LANDMARKS_FACE_OVAL=Jl,de.FACE_LANDMARKS_CONTOURS=Og,de.FACE_LANDMARKS_TESSELATION=Mg;var ht=class extends Xe{constructor(t,e){super(new yt(t,e),"input_image","norm_rect",!0),this.j={classifications:[]},N(t=this.h=new yg,0,1,e=new pe)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return N(this.h,0,2,Qa(t,z(this.h,Ll,2))),this.l(t)}sa(t,e){return this.j={classifications:[]},vt(this,t,e),this.j}ta(t,e,n){return this.j={classifications:[]},Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"input_image"),ue(t,"norm_rect"),Q(t,"classifications");const e=new it;St(e,Hv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),ce(n,"IMAGE:input_image"),ce(n,"NORM_RECT:norm_rect"),j(n,"CLASSIFICATIONS:classifications"),n.o(e),at(t,n),this.g.attachProtoListener("classifications",(s,i)=>{this.j=function(r){const o={classifications:Qt(r,Rv,1).map(a=>{var c;return Wl(((c=z(a,Qm,4))==null?void 0:c.g())??[],pt(a,2)??0,gt(a,3)??"")})};return Mr(ys(r,2))!=null&&(o.timestampMs=Mr(ys(r,2))??0),o}(Iv(s)),S(this,i)}),this.g.attachEmptyPacketListener("classifications",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};ht.prototype.classifyForVideo=ht.prototype.ta,ht.prototype.classify=ht.prototype.sa,ht.prototype.setOptions=ht.prototype.o,ht.createFromModelPath=function(t,e){return W(ht,t,{baseOptions:{modelAssetPath:e}})},ht.createFromModelBuffer=function(t,e){return W(ht,t,{baseOptions:{modelAssetBuffer:e}})},ht.createFromOptions=function(t,e){return W(ht,t,e)};var et=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!0),this.h=new vg,this.embeddings={embeddings:[]},N(t=this.h,0,1,e=new pe)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){var e=this.h,n=z(this.h,xu,2);return n=n?n.clone():new xu,t.l2Normalize!==void 0?vi(n,1,t.l2Normalize):"l2Normalize"in t&&ae(n,1),t.quantize!==void 0?vi(n,2,t.quantize):"quantize"in t&&ae(n,2),N(e,0,2,n),this.l(t)}za(t,e){return vt(this,t,e),this.embeddings}Aa(t,e,n){return Ut(this,t,n,e),this.embeddings}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"embeddings_out");const e=new it;St(e,Wv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),j(n,"EMBEDDINGS:embeddings_out"),n.o(e),at(t,n),this.g.attachProtoListener("embeddings_out",(s,i)=>{s=Nv(s),this.embeddings=function(r){return{embeddings:Qt(r,Fv,1).map(o=>{var c,l;const a={headIndex:pt(o,3)??0??-1,headName:gt(o,4)??""??""};if(gm(o,Iu,ia(o,1))!==void 0)o=Fn(o=z(o,Iu,ia(o,1)),1,yn,xn()),a.floatEmbedding=o.slice();else{const h=new Uint8Array(0);a.quantizedEmbedding=((l=(c=z(o,xv,ia(o,2)))==null?void 0:c.oa())==null?void 0:l.h())??h}return a}),timestampMs:Mr(ys(r,2))??0}}(s),S(this,i)}),this.g.attachEmptyPacketListener("embeddings_out",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};et.cosineSimilarity=function(t,e){if(t.floatEmbedding&&e.floatEmbedding)t=Lu(t.floatEmbedding,e.floatEmbedding);else{if(!t.quantizedEmbedding||!e.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");t=Lu(Pu(t.quantizedEmbedding),Pu(e.quantizedEmbedding))}return t},et.prototype.embedForVideo=et.prototype.Aa,et.prototype.embed=et.prototype.za,et.prototype.setOptions=et.prototype.o,et.createFromModelPath=function(t,e){return W(et,t,{baseOptions:{modelAssetPath:e}})},et.createFromModelBuffer=function(t,e){return W(et,t,{baseOptions:{modelAssetBuffer:e}})},et.createFromOptions=function(t,e){return W(et,t,e)};var ec=class{constructor(t,e,n){this.confidenceMasks=t,this.categoryMask=e,this.qualityScores=n}close(){var t,e;(t=this.confidenceMasks)==null||t.forEach(n=>{n.close()}),(e=this.categoryMask)==null||e.close()}};function sd(t){t.categoryMask=void 0,t.confidenceMasks=void 0,t.qualityScores=void 0}function id(t){try{const e=new ec(t.confidenceMasks,t.categoryMask,t.qualityScores);if(!t.j)return e;t.j(e)}finally{Ao(t)}}ec.prototype.close=ec.prototype.close;var Ge=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.s=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Hl,this.v=new Eg,N(this.h,0,3,this.v),N(t=this.h,0,1,e=new pe)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return t.displayNamesLocale!==void 0?ae(this.h,2,Is(t.displayNamesLocale)):"displayNamesLocale"in t&&ae(this.h,2),"outputCategoryMask"in t&&(this.outputCategoryMask=t.outputCategoryMask??!1),"outputConfidenceMasks"in t&&(this.outputConfidenceMasks=t.outputConfidenceMasks??!0),super.l(t)}I(){(function(t){var n,s;const e=Qt(t.da(),$e,1).filter(i=>(gt(i,1)??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(t.s=[],e.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");e.length===1&&(((s=(n=z(e[0],it,7))==null?void 0:n.l())==null?void 0:s.g())??new Map).forEach((i,r)=>{t.s[Number(r)]=gt(i,1)??""})})(this)}segment(t,e,n){const s=typeof e!="function"?e:{};return this.j=typeof e=="function"?e:n,sd(this),vt(this,t,s),id(this)}Ma(t,e,n,s){const i=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:s,sd(this),Ut(this,t,i,e),id(this)}Da(){return this.s}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect");const e=new it;St(e,bg,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),n.o(e),at(t,n),ko(this,t),this.outputConfidenceMasks&&(Q(t,"confidence_masks"),j(n,"CONFIDENCE_MASKS:confidence_masks"),Es(this,"confidence_masks"),this.g.ca("confidence_masks",(s,i)=>{this.confidenceMasks=s.map(r=>Cs(this,r,!0,!this.j)),S(this,i)}),this.g.attachEmptyPacketListener("confidence_masks",s=>{this.confidenceMasks=[],S(this,s)})),this.outputCategoryMask&&(Q(t,"category_mask"),j(n,"CATEGORY_MASK:category_mask"),Es(this,"category_mask"),this.g.U("category_mask",(s,i)=>{this.categoryMask=Cs(this,s,!1,!this.j),S(this,i)}),this.g.attachEmptyPacketListener("category_mask",s=>{this.categoryMask=void 0,S(this,s)})),Q(t,"quality_scores"),j(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(s,i)=>{this.qualityScores=s,S(this,i)}),this.g.attachEmptyPacketListener("quality_scores",s=>{this.categoryMask=void 0,S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Ge.prototype.getLabels=Ge.prototype.Da,Ge.prototype.segmentForVideo=Ge.prototype.Ma,Ge.prototype.segment=Ge.prototype.segment,Ge.prototype.setOptions=Ge.prototype.o,Ge.createFromModelPath=function(t,e){return W(Ge,t,{baseOptions:{modelAssetPath:e}})},Ge.createFromModelBuffer=function(t,e){return W(Ge,t,{baseOptions:{modelAssetBuffer:e}})},Ge.createFromOptions=function(t,e){return W(Ge,t,e)};var tc=class{constructor(t,e,n){this.confidenceMasks=t,this.categoryMask=e,this.qualityScores=n}close(){var t,e;(t=this.confidenceMasks)==null||t.forEach(n=>{n.close()}),(e=this.categoryMask)==null||e.close()}};tc.prototype.close=tc.prototype.close;var eE=class extends A{constructor(t){super(t)}},Kn=[0,ve,-2],Hr=[0,Ht,-3,fe,Ht,-1],rd=[0,Hr],od=[0,Hr,ve,-1],ua=class extends A{constructor(t){super(t)}},ad=[0,Ht,-1,fe],tE=class extends A{constructor(t){super(t)}},cd=class extends A{constructor(t){super(t)}},nc=[1,2,3,4,5,6,7,8,9,10,14,15],Ug=class extends A{constructor(t){super(t)}};Ug.prototype.g=bo([0,Ae,[0,nc,ee,Hr,ee,[0,Hr,Kn],ee,rd,ee,[0,rd,Kn],ee,ad,ee,[0,Ht,-3,fe,_t],ee,[0,Ht,-3,fe],ee,[0,Z,Ht,-2,fe,ve,fe,-1,2,Ht,Kn],ee,od,ee,[0,od,Kn],Ht,Kn,Z,ee,[0,Ht,-3,fe,Kn,-1],ee,[0,Ae,ad]],Z,[0,Z,ve,-1,fe]]);var Dt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Hl,this.s=new Eg,N(this.h,0,3,this.s),N(t=this.h,0,1,e=new pe)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return"outputCategoryMask"in t&&(this.outputCategoryMask=t.outputCategoryMask??!1),"outputConfidenceMasks"in t&&(this.outputConfidenceMasks=t.outputConfidenceMasks??!0),super.l(t)}segment(t,e,n,s){const i=typeof n!="function"?n:{};this.j=typeof n=="function"?n:s,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.B+1,s=new Ug;const r=new cd;var o=new eE;if(Mt(o,1,255),N(r,0,12,o),e.keypoint&&e.scribble)throw Error("Cannot provide both keypoint and scribble.");if(e.keypoint){var a=new ua;vi(a,3,!0),I(a,1,e.keypoint.x),I(a,2,e.keypoint.y),ii(r,5,nc,a)}else{if(!e.scribble)throw Error("Must provide either a keypoint or a scribble.");for(a of(o=new tE,e.scribble))vi(e=new ua,3,!0),I(e,1,a.x),I(e,2,a.y),Br(o,1,ua,e);ii(r,15,nc,o)}Br(s,1,cd,r),this.g.addProtoToStream(s.g(),"drishti.RenderData","roi_in",n),vt(this,t,i);e:{try{const l=new tc(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var c=l;break e}this.j(l)}finally{Ao(this)}c=void 0}return c}m(){var t=new Qe;ue(t,"image_in"),ue(t,"roi_in"),ue(t,"norm_rect_in");const e=new it;St(e,bg,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraph"),ce(n,"IMAGE:image_in"),ce(n,"ROI:roi_in"),ce(n,"NORM_RECT:norm_rect_in"),n.o(e),at(t,n),ko(this,t),this.outputConfidenceMasks&&(Q(t,"confidence_masks"),j(n,"CONFIDENCE_MASKS:confidence_masks"),Es(this,"confidence_masks"),this.g.ca("confidence_masks",(s,i)=>{this.confidenceMasks=s.map(r=>Cs(this,r,!0,!this.j)),S(this,i)}),this.g.attachEmptyPacketListener("confidence_masks",s=>{this.confidenceMasks=[],S(this,s)})),this.outputCategoryMask&&(Q(t,"category_mask"),j(n,"CATEGORY_MASK:category_mask"),Es(this,"category_mask"),this.g.U("category_mask",(s,i)=>{this.categoryMask=Cs(this,s,!1,!this.j),S(this,i)}),this.g.attachEmptyPacketListener("category_mask",s=>{this.categoryMask=void 0,S(this,s)})),Q(t,"quality_scores"),j(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(s,i)=>{this.qualityScores=s,S(this,i)}),this.g.attachEmptyPacketListener("quality_scores",s=>{this.categoryMask=void 0,S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Dt.prototype.segment=Dt.prototype.segment,Dt.prototype.setOptions=Dt.prototype.o,Dt.createFromModelPath=function(t,e){return W(Dt,t,{baseOptions:{modelAssetPath:e}})},Dt.createFromModelBuffer=function(t,e){return W(Dt,t,{baseOptions:{modelAssetBuffer:e}})},Dt.createFromOptions=function(t,e){return W(Dt,t,e)};var ut=class extends Xe{constructor(t,e){super(new yt(t,e),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},N(t=this.h=new Cg,0,1,e=new pe)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return t.displayNamesLocale!==void 0?ae(this.h,2,Is(t.displayNamesLocale)):"displayNamesLocale"in t&&ae(this.h,2),t.maxResults!==void 0?Mt(this.h,3,t.maxResults):"maxResults"in t&&ae(this.h,3),t.scoreThreshold!==void 0?I(this.h,4,t.scoreThreshold):"scoreThreshold"in t&&ae(this.h,4),t.categoryAllowlist!==void 0?Ur(this.h,5,t.categoryAllowlist):"categoryAllowlist"in t&&ae(this.h,5),t.categoryDenylist!==void 0?Ur(this.h,6,t.categoryDenylist):"categoryDenylist"in t&&ae(this.h,6),this.l(t)}D(t,e){return this.j={detections:[]},vt(this,t,e),this.j}F(t,e,n){return this.j={detections:[]},Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"input_frame_gpu"),ue(t,"norm_rect"),Q(t,"detections");const e=new it;St(e,jv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.ObjectDetectorGraph"),ce(n,"IMAGE:input_frame_gpu"),ce(n,"NORM_RECT:norm_rect"),j(n,"DETECTIONS:detections"),n.o(e),at(t,n),this.g.attachProtoVectorListener("detections",(s,i)=>{for(const r of s)s=Zm(r),this.j.detections.push(Sg(s));S(this,i)}),this.g.attachEmptyPacketListener("detections",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};ut.prototype.detectForVideo=ut.prototype.F,ut.prototype.detect=ut.prototype.D,ut.prototype.setOptions=ut.prototype.o,ut.createFromModelPath=async function(t,e){return W(ut,t,{baseOptions:{modelAssetPath:e}})},ut.createFromModelBuffer=function(t,e){return W(ut,t,{baseOptions:{modelAssetBuffer:e}})},ut.createFromOptions=function(t,e){return W(ut,t,e)};var sc=class{constructor(t,e,n){this.landmarks=t,this.worldLandmarks=e,this.segmentationMasks=n}close(){var t;(t=this.segmentationMasks)==null||t.forEach(e=>{e.close()})}};function ld(t){t.landmarks=[],t.worldLandmarks=[],t.segmentationMasks=void 0}function hd(t){try{const e=new sc(t.landmarks,t.worldLandmarks,t.segmentationMasks);if(!t.s)return e;t.s(e)}finally{Ao(t)}}sc.prototype.close=sc.prototype.close;var tt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,N(t=this.h=new Tg,0,1,e=new pe),this.v=new gg,N(this.h,0,3,this.v),this.j=new mg,N(this.h,0,2,this.j),Mt(this.j,4,1),I(this.j,2,.5),I(this.v,2,.5),I(this.h,4,.5)}get baseOptions(){return z(this.h,pe,1)}set baseOptions(t){N(this.h,0,1,t)}o(t){return"numPoses"in t&&Mt(this.j,4,t.numPoses??1),"minPoseDetectionConfidence"in t&&I(this.j,2,t.minPoseDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.h,4,t.minTrackingConfidence??.5),"minPosePresenceConfidence"in t&&I(this.v,2,t.minPosePresenceConfidence??.5),"outputSegmentationMasks"in t&&(this.outputSegmentationMasks=t.outputSegmentationMasks??!1),this.l(t)}D(t,e,n){const s=typeof e!="function"?e:{};return this.s=typeof e=="function"?e:n,ld(this),vt(this,t,s),hd(this)}F(t,e,n,s){const i=typeof n!="function"?n:{};return this.s=typeof n=="function"?n:s,ld(this),Ut(this,t,i,e),hd(this)}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"normalized_landmarks"),Q(t,"world_landmarks"),Q(t,"segmentation_masks");const e=new it;St(e,qv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),j(n,"NORM_LANDMARKS:normalized_landmarks"),j(n,"WORLD_LANDMARKS:world_landmarks"),n.o(e),at(t,n),ko(this,t),this.g.attachProtoVectorListener("normalized_landmarks",(s,i)=>{this.landmarks=[];for(const r of s)s=Pi(r),this.landmarks.push(So(s));S(this,i)}),this.g.attachEmptyPacketListener("normalized_landmarks",s=>{this.landmarks=[],S(this,s)}),this.g.attachProtoVectorListener("world_landmarks",(s,i)=>{this.worldLandmarks=[];for(const r of s)s=cs(r),this.worldLandmarks.push(oi(s));S(this,i)}),this.g.attachEmptyPacketListener("world_landmarks",s=>{this.worldLandmarks=[],S(this,s)}),this.outputSegmentationMasks&&(j(n,"SEGMENTATION_MASK:segmentation_masks"),Es(this,"segmentation_masks"),this.g.ca("segmentation_masks",(s,i)=>{this.segmentationMasks=s.map(r=>Cs(this,r,!0,!this.s)),S(this,i)}),this.g.attachEmptyPacketListener("segmentation_masks",s=>{this.segmentationMasks=[],S(this,s)})),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};tt.prototype.detectForVideo=tt.prototype.F,tt.prototype.detect=tt.prototype.D,tt.prototype.setOptions=tt.prototype.o,tt.createFromModelPath=function(t,e){return W(tt,t,{baseOptions:{modelAssetPath:e}})},tt.createFromModelBuffer=function(t,e){return W(tt,t,{baseOptions:{modelAssetBuffer:e}})},tt.createFromOptions=function(t,e){return W(tt,t,e)},tt.POSE_CONNECTIONS=Bg;function nE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function sE(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function s(){return this instanceof s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(s){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(n,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}),n}const iE={},rE=Object.freeze(Object.defineProperty({__proto__:null,default:iE},Symbol.toStringTag,{value:"Module"})),Jn=sE(rE);var Pt={exports:{}};const oE="16.6.1",aE={version:oE};var ud;function cE(){if(ud)return Pt.exports;ud=1;const t=Jn,e=Jn,n=Jn,s=Jn,r=aE.version,o=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function a(v){const R={};let D=v.toString();D=D.replace(/\r\n?/mg,`
1634
+ `}C(){const t=this.g;t.activeTexture(t.TEXTURE1),this.j=gn(this,t),t.activeTexture(t.TEXTURE2),this.B=gn(this,t)}m(){super.m();const t=this.g;this.J=Ve(t.getUniformLocation(this.h,"defaultTexture"),"Uniform location"),this.K=Ve(t.getUniformLocation(this.h,"overlayTexture"),"Uniform location"),this.H=Ve(t.getUniformLocation(this.h,"maskTexture"),"Uniform location")}l(){super.l();const t=this.g;t.uniform1i(this.H,0),t.uniform1i(this.J,1),t.uniform1i(this.K,2)}close(){this.j&&this.g.deleteTexture(this.j),this.B&&this.g.deleteTexture(this.B),super.close()}};function Wt(t,e){switch(e){case 0:return t.g.find(n=>n instanceof Uint8Array);case 1:return t.g.find(n=>n instanceof Float32Array);case 2:return t.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${e}`)}}function Qa(t){var e=Wt(t,1);if(!e){if(e=Wt(t,0))e=new Float32Array(e).map(s=>s/255);else{e=new Float32Array(t.width*t.height);const s=ws(t);var n=ql(t);if(Ao(n,s,xg(t)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){n=new Float32Array(t.width*t.height*4),s.readPixels(0,0,t.width,t.height,s.RGBA,s.FLOAT,n);for(let i=0,r=0;i<e.length;++i,r+=4)e[i]=n[r]}else s.readPixels(0,0,t.width,t.height,s.RED,s.FLOAT,e)}t.g.push(e)}return e}function xg(t){let e=Wt(t,2);if(!e){const n=ws(t);e=Fg(t);const s=Qa(t),i=Ng(t);n.texImage2D(n.TEXTURE_2D,0,i,t.width,t.height,0,n.RED,n.FLOAT,s),Ja(t)}return e}function ws(t){if(!t.canvas)throw Error("Conversion to different image formats require that a canvas is passed when initializing the image.");return t.h||(t.h=Ve(t.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),t.h}function Ng(t){if(t=ws(t),!ji)if(t.getExtension("EXT_color_buffer_float")&&t.getExtension("OES_texture_float_linear")&&t.getExtension("EXT_float_blend"))ji=t.R32F;else{if(!t.getExtension("EXT_color_buffer_half_float"))throw Error("GPU does not fully support 4-channel float32 or float16 formats");ji=t.R16F}return ji}function ql(t){return t.l||(t.l=new Ls),t.l}function Fg(t){const e=ws(t);e.viewport(0,0,t.width,t.height),e.activeTexture(e.TEXTURE0);let n=Wt(t,2);return n||(n=gn(ql(t),e,t.m?e.LINEAR:e.NEAREST),t.g.push(n),t.j=!0),e.bindTexture(e.TEXTURE_2D,n),n}function Ja(t){t.h.bindTexture(t.h.TEXTURE_2D,null)}var ji,ke=class{constructor(t,e,n,s,i,r,o){this.g=t,this.m=e,this.j=n,this.canvas=s,this.l=i,this.width=r,this.height=o,this.j&&--Hu===0&&console.error("You seem to be creating MPMask instances without invoking .close(). This leaks resources.")}Fa(){return!!Wt(this,0)}ja(){return!!Wt(this,1)}P(){return!!Wt(this,2)}ia(){return(e=Wt(t=this,0))||(e=Qa(t),e=new Uint8Array(e.map(n=>255*n)),t.g.push(e)),e;var t,e}ha(){return Qa(this)}M(){return xg(this)}clone(){const t=[];for(const e of this.g){let n;if(e instanceof Uint8Array)n=new Uint8Array(e);else if(e instanceof Float32Array)n=new Float32Array(e);else{if(!(e instanceof WebGLTexture))throw Error(`Type is not supported: ${e}`);{const s=ws(this),i=ql(this);s.activeTexture(s.TEXTURE1),n=gn(i,s,this.m?s.LINEAR:s.NEAREST),s.bindTexture(s.TEXTURE_2D,n);const r=Ng(this);s.texImage2D(s.TEXTURE_2D,0,r,this.width,this.height,0,s.RED,s.FLOAT,null),s.bindTexture(s.TEXTURE_2D,null),Ao(i,s,n),Li(i,s,!1,()=>{Fg(this),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.drawArrays(s.TRIANGLE_FAN,0,4),Ja(this)}),jl(i),Ja(this)}}t.push(n)}return new ke(t,this.m,this.P(),this.canvas,this.l,this.width,this.height)}close(){this.j&&ws(this).deleteTexture(Wt(this,2)),Hu=-1}};ke.prototype.close=ke.prototype.close,ke.prototype.clone=ke.prototype.clone,ke.prototype.getAsWebGLTexture=ke.prototype.M,ke.prototype.getAsFloat32Array=ke.prototype.ha,ke.prototype.getAsUint8Array=ke.prototype.ia,ke.prototype.hasWebGLTexture=ke.prototype.P,ke.prototype.hasFloat32Array=ke.prototype.ja,ke.prototype.hasUint8Array=ke.prototype.Fa;var Hu=250;const Zv={color:"white",lineWidth:4,radius:6};function la(t){return{...Zv,fillColor:(t=t||{}).color,...t}}function Vt(t,e){return t instanceof Function?t(e):t}function Wu(t,e,n){return Math.max(Math.min(e,n),Math.min(Math.max(e,n),t))}function qs(t){if(!t.l)throw Error("CPU rendering requested but CanvasRenderingContext2D not provided.");return t.l}function wi(t){if(!t.j)throw Error("GPU rendering requested but WebGL2RenderingContext not provided.");return t.j}function Gu(t,e,n){if(e.P())n(e.M());else{const s=e.ja()?e.ha():e.ia();t.m=t.m??new Ls;const i=wi(t);n((t=new ke([s],e.m,!1,i.canvas,t.m,e.width,e.height)).M()),t.close()}}function ju(t,e,n,s){const i=function(a){return a.g||(a.g=new Qv),a.g}(t),r=wi(t),o=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n;Li(i,r,!0,()=>{(function(c,l,h,u){const d=c.g;if(d.activeTexture(d.TEXTURE0),d.bindTexture(d.TEXTURE_2D,l),d.activeTexture(d.TEXTURE1),d.bindTexture(d.TEXTURE_2D,c.B),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,h),c.H&&function(p,m){if(p!==m)return!1;p=p.entries(),m=m.entries();for(const[w,k]of p){p=w;const E=k;var y=m.next();if(y.done)return!1;const[T,P]=y.value;if(y=P,p!==T||E[0]!==y[0]||E[1]!==y[1]||E[2]!==y[2]||E[3]!==y[3])return!1}return!!m.next().done}(c.H,u))d.activeTexture(d.TEXTURE2),d.bindTexture(d.TEXTURE_2D,c.j);else{c.H=u;const p=Array(1024).fill(0);u.forEach((m,y)=>{if(m.length!==4)throw Error(`Color at index ${y} is not a four-channel value.`);p[4*y]=m[0],p[4*y+1]=m[1],p[4*y+2]=m[2],p[4*y+3]=m[3]}),d.activeTexture(d.TEXTURE2),d.bindTexture(d.TEXTURE_2D,c.j),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,256,1,0,d.RGBA,d.UNSIGNED_BYTE,new Uint8Array(p))}})(i,e,o,s),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4);const a=i.g;a.activeTexture(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,null),a.activeTexture(a.TEXTURE1),a.bindTexture(a.TEXTURE_2D,null),a.activeTexture(a.TEXTURE2),a.bindTexture(a.TEXTURE_2D,null)})}function qu(t,e,n,s){const i=wi(t),r=function(c){return c.h||(c.h=new Jv),c.h}(t),o=Array.isArray(n)?new ImageData(new Uint8ClampedArray(n),1,1):n,a=Array.isArray(s)?new ImageData(new Uint8ClampedArray(s),1,1):s;Li(r,i,!0,()=>{var c=r.g;c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,e),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,r.j),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,o),c.activeTexture(c.TEXTURE2),c.bindTexture(c.TEXTURE_2D,r.B),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,a),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLE_FAN,0,4),i.bindTexture(i.TEXTURE_2D,null),(c=r.g).activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,null),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,null),c.activeTexture(c.TEXTURE2),c.bindTexture(c.TEXTURE_2D,null)})}var Pe=class{constructor(t,e){t instanceof CanvasRenderingContext2D||t instanceof OffscreenCanvasRenderingContext2D?(this.l=t,this.j=e):this.j=t}ya(t,e){if(t){var n=qs(this);e=la(e),n.save();var s=n.canvas,i=0;for(const r of t)n.fillStyle=Vt(e.fillColor,{index:i,from:r}),n.strokeStyle=Vt(e.color,{index:i,from:r}),n.lineWidth=Vt(e.lineWidth,{index:i,from:r}),(t=new Path2D).arc(r.x*s.width,r.y*s.height,Vt(e.radius,{index:i,from:r}),0,2*Math.PI),n.fill(t),n.stroke(t),++i;n.restore()}}xa(t,e,n){if(t&&e){var s=qs(this);n=la(n),s.save();var i=s.canvas,r=0;for(const o of e){s.beginPath(),e=t[o.start];const a=t[o.end];e&&a&&(s.strokeStyle=Vt(n.color,{index:r,from:e,to:a}),s.lineWidth=Vt(n.lineWidth,{index:r,from:e,to:a}),s.moveTo(e.x*i.width,e.y*i.height),s.lineTo(a.x*i.width,a.y*i.height)),++r,s.stroke()}s.restore()}}ua(t,e){const n=qs(this);e=la(e),n.save(),n.beginPath(),n.lineWidth=Vt(e.lineWidth,{}),n.strokeStyle=Vt(e.color,{}),n.fillStyle=Vt(e.fillColor,{}),n.moveTo(t.originX,t.originY),n.lineTo(t.originX+t.width,t.originY),n.lineTo(t.originX+t.width,t.originY+t.height),n.lineTo(t.originX,t.originY+t.height),n.lineTo(t.originX,t.originY),n.stroke(),n.fill(),n.restore()}va(t,e,n=[0,0,0,255]){this.l?function(s,i,r,o){const a=wi(s);Gu(s,i,c=>{ju(s,c,r,o),(c=qs(s)).drawImage(a.canvas,0,0,c.canvas.width,c.canvas.height)})}(this,t,n,e):ju(this,t.M(),n,e)}wa(t,e,n){this.l?function(s,i,r,o){const a=wi(s);Gu(s,i,c=>{qu(s,c,r,o),(c=qs(s)).drawImage(a.canvas,0,0,c.canvas.width,c.canvas.height)})}(this,t,e,n):qu(this,t.M(),e,n)}close(){var t,e,n;(t=this.g)==null||t.close(),this.g=void 0,(e=this.h)==null||e.close(),this.h=void 0,(n=this.m)==null||n.close(),this.m=void 0}};function Ot(t,e){switch(e){case 0:return t.g.find(n=>n instanceof ImageData);case 1:return t.g.find(n=>typeof ImageBitmap<"u"&&n instanceof ImageBitmap);case 2:return t.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${e}`)}}function Dg(t){var e=Ot(t,0);if(!e){e=bs(t);const n=Ro(t),s=new Uint8Array(t.width*t.height*4);Ao(n,e,rr(t)),e.readPixels(0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,s),jl(n),e=new ImageData(new Uint8ClampedArray(s.buffer),t.width,t.height),t.g.push(e)}return e}function rr(t){let e=Ot(t,2);if(!e){const n=bs(t);e=or(t);const s=Ot(t,1)||Dg(t);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,s),Qs(t)}return e}function bs(t){if(!t.canvas)throw Error("Conversion to different image formats require that a canvas is passed when initializing the image.");return t.h||(t.h=Ve(t.canvas.getContext("webgl2"),"You cannot use a canvas that is already bound to a different type of rendering context.")),t.h}function Ro(t){return t.l||(t.l=new Ls),t.l}function or(t){const e=bs(t);e.viewport(0,0,t.width,t.height),e.activeTexture(e.TEXTURE0);let n=Ot(t,2);return n||(n=gn(Ro(t),e),t.g.push(n),t.m=!0),e.bindTexture(e.TEXTURE_2D,n),n}function Qs(t){t.h.bindTexture(t.h.TEXTURE_2D,null)}function zu(t){const e=bs(t);return Li(Ro(t),e,!0,()=>function(n,s){const i=n.canvas;if(i.width===n.width&&i.height===n.height)return s();const r=i.width,o=i.height;return i.width=n.width,i.height=n.height,n=s(),i.width=r,i.height=o,n}(t,()=>{if(e.bindFramebuffer(e.FRAMEBUFFER,null),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_FAN,0,4),!(t.canvas instanceof OffscreenCanvas))throw Error("Conversion to ImageBitmap requires that the MediaPipe Tasks is initialized with an OffscreenCanvas");return t.canvas.transferToImageBitmap()}))}Pe.prototype.close=Pe.prototype.close,Pe.prototype.drawConfidenceMask=Pe.prototype.wa,Pe.prototype.drawCategoryMask=Pe.prototype.va,Pe.prototype.drawBoundingBox=Pe.prototype.ua,Pe.prototype.drawConnectors=Pe.prototype.xa,Pe.prototype.drawLandmarks=Pe.prototype.ya,Pe.lerp=function(t,e,n,s,i){return Wu(s*(1-(t-e)/(n-e))+i*(1-(n-t)/(n-e)),s,i)},Pe.clamp=Wu;var Ie=class{constructor(t,e,n,s,i,r,o){this.g=t,this.j=e,this.m=n,this.canvas=s,this.l=i,this.width=r,this.height=o,(this.j||this.m)&&--Ku===0&&console.error("You seem to be creating MPImage instances without invoking .close(). This leaks resources.")}Ea(){return!!Ot(this,0)}ka(){return!!Ot(this,1)}P(){return!!Ot(this,2)}Ca(){return Dg(this)}Ba(){var t=Ot(this,1);return t||(rr(this),or(this),t=zu(this),Qs(this),this.g.push(t),this.j=!0),t}M(){return rr(this)}clone(){const t=[];for(const e of this.g){let n;if(e instanceof ImageData)n=new ImageData(e.data,this.width,this.height);else if(e instanceof WebGLTexture){const s=bs(this),i=Ro(this);s.activeTexture(s.TEXTURE1),n=gn(i,s),s.bindTexture(s.TEXTURE_2D,n),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.bindTexture(s.TEXTURE_2D,null),Ao(i,s,n),Li(i,s,!1,()=>{or(this),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.drawArrays(s.TRIANGLE_FAN,0,4),Qs(this)}),jl(i),Qs(this)}else{if(!(e instanceof ImageBitmap))throw Error(`Type is not supported: ${e}`);rr(this),or(this),n=zu(this),Qs(this)}t.push(n)}return new Ie(t,this.ka(),this.P(),this.canvas,this.l,this.width,this.height)}close(){this.j&&Ot(this,1).close(),this.m&&bs(this).deleteTexture(Ot(this,2)),Ku=-1}};Ie.prototype.close=Ie.prototype.close,Ie.prototype.clone=Ie.prototype.clone,Ie.prototype.getAsWebGLTexture=Ie.prototype.M,Ie.prototype.getAsImageBitmap=Ie.prototype.Ba,Ie.prototype.getAsImageData=Ie.prototype.Ca,Ie.prototype.hasWebGLTexture=Ie.prototype.P,Ie.prototype.hasImageBitmap=Ie.prototype.ka,Ie.prototype.hasImageData=Ie.prototype.Ea;var Ku=250;function Rt(...t){return t.map(([e,n])=>({start:e,end:n}))}const eE=function(t){return class extends t{La(){this.i._registerModelResourcesGraphService()}}}((Yu=class{constructor(t,e){this.l=!0,this.i=t,this.g=null,this.h=0,this.m=typeof this.i._addIntToInputStream=="function",e!==void 0?this.i.canvas=e:Rg()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(t){const e=await(await fetch(t)).arrayBuffer();t=!(t.endsWith(".pbtxt")||t.endsWith(".textproto")),this.setGraph(new Uint8Array(e),t)}setGraphFromString(t){this.setGraph(new TextEncoder().encode(t),!1)}setGraph(t,e){const n=t.length,s=this.i._malloc(n);this.i.HEAPU8.set(t,s),e?this.i._changeBinaryGraph(n,s):this.i._changeTextGraph(n,s),this.i._free(s)}configureAudio(t,e,n,s,i){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),x(this,s||"input_audio",r=>{x(this,i=i||"audio_header",o=>{this.i._configureAudio(r,o,t,e??0,n)})})}setAutoResizeCanvas(t){this.l=t}setAutoRenderToScreen(t){this.i._setAutoRenderToScreen(t)}setGpuBufferVerticalFlip(t){this.i.gpuOriginForWebTexturesIsBottomLeft=t}da(t){Nt(this,"__graph_config__",e=>{t(e)}),x(this,"__graph_config__",e=>{this.i._getGraphConfig(e,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(t){this.i.errorListener=t}attachEmptyPacketListener(t,e){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[t]=e}addAudioToStream(t,e,n){this.addAudioToStreamWithShape(t,0,0,e,n)}addAudioToStreamWithShape(t,e,n,s,i){const r=4*t.length;this.h!==r&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(r),this.h=r),this.i.HEAPF32.set(t,this.g/4),x(this,s,o=>{this.i._addAudioToInputStream(this.g,e,n,o,i)})}addGpuBufferToStream(t,e,n){x(this,e,s=>{const[i,r]=Mu(this,t,s);this.i._addBoundTextureToStream(s,i,r,n)})}addBoolToStream(t,e,n){x(this,e,s=>{this.i._addBoolToInputStream(t,s,n)})}addDoubleToStream(t,e,n){x(this,e,s=>{this.i._addDoubleToInputStream(t,s,n)})}addFloatToStream(t,e,n){x(this,e,s=>{this.i._addFloatToInputStream(t,s,n)})}addIntToStream(t,e,n){x(this,e,s=>{this.i._addIntToInputStream(t,s,n)})}addUintToStream(t,e,n){x(this,e,s=>{this.i._addUintToInputStream(t,s,n)})}addStringToStream(t,e,n){x(this,e,s=>{x(this,t,i=>{this.i._addStringToInputStream(i,s,n)})})}addStringRecordToStream(t,e,n){x(this,e,s=>{Bu(this,Object.keys(t),i=>{Bu(this,Object.values(t),r=>{this.i._addFlatHashMapToInputStream(i,r,Object.keys(t).length,s,n)})})})}addProtoToStream(t,e,n,s){x(this,n,i=>{x(this,e,r=>{const o=this.i._malloc(t.length);this.i.HEAPU8.set(t,o),this.i._addProtoToInputStream(o,t.length,r,i,s),this.i._free(o)})})}addEmptyPacketToStream(t,e){x(this,t,n=>{this.i._addEmptyPacketToInputStream(n,e)})}addBoolVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateBoolVector(t.length);if(!i)throw Error("Unable to allocate new bool vector on heap.");for(const r of t)this.i._addBoolVectorEntry(i,r);this.i._addBoolVectorToInputStream(i,s,n)})}addDoubleVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateDoubleVector(t.length);if(!i)throw Error("Unable to allocate new double vector on heap.");for(const r of t)this.i._addDoubleVectorEntry(i,r);this.i._addDoubleVectorToInputStream(i,s,n)})}addFloatVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateFloatVector(t.length);if(!i)throw Error("Unable to allocate new float vector on heap.");for(const r of t)this.i._addFloatVectorEntry(i,r);this.i._addFloatVectorToInputStream(i,s,n)})}addIntVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateIntVector(t.length);if(!i)throw Error("Unable to allocate new int vector on heap.");for(const r of t)this.i._addIntVectorEntry(i,r);this.i._addIntVectorToInputStream(i,s,n)})}addUintVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateUintVector(t.length);if(!i)throw Error("Unable to allocate new unsigned int vector on heap.");for(const r of t)this.i._addUintVectorEntry(i,r);this.i._addUintVectorToInputStream(i,s,n)})}addStringVectorToStream(t,e,n){x(this,e,s=>{const i=this.i._allocateStringVector(t.length);if(!i)throw Error("Unable to allocate new string vector on heap.");for(const r of t)x(this,r,o=>{this.i._addStringVectorEntry(i,o)});this.i._addStringVectorToInputStream(i,s,n)})}addBoolToInputSidePacket(t,e){x(this,e,n=>{this.i._addBoolToInputSidePacket(t,n)})}addDoubleToInputSidePacket(t,e){x(this,e,n=>{this.i._addDoubleToInputSidePacket(t,n)})}addFloatToInputSidePacket(t,e){x(this,e,n=>{this.i._addFloatToInputSidePacket(t,n)})}addIntToInputSidePacket(t,e){x(this,e,n=>{this.i._addIntToInputSidePacket(t,n)})}addUintToInputSidePacket(t,e){x(this,e,n=>{this.i._addUintToInputSidePacket(t,n)})}addStringToInputSidePacket(t,e){x(this,e,n=>{x(this,t,s=>{this.i._addStringToInputSidePacket(s,n)})})}addProtoToInputSidePacket(t,e,n){x(this,n,s=>{x(this,e,i=>{const r=this.i._malloc(t.length);this.i.HEAPU8.set(t,r),this.i._addProtoToInputSidePacket(r,t.length,i,s),this.i._free(r)})})}addBoolVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateBoolVector(t.length);if(!s)throw Error("Unable to allocate new bool vector on heap.");for(const i of t)this.i._addBoolVectorEntry(s,i);this.i._addBoolVectorToInputSidePacket(s,n)})}addDoubleVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateDoubleVector(t.length);if(!s)throw Error("Unable to allocate new double vector on heap.");for(const i of t)this.i._addDoubleVectorEntry(s,i);this.i._addDoubleVectorToInputSidePacket(s,n)})}addFloatVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateFloatVector(t.length);if(!s)throw Error("Unable to allocate new float vector on heap.");for(const i of t)this.i._addFloatVectorEntry(s,i);this.i._addFloatVectorToInputSidePacket(s,n)})}addIntVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateIntVector(t.length);if(!s)throw Error("Unable to allocate new int vector on heap.");for(const i of t)this.i._addIntVectorEntry(s,i);this.i._addIntVectorToInputSidePacket(s,n)})}addUintVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateUintVector(t.length);if(!s)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of t)this.i._addUintVectorEntry(s,i);this.i._addUintVectorToInputSidePacket(s,n)})}addStringVectorToInputSidePacket(t,e){x(this,e,n=>{const s=this.i._allocateStringVector(t.length);if(!s)throw Error("Unable to allocate new string vector on heap.");for(const i of t)x(this,i,r=>{this.i._addStringVectorEntry(s,r)});this.i._addStringVectorToInputSidePacket(s,n)})}attachBoolListener(t,e){Nt(this,t,e),x(this,t,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(t,e){Nt(this,t,e),x(this,t,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(t,e){Nt(this,t,e),x(this,t,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(t,e){Nt(this,t,e),x(this,t,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(t,e){Nt(this,t,e),x(this,t,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(t,e){Nt(this,t,e),x(this,t,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(t,e){nn(this,t,e),x(this,t,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(t,e,n){Nt(this,t,e),x(this,t,s=>{this.i._attachProtoListener(s,n||!1)})}attachProtoVectorListener(t,e,n){nn(this,t,e),x(this,t,s=>{this.i._attachProtoVectorListener(s,n||!1)})}attachAudioListener(t,e,n){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),Nt(this,t,(s,i)=>{s=new Float32Array(s.buffer,s.byteOffset,s.length/4),e(s,i)}),x(this,t,s=>{this.i._attachAudioListener(s,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends Yu{get ea(){return this.i}qa(t,e,n){x(this,e,s=>{const[i,r]=Mu(this,t,s);this.ea._addBoundTextureAsImageToStream(s,i,r,n)})}U(t,e){Nt(this,t,e),x(this,t,n=>{this.ea._attachImageListener(n)})}ca(t,e){nn(this,t,e),x(this,t,n=>{this.ea._attachImageVectorListener(n)})}}));var Yu,yt=class extends eE{};async function G(t,e,n){return async function(s,i,r,o){return Yv(s,i,r,o)}(t,n.canvas??(Rg()?void 0:document.createElement("canvas")),e,n)}function Pg(t,e,n,s){if(t.T){const r=new sg;if(n!=null&&n.regionOfInterest){if(!t.pa)throw Error("This task doesn't support region-of-interest.");var i=n.regionOfInterest;if(i.left>=i.right||i.top>=i.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(i.left<0||i.top<0||i.right>1||i.bottom>1)throw Error("Expected RectF values to be in [0,1].");I(r,1,(i.left+i.right)/2),I(r,2,(i.top+i.bottom)/2),I(r,4,i.right-i.left),I(r,3,i.bottom-i.top)}else I(r,1,.5),I(r,2,.5),I(r,4,1),I(r,3,1);if(n!=null&&n.rotationDegrees){if((n==null?void 0:n.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(I(r,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[o,a]=Ig(e);n=Ee(r,3)*a/o,i=Ee(r,4)*o/a,I(r,4,n),I(r,3,i)}}t.g.addProtoToStream(r.g(),"mediapipe.NormalizedRect",t.T,s)}t.g.qa(e,t.aa,s??performance.now()),t.finishProcessing()}function vt(t,e,n){var s;if((s=t.baseOptions)!=null&&s.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");Pg(t,e,n,t.B+1)}function Ut(t,e,n,s){var i;if(!((i=t.baseOptions)!=null&&i.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");Pg(t,e,n,s)}function Cs(t,e,n,s){var i=e.data;const r=e.width,o=r*(e=e.height);if((i instanceof Uint8Array||i instanceof Float32Array)&&i.length!==o)throw Error("Unsupported channel count: "+i.length/o);return t=new ke([i],n,!1,t.g.i.canvas,t.O,r,e),s?t.clone():t}var Xe=class extends ir{constructor(t,e,n,s){super(t),this.g=t,this.aa=e,this.T=n,this.pa=s,this.O=new Ls}l(t,e=!0){if("runningMode"in t&&vi(this.baseOptions,2,!!t.runningMode&&t.runningMode!=="IMAGE"),t.canvas!==void 0&&this.g.i.canvas!==t.canvas)throw Error("You must create a new task to reset the canvas.");return super.l(t,e)}close(){this.O.close(),super.close()}};Xe.prototype.close=Xe.prototype.close;var lt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect_in",!1),this.j={detections:[]},F(t=this.h=new Co,0,1,e=new pe),I(this.h,2,.5),I(this.h,3,.3)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return"minDetectionConfidence"in t&&I(this.h,2,t.minDetectionConfidence??.5),"minSuppressionThreshold"in t&&I(this.h,3,t.minSuppressionThreshold??.3),this.l(t)}D(t,e){return this.j={detections:[]},vt(this,t,e),this.j}F(t,e,n){return this.j={detections:[]},Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect_in"),Q(t,"detections");const e=new it;St(e,Lv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect_in"),q(n,"DETECTIONS:detections"),n.o(e),at(t,n),this.g.attachProtoVectorListener("detections",(s,i)=>{for(const r of s)s=eg(r),this.j.detections.push(kg(s));S(this,i)}),this.g.attachEmptyPacketListener("detections",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};lt.prototype.detectForVideo=lt.prototype.F,lt.prototype.detect=lt.prototype.D,lt.prototype.setOptions=lt.prototype.o,lt.createFromModelPath=async function(t,e){return G(lt,t,{baseOptions:{modelAssetPath:e}})},lt.createFromModelBuffer=function(t,e){return G(lt,t,{baseOptions:{modelAssetBuffer:e}})},lt.createFromOptions=function(t,e){return G(lt,t,e)};var zl=Rt([61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]),Kl=Rt([263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]),Yl=Rt([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),Lg=Rt([474,475],[475,476],[476,477],[477,474]),Xl=Rt([33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]),Ql=Rt([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),Og=Rt([469,470],[470,471],[471,472],[472,469]),Jl=Rt([10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]),Mg=[...zl,...Kl,...Yl,...Xl,...Ql,...Jl],Bg=Rt([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function Xu(t){t.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var X=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,F(t=this.h=new cg,0,1,e=new pe),this.v=new ag,F(this.h,0,3,this.v),this.s=new Co,F(this.h,0,2,this.s),Mt(this.s,4,1),I(this.s,2,.5),I(this.v,2,.5),I(this.h,4,.5)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return"numFaces"in t&&Mt(this.s,4,t.numFaces??1),"minFaceDetectionConfidence"in t&&I(this.s,2,t.minFaceDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.h,4,t.minTrackingConfidence??.5),"minFacePresenceConfidence"in t&&I(this.v,2,t.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in t&&(this.outputFaceBlendshapes=!!t.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in t&&(this.outputFacialTransformationMatrixes=!!t.outputFacialTransformationMatrixes),this.l(t)}D(t,e){return Xu(this),vt(this,t,e),this.j}F(t,e,n){return Xu(this),Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"face_landmarks");const e=new it;St(e,Mv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),q(n,"NORM_LANDMARKS:face_landmarks"),n.o(e),at(t,n),this.g.attachProtoVectorListener("face_landmarks",(s,i)=>{for(const r of s)s=Pi(r),this.j.faceLandmarks.push(To(s));S(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",s=>{S(this,s)}),this.outputFaceBlendshapes&&(Q(t,"blendshapes"),q(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(s,i)=>{if(this.outputFaceBlendshapes)for(const r of s)s=bo(r),this.j.faceBlendshapes.push(Wl(s.g()??[]));S(this,i)}),this.g.attachEmptyPacketListener("blendshapes",s=>{S(this,s)})),this.outputFacialTransformationMatrixes&&(Q(t,"face_geometry"),q(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(s,i)=>{if(this.outputFacialTransformationMatrixes)for(const r of s)(s=Y(Ov(r),Av,2))&&this.j.facialTransformationMatrixes.push({rows:pt(s,1)??0??0,columns:pt(s,2)??0??0,data:Nn(s,3,yn,xn()).slice()??[]});S(this,i)}),this.g.attachEmptyPacketListener("face_geometry",s=>{S(this,s)})),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};X.prototype.detectForVideo=X.prototype.F,X.prototype.detect=X.prototype.D,X.prototype.setOptions=X.prototype.o,X.createFromModelPath=function(t,e){return G(X,t,{baseOptions:{modelAssetPath:e}})},X.createFromModelBuffer=function(t,e){return G(X,t,{baseOptions:{modelAssetBuffer:e}})},X.createFromOptions=function(t,e){return G(X,t,e)},X.FACE_LANDMARKS_LIPS=zl,X.FACE_LANDMARKS_LEFT_EYE=Kl,X.FACE_LANDMARKS_LEFT_EYEBROW=Yl,X.FACE_LANDMARKS_LEFT_IRIS=Lg,X.FACE_LANDMARKS_RIGHT_EYE=Xl,X.FACE_LANDMARKS_RIGHT_EYEBROW=Ql,X.FACE_LANDMARKS_RIGHT_IRIS=Og,X.FACE_LANDMARKS_FACE_OVAL=Jl,X.FACE_LANDMARKS_CONTOURS=Mg,X.FACE_LANDMARKS_TESSELATION=Bg;var Ft=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!0),F(t=this.j=new hg,0,1,e=new pe)}get baseOptions(){return Y(this.j,pe,1)}set baseOptions(t){F(this.j,0,1,t)}o(t){return super.l(t)}Oa(t,e,n){const s=typeof e!="function"?e:{};if(this.h=typeof e=="function"?e:n,vt(this,t,s??{}),!this.h)return this.s}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"stylized_image");const e=new it;St(e,Bv,this.j);const n=new $e;ot(n,"mediapipe.tasks.vision.face_stylizer.FaceStylizerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),q(n,"STYLIZED_IMAGE:stylized_image"),n.o(e),at(t,n),this.g.U("stylized_image",(s,i)=>{var r=!this.h,o=s.data,a=s.width;const c=a*(s=s.height);if(o instanceof Uint8Array)if(o.length===3*c){const l=new Uint8ClampedArray(4*c);for(let h=0;h<c;++h)l[4*h]=o[3*h],l[4*h+1]=o[3*h+1],l[4*h+2]=o[3*h+2],l[4*h+3]=255;o=new ImageData(l,a,s)}else{if(o.length!==4*c)throw Error("Unsupported channel count: "+o.length/c);o=new ImageData(new Uint8ClampedArray(o.buffer,o.byteOffset,o.length),a,s)}else if(!(o instanceof WebGLTexture))throw Error(`Unsupported format: ${o.constructor.name}`);a=new Ie([o],!1,!1,this.g.i.canvas,this.O,a,s),this.s=r=r?a.clone():a,this.h&&this.h(r),S(this,i)}),this.g.attachEmptyPacketListener("stylized_image",s=>{this.s=null,this.h&&this.h(null),S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Ft.prototype.stylize=Ft.prototype.Oa,Ft.prototype.setOptions=Ft.prototype.o,Ft.createFromModelPath=function(t,e){return G(Ft,t,{baseOptions:{modelAssetPath:e}})},Ft.createFromModelBuffer=function(t,e){return G(Ft,t,{baseOptions:{modelAssetBuffer:e}})},Ft.createFromOptions=function(t,e){return G(Ft,t,e)};var Zl=Rt([0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]);function Qu(t){t.gestures=[],t.landmarks=[],t.worldLandmarks=[],t.handedness=[]}function Ju(t){return t.gestures.length===0?{gestures:[],landmarks:[],worldLandmarks:[],handedness:[],handednesses:[]}:{gestures:t.gestures,landmarks:t.landmarks,worldLandmarks:t.worldLandmarks,handedness:t.handedness,handednesses:t.handedness}}function Zu(t,e=!0){const n=[];for(const i of t){var s=bo(i);t=[];for(const r of s.g())s=e&&pt(r,1)!=null?pt(r,1)??0:-1,t.push({score:Ee(r,2)??0,index:s,categoryName:gt(r,3)??""??"",displayName:gt(r,4)??""??""});n.push(t)}return n}var Je=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],F(t=this.j=new fg,0,1,e=new pe),this.s=new Ul,F(this.j,0,2,this.s),this.C=new Bl,F(this.s,0,3,this.C),this.v=new dg,F(this.s,0,2,this.v),this.h=new Uv,F(this.j,0,3,this.h),I(this.v,2,.5),I(this.s,4,.5),I(this.C,2,.5)}get baseOptions(){return Y(this.j,pe,1)}set baseOptions(t){F(this.j,0,1,t)}o(t){var i,r,o,a;if(Mt(this.v,3,t.numHands??1),"minHandDetectionConfidence"in t&&I(this.v,2,t.minHandDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.s,4,t.minTrackingConfidence??.5),"minHandPresenceConfidence"in t&&I(this.C,2,t.minHandPresenceConfidence??.5),t.cannedGesturesClassifierOptions){var e=new zn,n=e,s=Xa(t.cannedGesturesClassifierOptions,(i=Y(this.h,zn,3))==null?void 0:i.h());F(n,0,2,s),F(this.h,0,3,e)}else t.cannedGesturesClassifierOptions===void 0&&((r=Y(this.h,zn,3))==null||r.g());return t.customGesturesClassifierOptions?(F(n=e=new zn,0,2,s=Xa(t.customGesturesClassifierOptions,(o=Y(this.h,zn,4))==null?void 0:o.h())),F(this.h,0,4,e)):t.customGesturesClassifierOptions===void 0&&((a=Y(this.h,zn,4))==null||a.g()),this.l(t)}Ja(t,e){return Qu(this),vt(this,t,e),Ju(this)}Ka(t,e,n){return Qu(this),Ut(this,t,n,e),Ju(this)}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"hand_gestures"),Q(t,"hand_landmarks"),Q(t,"world_hand_landmarks"),Q(t,"handedness");const e=new it;St(e,Vv,this.j);const n=new $e;ot(n,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),q(n,"HAND_GESTURES:hand_gestures"),q(n,"LANDMARKS:hand_landmarks"),q(n,"WORLD_LANDMARKS:world_hand_landmarks"),q(n,"HANDEDNESS:handedness"),n.o(e),at(t,n),this.g.attachProtoVectorListener("hand_landmarks",(s,i)=>{for(const r of s){s=Pi(r);const o=[];for(const a of Qt(s,ng,1))o.push({x:Ee(a,1)??0,y:Ee(a,2)??0,z:Ee(a,3)??0,visibility:Ee(a,4)??0});this.landmarks.push(o)}S(this,i)}),this.g.attachEmptyPacketListener("hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("world_hand_landmarks",(s,i)=>{for(const r of s){s=cs(r);const o=[];for(const a of Qt(s,tg,1))o.push({x:Ee(a,1)??0,y:Ee(a,2)??0,z:Ee(a,3)??0,visibility:Ee(a,4)??0});this.worldLandmarks.push(o)}S(this,i)}),this.g.attachEmptyPacketListener("world_hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("hand_gestures",(s,i)=>{this.gestures.push(...Zu(s,!1)),S(this,i)}),this.g.attachEmptyPacketListener("hand_gestures",s=>{S(this,s)}),this.g.attachProtoVectorListener("handedness",(s,i)=>{this.handedness.push(...Zu(s)),S(this,i)}),this.g.attachEmptyPacketListener("handedness",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};function ed(t){return{landmarks:t.landmarks,worldLandmarks:t.worldLandmarks,handednesses:t.handedness,handedness:t.handedness}}Je.prototype.recognizeForVideo=Je.prototype.Ka,Je.prototype.recognize=Je.prototype.Ja,Je.prototype.setOptions=Je.prototype.o,Je.createFromModelPath=function(t,e){return G(Je,t,{baseOptions:{modelAssetPath:e}})},Je.createFromModelBuffer=function(t,e){return G(Je,t,{baseOptions:{modelAssetBuffer:e}})},Je.createFromOptions=function(t,e){return G(Je,t,e)},Je.HAND_CONNECTIONS=Zl;var Ze=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],F(t=this.h=new Ul,0,1,e=new pe),this.s=new Bl,F(this.h,0,3,this.s),this.j=new dg,F(this.h,0,2,this.j),Mt(this.j,3,1),I(this.j,2,.5),I(this.s,2,.5),I(this.h,4,.5)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return"numHands"in t&&Mt(this.j,3,t.numHands??1),"minHandDetectionConfidence"in t&&I(this.j,2,t.minHandDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.h,4,t.minTrackingConfidence??.5),"minHandPresenceConfidence"in t&&I(this.s,2,t.minHandPresenceConfidence??.5),this.l(t)}D(t,e){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],vt(this,t,e),ed(this)}F(t,e,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Ut(this,t,n,e),ed(this)}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"hand_landmarks"),Q(t,"world_hand_landmarks"),Q(t,"handedness");const e=new it;St(e,$v,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),q(n,"LANDMARKS:hand_landmarks"),q(n,"WORLD_LANDMARKS:world_hand_landmarks"),q(n,"HANDEDNESS:handedness"),n.o(e),at(t,n),this.g.attachProtoVectorListener("hand_landmarks",(s,i)=>{for(const r of s)s=Pi(r),this.landmarks.push(To(s));S(this,i)}),this.g.attachEmptyPacketListener("hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("world_hand_landmarks",(s,i)=>{for(const r of s)s=cs(r),this.worldLandmarks.push(oi(s));S(this,i)}),this.g.attachEmptyPacketListener("world_hand_landmarks",s=>{S(this,s)}),this.g.attachProtoVectorListener("handedness",(s,i)=>{var r=this.handedness,o=r.push;const a=[];for(const c of s){s=bo(c);const l=[];for(const h of s.g())l.push({score:Ee(h,2)??0,index:pt(h,1)??0??-1,categoryName:gt(h,3)??""??"",displayName:gt(h,4)??""??""});a.push(l)}o.call(r,...a),S(this,i)}),this.g.attachEmptyPacketListener("handedness",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Ze.prototype.detectForVideo=Ze.prototype.F,Ze.prototype.detect=Ze.prototype.D,Ze.prototype.setOptions=Ze.prototype.o,Ze.createFromModelPath=function(t,e){return G(Ze,t,{baseOptions:{modelAssetPath:e}})},Ze.createFromModelBuffer=function(t,e){return G(Ze,t,{baseOptions:{modelAssetBuffer:e}})},Ze.createFromOptions=function(t,e){return G(Ze,t,e)},Ze.HAND_CONNECTIONS=Zl;var Ug=Rt([0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10],[11,12],[11,13],[13,15],[15,17],[15,19],[15,21],[17,19],[12,14],[14,16],[16,18],[16,20],[16,22],[18,20],[11,23],[12,24],[23,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,31],[30,32],[27,31],[28,32]);function td(t){t.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function nd(t){try{if(!t.C)return t.h;t.C(t.h)}finally{ko(t)}}function qi(t,e){t=Pi(t),e.push(To(t))}var de=class extends Xe{constructor(t,e){super(new yt(t,e),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,F(t=this.j=new yg,0,1,e=new pe),this.J=new Bl,F(this.j,0,2,this.J),this.Z=new Hv,F(this.j,0,3,this.Z),this.s=new Co,F(this.j,0,4,this.s),this.H=new ag,F(this.j,0,5,this.H),this.v=new gg,F(this.j,0,6,this.v),this.K=new _g,F(this.j,0,7,this.K),I(this.s,2,.5),I(this.s,3,.3),I(this.H,2,.5),I(this.v,2,.5),I(this.v,3,.3),I(this.K,2,.5),I(this.J,2,.5)}get baseOptions(){return Y(this.j,pe,1)}set baseOptions(t){F(this.j,0,1,t)}o(t){return"minFaceDetectionConfidence"in t&&I(this.s,2,t.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in t&&I(this.s,3,t.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in t&&I(this.H,2,t.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in t&&(this.outputFaceBlendshapes=!!t.outputFaceBlendshapes),"minPoseDetectionConfidence"in t&&I(this.v,2,t.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in t&&I(this.v,3,t.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in t&&I(this.K,2,t.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in t&&(this.outputPoseSegmentationMasks=!!t.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in t&&I(this.J,2,t.minHandLandmarksConfidence??.5),this.l(t)}D(t,e,n){const s=typeof e!="function"?e:{};return this.C=typeof e=="function"?e:n,td(this),vt(this,t,s),nd(this)}F(t,e,n,s){const i=typeof n!="function"?n:{};return this.C=typeof n=="function"?n:s,td(this),Ut(this,t,i,e),nd(this)}m(){var t=new Qe;ue(t,"input_frames_image"),Q(t,"pose_landmarks"),Q(t,"pose_world_landmarks"),Q(t,"face_landmarks"),Q(t,"left_hand_landmarks"),Q(t,"left_hand_world_landmarks"),Q(t,"right_hand_landmarks"),Q(t,"right_hand_world_landmarks");const e=new it,n=new wu;Ga(n,1,Is("type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),""),function(i,r){if(r!=null)if(Array.isArray(r))ae(i,2,dm(r));else{if(!(typeof r=="string"||r instanceof zt||xi(r)))throw Error("invalid value in Any.value field: "+r+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");Ga(i,2,nl(r,!1),Vn())}}(n,this.j.g());const s=new $e;ot(s,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Br(s,8,wu,n),ce(s,"IMAGE:input_frames_image"),q(s,"POSE_LANDMARKS:pose_landmarks"),q(s,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),q(s,"FACE_LANDMARKS:face_landmarks"),q(s,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),q(s,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),q(s,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),q(s,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),s.o(e),at(t,s),So(this,t),this.g.attachProtoListener("pose_landmarks",(i,r)=>{qi(i,this.h.poseLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("pose_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("pose_world_landmarks",(i,r)=>{var o=this.h.poseWorldLandmarks;i=cs(i),o.push(oi(i)),S(this,r)}),this.g.attachEmptyPacketListener("pose_world_landmarks",i=>{S(this,i)}),this.outputPoseSegmentationMasks&&(q(s,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),Es(this,"pose_segmentation_mask"),this.g.U("pose_segmentation_mask",(i,r)=>{this.h.poseSegmentationMasks=[Cs(this,i,!0,!this.C)],S(this,r)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",i=>{this.h.poseSegmentationMasks=[],S(this,i)})),this.g.attachProtoListener("face_landmarks",(i,r)=>{qi(i,this.h.faceLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("face_landmarks",i=>{S(this,i)}),this.outputFaceBlendshapes&&(Q(t,"extra_blendshapes"),q(s,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(i,r)=>{var o=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(i=bo(i),o.push(Wl(i.g()??[]))),S(this,r)}),this.g.attachEmptyPacketListener("extra_blendshapes",i=>{S(this,i)})),this.g.attachProtoListener("left_hand_landmarks",(i,r)=>{qi(i,this.h.leftHandLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("left_hand_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("left_hand_world_landmarks",(i,r)=>{var o=this.h.leftHandWorldLandmarks;i=cs(i),o.push(oi(i)),S(this,r)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("right_hand_landmarks",(i,r)=>{qi(i,this.h.rightHandLandmarks),S(this,r)}),this.g.attachEmptyPacketListener("right_hand_landmarks",i=>{S(this,i)}),this.g.attachProtoListener("right_hand_world_landmarks",(i,r)=>{var o=this.h.rightHandWorldLandmarks;i=cs(i),o.push(oi(i)),S(this,r)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",i=>{S(this,i)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};de.prototype.detectForVideo=de.prototype.F,de.prototype.detect=de.prototype.D,de.prototype.setOptions=de.prototype.o,de.createFromModelPath=function(t,e){return G(de,t,{baseOptions:{modelAssetPath:e}})},de.createFromModelBuffer=function(t,e){return G(de,t,{baseOptions:{modelAssetBuffer:e}})},de.createFromOptions=function(t,e){return G(de,t,e)},de.HAND_CONNECTIONS=Zl,de.POSE_CONNECTIONS=Ug,de.FACE_LANDMARKS_LIPS=zl,de.FACE_LANDMARKS_LEFT_EYE=Kl,de.FACE_LANDMARKS_LEFT_EYEBROW=Yl,de.FACE_LANDMARKS_LEFT_IRIS=Lg,de.FACE_LANDMARKS_RIGHT_EYE=Xl,de.FACE_LANDMARKS_RIGHT_EYEBROW=Ql,de.FACE_LANDMARKS_RIGHT_IRIS=Og,de.FACE_LANDMARKS_FACE_OVAL=Jl,de.FACE_LANDMARKS_CONTOURS=Mg,de.FACE_LANDMARKS_TESSELATION=Bg;var ht=class extends Xe{constructor(t,e){super(new yt(t,e),"input_image","norm_rect",!0),this.j={classifications:[]},F(t=this.h=new vg,0,1,e=new pe)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return F(this.h,0,2,Xa(t,Y(this.h,Ll,2))),this.l(t)}sa(t,e){return this.j={classifications:[]},vt(this,t,e),this.j}ta(t,e,n){return this.j={classifications:[]},Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"input_image"),ue(t,"norm_rect"),Q(t,"classifications");const e=new it;St(e,Wv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),ce(n,"IMAGE:input_image"),ce(n,"NORM_RECT:norm_rect"),q(n,"CLASSIFICATIONS:classifications"),n.o(e),at(t,n),this.g.attachProtoListener("classifications",(s,i)=>{this.j=function(r){const o={classifications:Qt(r,Iv,1).map(a=>{var c;return Wl(((c=Y(a,Jm,4))==null?void 0:c.g())??[],pt(a,2)??0,gt(a,3)??"")})};return Mr(ys(r,2))!=null&&(o.timestampMs=Mr(ys(r,2))??0),o}(xv(s)),S(this,i)}),this.g.attachEmptyPacketListener("classifications",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};ht.prototype.classifyForVideo=ht.prototype.ta,ht.prototype.classify=ht.prototype.sa,ht.prototype.setOptions=ht.prototype.o,ht.createFromModelPath=function(t,e){return G(ht,t,{baseOptions:{modelAssetPath:e}})},ht.createFromModelBuffer=function(t,e){return G(ht,t,{baseOptions:{modelAssetBuffer:e}})},ht.createFromOptions=function(t,e){return G(ht,t,e)};var et=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!0),this.h=new Eg,this.embeddings={embeddings:[]},F(t=this.h,0,1,e=new pe)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){var e=this.h,n=Y(this.h,xu,2);return n=n?n.clone():new xu,t.l2Normalize!==void 0?vi(n,1,t.l2Normalize):"l2Normalize"in t&&ae(n,1),t.quantize!==void 0?vi(n,2,t.quantize):"quantize"in t&&ae(n,2),F(e,0,2,n),this.l(t)}za(t,e){return vt(this,t,e),this.embeddings}Aa(t,e,n){return Ut(this,t,n,e),this.embeddings}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"embeddings_out");const e=new it;St(e,Gv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),q(n,"EMBEDDINGS:embeddings_out"),n.o(e),at(t,n),this.g.attachProtoListener("embeddings_out",(s,i)=>{s=Dv(s),this.embeddings=function(r){return{embeddings:Qt(r,Fv,1).map(o=>{var c,l;const a={headIndex:pt(o,3)??0??-1,headName:gt(o,4)??""??""};if(_m(o,Iu,sa(o,1))!==void 0)o=Nn(o=Y(o,Iu,sa(o,1)),1,yn,xn()),a.floatEmbedding=o.slice();else{const h=new Uint8Array(0);a.quantizedEmbedding=((l=(c=Y(o,Nv,sa(o,2)))==null?void 0:c.oa())==null?void 0:l.h())??h}return a}),timestampMs:Mr(ys(r,2))??0}}(s),S(this,i)}),this.g.attachEmptyPacketListener("embeddings_out",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};et.cosineSimilarity=function(t,e){if(t.floatEmbedding&&e.floatEmbedding)t=Lu(t.floatEmbedding,e.floatEmbedding);else{if(!t.quantizedEmbedding||!e.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");t=Lu(Pu(t.quantizedEmbedding),Pu(e.quantizedEmbedding))}return t},et.prototype.embedForVideo=et.prototype.Aa,et.prototype.embed=et.prototype.za,et.prototype.setOptions=et.prototype.o,et.createFromModelPath=function(t,e){return G(et,t,{baseOptions:{modelAssetPath:e}})},et.createFromModelBuffer=function(t,e){return G(et,t,{baseOptions:{modelAssetBuffer:e}})},et.createFromOptions=function(t,e){return G(et,t,e)};var Za=class{constructor(t,e,n){this.confidenceMasks=t,this.categoryMask=e,this.qualityScores=n}close(){var t,e;(t=this.confidenceMasks)==null||t.forEach(n=>{n.close()}),(e=this.categoryMask)==null||e.close()}};function sd(t){t.categoryMask=void 0,t.confidenceMasks=void 0,t.qualityScores=void 0}function id(t){try{const e=new Za(t.confidenceMasks,t.categoryMask,t.qualityScores);if(!t.j)return e;t.j(e)}finally{ko(t)}}Za.prototype.close=Za.prototype.close;var Ge=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.s=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Hl,this.v=new wg,F(this.h,0,3,this.v),F(t=this.h,0,1,e=new pe)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return t.displayNamesLocale!==void 0?ae(this.h,2,Is(t.displayNamesLocale)):"displayNamesLocale"in t&&ae(this.h,2),"outputCategoryMask"in t&&(this.outputCategoryMask=t.outputCategoryMask??!1),"outputConfidenceMasks"in t&&(this.outputConfidenceMasks=t.outputConfidenceMasks??!0),super.l(t)}I(){(function(t){var n,s;const e=Qt(t.da(),$e,1).filter(i=>(gt(i,1)??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(t.s=[],e.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");e.length===1&&(((s=(n=Y(e[0],it,7))==null?void 0:n.l())==null?void 0:s.g())??new Map).forEach((i,r)=>{t.s[Number(r)]=gt(i,1)??""})})(this)}segment(t,e,n){const s=typeof e!="function"?e:{};return this.j=typeof e=="function"?e:n,sd(this),vt(this,t,s),id(this)}Ma(t,e,n,s){const i=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:s,sd(this),Ut(this,t,i,e),id(this)}Da(){return this.s}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect");const e=new it;St(e,Cg,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),n.o(e),at(t,n),So(this,t),this.outputConfidenceMasks&&(Q(t,"confidence_masks"),q(n,"CONFIDENCE_MASKS:confidence_masks"),Es(this,"confidence_masks"),this.g.ca("confidence_masks",(s,i)=>{this.confidenceMasks=s.map(r=>Cs(this,r,!0,!this.j)),S(this,i)}),this.g.attachEmptyPacketListener("confidence_masks",s=>{this.confidenceMasks=[],S(this,s)})),this.outputCategoryMask&&(Q(t,"category_mask"),q(n,"CATEGORY_MASK:category_mask"),Es(this,"category_mask"),this.g.U("category_mask",(s,i)=>{this.categoryMask=Cs(this,s,!1,!this.j),S(this,i)}),this.g.attachEmptyPacketListener("category_mask",s=>{this.categoryMask=void 0,S(this,s)})),Q(t,"quality_scores"),q(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(s,i)=>{this.qualityScores=s,S(this,i)}),this.g.attachEmptyPacketListener("quality_scores",s=>{this.categoryMask=void 0,S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Ge.prototype.getLabels=Ge.prototype.Da,Ge.prototype.segmentForVideo=Ge.prototype.Ma,Ge.prototype.segment=Ge.prototype.segment,Ge.prototype.setOptions=Ge.prototype.o,Ge.createFromModelPath=function(t,e){return G(Ge,t,{baseOptions:{modelAssetPath:e}})},Ge.createFromModelBuffer=function(t,e){return G(Ge,t,{baseOptions:{modelAssetBuffer:e}})},Ge.createFromOptions=function(t,e){return G(Ge,t,e)};var ec=class{constructor(t,e,n){this.confidenceMasks=t,this.categoryMask=e,this.qualityScores=n}close(){var t,e;(t=this.confidenceMasks)==null||t.forEach(n=>{n.close()}),(e=this.categoryMask)==null||e.close()}};ec.prototype.close=ec.prototype.close;var tE=class extends A{constructor(t){super(t)}},Kn=[0,ve,-2],Hr=[0,Ht,-3,fe,Ht,-1],rd=[0,Hr],od=[0,Hr,ve,-1],ha=class extends A{constructor(t){super(t)}},ad=[0,Ht,-1,fe],nE=class extends A{constructor(t){super(t)}},cd=class extends A{constructor(t){super(t)}},tc=[1,2,3,4,5,6,7,8,9,10,14,15],Vg=class extends A{constructor(t){super(t)}};Vg.prototype.g=wo([0,Ae,[0,tc,ee,Hr,ee,[0,Hr,Kn],ee,rd,ee,[0,rd,Kn],ee,ad,ee,[0,Ht,-3,fe,_t],ee,[0,Ht,-3,fe],ee,[0,Z,Ht,-2,fe,ve,fe,-1,2,Ht,Kn],ee,od,ee,[0,od,Kn],Ht,Kn,Z,ee,[0,Ht,-3,fe,Kn,-1],ee,[0,Ae,ad]],Z,[0,Z,ve,-1,fe]]);var Dt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new Hl,this.s=new wg,F(this.h,0,3,this.s),F(t=this.h,0,1,e=new pe)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return"outputCategoryMask"in t&&(this.outputCategoryMask=t.outputCategoryMask??!1),"outputConfidenceMasks"in t&&(this.outputConfidenceMasks=t.outputConfidenceMasks??!0),super.l(t)}segment(t,e,n,s){const i=typeof n!="function"?n:{};this.j=typeof n=="function"?n:s,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.B+1,s=new Vg;const r=new cd;var o=new tE;if(Mt(o,1,255),F(r,0,12,o),e.keypoint&&e.scribble)throw Error("Cannot provide both keypoint and scribble.");if(e.keypoint){var a=new ha;vi(a,3,!0),I(a,1,e.keypoint.x),I(a,2,e.keypoint.y),ii(r,5,tc,a)}else{if(!e.scribble)throw Error("Must provide either a keypoint or a scribble.");for(a of(o=new nE,e.scribble))vi(e=new ha,3,!0),I(e,1,a.x),I(e,2,a.y),Br(o,1,ha,e);ii(r,15,tc,o)}Br(s,1,cd,r),this.g.addProtoToStream(s.g(),"drishti.RenderData","roi_in",n),vt(this,t,i);e:{try{const l=new ec(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var c=l;break e}this.j(l)}finally{ko(this)}c=void 0}return c}m(){var t=new Qe;ue(t,"image_in"),ue(t,"roi_in"),ue(t,"norm_rect_in");const e=new it;St(e,Cg,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraph"),ce(n,"IMAGE:image_in"),ce(n,"ROI:roi_in"),ce(n,"NORM_RECT:norm_rect_in"),n.o(e),at(t,n),So(this,t),this.outputConfidenceMasks&&(Q(t,"confidence_masks"),q(n,"CONFIDENCE_MASKS:confidence_masks"),Es(this,"confidence_masks"),this.g.ca("confidence_masks",(s,i)=>{this.confidenceMasks=s.map(r=>Cs(this,r,!0,!this.j)),S(this,i)}),this.g.attachEmptyPacketListener("confidence_masks",s=>{this.confidenceMasks=[],S(this,s)})),this.outputCategoryMask&&(Q(t,"category_mask"),q(n,"CATEGORY_MASK:category_mask"),Es(this,"category_mask"),this.g.U("category_mask",(s,i)=>{this.categoryMask=Cs(this,s,!1,!this.j),S(this,i)}),this.g.attachEmptyPacketListener("category_mask",s=>{this.categoryMask=void 0,S(this,s)})),Q(t,"quality_scores"),q(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(s,i)=>{this.qualityScores=s,S(this,i)}),this.g.attachEmptyPacketListener("quality_scores",s=>{this.categoryMask=void 0,S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};Dt.prototype.segment=Dt.prototype.segment,Dt.prototype.setOptions=Dt.prototype.o,Dt.createFromModelPath=function(t,e){return G(Dt,t,{baseOptions:{modelAssetPath:e}})},Dt.createFromModelBuffer=function(t,e){return G(Dt,t,{baseOptions:{modelAssetBuffer:e}})},Dt.createFromOptions=function(t,e){return G(Dt,t,e)};var ut=class extends Xe{constructor(t,e){super(new yt(t,e),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},F(t=this.h=new Tg,0,1,e=new pe)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return t.displayNamesLocale!==void 0?ae(this.h,2,Is(t.displayNamesLocale)):"displayNamesLocale"in t&&ae(this.h,2),t.maxResults!==void 0?Mt(this.h,3,t.maxResults):"maxResults"in t&&ae(this.h,3),t.scoreThreshold!==void 0?I(this.h,4,t.scoreThreshold):"scoreThreshold"in t&&ae(this.h,4),t.categoryAllowlist!==void 0?Ur(this.h,5,t.categoryAllowlist):"categoryAllowlist"in t&&ae(this.h,5),t.categoryDenylist!==void 0?Ur(this.h,6,t.categoryDenylist):"categoryDenylist"in t&&ae(this.h,6),this.l(t)}D(t,e){return this.j={detections:[]},vt(this,t,e),this.j}F(t,e,n){return this.j={detections:[]},Ut(this,t,n,e),this.j}m(){var t=new Qe;ue(t,"input_frame_gpu"),ue(t,"norm_rect"),Q(t,"detections");const e=new it;St(e,qv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.ObjectDetectorGraph"),ce(n,"IMAGE:input_frame_gpu"),ce(n,"NORM_RECT:norm_rect"),q(n,"DETECTIONS:detections"),n.o(e),at(t,n),this.g.attachProtoVectorListener("detections",(s,i)=>{for(const r of s)s=eg(r),this.j.detections.push(kg(s));S(this,i)}),this.g.attachEmptyPacketListener("detections",s=>{S(this,s)}),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};ut.prototype.detectForVideo=ut.prototype.F,ut.prototype.detect=ut.prototype.D,ut.prototype.setOptions=ut.prototype.o,ut.createFromModelPath=async function(t,e){return G(ut,t,{baseOptions:{modelAssetPath:e}})},ut.createFromModelBuffer=function(t,e){return G(ut,t,{baseOptions:{modelAssetBuffer:e}})},ut.createFromOptions=function(t,e){return G(ut,t,e)};var nc=class{constructor(t,e,n){this.landmarks=t,this.worldLandmarks=e,this.segmentationMasks=n}close(){var t;(t=this.segmentationMasks)==null||t.forEach(e=>{e.close()})}};function ld(t){t.landmarks=[],t.worldLandmarks=[],t.segmentationMasks=void 0}function hd(t){try{const e=new nc(t.landmarks,t.worldLandmarks,t.segmentationMasks);if(!t.s)return e;t.s(e)}finally{ko(t)}}nc.prototype.close=nc.prototype.close;var tt=class extends Xe{constructor(t,e){super(new yt(t,e),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,F(t=this.h=new Sg,0,1,e=new pe),this.v=new _g,F(this.h,0,3,this.v),this.j=new gg,F(this.h,0,2,this.j),Mt(this.j,4,1),I(this.j,2,.5),I(this.v,2,.5),I(this.h,4,.5)}get baseOptions(){return Y(this.h,pe,1)}set baseOptions(t){F(this.h,0,1,t)}o(t){return"numPoses"in t&&Mt(this.j,4,t.numPoses??1),"minPoseDetectionConfidence"in t&&I(this.j,2,t.minPoseDetectionConfidence??.5),"minTrackingConfidence"in t&&I(this.h,4,t.minTrackingConfidence??.5),"minPosePresenceConfidence"in t&&I(this.v,2,t.minPosePresenceConfidence??.5),"outputSegmentationMasks"in t&&(this.outputSegmentationMasks=t.outputSegmentationMasks??!1),this.l(t)}D(t,e,n){const s=typeof e!="function"?e:{};return this.s=typeof e=="function"?e:n,ld(this),vt(this,t,s),hd(this)}F(t,e,n,s){const i=typeof n!="function"?n:{};return this.s=typeof n=="function"?n:s,ld(this),Ut(this,t,i,e),hd(this)}m(){var t=new Qe;ue(t,"image_in"),ue(t,"norm_rect"),Q(t,"normalized_landmarks"),Q(t,"world_landmarks"),Q(t,"segmentation_masks");const e=new it;St(e,zv,this.h);const n=new $e;ot(n,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),ce(n,"IMAGE:image_in"),ce(n,"NORM_RECT:norm_rect"),q(n,"NORM_LANDMARKS:normalized_landmarks"),q(n,"WORLD_LANDMARKS:world_landmarks"),n.o(e),at(t,n),So(this,t),this.g.attachProtoVectorListener("normalized_landmarks",(s,i)=>{this.landmarks=[];for(const r of s)s=Pi(r),this.landmarks.push(To(s));S(this,i)}),this.g.attachEmptyPacketListener("normalized_landmarks",s=>{this.landmarks=[],S(this,s)}),this.g.attachProtoVectorListener("world_landmarks",(s,i)=>{this.worldLandmarks=[];for(const r of s)s=cs(r),this.worldLandmarks.push(oi(s));S(this,i)}),this.g.attachEmptyPacketListener("world_landmarks",s=>{this.worldLandmarks=[],S(this,s)}),this.outputSegmentationMasks&&(q(n,"SEGMENTATION_MASK:segmentation_masks"),Es(this,"segmentation_masks"),this.g.ca("segmentation_masks",(s,i)=>{this.segmentationMasks=s.map(r=>Cs(this,r,!0,!this.s)),S(this,i)}),this.g.attachEmptyPacketListener("segmentation_masks",s=>{this.segmentationMasks=[],S(this,s)})),t=t.g(),this.setGraph(new Uint8Array(t),!0)}};tt.prototype.detectForVideo=tt.prototype.F,tt.prototype.detect=tt.prototype.D,tt.prototype.setOptions=tt.prototype.o,tt.createFromModelPath=function(t,e){return G(tt,t,{baseOptions:{modelAssetPath:e}})},tt.createFromModelBuffer=function(t,e){return G(tt,t,{baseOptions:{modelAssetBuffer:e}})},tt.createFromOptions=function(t,e){return G(tt,t,e)},tt.POSE_CONNECTIONS=Ug;function sE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function iE(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function s(){return this instanceof s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(s){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(n,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}),n}const rE={},oE=Object.freeze(Object.defineProperty({__proto__:null,default:rE},Symbol.toStringTag,{value:"Module"})),Jn=iE(oE);var Pt={exports:{}};const aE="16.6.1",cE={version:aE};var ud;function lE(){if(ud)return Pt.exports;ud=1;const t=Jn,e=Jn,n=Jn,s=Jn,r=cE.version,o=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function a(v){const R={};let D=v.toString();D=D.replace(/\r\n?/mg,`
1635
1635
  `);let U;for(;(U=o.exec(D))!=null;){const me=U[1];let V=U[2]||"";V=V.trim();const ne=V[0];V=V.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),ne==='"'&&(V=V.replace(/\\n/g,`
1636
- `),V=V.replace(/\\r/g,"\r")),R[me]=V}return R}function c(v){v=v||{};const R=m(v);v.path=R;const D=C.configDotenv(v);if(!D.parsed){const ne=new Error(`MISSING_DATA: Cannot parse ${R} for an unknown reason`);throw ne.code="MISSING_DATA",ne}const U=d(v).split(","),me=U.length;let V;for(let ne=0;ne<me;ne++)try{const le=U[ne].trim(),ct=p(D,le);V=C.decrypt(ct.ciphertext,ct.key);break}catch(le){if(ne+1>=me)throw le}return C.parse(V)}function l(v){console.log(`[dotenv@${r}][WARN] ${v}`)}function h(v){console.log(`[dotenv@${r}][DEBUG] ${v}`)}function u(v){console.log(`[dotenv@${r}] ${v}`)}function d(v){return v&&v.DOTENV_KEY&&v.DOTENV_KEY.length>0?v.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function p(v,R){let D;try{D=new URL(R)}catch(le){if(le.code==="ERR_INVALID_URL"){const ct=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw ct.code="INVALID_DOTENV_KEY",ct}throw le}const U=D.password;if(!U){const le=new Error("INVALID_DOTENV_KEY: Missing key part");throw le.code="INVALID_DOTENV_KEY",le}const me=D.searchParams.get("environment");if(!me){const le=new Error("INVALID_DOTENV_KEY: Missing environment part");throw le.code="INVALID_DOTENV_KEY",le}const V=`DOTENV_VAULT_${me.toUpperCase()}`,ne=v.parsed[V];if(!ne){const le=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${V} in your .env.vault file.`);throw le.code="NOT_FOUND_DOTENV_ENVIRONMENT",le}return{ciphertext:ne,key:U}}function m(v){let R=null;if(v&&v.path&&v.path.length>0)if(Array.isArray(v.path))for(const D of v.path)t.existsSync(D)&&(R=D.endsWith(".vault")?D:`${D}.vault`);else R=v.path.endsWith(".vault")?v.path:`${v.path}.vault`;else R=e.resolve(process.cwd(),".env.vault");return t.existsSync(R)?R:null}function y(v){return v[0]==="~"?e.join(n.homedir(),v.slice(1)):v}function w(v){const R=!!(v&&v.debug),D=v&&"quiet"in v?v.quiet:!0;(R||!D)&&u("Loading env from encrypted .env.vault");const U=C._parseVault(v);let me=process.env;return v&&v.processEnv!=null&&(me=v.processEnv),C.populate(me,U,v),{parsed:U}}function k(v){const R=e.resolve(process.cwd(),".env");let D="utf8";const U=!!(v&&v.debug),me=v&&"quiet"in v?v.quiet:!0;v&&v.encoding?D=v.encoding:U&&h("No encoding is specified. UTF-8 is used by default");let V=[R];if(v&&v.path)if(!Array.isArray(v.path))V=[y(v.path)];else{V=[];for(const xt of v.path)V.push(y(xt))}let ne;const le={};for(const xt of V)try{const Ue=C.parse(t.readFileSync(xt,{encoding:D}));C.populate(le,Ue,v)}catch(Ue){U&&h(`Failed to load ${xt} ${Ue.message}`),ne=Ue}let ct=process.env;if(v&&v.processEnv!=null&&(ct=v.processEnv),C.populate(ct,le,v),U||!me){const xt=Object.keys(le).length,Ue=[];for(const Bi of V)try{const jn=e.relative(process.cwd(),Bi);Ue.push(jn)}catch(jn){U&&h(`Failed to load ${Bi} ${jn.message}`),ne=jn}u(`injecting env (${xt}) from ${Ue.join(",")}`)}return ne?{parsed:le,error:ne}:{parsed:le}}function E(v){if(d(v).length===0)return C.configDotenv(v);const R=m(v);return R?C._configVault(v):(l(`You set DOTENV_KEY but you are missing a .env.vault file at ${R}. Did you forget to build it?`),C.configDotenv(v))}function T(v,R){const D=Buffer.from(R.slice(-64),"hex");let U=Buffer.from(v,"base64");const me=U.subarray(0,12),V=U.subarray(-16);U=U.subarray(12,-16);try{const ne=s.createDecipheriv("aes-256-gcm",D,me);return ne.setAuthTag(V),`${ne.update(U)}${ne.final()}`}catch(ne){const le=ne instanceof RangeError,ct=ne.message==="Invalid key length",xt=ne.message==="Unsupported state or unable to authenticate data";if(le||ct){const Ue=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw Ue.code="INVALID_DOTENV_KEY",Ue}else if(xt){const Ue=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw Ue.code="DECRYPTION_FAILED",Ue}else throw ne}}function P(v,R,D={}){const U=!!(D&&D.debug),me=!!(D&&D.override);if(typeof R!="object"){const V=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw V.code="OBJECT_REQUIRED",V}for(const V of Object.keys(R))Object.prototype.hasOwnProperty.call(v,V)?(me===!0&&(v[V]=R[V]),U&&h(me===!0?`"${V}" is already defined and WAS overwritten`:`"${V}" is already defined and was NOT overwritten`)):v[V]=R[V]}const C={configDotenv:k,_configVault:w,_parseVault:c,config:E,decrypt:T,parse:a,populate:P};return Pt.exports.configDotenv=C.configDotenv,Pt.exports._configVault=C._configVault,Pt.exports._parseVault=C._parseVault,Pt.exports.config=C.config,Pt.exports.decrypt=C.decrypt,Pt.exports.parse=C.parse,Pt.exports.populate=C.populate,Pt.exports=C,Pt.exports}const lE="4.1.0",hE={version:lE};var da,dd;function uE(){if(dd)return da;dd=1;const t=Jn,e=Jn,n=cE(),{version:s}=hE,i=".env[.node_env][.local]",r=/\[(\W*\blocal\b\W*)]/g,o=/\[(\W*\b)node_env(\b\W*)]/g;function a(E,T){let P=E;return P=P.replace(r,T&&T.local?"$1":""),P=P.replace(o,T&&T.node_env?`$1${T.node_env}$2`:""),P}function c(E={}){E.debug&&k("listing effective `.env*` files…");const{node_env:T,path:P=process.cwd(),pattern:C=i}=E,v=r.test(C),R={};if(C===i&&(R[".env.defaults"]=".env.defaults"),R[".env"]=a(C),v){const D=a(C,{local:!0});T!=="test"?R[".env.local"]=D:E.debug&&t.existsSync(e.resolve(P,D))&&k('[!] note that `%s` is being skipped for "test" environment',D)}return T&&o.test(C)&&(R[".env.node_env"]=a(C,{node_env:T}),v&&(R[".env.node_env.local"]=a(C,{node_env:T,local:!0}))),[".env.defaults",".env",".env.local",".env.node_env",".env.node_env.local"].reduce((D,U)=>{if(!R[U])return D;const me=e.resolve(P,R[U]);return t.existsSync(me)&&(E.debug&&k(">> %s",me),D.push(me)),D},[])}function l(E,T={}){if(typeof E=="string"){T.debug&&k('parsing "%s"…',E);const P=n.parse(t.readFileSync(E,T.encoding&&{encoding:T.encoding}));return T.debug&&Object.keys(P).forEach(C=>k(">> %s",C)),P}return E.reduce((P,C)=>{const v=l(C,T);return T.debug&&Object.keys(v).filter(R=>P.hasOwnProperty(R)).forEach(R=>k('`%s` is being overwritten by merge from "%s"',R,C)),Object.assign(P,v)},{})}function h(E,T={}){try{const P=l(E,{encoding:T.encoding,debug:T.debug});T.debug&&k("safe-merging parsed environment variables into `process.env`…");for(const C of Object.keys(P))process.env.hasOwnProperty(C)?T.debug&&process.env[C]!==P[C]&&k("environment variable `%s` is predefined and not being overwritten",C):(T.debug&&k(">> process.env.%s",C),process.env[C]=P[C]);return{parsed:P}}catch(P){return y(P,T)}}function u(E,T={}){const P=l(E,T);Object.keys(P).forEach(C=>{process.env[C]===P[C]&&delete process.env[C]})}function d(E={}){if(E.node_env)return E.debug&&k(`operating in "${E.node_env}" environment (set by \`options.node_env\`)`),E.node_env;if(process.env.NODE_ENV)return E.debug&&k(`operating in "${process.env.NODE_ENV}" environment (as per \`process.env.NODE_ENV\`)`),process.env.NODE_ENV;if(E.default_node_env)return E.debug&&k(`operating in "${E.default_node_env}" environment (taken from \`options.default_node_env\`)`),E.default_node_env;E.debug&&k('operating in "no environment" mode (no environment-related options are set)')}const p=["node_env","default_node_env","path","pattern","files","encoding","purge_dotenv","silent"];function m(E={}){E.debug&&(k("initializing…"),p.filter(C=>C in E).forEach(C=>k(`| options.${C} =`,E[C])));const{path:T=process.cwd(),pattern:P=i}=E;if(E.purge_dotenv){E.debug&&k("`options.purge_dotenv` is enabled, unloading potentially pre-loaded `.env`…");const C=e.resolve(T,".env");try{t.existsSync(C)&&u(C,{encoding:E.encoding})}catch(v){!E.silent&&w("unloading failed: ",v)}}try{let C;if(E.files)E.debug&&k("using explicit list of `.env*` files: %s…",E.files.join(", ")),C=E.files.reduce((R,D)=>{const U=e.resolve(T,D);return t.existsSync(U)?R.push(U):E.debug&&k(">> %s does not exist, skipping…",U),R},[]);else{const R=d(E);if(C=c({node_env:R,path:T,pattern:P,debug:E.debug}),C.length===0){const D=R?P.replace(o,`[$1${R}$2]`):P;return y(new Error(`no ".env*" files matching pattern "${D}" in "${T}" dir`),E)}}const v=h(C,{encoding:E.encoding,debug:E.debug,silent:E.silent});return E.debug&&k("initialization completed."),v}catch(C){return y(C,E)}}function y(E,T){return T.silent||w(`".env*" files loading failed: ${E.message||E}`),{error:E}}function w(E,T){T&&(E+=": %s"),console.warn(`[dotenv-flow@${s}]: ${E}`,T)}function k(E,...T){console.debug(`[dotenv-flow@${s}]: ${E}`,...T)}return da={DEFAULT_PATTERN:i,listFiles:c,parse:l,load:h,unload:u,config:m},da}var dE=uE();const fE=nE(dE),fa={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_IS_DEV:"0",VITE_LOCAL_URL:"http://localhost:5001",VITE_SERVERLESS_URL:"https://backendv2-dev.nervoscan.com",VITE_SERVER_URL:"https://backend.nervoscan.com"};var Ld;typeof process<"u"&&process.env&&((Ld=process.versions)!=null&&Ld.node)&&fE.config();const zi=t=>typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Zn&&Zn.tagName.toUpperCase()==="SCRIPT"&&Zn.src||new URL("nervoscan-js-sdk.cjs",document.baseURI).href}<"u"&&fa&&t in fa?fa[t]||"":typeof process<"u"&&process.env&&t in process.env?process.env[t]||"":(q.throwKnownError(O.EnvIncompatibleError),""),xo=t=>zi("VITE_IS_DEV")==="1"?zi("VITE_LOCAL_URL"):zi(t==="serverless"?"VITE_SERVERLESS_URL":"VITE_SERVER_URL"),pE=t=>{let e=t.reduce((n,s)=>[n[0]+s[0],n[1]+s[1]],[0,0]);return e=[e[0]/t.length,e[1]/t.length],t.slice().sort((n,s)=>{const i=Math.atan2(n[1]-e[1],n[0]-e[0]),r=Math.atan2(s[1]-e[1],s[0]-e[0]);return i-r})},mE=["bigForehead","smallForehead","leftCheek","rightCheek","cheeksNose","face"];function gE(){return{r:[],g:[],b:[],timestamps:[]}}function fd(){return Object.fromEntries(mE.map(t=>[t,gE()]))}function wn(t,e){if(!(e.length<3)){t.beginPath(),t.moveTo(e[0][0],e[0][1]);for(let n=1;n<e.length;n++)t.lineTo(e[n][0],e[n][1]);t.closePath(),t.stroke()}}function bn(t,e,n,s,i){const r=t[e],o=(s-i)/1e3;if(r.timestamps.length>0){const a=r.timestamps[r.timestamps.length-1];if(o<=a){f.warn(`Timestamp inconsistency detected in ${e}: ${o} <= ${a}`);return}}r.r.push(n[0]),r.g.push(n[1]),r.b.push(n[2]),r.timestamps.push(o)}function $t(t,e,n,s,i){if(!t||t.length<3)return 0;let r=0;const o=t.length;for(let a=0;a<o;a++){const c=(a+1)%o;r+=t[a][0]*t[c][1],r-=t[c][0]*t[a][1]}return Math.abs(r)/2}function pa(t,e,n,s,i){let r="ALIGNED";const u=s/640,d=i/480,p=u*d,m=19e3*p,y=5e4*p,w=800*p;return t<m?r="TOO_FAR":t>y?r="TOO_CLOSE":e<w?r="LOOKING_RIGHT":n<w&&(r="LOOKING_LEFT"),r}const _E=[[67,109],[109,10],[10,338],[338,297],[66,107],[107,9],[9,336],[336,296],[67,69],[69,66],[297,299],[299,296]],yE=[[109,10],[10,338],[338,337],[337,151],[151,108],[108,109]],vE=[[345,352],[352,376],[376,433],[433,416],[416,436],[436,426],[426,423],[423,266],[266,330],[330,347],[347,346],[346,345]],EE=[[116,123],[123,147],[147,213],[213,192],[192,216],[216,206],[206,203],[203,36],[36,101],[101,118],[118,117],[117,116]],wE=[[118,50],[50,216],[216,2],[2,436],[436,280],[280,347],[347,6],[6,118]],bE=[[103,67],[67,109],[109,10],[10,338],[338,297],[297,332],[332,298],[298,300],[300,383],[383,372],[372,345],[345,352],[352,411],[411,427],[427,436],[436,322],[322,2],[2,92],[92,216],[216,207],[207,187],[187,123],[123,116],[116,143],[143,156],[156,70],[70,68],[68,103]];function Os(t){const e=new Set;for(const n of t)e.add(n[0]),e.add(n[1]);return Array.from(e)}const pd=Os(_E),md=Os(yE),Ki=Os(vE),Yi=Os(EE),gd=Os(wE),ma=Os(bE);class CE{constructor(){_(this,"wasmUrl","https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm");_(this,"modelUrl","https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task");_(this,"faceLandmarker");_(this,"canvasCtx");_(this,"video");_(this,"videoWidth");_(this,"canvas");_(this,"rgbDataBuffer");_(this,"alignmentStatusCallback");_(this,"startTimeMs",0);_(this,"backendRepository");_(this,"isDetectionActive",!1);_(this,"tempCanvas");_(this,"tempCanvasCtx");_(this,"mediaPipeTimestamp",0);_(this,"lastVideoTime",0);_(this,"videoTimeOffset",0);_(this,"timestampAdjustmentCount",0);_(this,"dataCollectionThreshold",500);_(this,"batchCount",0);_(this,"totalFramesProcessed",0);_(this,"isStreamingActive",!1);_(this,"pendingResults",[]);_(this,"finalResultsCallback");_(this,"mediaPipeTimingData",{canvasSetup:[],mlDetection:[],canvasOps:[],landmarkDraw:[],roiCoords:[],contourDraw:[],rgbCalc:[],dataStorage:[],alignment:[]});_(this,"faceDetectionLoop",async()=>{let e=0,n=0,s=1/0,i=0;const r=async()=>{if(!this.isDetectionActive){if(e>0){const l=n/e,h=1e3/l,u=1e3/i,d=1e3/s;f.log("=== FACE DETECTION PERFORMANCE SUMMARY ==="),f.log(`Total detection frames: ${e}`),f.log(`Average detection FPS: ${h.toFixed(1)} fps (${l.toFixed(2)}ms per frame)`),f.log(`Min detection FPS: ${u.toFixed(1)} fps (worst performance)`),f.log(`Max detection FPS: ${d.toFixed(1)} fps (best performance)`),f.log(`Detection FPS range: ${(d-u).toFixed(1)} fps variation`),f.log("==========================================")}return}const o=performance.now();try{await this.predictAlignmentOnly()}catch(l){f.warn("Face detection error:",l)}const c=performance.now()-o;if(e++,n+=c,c<s&&(s=c),c>i&&(i=c),e%10===0){const l=n/e,h=1e3/c,u=1e3/l;f.log(`Detection Frame ${e}: ${h.toFixed(1)} fps (avg: ${u.toFixed(1)} fps)`)}setTimeout(r,100)};r()});this.videoWidth=640}calculateTimingStats(e){if(e.length===0)return{min:0,max:0,avg:0,total:0};const n=Math.min(...e),s=Math.max(...e),i=e.reduce((o,a)=>o+a,0),r=i/e.length;return{min:n,max:s,avg:r,total:i}}getTimingBreakdown(){return{canvasSetup:this.calculateTimingStats(this.mediaPipeTimingData.canvasSetup),mlDetection:this.calculateTimingStats(this.mediaPipeTimingData.mlDetection),canvasOps:this.calculateTimingStats(this.mediaPipeTimingData.canvasOps),landmarkDraw:this.calculateTimingStats(this.mediaPipeTimingData.landmarkDraw),roiCoords:this.calculateTimingStats(this.mediaPipeTimingData.roiCoords),contourDraw:this.calculateTimingStats(this.mediaPipeTimingData.contourDraw),rgbCalc:this.calculateTimingStats(this.mediaPipeTimingData.rgbCalc),dataStorage:this.calculateTimingStats(this.mediaPipeTimingData.dataStorage),alignment:this.calculateTimingStats(this.mediaPipeTimingData.alignment)}}resetTimingData(){this.mediaPipeTimingData={canvasSetup:[],mlDetection:[],canvasOps:[],landmarkDraw:[],roiCoords:[],contourDraw:[],rgbCalc:[],dataStorage:[],alignment:[]}}setStartTimeMs(e){this.startTimeMs=e}setDataCollectionThreshold(e){if(e<=0)throw new Error("Data collection threshold must be greater than 0");this.dataCollectionThreshold=e,f.log(`[RGB Processing] Data collection threshold set to ${e} points`)}startContinuousDataCollection(e,n){f.log(`[FaceLandmarker] startContinuousDataCollection called with apiKey: ${e}`),this.isStreamingActive=!0,this.batchCount=0,this.totalFramesProcessed=0,this.pendingResults=[],this.finalResultsCallback=n,f.log(`[FaceLandmarker] Starting continuous data collection with threshold: ${this.dataCollectionThreshold}`),f.log(`[FaceLandmarker] isStreamingActive set to: ${this.isStreamingActive}`)}stopContinuousDataCollection(){this.isStreamingActive=!1,f.log(`[FaceLandmarker] Stopping continuous data collection. Processed ${this.totalFramesProcessed} frames in ${this.batchCount} batches`),this.pendingResults.length>0&&this.aggregateFinalResults()}isContinuousDataCollectionActive(){return this.isStreamingActive}getDataCollectionStats(){return{batchCount:this.batchCount,totalFramesProcessed:this.totalFramesProcessed,pendingResults:this.pendingResults.length}}async initialize(e,n){if(this.backendRepository=n,await this.createFaceLandmarker(),this.video=e,this.canvas=document.createElement("canvas"),this.canvas.width=e.videoWidth||640,this.canvas.height=e.videoHeight||480,f.log(`[RGB Processing] Initial resolution: ${this.canvas.width}x${this.canvas.height} (fallback: 640x480)`),this.canvasCtx=this.canvas.getContext("2d"),!this.canvasCtx)throw new Error("Failed to get canvas context");this.tempCanvas=document.createElement("canvas"),this.tempCanvas.width=e.videoWidth||640,this.tempCanvas.height=e.videoHeight||480,this.tempCanvasCtx=this.tempCanvas.getContext("2d"),this.rgbDataBuffer=fd(),this.resetTimingData()}ensureCanvasDimensions(){if(!this.video)return;const e=this.video.videoWidth,n=this.video.videoHeight;e>0&&n>0&&((this.canvas.width!==e||this.canvas.height!==n)&&(f.log(`[RGB Processing] Canvas resolution updated: ${this.canvas.width}x${this.canvas.height} -> ${e}x${n}`),this.canvas.width=e,this.canvas.height=n),(this.tempCanvas.width!==e||this.tempCanvas.height!==n)&&(this.tempCanvas.width=e,this.tempCanvas.height=n))}setAlignmentStatusCallback(e){this.alignmentStatusCallback=e}startFaceDetection(){this.isDetectionActive=!0,this.faceDetectionLoop()}stopFaceDetection(){this.isDetectionActive=!1}isFaceDetectionActive(){return this.isDetectionActive}generateMediaPipeTimestamp(){if(!this.video)return this.mediaPipeTimestamp;const e=this.video.currentTime;e<this.lastVideoTime&&(this.videoTimeOffset+=this.lastVideoTime,f.log(`Video time reset detected. New offset: ${this.videoTimeOffset.toFixed(3)}s`));const n=(e+this.videoTimeOffset)*1e3;if(n<=this.mediaPipeTimestamp){const s=this.mediaPipeTimestamp+1;this.timestampAdjustmentCount++,this.timestampAdjustmentCount%100===0&&f.log(`MediaPipe timestamp adjusted: ${n.toFixed(1)} -> ${s.toFixed(1)} (adjustment #${this.timestampAdjustmentCount})`),this.mediaPipeTimestamp=s}else this.mediaPipeTimestamp=n;return this.lastVideoTime=e,this.mediaPipeTimestamp}resetMediaPipeTimestamps(){const e=this.mediaPipeTimestamp,n=this.timestampAdjustmentCount;this.mediaPipeTimestamp=0,this.lastVideoTime=0,this.videoTimeOffset=0,this.timestampAdjustmentCount=0,f.log(`MediaPipe timestamps reset for fresh initialization (was: ${e}ms, adjustments: ${n})`)}getMediaPipeTimestampInfo(){return{current:this.mediaPipeTimestamp,lastVideo:this.lastVideoTime,offset:this.videoTimeOffset}}async createFaceLandmarker(){const e=await Sn.forVisionTasks(this.wasmUrl);this.faceLandmarker=await X.createFromOptions(e,{baseOptions:{modelAssetPath:this.modelUrl,delegate:"GPU"},outputFaceBlendshapes:!1,runningMode:"VIDEO",numFaces:1})}getLandmarkCoordinates(e,n,s,i){const r=[];for(const o of n)if(e[0]&&o<e[0].length){const a=e[0][o];r.push([Math.round(a.x*s),Math.round(a.y*i)])}return r.length>0?pE(r):[]}detect(e){return this.faceLandmarker||q.throwKnownError(O.FaceLandmarkerNotInitializedError),this.faceLandmarker.detectForVideo(e,performance.now())}calculateRgbMean(e,n,s,i){if(e.length<3)return[0,0,0];if(s<=0||i<=0)return[0,0,0];const r=this.getBoundingBox(e),o=Math.max(0,Math.floor(r.minX)),a=Math.min(s-1,Math.ceil(r.maxX)),c=Math.max(0,Math.floor(r.minY)),l=Math.min(i-1,Math.ceil(r.maxY));if(o>=a||c>=l)return[0,0,0];let h=0,u=0,d=0,p=0;for(let m=c;m<=l;m++)for(let y=o;y<=a;y++)if(this.isPointInPolygon(y,m,e)){const w=(m*s+y)*4;u+=n.data[w],d+=n.data[w+1],p+=n.data[w+2],h++}return h>0?(u=Math.round(u/h),d=Math.round(d/h),p=Math.round(p/h),[u,d,p]):[0,0,0]}getBoundingBox(e){let n=1/0,s=-1/0,i=1/0,r=-1/0;for(const[o,a]of e)o<n&&(n=o),o>s&&(s=o),a<i&&(i=a),a>r&&(r=a);return{minX:n,maxX:s,minY:i,maxY:r}}isPointInPolygon(e,n,s){let i=!1;const r=s.length;for(let o=0,a=r-1;o<r;a=o++){const c=s[o][0],l=s[o][1],h=s[a][0],u=s[a][1];l>n!=u>n&&e<(h-c)*(n-l)/(u-l)+c&&(i=!i)}return i}async predictAlignmentOnly(){if(!this.canvasCtx||!this.video||!this.video.videoWidth||!this.video.videoHeight||this.video.readyState<2||(this.ensureCanvasDimensions(),!this.faceLandmarker))return;const e=this.generateMediaPipeTimestamp();let n;try{n=this.faceLandmarker.detectForVideo(this.video,e)}catch(s){if(s instanceof Error&&s.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error detected, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{n=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(i){f.error("MediaPipe recovery failed, skipping frame:",i);return}}else throw s}if(n.faceLandmarks&&n.faceLandmarks.length>0){const s=this.getLandmarkCoordinates(n.faceLandmarks,ma,this.video.videoWidth,this.video.videoHeight),i=this.getLandmarkCoordinates(n.faceLandmarks,Ki,this.video.videoWidth,this.video.videoHeight),r=this.getLandmarkCoordinates(n.faceLandmarks,Yi,this.video.videoWidth,this.video.videoHeight),o=$t(s,this.video.videoWidth,this.video.videoHeight),a=$t(i,this.video.videoWidth,this.video.videoHeight),c=$t(r,this.video.videoWidth,this.video.videoHeight),l=pa(o,a,c,this.video.videoWidth,this.video.videoHeight);this.alignmentStatusCallback&&this.alignmentStatusCallback(l)}else this.alignmentStatusCallback&&this.alignmentStatusCallback("NO_FACE")}async predictFromCanvas(e,n,s){this.stopFaceDetection();const i=this.checkDataCollectionStatus(n);if(!this.canvasCtx)throw new Error("Canvas context not initialized");this.ensureCanvasDimensionsForCanvas(e);const r=new Pe(this.canvasCtx),o=e.height/e.width;this.canvas.style.width=this.videoWidth+"px",this.canvas.style.height=this.videoWidth*o+"px",this.canvas.width=e.width,this.canvas.height=e.height,this.faceLandmarker||q.throwKnownError(O.FaceLandmarkerNotInitializedError);const a=this.generateMediaPipeTimestamp();let c;try{c=this.faceLandmarker.detectForVideo(this.video,a)}catch(l){if(l instanceof Error&&l.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error in predictFromCanvas, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{c=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(h){return f.error("MediaPipe recovery failed in predictFromCanvas, skipping frame:",h),i}}else return f.error("MediaPipe canvas detection error:",l),i}if(this.canvasCtx.clearRect(0,0,this.canvas.width,this.canvas.height),c.faceLandmarks&&c.faceLandmarks.length>0){const l=s;this.rgbDataBuffer.bigForehead.r.length%100===0&&f.log(`[RGB Canvas Processing] Processing frame at resolution: ${e.width}x${e.height}`);const h=e.getContext("2d");if(!h)throw new Error("Unable to get canvas context");const u=h.getImageData(0,0,e.width,e.height);this.drawFaceLandmarks(r,c.faceLandmarks);const d=this.getLandmarkCoordinates(c.faceLandmarks,pd,e.width,e.height),p=this.getLandmarkCoordinates(c.faceLandmarks,md,e.width,e.height),m=this.getLandmarkCoordinates(c.faceLandmarks,Ki,e.width,e.height),y=this.getLandmarkCoordinates(c.faceLandmarks,Yi,e.width,e.height),w=this.getLandmarkCoordinates(c.faceLandmarks,gd,e.width,e.height);await this.processROIData(d,"bigForehead",u,l),await this.processROIData(p,"smallForehead",u,l),await this.processROIData(m,"leftCheek",u,l),await this.processROIData(y,"rightCheek",u,l),await this.processROIData(w,"cheeksNose",u,l)}return i}async predictAlignmentFromCanvas(e){if(!this.canvasCtx||!e.width||!e.height||!this.faceLandmarker)return;const n=this.generateMediaPipeTimestamp();let s;try{s=this.faceLandmarker.detectForVideo(this.video,n)}catch(i){if(i instanceof Error&&i.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error in alignment detection, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{s=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(r){f.error("MediaPipe recovery failed in alignment detection:",r);return}}else{f.error("MediaPipe canvas alignment detection error:",i);return}}if(s.faceLandmarks&&s.faceLandmarks.length>0){const i=this.getLandmarkCoordinates(s.faceLandmarks,ma,e.width,e.height),r=this.getLandmarkCoordinates(s.faceLandmarks,Ki,e.width,e.height),o=this.getLandmarkCoordinates(s.faceLandmarks,Yi,e.width,e.height),a=$t(i,e.width,e.height),c=$t(r,e.width,e.height),l=$t(o,e.width,e.height),h=pa(a,c,l,e.width,e.height);this.alignmentStatusCallback&&this.alignmentStatusCallback(h)}else this.alignmentStatusCallback&&this.alignmentStatusCallback("NO_FACE")}async predict(e,n){performance.now(),this.stopFaceDetection(),this.rgbDataBuffer.bigForehead.r.length%100===0&&f.log(`[RGB Processing] predict() called - isStreamingActive: ${this.isStreamingActive}, buffer: ${this.rgbDataBuffer.bigForehead.r.length}/${this.dataCollectionThreshold}`);const s=this.checkDataCollectionStatus(e);if(!this.canvasCtx||!this.video)throw new Error("Not initialized");const i=performance.now();this.ensureCanvasDimensions();const r=new Pe(this.canvasCtx),o=this.video.videoHeight/this.video.videoWidth;this.canvas.style.width=this.videoWidth+"px",this.canvas.style.height=this.videoWidth*o+"px",this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight;const a=performance.now()-i;this.faceLandmarker||q.throwKnownError(O.FaceLandmarkerNotInitializedError);const c=this.generateMediaPipeTimestamp(),l=performance.now();let h;try{h=this.faceLandmarker.detectForVideo(this.video,c)}catch(p){if(p instanceof Error&&p.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error in predict, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{h=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(m){return f.error("MediaPipe recovery failed in predict, skipping frame:",m),s}}else throw p}const u=performance.now()-l,d=performance.now();if(this.canvasCtx.clearRect(0,0,this.canvas.width,this.canvas.height),h.faceLandmarks&&h.faceLandmarks.length>0){const p=n||this.video.currentTime*1e3;this.rgbDataBuffer.bigForehead.r.length%100===0&&f.log(`[RGB Processing] Processing frame at resolution: ${this.video.videoWidth}x${this.video.videoHeight}`),this.tempCanvasCtx.clearRect(0,0,this.tempCanvas.width,this.tempCanvas.height),this.tempCanvasCtx.drawImage(this.video,0,0,this.tempCanvas.width,this.tempCanvas.height);const m=this.tempCanvasCtx.getImageData(0,0,this.tempCanvas.width,this.tempCanvas.height),y=performance.now()-d,w=performance.now();this.drawFaceLandmarks(r,h.faceLandmarks);const k=performance.now()-w;this.mediaPipeTimingData.landmarkDraw.push(k);const E=performance.now(),T=this.getLandmarkCoordinates(h.faceLandmarks,pd,this.video.videoWidth,this.video.videoHeight),P=this.getLandmarkCoordinates(h.faceLandmarks,md,this.video.videoWidth,this.video.videoHeight),C=this.getLandmarkCoordinates(h.faceLandmarks,Ki,this.video.videoWidth,this.video.videoHeight),v=this.getLandmarkCoordinates(h.faceLandmarks,Yi,this.video.videoWidth,this.video.videoHeight),R=this.getLandmarkCoordinates(h.faceLandmarks,gd,this.video.videoWidth,this.video.videoHeight),D=this.getLandmarkCoordinates(h.faceLandmarks,ma,this.video.videoWidth,this.video.videoHeight),U=performance.now()-E;this.mediaPipeTimingData.roiCoords.push(U);const me=performance.now();this.canvasCtx.strokeStyle="rgba(255, 255, 255, 0.7)",this.canvasCtx.lineWidth=1,wn(this.canvasCtx,T),wn(this.canvasCtx,P),wn(this.canvasCtx,C),wn(this.canvasCtx,v),wn(this.canvasCtx,R),wn(this.canvasCtx,D);const V=performance.now()-me;this.mediaPipeTimingData.contourDraw.push(V);const ne=performance.now(),le=this.calculateRgbMean(T,m,this.video.videoWidth,this.video.videoHeight),ct=this.calculateRgbMean(P,m,this.video.videoWidth,this.video.videoHeight),xt=this.calculateRgbMean(C,m,this.video.videoWidth,this.video.videoHeight),Ue=this.calculateRgbMean(v,m,this.video.videoWidth,this.video.videoHeight),Bi=this.calculateRgbMean(R,m,this.video.videoWidth,this.video.videoHeight),jn=this.calculateRgbMean(D,m,this.video.videoWidth,this.video.videoHeight),S1=performance.now()-ne;this.mediaPipeTimingData.rgbCalc.push(S1);const k1=performance.now();s&&(bn(this.rgbDataBuffer,"bigForehead",le,p,this.startTimeMs),bn(this.rgbDataBuffer,"smallForehead",ct,p,this.startTimeMs),bn(this.rgbDataBuffer,"leftCheek",xt,p,this.startTimeMs),bn(this.rgbDataBuffer,"rightCheek",Ue,p,this.startTimeMs),bn(this.rgbDataBuffer,"cheeksNose",Bi,p,this.startTimeMs),bn(this.rgbDataBuffer,"face",jn,p,this.startTimeMs));const A1=performance.now()-k1;this.mediaPipeTimingData.dataStorage.push(A1);const R1=performance.now(),I1=$t(D,this.video.videoWidth,this.video.videoHeight),x1=$t(C,this.video.videoWidth,this.video.videoHeight),F1=$t(v,this.video.videoWidth,this.video.videoHeight),N1=pa(I1,x1,F1,this.video.videoWidth,this.video.videoHeight);this.alignmentStatusCallback&&this.alignmentStatusCallback(N1);const D1=performance.now()-R1;this.mediaPipeTimingData.alignment.push(D1),this.mediaPipeTimingData.canvasSetup.push(a),this.mediaPipeTimingData.mlDetection.push(u),this.mediaPipeTimingData.canvasOps.push(y)}else this.alignmentStatusCallback&&this.alignmentStatusCallback("NO_FACE");return s}drawFaceLandmarks(e,n){for(const s of n)e.drawConnectors(s,X.FACE_LANDMARKS_TESSELATION,{color:"#C0C0C070",lineWidth:1}),e.drawConnectors(s,X.FACE_LANDMARKS_RIGHT_EYE,{color:"#FF3030"}),e.drawConnectors(s,X.FACE_LANDMARKS_RIGHT_EYEBROW,{color:"#FF3030"}),e.drawConnectors(s,X.FACE_LANDMARKS_LEFT_EYE,{color:"#30FF30"}),e.drawConnectors(s,X.FACE_LANDMARKS_LEFT_EYEBROW,{color:"#30FF30"}),e.drawConnectors(s,X.FACE_LANDMARKS_FACE_OVAL,{color:"#E0E0E0"}),e.drawConnectors(s,X.FACE_LANDMARKS_LIPS,{color:"#E0E0E0"}),e.drawConnectors(s,X.FACE_LANDMARKS_RIGHT_IRIS,{color:"#FF3030"}),e.drawConnectors(s,X.FACE_LANDMARKS_LEFT_IRIS,{color:"#30FF30"})}checkDataCollectionStatus(e){var s,i,r,o;let n=!0;return this.rgbDataBuffer.bigForehead.r.length>=this.dataCollectionThreshold?(this.batchCount++,this.totalFramesProcessed+=this.rgbDataBuffer.bigForehead.r.length,f.log(`[RGB Processing] Sending batch ${this.batchCount} with ${this.dataCollectionThreshold} points and resolution: ${((s=this.video)==null?void 0:s.videoWidth)||0}x${((i=this.video)==null?void 0:i.videoHeight)||0}`),f.log(`[RGB Processing] Total frames processed: ${this.totalFramesProcessed}`),f.log(`[RGB Processing] isStreamingActive: ${this.isStreamingActive}`),this.backendRepository.sendRgbDataToBackend(this.rgbDataBuffer,((r=this.video)==null?void 0:r.videoWidth)||0,((o=this.video)==null?void 0:o.videoHeight)||0,e),this.resetDataBuffer(),this.isStreamingActive?(n=!0,f.log(`[RGB Processing] Continuing data collection for batch ${this.batchCount+1}`)):(n=!1,f.log("[RGB Processing] Stopping data collection (legacy mode)"))):this.rgbDataBuffer.bigForehead.r.length%50===0&&f.log(`[RGB Processing] Buffer status: ${this.rgbDataBuffer.bigForehead.r.length}/${this.dataCollectionThreshold} frames collected`),this.rgbDataBuffer.bigForehead.r.length>=this.dataCollectionThreshold&&f.log(`[RGB Processing] checkDataCollectionStatus returning: ${n}`),n}getRGBDataBufferSize(){var e,n,s;return((s=(n=(e=this.rgbDataBuffer)==null?void 0:e.bigForehead)==null?void 0:n.r)==null?void 0:s.length)||0}getDataCollectionThreshold(){return this.dataCollectionThreshold}getRGBTimestamps(){var e,n;return((n=(e=this.rgbDataBuffer)==null?void 0:e.bigForehead)==null?void 0:n.timestamps)||[]}isDetectionCurrentlyActive(){return this.isDetectionActive}aggregateFinalResults(){if(this.pendingResults.length===0){f.warn("[FaceLandmarker] No pending results to aggregate");return}f.log(`[FaceLandmarker] Aggregating ${this.pendingResults.length} batch results`);const e={},n=["HR","RR","SDNN","SPO2","DBP","SBP","GLUCOSE","HEMOGLOBIN","AGE","HEALTHSCORE","PNN50","RMSSD"];for(const s of n){const i=this.pendingResults.map(r=>r[s]).filter(r=>r!=null&&!isNaN(r));if(i.length>0){const r=i.reduce((o,a)=>o+a,0)/i.length;e[s]=Math.round(r*100)/100}}e.batchCount=this.batchCount,e.totalFramesProcessed=this.totalFramesProcessed,e.aggregatedFrom=this.pendingResults.length,f.log("[FaceLandmarker] Final aggregated results:",e),this.finalResultsCallback&&this.finalResultsCallback(e)}handleBatchResults(e){if(!this.isStreamingActive){f.warn("[FaceLandmarker] Received batch results but continuous collection is not active");return}f.log(`[FaceLandmarker] Received results for batch ${this.pendingResults.length+1}:`,e),this.pendingResults.push(e),f.log(`[FaceLandmarker] Added batch ${this.pendingResults.length} to pending results. Total pending: ${this.pendingResults.length}`)}resetDataBuffer(){this.rgbDataBuffer=fd()}ensureCanvasDimensionsForCanvas(e){(this.tempCanvas.width!==e.width||this.tempCanvas.height!==e.height)&&(this.tempCanvas.width=e.width,this.tempCanvas.height=e.height)}async processROIData(e,n,s,i){const r=this.calculateRgbMean(e,s,s.width,s.height);bn(this.rgbDataBuffer,n,r,i,this.startTimeMs),this.canvasCtx&&wn(this.canvasCtx,e)}}var Wr=(t=>(t.LEGACY="legacy",t))(Wr||{});class TE{constructor(){_(this,"targetFPS",30);_(this,"frameInterval",1e3/30);_(this,"isCapturing",!1);_(this,"frameCallback",null);_(this,"lastFrameTime",0);_(this,"framesProcessed",0);_(this,"framesSkipped",0)}setTargetFPS(e){this.targetFPS=Math.max(1,Math.min(120,e)),this.frameInterval=1e3/this.targetFPS}getTargetFPS(){return this.targetFPS}isActive(){return this.isCapturing}resetFrameCounters(){this.framesProcessed=0,this.framesSkipped=0,this.lastFrameTime=0}shouldCaptureFrame(e){return e-this.lastFrameTime>=this.frameInterval}updateFrameTime(e){this.lastFrameTime=e}}class SE extends TE{constructor(){super(...arguments);_(this,"videoElement",null);_(this,"canvas",null);_(this,"context",null);_(this,"captureLoop",null)}async initialize(n){if(this.videoElement=n,await this.waitForVideoReady(),this.canvas=document.createElement("canvas"),this.canvas.width=n.videoWidth||640,this.canvas.height=n.videoHeight||480,this.context=this.canvas.getContext("2d"),!this.context)throw new Error("Failed to get 2D canvas context");f.log("[LegacyCanvasCapture] Initialized:",{width:this.canvas.width,height:this.canvas.height,videoReady:n.readyState})}async waitForVideoReady(){return new Promise(n=>{if(this.videoElement&&this.videoElement.readyState>=2){n();return}const s=()=>{this.videoElement&&this.videoElement.readyState>=2?n():setTimeout(s,50)};s()})}async startCapture(n){this.frameCallback=n,this.isCapturing=!0,this.resetFrameCounters(),this.lastFrameTime=performance.now(),this.startCaptureLoop(),f.log(`[LegacyCanvasCapture] Started capture at ${this.targetFPS} FPS`)}startCaptureLoop(){const n=()=>{if(!this.isCapturing){this.captureLoop=null;return}const s=performance.now();if(this.shouldCaptureFrame(s)){this.framesProcessed++;try{this.captureCurrentFrame(s),this.updateFrameTime(s)}catch(i){f.error("[LegacyCanvasCapture] Frame capture error:",i)}}else this.framesSkipped++;this.isCapturing&&(this.captureLoop=requestAnimationFrame(n))};this.captureLoop=requestAnimationFrame(n)}captureCurrentFrame(n){if(!this.videoElement||!this.canvas||!this.context||!this.isCapturing)return;if(this.videoElement.readyState<2){f.warn("[LegacyCanvasCapture] Video not ready for capture");return}this.context.drawImage(this.videoElement,0,0,this.canvas.width,this.canvas.height);const i={imageData:this.context.getImageData(0,0,this.canvas.width,this.canvas.height),timestamp:n,videoTime:this.videoElement.currentTime,width:this.canvas.width,height:this.canvas.height,quality:1};this.frameCallback&&this.frameCallback(i)}stopCapture(){this.isCapturing=!1,this.frameCallback=null,this.captureLoop&&(cancelAnimationFrame(this.captureLoop),this.captureLoop=null);const n=this.framesProcessed+this.framesSkipped,s=n>0?(this.framesSkipped/n*100).toFixed(1):"0";f.log(`🎯 [LegacyCanvasCapture] Capture stopped - Processed: ${this.framesProcessed}, Skipped: ${this.framesSkipped}, Skip rate: ${s}%`)}cleanup(){this.stopCapture(),this.canvas=null,this.context=null,this.videoElement=null}}function kE(t){return{method:"legacy",capture:new SE}}const kn=class kn{constructor(){_(this,"faceLandmarker");_(this,"isCollectingData",!1);_(this,"mediaStream");_(this,"videoElement");_(this,"backendRepository");_(this,"apiKey","");_(this,"onDisconnection",()=>{});_(this,"onAlignmentStatus");_(this,"frameCapture",null);_(this,"captureMethod",Wr.LEGACY);_(this,"config",{targetFPS:30,captureMethod:Wr.LEGACY,minFrameQuality:0,enableQualityControl:!0,enableFrameValidation:!0});_(this,"frameCount",0);_(this,"totalFrameCount",0);_(this,"droppedFrames",0);_(this,"qualityDrops",0);_(this,"duplicateFrames",0);_(this,"startTime",0);_(this,"frameTimes",[]);_(this,"qualityBuffer",[]);_(this,"lastFrameTimestamp",0);_(this,"lastVideoTime",0);_(this,"maxQualityBufferSize",30);_(this,"maxFrameTimesSize",100);_(this,"minFrameTimeDelta",.001);_(this,"timingData",{validation:[],qualityCheck:[],mediaPipe:[],totalFrame:[]});_(this,"frameIntervals",[]);_(this,"lastFrameProcessTime",0);_(this,"isContinuousMode",!1);_(this,"videoEndDetectionEnabled",!1);_(this,"noFrameTimeout",5e3);_(this,"lastFrameReceivedTime",0);_(this,"videoEndCheckInterval",null);_(this,"onVideoEnd");_(this,"continuousModeCallback")}static getInstance(){return kn.instance||(kn.instance=new kn),kn.instance}async initialize(e,n,s,i,r={}){this.config={...this.config,...r},this.backendRepository=s,this.mediaStream=e,this.videoElement=n,this.videoElement.srcObject=e,this.onDisconnection=i,this.faceLandmarker=new CE,this.faceLandmarker.setDataCollectionThreshold(300),await this.faceLandmarker.initialize(this.videoElement,this.backendRepository),this.onAlignmentStatus&&this.faceLandmarker.setAlignmentStatusCallback(this.onAlignmentStatus),await this.initializeFrameCapture(),f.log("[RGBManager] Initialized with configuration:",this.config),f.log(`[RGBManager] Video resolution: ${n.videoWidth}x${n.videoHeight}`),f.log(`[RGBManager] Using capture method: ${this.captureMethod}`)}async initializeFrameCapture(){try{const{method:e,capture:n}=kE(this.config.captureMethod);this.captureMethod=e,this.frameCapture=n,this.frameCapture.setTargetFPS(this.config.targetFPS),await this.frameCapture.initialize(this.videoElement),f.log(`[RGBManager] Frame capture initialized: ${e}`)}catch(e){throw f.error("[RGBManager] Frame capture initialization failed:",e),e}}startFaceDetection(){this.faceLandmarker&&(f.log("[RGBManager] Starting face detection for alignment feedback..."),this.faceLandmarker.startFaceDetection())}stopFaceDetection(){this.faceLandmarker&&(f.log("[RGBManager] Stopping face detection..."),this.faceLandmarker.stopFaceDetection())}setAlignmentStatusCallback(e){this.onAlignmentStatus=e,this.faceLandmarker&&this.faceLandmarker.setAlignmentStatusCallback(e)}async startStreaming(e){if(!this.frameCapture)throw new Error("Frame capture not initialized");this.isCollectingData=!0,this.apiKey=e,this.resetStatistics(),f.log(`[RGBManager] Starting RGB streaming with ${this.captureMethod}`),f.log(`[RGBManager] Target FPS: ${this.config.targetFPS}, Quality control: ${this.config.enableQualityControl}`),this.faceLandmarker.setStartTimeMs(performance.now()),this.isContinuousMode&&this.faceLandmarker&&this.continuousModeCallback&&(f.log("[RGBManager] Starting continuous data collection with apiKey:",e),this.faceLandmarker.startContinuousDataCollection(e,this.continuousModeCallback)),await this.frameCapture.startCapture(this.processFrame.bind(this))}resetStatistics(){this.startTime=performance.now(),this.frameCount=0,this.droppedFrames=0,this.qualityDrops=0,this.duplicateFrames=0,this.frameTimes=[],this.qualityBuffer=[],this.lastFrameTimestamp=0,this.lastVideoTime=0,this.timingData={validation:[],qualityCheck:[],mediaPipe:[],totalFrame:[]},this.frameIntervals=[],this.lastFrameProcessTime=0}async processFrame(e){if(!this.isCollectingData)return;this.lastFrameReceivedTime=performance.now();const n=performance.now();if(this.lastFrameProcessTime>0){const s=n-this.lastFrameProcessTime;this.frameIntervals.push(s)}this.lastFrameProcessTime=n;try{const s=performance.now();if(this.config.enableFrameValidation&&!this.validateFrame(e)){const d=performance.now()-s;this.timingData.validation.push(d);return}const i=performance.now()-s;this.timingData.validation.push(i);const r=performance.now();if(this.config.enableQualityControl&&!this.passesQualityControl(e)){this.qualityDrops++;const d=performance.now()-r;this.timingData.qualityCheck.push(d);return}const o=performance.now()-r;this.timingData.qualityCheck.push(o),this.updateFrameStatistics(e);const a=this.generateUnifiedTimestamp(e),c=performance.now(),l=this.isCollectingData;this.isCollectingData=await this.faceLandmarker.predict(this.apiKey,a),l!==this.isCollectingData&&(f.log(`[RGBManager] isCollectingData changed from ${l} to ${this.isCollectingData}`),f.log(`[RGBManager] Continuous mode enabled: ${this.isContinuousMode}`));const h=performance.now()-c;this.timingData.mediaPipe.push(h);const u=performance.now()-n;this.timingData.totalFrame.push(u),this.frameCount%100===0&&f.log(`📊 [Progress] Frame ${this.frameCount} - ${u.toFixed(1)}ms`)}catch(s){const i=performance.now()-n;this.timingData.totalFrame.push(i),f.error(`❌ [Frame ${this.frameCount}] Error after ${i.toFixed(2)}ms:`,s)}}validateFrame(e){if(e.videoTime!==void 0){if(e.videoTime-this.lastVideoTime<this.minFrameTimeDelta)return f.warn("[RGBManager] Duplicate frame detected, skipping"),this.duplicateFrames++,!1;this.lastVideoTime=e.videoTime}return e.timestamp<this.lastFrameTimestamp?(f.warn("[RGBManager] Out-of-order frame detected, skipping"),!1):(this.lastFrameTimestamp=e.timestamp,!0)}passesQualityControl(e){return e.quality===void 0?(f.warn("[RGBManager] No quality info available, skipping"),!0):e.quality<this.config.minFrameQuality?(f.warn("[RGBManager] Frame quality below threshold, skipping"),!1):(this.qualityBuffer.push(e.quality),this.qualityBuffer.length>this.maxQualityBufferSize&&this.qualityBuffer.shift(),!0)}updateFrameStatistics(e){this.frameCount++,this.totalFrameCount++,this.frameTimes.push(e.timestamp),this.frameTimes.length>this.maxFrameTimesSize&&this.frameTimes.shift()}createCanvasFromImageData(e){const n=document.createElement("canvas");n.width=e.width,n.height=e.height;const s=n.getContext("2d");return s&&s.putImageData(e,0,0),n}generateUnifiedTimestamp(e){return e.videoTime!==void 0?e.videoTime*1e3:e.timestamp-this.startTime}logProgress(){var n;const e=this.getFrameStatistics();f.log(`--- Frame ${this.frameCount} Progress ---`),f.log(`Capture: ${this.captureMethod} | Target: ${e.targetFPS} FPS | Actual: ${e.actualFPS.toFixed(1)} FPS`),f.log(`Quality: Avg ${((n=e.averageQuality)==null?void 0:n.toFixed(3))||"N/A"} | Drops: ${e.qualityDrops}`),f.log(`Frames: Processed ${e.frameCount} | Dropped ${e.droppedFrames} | Duplicates ${e.duplicateFrames}`),f.log(`Stability: ${e.temporalStability.toFixed(1)}%`)}stopStreaming(){this.isCollectingData=!1,this.stopVideoEndDetection(),this.frameCapture&&this.frameCapture.stopCapture(),this.isContinuousMode&&this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),this.logFinalStatistics()}calculateTimingStats(e){if(e.length===0)return{min:0,max:0,avg:0,total:0};const n=Math.min(...e),s=Math.max(...e),i=e.reduce((o,a)=>o+a,0),r=i/e.length;return{min:n,max:s,avg:r,total:i}}getDetailedTimingStats(){var n,s;const e=(s=(n=this.faceLandmarker).getTimingBreakdown)==null?void 0:s.call(n);return{validation:this.calculateTimingStats(this.timingData.validation),qualityCheck:this.calculateTimingStats(this.timingData.qualityCheck),mediaPipe:this.calculateTimingStats(this.timingData.mediaPipe),totalFrame:this.calculateTimingStats(this.timingData.totalFrame),mediaPipeBreakdown:e}}logFinalStatistics(){var d;const e=this.getFrameStatistics();if(e.frameCount===0){f.log("[RGBManager] No frames processed - skipping comprehensive analysis");return}const n=this.getDetailedTimingStats();f.log(`
1636
+ `),V=V.replace(/\\r/g,"\r")),R[me]=V}return R}function c(v){v=v||{};const R=m(v);v.path=R;const D=C.configDotenv(v);if(!D.parsed){const ne=new Error(`MISSING_DATA: Cannot parse ${R} for an unknown reason`);throw ne.code="MISSING_DATA",ne}const U=d(v).split(","),me=U.length;let V;for(let ne=0;ne<me;ne++)try{const le=U[ne].trim(),ct=p(D,le);V=C.decrypt(ct.ciphertext,ct.key);break}catch(le){if(ne+1>=me)throw le}return C.parse(V)}function l(v){console.log(`[dotenv@${r}][WARN] ${v}`)}function h(v){console.log(`[dotenv@${r}][DEBUG] ${v}`)}function u(v){console.log(`[dotenv@${r}] ${v}`)}function d(v){return v&&v.DOTENV_KEY&&v.DOTENV_KEY.length>0?v.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function p(v,R){let D;try{D=new URL(R)}catch(le){if(le.code==="ERR_INVALID_URL"){const ct=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw ct.code="INVALID_DOTENV_KEY",ct}throw le}const U=D.password;if(!U){const le=new Error("INVALID_DOTENV_KEY: Missing key part");throw le.code="INVALID_DOTENV_KEY",le}const me=D.searchParams.get("environment");if(!me){const le=new Error("INVALID_DOTENV_KEY: Missing environment part");throw le.code="INVALID_DOTENV_KEY",le}const V=`DOTENV_VAULT_${me.toUpperCase()}`,ne=v.parsed[V];if(!ne){const le=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${V} in your .env.vault file.`);throw le.code="NOT_FOUND_DOTENV_ENVIRONMENT",le}return{ciphertext:ne,key:U}}function m(v){let R=null;if(v&&v.path&&v.path.length>0)if(Array.isArray(v.path))for(const D of v.path)t.existsSync(D)&&(R=D.endsWith(".vault")?D:`${D}.vault`);else R=v.path.endsWith(".vault")?v.path:`${v.path}.vault`;else R=e.resolve(process.cwd(),".env.vault");return t.existsSync(R)?R:null}function y(v){return v[0]==="~"?e.join(n.homedir(),v.slice(1)):v}function w(v){const R=!!(v&&v.debug),D=v&&"quiet"in v?v.quiet:!0;(R||!D)&&u("Loading env from encrypted .env.vault");const U=C._parseVault(v);let me=process.env;return v&&v.processEnv!=null&&(me=v.processEnv),C.populate(me,U,v),{parsed:U}}function k(v){const R=e.resolve(process.cwd(),".env");let D="utf8";const U=!!(v&&v.debug),me=v&&"quiet"in v?v.quiet:!0;v&&v.encoding?D=v.encoding:U&&h("No encoding is specified. UTF-8 is used by default");let V=[R];if(v&&v.path)if(!Array.isArray(v.path))V=[y(v.path)];else{V=[];for(const xt of v.path)V.push(y(xt))}let ne;const le={};for(const xt of V)try{const Ue=C.parse(t.readFileSync(xt,{encoding:D}));C.populate(le,Ue,v)}catch(Ue){U&&h(`Failed to load ${xt} ${Ue.message}`),ne=Ue}let ct=process.env;if(v&&v.processEnv!=null&&(ct=v.processEnv),C.populate(ct,le,v),U||!me){const xt=Object.keys(le).length,Ue=[];for(const Bi of V)try{const jn=e.relative(process.cwd(),Bi);Ue.push(jn)}catch(jn){U&&h(`Failed to load ${Bi} ${jn.message}`),ne=jn}u(`injecting env (${xt}) from ${Ue.join(",")}`)}return ne?{parsed:le,error:ne}:{parsed:le}}function E(v){if(d(v).length===0)return C.configDotenv(v);const R=m(v);return R?C._configVault(v):(l(`You set DOTENV_KEY but you are missing a .env.vault file at ${R}. Did you forget to build it?`),C.configDotenv(v))}function T(v,R){const D=Buffer.from(R.slice(-64),"hex");let U=Buffer.from(v,"base64");const me=U.subarray(0,12),V=U.subarray(-16);U=U.subarray(12,-16);try{const ne=s.createDecipheriv("aes-256-gcm",D,me);return ne.setAuthTag(V),`${ne.update(U)}${ne.final()}`}catch(ne){const le=ne instanceof RangeError,ct=ne.message==="Invalid key length",xt=ne.message==="Unsupported state or unable to authenticate data";if(le||ct){const Ue=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw Ue.code="INVALID_DOTENV_KEY",Ue}else if(xt){const Ue=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw Ue.code="DECRYPTION_FAILED",Ue}else throw ne}}function P(v,R,D={}){const U=!!(D&&D.debug),me=!!(D&&D.override);if(typeof R!="object"){const V=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw V.code="OBJECT_REQUIRED",V}for(const V of Object.keys(R))Object.prototype.hasOwnProperty.call(v,V)?(me===!0&&(v[V]=R[V]),U&&h(me===!0?`"${V}" is already defined and WAS overwritten`:`"${V}" is already defined and was NOT overwritten`)):v[V]=R[V]}const C={configDotenv:k,_configVault:w,_parseVault:c,config:E,decrypt:T,parse:a,populate:P};return Pt.exports.configDotenv=C.configDotenv,Pt.exports._configVault=C._configVault,Pt.exports._parseVault=C._parseVault,Pt.exports.config=C.config,Pt.exports.decrypt=C.decrypt,Pt.exports.parse=C.parse,Pt.exports.populate=C.populate,Pt.exports=C,Pt.exports}const hE="4.1.0",uE={version:hE};var ua,dd;function dE(){if(dd)return ua;dd=1;const t=Jn,e=Jn,n=lE(),{version:s}=uE,i=".env[.node_env][.local]",r=/\[(\W*\blocal\b\W*)]/g,o=/\[(\W*\b)node_env(\b\W*)]/g;function a(E,T){let P=E;return P=P.replace(r,T&&T.local?"$1":""),P=P.replace(o,T&&T.node_env?`$1${T.node_env}$2`:""),P}function c(E={}){E.debug&&k("listing effective `.env*` files…");const{node_env:T,path:P=process.cwd(),pattern:C=i}=E,v=r.test(C),R={};if(C===i&&(R[".env.defaults"]=".env.defaults"),R[".env"]=a(C),v){const D=a(C,{local:!0});T!=="test"?R[".env.local"]=D:E.debug&&t.existsSync(e.resolve(P,D))&&k('[!] note that `%s` is being skipped for "test" environment',D)}return T&&o.test(C)&&(R[".env.node_env"]=a(C,{node_env:T}),v&&(R[".env.node_env.local"]=a(C,{node_env:T,local:!0}))),[".env.defaults",".env",".env.local",".env.node_env",".env.node_env.local"].reduce((D,U)=>{if(!R[U])return D;const me=e.resolve(P,R[U]);return t.existsSync(me)&&(E.debug&&k(">> %s",me),D.push(me)),D},[])}function l(E,T={}){if(typeof E=="string"){T.debug&&k('parsing "%s"…',E);const P=n.parse(t.readFileSync(E,T.encoding&&{encoding:T.encoding}));return T.debug&&Object.keys(P).forEach(C=>k(">> %s",C)),P}return E.reduce((P,C)=>{const v=l(C,T);return T.debug&&Object.keys(v).filter(R=>P.hasOwnProperty(R)).forEach(R=>k('`%s` is being overwritten by merge from "%s"',R,C)),Object.assign(P,v)},{})}function h(E,T={}){try{const P=l(E,{encoding:T.encoding,debug:T.debug});T.debug&&k("safe-merging parsed environment variables into `process.env`…");for(const C of Object.keys(P))process.env.hasOwnProperty(C)?T.debug&&process.env[C]!==P[C]&&k("environment variable `%s` is predefined and not being overwritten",C):(T.debug&&k(">> process.env.%s",C),process.env[C]=P[C]);return{parsed:P}}catch(P){return y(P,T)}}function u(E,T={}){const P=l(E,T);Object.keys(P).forEach(C=>{process.env[C]===P[C]&&delete process.env[C]})}function d(E={}){if(E.node_env)return E.debug&&k(`operating in "${E.node_env}" environment (set by \`options.node_env\`)`),E.node_env;if(process.env.NODE_ENV)return E.debug&&k(`operating in "${process.env.NODE_ENV}" environment (as per \`process.env.NODE_ENV\`)`),process.env.NODE_ENV;if(E.default_node_env)return E.debug&&k(`operating in "${E.default_node_env}" environment (taken from \`options.default_node_env\`)`),E.default_node_env;E.debug&&k('operating in "no environment" mode (no environment-related options are set)')}const p=["node_env","default_node_env","path","pattern","files","encoding","purge_dotenv","silent"];function m(E={}){E.debug&&(k("initializing…"),p.filter(C=>C in E).forEach(C=>k(`| options.${C} =`,E[C])));const{path:T=process.cwd(),pattern:P=i}=E;if(E.purge_dotenv){E.debug&&k("`options.purge_dotenv` is enabled, unloading potentially pre-loaded `.env`…");const C=e.resolve(T,".env");try{t.existsSync(C)&&u(C,{encoding:E.encoding})}catch(v){!E.silent&&w("unloading failed: ",v)}}try{let C;if(E.files)E.debug&&k("using explicit list of `.env*` files: %s…",E.files.join(", ")),C=E.files.reduce((R,D)=>{const U=e.resolve(T,D);return t.existsSync(U)?R.push(U):E.debug&&k(">> %s does not exist, skipping…",U),R},[]);else{const R=d(E);if(C=c({node_env:R,path:T,pattern:P,debug:E.debug}),C.length===0){const D=R?P.replace(o,`[$1${R}$2]`):P;return y(new Error(`no ".env*" files matching pattern "${D}" in "${T}" dir`),E)}}const v=h(C,{encoding:E.encoding,debug:E.debug,silent:E.silent});return E.debug&&k("initialization completed."),v}catch(C){return y(C,E)}}function y(E,T){return T.silent||w(`".env*" files loading failed: ${E.message||E}`),{error:E}}function w(E,T){T&&(E+=": %s"),console.warn(`[dotenv-flow@${s}]: ${E}`,T)}function k(E,...T){console.debug(`[dotenv-flow@${s}]: ${E}`,...T)}return ua={DEFAULT_PATTERN:i,listFiles:c,parse:l,load:h,unload:u,config:m},ua}var fE=dE();const pE=sE(fE),da={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_IS_DEV:"0",VITE_LOCAL_URL:"http://localhost:5001",VITE_SERVERLESS_URL:"https://backendv2-dev.nervoscan.com",VITE_SERVER_URL:"https://backend.nervoscan.com"};var Ld;typeof process<"u"&&process.env&&((Ld=process.versions)!=null&&Ld.node)&&pE.config();const zi=t=>typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Zn&&Zn.tagName.toUpperCase()==="SCRIPT"&&Zn.src||new URL("nervoscan-js-sdk.cjs",document.baseURI).href}<"u"&&da&&t in da?da[t]||"":typeof process<"u"&&process.env&&t in process.env?process.env[t]||"":(W.throwKnownError(L.EnvIncompatibleError),""),Io=t=>zi("VITE_IS_DEV")==="1"?zi("VITE_LOCAL_URL"):zi(t==="serverless"?"VITE_SERVERLESS_URL":"VITE_SERVER_URL"),mE=t=>{let e=t.reduce((n,s)=>[n[0]+s[0],n[1]+s[1]],[0,0]);return e=[e[0]/t.length,e[1]/t.length],t.slice().sort((n,s)=>{const i=Math.atan2(n[1]-e[1],n[0]-e[0]),r=Math.atan2(s[1]-e[1],s[0]-e[0]);return i-r})},gE=["bigForehead","smallForehead","leftCheek","rightCheek","cheeksNose","face"];function _E(){return{r:[],g:[],b:[],timestamps:[]}}function fd(){return Object.fromEntries(gE.map(t=>[t,_E()]))}function wn(t,e){if(!(e.length<3)){t.beginPath(),t.moveTo(e[0][0],e[0][1]);for(let n=1;n<e.length;n++)t.lineTo(e[n][0],e[n][1]);t.closePath(),t.stroke()}}function bn(t,e,n,s,i){const r=t[e],o=(s-i)/1e3;if(r.timestamps.length>0){const a=r.timestamps[r.timestamps.length-1];if(o<=a){f.warn(`Timestamp inconsistency detected in ${e}: ${o} <= ${a}`);return}}r.r.push(n[0]),r.g.push(n[1]),r.b.push(n[2]),r.timestamps.push(o)}function $t(t,e,n,s,i){if(!t||t.length<3)return 0;let r=0;const o=t.length;for(let a=0;a<o;a++){const c=(a+1)%o;r+=t[a][0]*t[c][1],r-=t[c][0]*t[a][1]}return Math.abs(r)/2}function fa(t,e,n,s,i){let r="ALIGNED";const u=s/640,d=i/480,p=u*d,m=19e3*p,y=5e4*p,w=800*p;return t<m?r="TOO_FAR":t>y?r="TOO_CLOSE":e<w?r="LOOKING_RIGHT":n<w&&(r="LOOKING_LEFT"),r}const yE=[[67,109],[109,10],[10,338],[338,297],[66,107],[107,9],[9,336],[336,296],[67,69],[69,66],[297,299],[299,296]],vE=[[109,10],[10,338],[338,337],[337,151],[151,108],[108,109]],EE=[[345,352],[352,376],[376,433],[433,416],[416,436],[436,426],[426,423],[423,266],[266,330],[330,347],[347,346],[346,345]],wE=[[116,123],[123,147],[147,213],[213,192],[192,216],[216,206],[206,203],[203,36],[36,101],[101,118],[118,117],[117,116]],bE=[[118,50],[50,216],[216,2],[2,436],[436,280],[280,347],[347,6],[6,118]],CE=[[103,67],[67,109],[109,10],[10,338],[338,297],[297,332],[332,298],[298,300],[300,383],[383,372],[372,345],[345,352],[352,411],[411,427],[427,436],[436,322],[322,2],[2,92],[92,216],[216,207],[207,187],[187,123],[123,116],[116,143],[143,156],[156,70],[70,68],[68,103]];function Os(t){const e=new Set;for(const n of t)e.add(n[0]),e.add(n[1]);return Array.from(e)}const pd=Os(yE),md=Os(vE),Ki=Os(EE),Yi=Os(wE),gd=Os(bE),pa=Os(CE);class TE{constructor(){_(this,"wasmUrl","https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm");_(this,"modelUrl","https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task");_(this,"faceLandmarker");_(this,"canvasCtx");_(this,"video");_(this,"videoWidth");_(this,"canvas");_(this,"rgbDataBuffer");_(this,"alignmentStatusCallback");_(this,"startTimeMs",0);_(this,"backendRepository");_(this,"isDetectionActive",!1);_(this,"tempCanvas");_(this,"tempCanvasCtx");_(this,"mediaPipeTimestamp",0);_(this,"lastVideoTime",0);_(this,"videoTimeOffset",0);_(this,"timestampAdjustmentCount",0);_(this,"dataCollectionThreshold",500);_(this,"batchCount",0);_(this,"totalFramesProcessed",0);_(this,"isStreamingActive",!1);_(this,"pendingResults",[]);_(this,"finalResultsCallback");_(this,"mediaPipeTimingData",{canvasSetup:[],mlDetection:[],canvasOps:[],landmarkDraw:[],roiCoords:[],contourDraw:[],rgbCalc:[],dataStorage:[],alignment:[]});_(this,"faceDetectionLoop",async()=>{let e=0,n=0,s=1/0,i=0;const r=async()=>{if(!this.isDetectionActive){if(e>0){const l=n/e,h=1e3/l,u=1e3/i,d=1e3/s;f.log("=== FACE DETECTION PERFORMANCE SUMMARY ==="),f.log(`Total detection frames: ${e}`),f.log(`Average detection FPS: ${h.toFixed(1)} fps (${l.toFixed(2)}ms per frame)`),f.log(`Min detection FPS: ${u.toFixed(1)} fps (worst performance)`),f.log(`Max detection FPS: ${d.toFixed(1)} fps (best performance)`),f.log(`Detection FPS range: ${(d-u).toFixed(1)} fps variation`),f.log("==========================================")}return}const o=performance.now();try{await this.predictAlignmentOnly()}catch(l){f.warn("Face detection error:",l)}const c=performance.now()-o;if(e++,n+=c,c<s&&(s=c),c>i&&(i=c),e%10===0){const l=n/e,h=1e3/c,u=1e3/l;f.log(`Detection Frame ${e}: ${h.toFixed(1)} fps (avg: ${u.toFixed(1)} fps)`)}setTimeout(r,100)};r()});this.videoWidth=640}calculateTimingStats(e){if(e.length===0)return{min:0,max:0,avg:0,total:0};const n=Math.min(...e),s=Math.max(...e),i=e.reduce((o,a)=>o+a,0),r=i/e.length;return{min:n,max:s,avg:r,total:i}}getTimingBreakdown(){return{canvasSetup:this.calculateTimingStats(this.mediaPipeTimingData.canvasSetup),mlDetection:this.calculateTimingStats(this.mediaPipeTimingData.mlDetection),canvasOps:this.calculateTimingStats(this.mediaPipeTimingData.canvasOps),landmarkDraw:this.calculateTimingStats(this.mediaPipeTimingData.landmarkDraw),roiCoords:this.calculateTimingStats(this.mediaPipeTimingData.roiCoords),contourDraw:this.calculateTimingStats(this.mediaPipeTimingData.contourDraw),rgbCalc:this.calculateTimingStats(this.mediaPipeTimingData.rgbCalc),dataStorage:this.calculateTimingStats(this.mediaPipeTimingData.dataStorage),alignment:this.calculateTimingStats(this.mediaPipeTimingData.alignment)}}resetTimingData(){this.mediaPipeTimingData={canvasSetup:[],mlDetection:[],canvasOps:[],landmarkDraw:[],roiCoords:[],contourDraw:[],rgbCalc:[],dataStorage:[],alignment:[]}}setStartTimeMs(e){this.startTimeMs=e}setDataCollectionThreshold(e){if(e<=0)throw new Error("Data collection threshold must be greater than 0");this.dataCollectionThreshold=e,f.log(`[RGB Processing] Data collection threshold set to ${e} points`)}startContinuousDataCollection(e,n){f.log(`[FaceLandmarker] startContinuousDataCollection called with apiKey: ${e}`),this.isStreamingActive=!0,this.batchCount=0,this.totalFramesProcessed=0,this.pendingResults=[],this.finalResultsCallback=n,f.log(`[FaceLandmarker] Starting continuous data collection with threshold: ${this.dataCollectionThreshold}`),f.log(`[FaceLandmarker] isStreamingActive set to: ${this.isStreamingActive}`)}stopContinuousDataCollection(){this.isStreamingActive=!1,f.log(`[FaceLandmarker] Stopping continuous data collection. Processed ${this.totalFramesProcessed} frames in ${this.batchCount} batches`),this.pendingResults.length>0&&this.aggregateFinalResults()}isContinuousDataCollectionActive(){return this.isStreamingActive}getDataCollectionStats(){return{batchCount:this.batchCount,totalFramesProcessed:this.totalFramesProcessed,pendingResults:this.pendingResults.length}}async initialize(e,n){if(this.backendRepository=n,await this.createFaceLandmarker(),this.video=e,this.canvas=document.createElement("canvas"),this.canvas.width=e.videoWidth||640,this.canvas.height=e.videoHeight||480,f.log(`[RGB Processing] Initial resolution: ${this.canvas.width}x${this.canvas.height} (fallback: 640x480)`),this.canvasCtx=this.canvas.getContext("2d"),!this.canvasCtx)throw new Error("Failed to get canvas context");this.tempCanvas=document.createElement("canvas"),this.tempCanvas.width=e.videoWidth||640,this.tempCanvas.height=e.videoHeight||480,this.tempCanvasCtx=this.tempCanvas.getContext("2d"),this.rgbDataBuffer=fd(),this.resetTimingData()}ensureCanvasDimensions(){if(!this.video)return;const e=this.video.videoWidth,n=this.video.videoHeight;e>0&&n>0&&((this.canvas.width!==e||this.canvas.height!==n)&&(f.log(`[RGB Processing] Canvas resolution updated: ${this.canvas.width}x${this.canvas.height} -> ${e}x${n}`),this.canvas.width=e,this.canvas.height=n),(this.tempCanvas.width!==e||this.tempCanvas.height!==n)&&(this.tempCanvas.width=e,this.tempCanvas.height=n))}setAlignmentStatusCallback(e){this.alignmentStatusCallback=e}startFaceDetection(){this.isDetectionActive=!0,this.faceDetectionLoop()}stopFaceDetection(){this.isDetectionActive=!1}isFaceDetectionActive(){return this.isDetectionActive}generateMediaPipeTimestamp(){if(!this.video)return this.mediaPipeTimestamp;const e=this.video.currentTime;e<this.lastVideoTime&&(this.videoTimeOffset+=this.lastVideoTime,f.log(`Video time reset detected. New offset: ${this.videoTimeOffset.toFixed(3)}s`));const n=(e+this.videoTimeOffset)*1e3;if(n<=this.mediaPipeTimestamp){const s=this.mediaPipeTimestamp+1;this.timestampAdjustmentCount++,this.timestampAdjustmentCount%100===0&&f.log(`MediaPipe timestamp adjusted: ${n.toFixed(1)} -> ${s.toFixed(1)} (adjustment #${this.timestampAdjustmentCount})`),this.mediaPipeTimestamp=s}else this.mediaPipeTimestamp=n;return this.lastVideoTime=e,this.mediaPipeTimestamp}resetMediaPipeTimestamps(){const e=this.mediaPipeTimestamp,n=this.timestampAdjustmentCount;this.mediaPipeTimestamp=0,this.lastVideoTime=0,this.videoTimeOffset=0,this.timestampAdjustmentCount=0,f.log(`MediaPipe timestamps reset for fresh initialization (was: ${e}ms, adjustments: ${n})`)}getMediaPipeTimestampInfo(){return{current:this.mediaPipeTimestamp,lastVideo:this.lastVideoTime,offset:this.videoTimeOffset}}async createFaceLandmarker(){const e=await Sn.forVisionTasks(this.wasmUrl);this.faceLandmarker=await X.createFromOptions(e,{baseOptions:{modelAssetPath:this.modelUrl,delegate:"GPU"},outputFaceBlendshapes:!1,runningMode:"VIDEO",numFaces:1})}getLandmarkCoordinates(e,n,s,i){const r=[];for(const o of n)if(e[0]&&o<e[0].length){const a=e[0][o];r.push([Math.round(a.x*s),Math.round(a.y*i)])}return r.length>0?mE(r):[]}detect(e){return this.faceLandmarker||W.throwKnownError(L.FaceLandmarkerNotInitializedError),this.faceLandmarker.detectForVideo(e,performance.now())}calculateRgbMean(e,n,s,i){if(e.length<3)return[0,0,0];if(s<=0||i<=0)return[0,0,0];const r=this.getBoundingBox(e),o=Math.max(0,Math.floor(r.minX)),a=Math.min(s-1,Math.ceil(r.maxX)),c=Math.max(0,Math.floor(r.minY)),l=Math.min(i-1,Math.ceil(r.maxY));if(o>=a||c>=l)return[0,0,0];let h=0,u=0,d=0,p=0;for(let m=c;m<=l;m++)for(let y=o;y<=a;y++)if(this.isPointInPolygon(y,m,e)){const w=(m*s+y)*4;u+=n.data[w],d+=n.data[w+1],p+=n.data[w+2],h++}return h>0?(u=Math.round(u/h),d=Math.round(d/h),p=Math.round(p/h),[u,d,p]):[0,0,0]}getBoundingBox(e){let n=1/0,s=-1/0,i=1/0,r=-1/0;for(const[o,a]of e)o<n&&(n=o),o>s&&(s=o),a<i&&(i=a),a>r&&(r=a);return{minX:n,maxX:s,minY:i,maxY:r}}isPointInPolygon(e,n,s){let i=!1;const r=s.length;for(let o=0,a=r-1;o<r;a=o++){const c=s[o][0],l=s[o][1],h=s[a][0],u=s[a][1];l>n!=u>n&&e<(h-c)*(n-l)/(u-l)+c&&(i=!i)}return i}async predictAlignmentOnly(){if(!this.canvasCtx||!this.video||!this.video.videoWidth||!this.video.videoHeight||this.video.readyState<2||(this.ensureCanvasDimensions(),!this.faceLandmarker))return;const e=this.generateMediaPipeTimestamp();let n;try{n=this.faceLandmarker.detectForVideo(this.video,e)}catch(s){if(s instanceof Error&&s.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error detected, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{n=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(i){f.error("MediaPipe recovery failed, skipping frame:",i);return}}else throw s}if(n.faceLandmarks&&n.faceLandmarks.length>0){const s=this.getLandmarkCoordinates(n.faceLandmarks,pa,this.video.videoWidth,this.video.videoHeight),i=this.getLandmarkCoordinates(n.faceLandmarks,Ki,this.video.videoWidth,this.video.videoHeight),r=this.getLandmarkCoordinates(n.faceLandmarks,Yi,this.video.videoWidth,this.video.videoHeight),o=$t(s,this.video.videoWidth,this.video.videoHeight),a=$t(i,this.video.videoWidth,this.video.videoHeight),c=$t(r,this.video.videoWidth,this.video.videoHeight),l=fa(o,a,c,this.video.videoWidth,this.video.videoHeight);this.alignmentStatusCallback&&this.alignmentStatusCallback(l)}else this.alignmentStatusCallback&&this.alignmentStatusCallback("NO_FACE")}async predictFromCanvas(e,n,s){this.stopFaceDetection();const i=this.checkDataCollectionStatus(n);if(!this.canvasCtx)throw new Error("Canvas context not initialized");this.ensureCanvasDimensionsForCanvas(e);const r=new Pe(this.canvasCtx),o=e.height/e.width;this.canvas.style.width=this.videoWidth+"px",this.canvas.style.height=this.videoWidth*o+"px",this.canvas.width=e.width,this.canvas.height=e.height,this.faceLandmarker||W.throwKnownError(L.FaceLandmarkerNotInitializedError);const a=this.generateMediaPipeTimestamp();let c;try{c=this.faceLandmarker.detectForVideo(this.video,a)}catch(l){if(l instanceof Error&&l.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error in predictFromCanvas, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{c=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(h){return f.error("MediaPipe recovery failed in predictFromCanvas, skipping frame:",h),i}}else return f.error("MediaPipe canvas detection error:",l),i}if(this.canvasCtx.clearRect(0,0,this.canvas.width,this.canvas.height),c.faceLandmarks&&c.faceLandmarks.length>0){const l=s;this.rgbDataBuffer.bigForehead.r.length%100===0&&f.log(`[RGB Canvas Processing] Processing frame at resolution: ${e.width}x${e.height}`);const h=e.getContext("2d");if(!h)throw new Error("Unable to get canvas context");const u=h.getImageData(0,0,e.width,e.height);this.drawFaceLandmarks(r,c.faceLandmarks);const d=this.getLandmarkCoordinates(c.faceLandmarks,pd,e.width,e.height),p=this.getLandmarkCoordinates(c.faceLandmarks,md,e.width,e.height),m=this.getLandmarkCoordinates(c.faceLandmarks,Ki,e.width,e.height),y=this.getLandmarkCoordinates(c.faceLandmarks,Yi,e.width,e.height),w=this.getLandmarkCoordinates(c.faceLandmarks,gd,e.width,e.height);await this.processROIData(d,"bigForehead",u,l),await this.processROIData(p,"smallForehead",u,l),await this.processROIData(m,"leftCheek",u,l),await this.processROIData(y,"rightCheek",u,l),await this.processROIData(w,"cheeksNose",u,l)}return i}async predictAlignmentFromCanvas(e){if(!this.canvasCtx||!e.width||!e.height||!this.faceLandmarker)return;const n=this.generateMediaPipeTimestamp();let s;try{s=this.faceLandmarker.detectForVideo(this.video,n)}catch(i){if(i instanceof Error&&i.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error in alignment detection, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{s=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(r){f.error("MediaPipe recovery failed in alignment detection:",r);return}}else{f.error("MediaPipe canvas alignment detection error:",i);return}}if(s.faceLandmarks&&s.faceLandmarks.length>0){const i=this.getLandmarkCoordinates(s.faceLandmarks,pa,e.width,e.height),r=this.getLandmarkCoordinates(s.faceLandmarks,Ki,e.width,e.height),o=this.getLandmarkCoordinates(s.faceLandmarks,Yi,e.width,e.height),a=$t(i,e.width,e.height),c=$t(r,e.width,e.height),l=$t(o,e.width,e.height),h=fa(a,c,l,e.width,e.height);this.alignmentStatusCallback&&this.alignmentStatusCallback(h)}else this.alignmentStatusCallback&&this.alignmentStatusCallback("NO_FACE")}async predict(e,n){performance.now(),this.stopFaceDetection(),this.rgbDataBuffer.bigForehead.r.length%100===0&&f.log(`[RGB Processing] predict() called - isStreamingActive: ${this.isStreamingActive}, buffer: ${this.rgbDataBuffer.bigForehead.r.length}/${this.dataCollectionThreshold}`);const s=this.checkDataCollectionStatus(e);if(!this.canvasCtx||!this.video)throw new Error("Not initialized");const i=performance.now();this.ensureCanvasDimensions();const r=new Pe(this.canvasCtx),o=this.video.videoHeight/this.video.videoWidth;this.canvas.style.width=this.videoWidth+"px",this.canvas.style.height=this.videoWidth*o+"px",this.canvas.width=this.video.videoWidth,this.canvas.height=this.video.videoHeight;const a=performance.now()-i;this.faceLandmarker||W.throwKnownError(L.FaceLandmarkerNotInitializedError);const c=this.generateMediaPipeTimestamp(),l=performance.now();let h;try{h=this.faceLandmarker.detectForVideo(this.video,c)}catch(p){if(p instanceof Error&&p.message.includes("timestamp mismatch")){f.warn("MediaPipe timestamp error in predict, attempting recovery..."),this.mediaPipeTimestamp+=100,this.timestampAdjustmentCount++;try{h=this.faceLandmarker.detectForVideo(this.video,this.mediaPipeTimestamp)}catch(m){return f.error("MediaPipe recovery failed in predict, skipping frame:",m),s}}else throw p}const u=performance.now()-l,d=performance.now();if(this.canvasCtx.clearRect(0,0,this.canvas.width,this.canvas.height),h.faceLandmarks&&h.faceLandmarks.length>0){const p=n||this.video.currentTime*1e3;this.rgbDataBuffer.bigForehead.r.length%100===0&&f.log(`[RGB Processing] Processing frame at resolution: ${this.video.videoWidth}x${this.video.videoHeight}`),this.tempCanvasCtx.clearRect(0,0,this.tempCanvas.width,this.tempCanvas.height),this.tempCanvasCtx.drawImage(this.video,0,0,this.tempCanvas.width,this.tempCanvas.height);const m=this.tempCanvasCtx.getImageData(0,0,this.tempCanvas.width,this.tempCanvas.height),y=performance.now()-d,w=performance.now();this.drawFaceLandmarks(r,h.faceLandmarks);const k=performance.now()-w;this.mediaPipeTimingData.landmarkDraw.push(k);const E=performance.now(),T=this.getLandmarkCoordinates(h.faceLandmarks,pd,this.video.videoWidth,this.video.videoHeight),P=this.getLandmarkCoordinates(h.faceLandmarks,md,this.video.videoWidth,this.video.videoHeight),C=this.getLandmarkCoordinates(h.faceLandmarks,Ki,this.video.videoWidth,this.video.videoHeight),v=this.getLandmarkCoordinates(h.faceLandmarks,Yi,this.video.videoWidth,this.video.videoHeight),R=this.getLandmarkCoordinates(h.faceLandmarks,gd,this.video.videoWidth,this.video.videoHeight),D=this.getLandmarkCoordinates(h.faceLandmarks,pa,this.video.videoWidth,this.video.videoHeight),U=performance.now()-E;this.mediaPipeTimingData.roiCoords.push(U);const me=performance.now();this.canvasCtx.strokeStyle="rgba(255, 255, 255, 0.7)",this.canvasCtx.lineWidth=1,wn(this.canvasCtx,T),wn(this.canvasCtx,P),wn(this.canvasCtx,C),wn(this.canvasCtx,v),wn(this.canvasCtx,R),wn(this.canvasCtx,D);const V=performance.now()-me;this.mediaPipeTimingData.contourDraw.push(V);const ne=performance.now(),le=this.calculateRgbMean(T,m,this.video.videoWidth,this.video.videoHeight),ct=this.calculateRgbMean(P,m,this.video.videoWidth,this.video.videoHeight),xt=this.calculateRgbMean(C,m,this.video.videoWidth,this.video.videoHeight),Ue=this.calculateRgbMean(v,m,this.video.videoWidth,this.video.videoHeight),Bi=this.calculateRgbMean(R,m,this.video.videoWidth,this.video.videoHeight),jn=this.calculateRgbMean(D,m,this.video.videoWidth,this.video.videoHeight),k1=performance.now()-ne;this.mediaPipeTimingData.rgbCalc.push(k1);const A1=performance.now();s&&(bn(this.rgbDataBuffer,"bigForehead",le,p,this.startTimeMs),bn(this.rgbDataBuffer,"smallForehead",ct,p,this.startTimeMs),bn(this.rgbDataBuffer,"leftCheek",xt,p,this.startTimeMs),bn(this.rgbDataBuffer,"rightCheek",Ue,p,this.startTimeMs),bn(this.rgbDataBuffer,"cheeksNose",Bi,p,this.startTimeMs),bn(this.rgbDataBuffer,"face",jn,p,this.startTimeMs));const R1=performance.now()-A1;this.mediaPipeTimingData.dataStorage.push(R1);const I1=performance.now(),x1=$t(D,this.video.videoWidth,this.video.videoHeight),N1=$t(C,this.video.videoWidth,this.video.videoHeight),F1=$t(v,this.video.videoWidth,this.video.videoHeight),D1=fa(x1,N1,F1,this.video.videoWidth,this.video.videoHeight);this.alignmentStatusCallback&&this.alignmentStatusCallback(D1);const P1=performance.now()-I1;this.mediaPipeTimingData.alignment.push(P1),this.mediaPipeTimingData.canvasSetup.push(a),this.mediaPipeTimingData.mlDetection.push(u),this.mediaPipeTimingData.canvasOps.push(y)}else this.alignmentStatusCallback&&this.alignmentStatusCallback("NO_FACE");return s}drawFaceLandmarks(e,n){for(const s of n)e.drawConnectors(s,X.FACE_LANDMARKS_TESSELATION,{color:"#C0C0C070",lineWidth:1}),e.drawConnectors(s,X.FACE_LANDMARKS_RIGHT_EYE,{color:"#FF3030"}),e.drawConnectors(s,X.FACE_LANDMARKS_RIGHT_EYEBROW,{color:"#FF3030"}),e.drawConnectors(s,X.FACE_LANDMARKS_LEFT_EYE,{color:"#30FF30"}),e.drawConnectors(s,X.FACE_LANDMARKS_LEFT_EYEBROW,{color:"#30FF30"}),e.drawConnectors(s,X.FACE_LANDMARKS_FACE_OVAL,{color:"#E0E0E0"}),e.drawConnectors(s,X.FACE_LANDMARKS_LIPS,{color:"#E0E0E0"}),e.drawConnectors(s,X.FACE_LANDMARKS_RIGHT_IRIS,{color:"#FF3030"}),e.drawConnectors(s,X.FACE_LANDMARKS_LEFT_IRIS,{color:"#30FF30"})}checkDataCollectionStatus(e){var s,i,r,o;let n=!0;return this.rgbDataBuffer.bigForehead.r.length>=this.dataCollectionThreshold?(this.batchCount++,this.totalFramesProcessed+=this.rgbDataBuffer.bigForehead.r.length,f.log(`[RGB Processing] Sending batch ${this.batchCount} with ${this.dataCollectionThreshold} points and resolution: ${((s=this.video)==null?void 0:s.videoWidth)||0}x${((i=this.video)==null?void 0:i.videoHeight)||0}`),f.log(`[RGB Processing] Total frames processed: ${this.totalFramesProcessed}`),f.log(`[RGB Processing] isStreamingActive: ${this.isStreamingActive}`),this.backendRepository.sendRgbDataToBackend(this.rgbDataBuffer,((r=this.video)==null?void 0:r.videoWidth)||0,((o=this.video)==null?void 0:o.videoHeight)||0,e),this.resetDataBuffer(),this.isStreamingActive?(n=!0,f.log(`[RGB Processing] Continuing data collection for batch ${this.batchCount+1}`)):(n=!1,f.log("[RGB Processing] Stopping data collection (legacy mode)"))):this.rgbDataBuffer.bigForehead.r.length%50===0&&f.log(`[RGB Processing] Buffer status: ${this.rgbDataBuffer.bigForehead.r.length}/${this.dataCollectionThreshold} frames collected`),this.rgbDataBuffer.bigForehead.r.length>=this.dataCollectionThreshold&&f.log(`[RGB Processing] checkDataCollectionStatus returning: ${n}`),n}getRGBDataBufferSize(){var e,n,s;return((s=(n=(e=this.rgbDataBuffer)==null?void 0:e.bigForehead)==null?void 0:n.r)==null?void 0:s.length)||0}getDataCollectionThreshold(){return this.dataCollectionThreshold}getRGBTimestamps(){var e,n;return((n=(e=this.rgbDataBuffer)==null?void 0:e.bigForehead)==null?void 0:n.timestamps)||[]}isDetectionCurrentlyActive(){return this.isDetectionActive}aggregateFinalResults(){if(this.pendingResults.length===0){f.warn("[FaceLandmarker] No pending results to aggregate");return}f.log(`[FaceLandmarker] Aggregating ${this.pendingResults.length} batch results`);const e={},n=["HR","RR","SDNN","SPO2","DBP","SBP","GLUCOSE","HEMOGLOBIN","AGE","HEALTHSCORE","PNN50","RMSSD"];for(const s of n){const i=this.pendingResults.map(r=>r[s]).filter(r=>r!=null&&!isNaN(r));if(i.length>0){const r=i.reduce((o,a)=>o+a,0)/i.length;e[s]=Math.round(r*100)/100}}e.batchCount=this.batchCount,e.totalFramesProcessed=this.totalFramesProcessed,e.aggregatedFrom=this.pendingResults.length,f.log("[FaceLandmarker] Final aggregated results:",e),this.finalResultsCallback&&this.finalResultsCallback(e)}handleBatchResults(e){if(!this.isStreamingActive){f.warn("[FaceLandmarker] Received batch results but continuous collection is not active");return}f.log(`[FaceLandmarker] Received results for batch ${this.pendingResults.length+1}:`,e),this.pendingResults.push(e),f.log(`[FaceLandmarker] Added batch ${this.pendingResults.length} to pending results. Total pending: ${this.pendingResults.length}`)}resetDataBuffer(){this.rgbDataBuffer=fd()}ensureCanvasDimensionsForCanvas(e){(this.tempCanvas.width!==e.width||this.tempCanvas.height!==e.height)&&(this.tempCanvas.width=e.width,this.tempCanvas.height=e.height)}async processROIData(e,n,s,i){const r=this.calculateRgbMean(e,s,s.width,s.height);bn(this.rgbDataBuffer,n,r,i,this.startTimeMs),this.canvasCtx&&wn(this.canvasCtx,e)}}var sc=(t=>(t.LEGACY="legacy",t))(sc||{});class SE{constructor(){_(this,"targetFPS",30);_(this,"frameInterval",1e3/30);_(this,"isCapturing",!1);_(this,"frameCallback",null);_(this,"lastFrameTime",0);_(this,"framesProcessed",0);_(this,"framesSkipped",0)}setTargetFPS(e){this.targetFPS=Math.max(1,Math.min(120,e)),this.frameInterval=1e3/this.targetFPS}getTargetFPS(){return this.targetFPS}isActive(){return this.isCapturing}resetFrameCounters(){this.framesProcessed=0,this.framesSkipped=0,this.lastFrameTime=0}shouldCaptureFrame(e){return e-this.lastFrameTime>=this.frameInterval}updateFrameTime(e){this.lastFrameTime=e}}class kE extends SE{constructor(){super(...arguments);_(this,"videoElement",null);_(this,"canvas",null);_(this,"context",null);_(this,"captureLoop",null)}async initialize(n){if(this.videoElement=n,await this.waitForVideoReady(),this.canvas=document.createElement("canvas"),this.canvas.width=n.videoWidth||640,this.canvas.height=n.videoHeight||480,this.context=this.canvas.getContext("2d"),!this.context)throw new Error("Failed to get 2D canvas context");f.log("[LegacyCanvasCapture] Initialized:",{width:this.canvas.width,height:this.canvas.height,videoReady:n.readyState})}async waitForVideoReady(){return new Promise(n=>{if(this.videoElement&&this.videoElement.readyState>=2){n();return}const s=()=>{this.videoElement&&this.videoElement.readyState>=2?n():setTimeout(s,50)};s()})}async startCapture(n){this.frameCallback=n,this.isCapturing=!0,this.resetFrameCounters(),this.lastFrameTime=performance.now(),this.startCaptureLoop(),f.log(`[LegacyCanvasCapture] Started capture at ${this.targetFPS} FPS`)}startCaptureLoop(){const n=()=>{if(!this.isCapturing){this.captureLoop=null;return}const s=performance.now();if(this.shouldCaptureFrame(s)){this.framesProcessed++;try{this.captureCurrentFrame(s),this.updateFrameTime(s)}catch(i){f.error("[LegacyCanvasCapture] Frame capture error:",i)}}else this.framesSkipped++;this.isCapturing&&(this.captureLoop=requestAnimationFrame(n))};this.captureLoop=requestAnimationFrame(n)}captureCurrentFrame(n){if(!this.videoElement||!this.canvas||!this.context||!this.isCapturing)return;if(this.videoElement.readyState<2){f.warn("[LegacyCanvasCapture] Video not ready for capture");return}this.context.drawImage(this.videoElement,0,0,this.canvas.width,this.canvas.height);const i={imageData:this.context.getImageData(0,0,this.canvas.width,this.canvas.height),timestamp:n,videoTime:this.videoElement.currentTime,width:this.canvas.width,height:this.canvas.height,quality:1};this.frameCallback&&this.frameCallback(i)}stopCapture(){this.isCapturing=!1,this.frameCallback=null,this.captureLoop&&(cancelAnimationFrame(this.captureLoop),this.captureLoop=null);const n=this.framesProcessed+this.framesSkipped,s=n>0?(this.framesSkipped/n*100).toFixed(1):"0";f.log(`🎯 [LegacyCanvasCapture] Capture stopped - Processed: ${this.framesProcessed}, Skipped: ${this.framesSkipped}, Skip rate: ${s}%`)}cleanup(){this.stopCapture(),this.canvas=null,this.context=null,this.videoElement=null}}function AE(t){return{method:"legacy",capture:new kE}}const kn=class kn{constructor(){_(this,"faceLandmarker");_(this,"isCollectingData",!1);_(this,"mediaStream");_(this,"videoElement");_(this,"backendRepository");_(this,"apiKey","");_(this,"onDisconnection",()=>{});_(this,"onAlignmentStatus");_(this,"frameCapture",null);_(this,"captureMethod",sc.LEGACY);_(this,"config",{targetFPS:30,captureMethod:sc.LEGACY,minFrameQuality:0,enableQualityControl:!0,enableFrameValidation:!0});_(this,"frameCount",0);_(this,"totalFrameCount",0);_(this,"droppedFrames",0);_(this,"qualityDrops",0);_(this,"duplicateFrames",0);_(this,"startTime",0);_(this,"frameTimes",[]);_(this,"qualityBuffer",[]);_(this,"lastFrameTimestamp",0);_(this,"lastVideoTime",0);_(this,"maxQualityBufferSize",30);_(this,"maxFrameTimesSize",100);_(this,"minFrameTimeDelta",.001);_(this,"timingData",{validation:[],qualityCheck:[],mediaPipe:[],totalFrame:[]});_(this,"frameIntervals",[]);_(this,"lastFrameProcessTime",0);_(this,"isContinuousMode",!1);_(this,"videoEndDetectionEnabled",!1);_(this,"noFrameTimeout",5e3);_(this,"lastFrameReceivedTime",0);_(this,"videoEndCheckInterval",null);_(this,"onVideoEnd");_(this,"continuousModeCallback")}static getInstance(){return kn.instance||(kn.instance=new kn),kn.instance}async initialize(e,n,s,i,r={}){this.config={...this.config,...r},this.backendRepository=s,this.mediaStream=e,this.videoElement=n,this.videoElement.srcObject=e,this.onDisconnection=i,this.faceLandmarker=new TE,this.faceLandmarker.setDataCollectionThreshold(300),await this.faceLandmarker.initialize(this.videoElement,this.backendRepository),this.onAlignmentStatus&&this.faceLandmarker.setAlignmentStatusCallback(this.onAlignmentStatus),await this.initializeFrameCapture(),f.log("[RGBManager] Initialized with configuration:",this.config),f.log(`[RGBManager] Video resolution: ${n.videoWidth}x${n.videoHeight}`),f.log(`[RGBManager] Using capture method: ${this.captureMethod}`)}async initializeFrameCapture(){try{const{method:e,capture:n}=AE(this.config.captureMethod);this.captureMethod=e,this.frameCapture=n,this.frameCapture.setTargetFPS(this.config.targetFPS),await this.frameCapture.initialize(this.videoElement),f.log(`[RGBManager] Frame capture initialized: ${e}`)}catch(e){throw f.error("[RGBManager] Frame capture initialization failed:",e),e}}startFaceDetection(){this.faceLandmarker&&(f.log("[RGBManager] Starting face detection for alignment feedback..."),this.faceLandmarker.startFaceDetection())}stopFaceDetection(){this.faceLandmarker&&(f.log("[RGBManager] Stopping face detection..."),this.faceLandmarker.stopFaceDetection())}setAlignmentStatusCallback(e){this.onAlignmentStatus=e,this.faceLandmarker&&this.faceLandmarker.setAlignmentStatusCallback(e)}async startStreaming(e){if(!this.frameCapture)throw new Error("Frame capture not initialized");this.isCollectingData=!0,this.apiKey=e,this.resetStatistics(),f.log(`[RGBManager] Starting RGB streaming with ${this.captureMethod}`),f.log(`[RGBManager] Target FPS: ${this.config.targetFPS}, Quality control: ${this.config.enableQualityControl}`),this.faceLandmarker.setStartTimeMs(performance.now()),this.isContinuousMode&&this.faceLandmarker&&this.continuousModeCallback&&(f.log("[RGBManager] Starting continuous data collection with apiKey:",e),this.faceLandmarker.startContinuousDataCollection(e,this.continuousModeCallback)),await this.frameCapture.startCapture(this.processFrame.bind(this))}resetStatistics(){this.startTime=performance.now(),this.frameCount=0,this.droppedFrames=0,this.qualityDrops=0,this.duplicateFrames=0,this.frameTimes=[],this.qualityBuffer=[],this.lastFrameTimestamp=0,this.lastVideoTime=0,this.timingData={validation:[],qualityCheck:[],mediaPipe:[],totalFrame:[]},this.frameIntervals=[],this.lastFrameProcessTime=0}async processFrame(e){if(!this.isCollectingData)return;this.lastFrameReceivedTime=performance.now();const n=performance.now();if(this.lastFrameProcessTime>0){const s=n-this.lastFrameProcessTime;this.frameIntervals.push(s)}this.lastFrameProcessTime=n;try{const s=performance.now();if(this.config.enableFrameValidation&&!this.validateFrame(e)){const d=performance.now()-s;this.timingData.validation.push(d);return}const i=performance.now()-s;this.timingData.validation.push(i);const r=performance.now();if(this.config.enableQualityControl&&!this.passesQualityControl(e)){this.qualityDrops++;const d=performance.now()-r;this.timingData.qualityCheck.push(d);return}const o=performance.now()-r;this.timingData.qualityCheck.push(o),this.updateFrameStatistics(e);const a=this.generateUnifiedTimestamp(e),c=performance.now(),l=this.isCollectingData;this.isCollectingData=await this.faceLandmarker.predict(this.apiKey,a),l!==this.isCollectingData&&(f.log(`[RGBManager] isCollectingData changed from ${l} to ${this.isCollectingData}`),f.log(`[RGBManager] Continuous mode enabled: ${this.isContinuousMode}`));const h=performance.now()-c;this.timingData.mediaPipe.push(h);const u=performance.now()-n;this.timingData.totalFrame.push(u),this.frameCount%100===0&&f.log(`📊 [Progress] Frame ${this.frameCount} - ${u.toFixed(1)}ms`)}catch(s){const i=performance.now()-n;this.timingData.totalFrame.push(i),f.error(`❌ [Frame ${this.frameCount}] Error after ${i.toFixed(2)}ms:`,s)}}validateFrame(e){if(e.videoTime!==void 0){if(e.videoTime-this.lastVideoTime<this.minFrameTimeDelta)return f.warn("[RGBManager] Duplicate frame detected, skipping"),this.duplicateFrames++,!1;this.lastVideoTime=e.videoTime}return e.timestamp<this.lastFrameTimestamp?(f.warn("[RGBManager] Out-of-order frame detected, skipping"),!1):(this.lastFrameTimestamp=e.timestamp,!0)}passesQualityControl(e){return e.quality===void 0?(f.warn("[RGBManager] No quality info available, skipping"),!0):e.quality<this.config.minFrameQuality?(f.warn("[RGBManager] Frame quality below threshold, skipping"),!1):(this.qualityBuffer.push(e.quality),this.qualityBuffer.length>this.maxQualityBufferSize&&this.qualityBuffer.shift(),!0)}updateFrameStatistics(e){this.frameCount++,this.totalFrameCount++,this.frameTimes.push(e.timestamp),this.frameTimes.length>this.maxFrameTimesSize&&this.frameTimes.shift()}createCanvasFromImageData(e){const n=document.createElement("canvas");n.width=e.width,n.height=e.height;const s=n.getContext("2d");return s&&s.putImageData(e,0,0),n}generateUnifiedTimestamp(e){return e.videoTime!==void 0?e.videoTime*1e3:e.timestamp-this.startTime}logProgress(){var n;const e=this.getFrameStatistics();f.log(`--- Frame ${this.frameCount} Progress ---`),f.log(`Capture: ${this.captureMethod} | Target: ${e.targetFPS} FPS | Actual: ${e.actualFPS.toFixed(1)} FPS`),f.log(`Quality: Avg ${((n=e.averageQuality)==null?void 0:n.toFixed(3))||"N/A"} | Drops: ${e.qualityDrops}`),f.log(`Frames: Processed ${e.frameCount} | Dropped ${e.droppedFrames} | Duplicates ${e.duplicateFrames}`),f.log(`Stability: ${e.temporalStability.toFixed(1)}%`)}stopStreaming(){this.isCollectingData=!1,this.stopVideoEndDetection(),this.frameCapture&&this.frameCapture.stopCapture(),this.isContinuousMode&&this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),this.logFinalStatistics()}calculateTimingStats(e){if(e.length===0)return{min:0,max:0,avg:0,total:0};const n=Math.min(...e),s=Math.max(...e),i=e.reduce((o,a)=>o+a,0),r=i/e.length;return{min:n,max:s,avg:r,total:i}}getDetailedTimingStats(){var n,s;const e=(s=(n=this.faceLandmarker).getTimingBreakdown)==null?void 0:s.call(n);return{validation:this.calculateTimingStats(this.timingData.validation),qualityCheck:this.calculateTimingStats(this.timingData.qualityCheck),mediaPipe:this.calculateTimingStats(this.timingData.mediaPipe),totalFrame:this.calculateTimingStats(this.timingData.totalFrame),mediaPipeBreakdown:e}}logFinalStatistics(){var d;const e=this.getFrameStatistics();if(e.frameCount===0){f.log("[RGBManager] No frames processed - skipping comprehensive analysis");return}const n=this.getDetailedTimingStats();f.log(`
1637
1637
  🎯 ===== COMPREHENSIVE PERFORMANCE ANALYSIS =====`),f.log(`📹 Capture Method: ${e.captureMethod}`),f.log(`📊 Total Frames: ${e.frameCount} processed in ${(e.elapsedTime/1e3).toFixed(1)}s`),f.log(`🎯 FPS Performance: ${e.actualFPS.toFixed(1)}/${e.targetFPS} (${(e.actualFPS/e.targetFPS*100).toFixed(1)}% accuracy)`),f.log(`⚠️ Frame Issues: ${e.droppedFrames} dropped, ${e.qualityDrops} quality drops, ${e.duplicateFrames} duplicates`),f.log(`✨ Quality: ${((d=e.averageQuality)==null?void 0:d.toFixed(3))||"N/A"} avg, ${e.temporalStability.toFixed(1)}% stability`),f.log(`
1638
1638
  ⏱️ ===== TIMING BREAKDOWN (milliseconds) =====`),f.log(`📝 Validation: ${n.validation.avg.toFixed(2)}ms avg (${n.validation.min.toFixed(2)}-${n.validation.max.toFixed(2)}ms range)`),f.log(`🔍 Quality Check: ${n.qualityCheck.avg.toFixed(2)}ms avg (${n.qualityCheck.min.toFixed(2)}-${n.qualityCheck.max.toFixed(2)}ms range)`),f.log(`🤖 MediaPipe: ${n.mediaPipe.avg.toFixed(2)}ms avg (${n.mediaPipe.min.toFixed(2)}-${n.mediaPipe.max.toFixed(2)}ms range)`),f.log(`⚡ Total Frame: ${n.totalFrame.avg.toFixed(2)}ms avg (${n.totalFrame.min.toFixed(2)}-${n.totalFrame.max.toFixed(2)}ms range)`);const s=n.totalFrame.avg,i=n.mediaPipe.avg/s*100,r=n.validation.avg/s*100,o=n.qualityCheck.avg/s*100;f.log(`
1639
1639
  📊 ===== BOTTLENECK ANALYSIS =====`),f.log(`🤖 MediaPipe Processing: ${i.toFixed(1)}% of total time`),f.log(`📝 Validation: ${r.toFixed(1)}% of total time`),f.log(`🔍 Quality Check: ${o.toFixed(1)}% of total time`),f.log("🎯 Target Frame Time: 33.33ms for 30 FPS"),f.log(`📈 Actual Frame Time: ${s.toFixed(2)}ms (${(1e3/s).toFixed(1)} FPS capability)`),f.log(`⚠️ Performance Gap: ${Math.max(0,s-33.33).toFixed(2)}ms overhead`);const c=(performance.now()-this.startTime)/e.frameCount,l=1e3/e.targetFPS,h=s/c*100,u=c-s;if(f.log(`
@@ -1641,9 +1641,9 @@ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of t
1641
1641
  📊 ===== FRAME INTERVAL DISTRIBUTION =====`),f.log(`📏 Measured Intervals: ${p.avg.toFixed(2)}ms avg (${p.min.toFixed(2)}-${p.max.toFixed(2)}ms range)`),f.log(`🎯 Target Interval: ${l.toFixed(2)}ms`),f.log(`📈 Interval Accuracy: ${(l/p.avg*100).toFixed(1)}%`);const m=Math.abs(p.avg-l);m>10&&(f.log(`⚠️ Large deviation from target interval: ${m.toFixed(1)}ms`),p.avg>l?f.log(" 🐌 Intervals too long - frame capture rate limiting issue"):f.log(" 🏃 Intervals too short - processing can't keep up"))}if(n.mediaPipeBreakdown){f.log(`
1642
1642
  🧠 ===== MEDIAPIPE DETAILED BREAKDOWN =====`);const p=n.mediaPipeBreakdown;f.log(`🛠️ Canvas Setup: ${p.canvasSetup.avg.toFixed(2)}ms avg`),f.log(`🤖 ML Detection: ${p.mlDetection.avg.toFixed(2)}ms avg`),f.log(`🖼️ Canvas Ops: ${p.canvasOps.avg.toFixed(2)}ms avg`),f.log(`✏️ Landmark Draw: ${p.landmarkDraw.avg.toFixed(2)}ms avg`),f.log(`📍 ROI Coords: ${p.roiCoords.avg.toFixed(2)}ms avg`),f.log(`🎨 Contour Draw: ${p.contourDraw.avg.toFixed(2)}ms avg`),f.log(`🎯 RGB Calc: ${p.rgbCalc.avg.toFixed(2)}ms avg`),f.log(`💾 Data Storage: ${p.dataStorage.avg.toFixed(2)}ms avg`),f.log(`📐 Alignment: ${p.alignment.avg.toFixed(2)}ms avg`);const m=p.mlDetection.avg/n.mediaPipe.avg*100,y=p.rgbCalc.avg/n.mediaPipe.avg*100;f.log(`🔥 Top MediaPipe Bottlenecks: ML Detection (${m.toFixed(1)}%), RGB Calc (${y.toFixed(1)}%)`)}f.log(`
1643
1643
  🚀 ===== OPTIMIZATION RECOMMENDATIONS =====`),s>50?(f.log(`⚠️ CRITICAL: Frame processing too slow (${s.toFixed(1)}ms > 50ms)`),i>70&&f.log(` 🎯 Focus on MediaPipe optimization (${i.toFixed(1)}% of time)`)):s>33.33?f.log(`⚠️ WARNING: Missing 30 FPS target by ${(s-33.33).toFixed(1)}ms`):f.log("✅ EXCELLENT: Frame processing within 30 FPS target"),f.log(`=================================================
1644
- `)}getFrameStatistics(){const e=performance.now()-this.startTime,n=this.isContinuousMode?this.totalFrameCount:this.frameCount,s=e>0?n*1e3/e:0,i=this.qualityBuffer.length>0?this.qualityBuffer.reduce((o,a)=>o+a,0)/this.qualityBuffer.length:null;let r=100;if(this.frameTimes.length>10){const o=[];for(let h=1;h<this.frameTimes.length;h++)o.push(this.frameTimes[h]-this.frameTimes[h-1]);const a=o.reduce((h,u)=>h+u,0)/o.length,c=o.reduce((h,u)=>h+Math.pow(u-a,2),0)/o.length,l=Math.sqrt(c);r=Math.max(0,(1-l/a)*100)}return{frameCount:n,droppedFrames:this.droppedFrames,qualityDrops:this.qualityDrops,duplicateFrames:this.duplicateFrames,targetFPS:this.config.targetFPS,actualFPS:s,averageQuality:i,captureMethod:this.captureMethod,elapsedTime:e,temporalStability:r}}setTargetFPS(e){this.config.targetFPS=Math.max(1,Math.min(120,e)),this.frameCapture&&this.frameCapture.setTargetFPS(this.config.targetFPS)}setMinFrameQuality(e){this.config.minFrameQuality=Math.max(0,Math.min(1,e))}setQualityControlEnabled(e){this.config.enableQualityControl=e,f.log(`[RGBManager] Quality control ${e?"enabled":"disabled"}`)}setFrameValidationEnabled(e){this.config.enableFrameValidation=e,f.log(`[RGBManager] Frame validation ${e?"enabled":"disabled"}`)}getConfiguration(){return{...this.config}}getCaptureMethod(){return this.captureMethod}getTotalFrameCount(){return this.totalFrameCount}resetTotalFrameCount(){this.totalFrameCount=0,f.log("[RGBManager] Total frame count reset to 0")}async switchCaptureMethod(e){if(this.isCollectingData)throw new Error("Cannot switch capture method during streaming");this.frameCapture&&this.frameCapture.cleanup(),this.config.captureMethod=e,await this.initializeFrameCapture(),f.log(`[RGBManager] Switched to capture method: ${this.captureMethod}`)}cleanup(){this.stopStreaming(),this.frameCapture&&(this.frameCapture.cleanup(),this.frameCapture=null)}setFrameValidationEnabled_Legacy(e){this.setFrameValidationEnabled(e)}isFrameValidationEnabled(){return this.config.enableFrameValidation}forceResetMediaPipeTimestamps(){this.faceLandmarker&&this.faceLandmarker.resetMediaPipeTimestamps()}enableContinuousMode(e){this.isContinuousMode=!0,this.continuousModeCallback=e,this.apiKey&&this.faceLandmarker&&this.faceLandmarker.startContinuousDataCollection(this.apiKey,e),f.log("[RGBManager] Continuous mode enabled")}disableContinuousMode(){this.isContinuousMode=!1,this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),f.log("[RGBManager] Continuous mode disabled")}isContinuousModeEnabled(){return this.isContinuousMode}getDataCollectionStatus(){return this.faceLandmarker?{isCollectingData:this.isCollectingData,bufferSize:this.faceLandmarker.getRGBDataBufferSize?this.faceLandmarker.getRGBDataBufferSize():"Unknown",threshold:this.faceLandmarker.getDataCollectionThreshold?this.faceLandmarker.getDataCollectionThreshold():300,frameCount:this.frameCount,totalFrameCount:this.totalFrameCount,captureMethod:this.captureMethod,isContinuousMode:this.isContinuousMode,isDetectionActive:this.faceLandmarker.isDetectionCurrentlyActive?this.faceLandmarker.isDetectionCurrentlyActive():"Unknown"}:{error:"Face landmarker not initialized"}}getRGBTimestamps(){return this.faceLandmarker?this.faceLandmarker.getRGBTimestamps?this.faceLandmarker.getRGBTimestamps():[]:[]}isFaceDetectionActive(){var e,n;return((n=(e=this.faceLandmarker)==null?void 0:e.isDetectionCurrentlyActive)==null?void 0:n.call(e))||!1}enableVideoEndDetection(e=5e3,n){this.videoEndDetectionEnabled=!0,this.noFrameTimeout=e,this.onVideoEnd=n,this.lastFrameReceivedTime=performance.now(),this.startVideoEndDetection(),f.log(`[RGBManager] Video end detection enabled with ${e}ms timeout`)}disableVideoEndDetection(){this.videoEndDetectionEnabled=!1,this.stopVideoEndDetection(),f.log("[RGBManager] Video end detection disabled")}startVideoEndDetection(){this.videoEndCheckInterval&&clearInterval(this.videoEndCheckInterval),this.videoEndCheckInterval=setInterval(()=>{const e=performance.now()-this.lastFrameReceivedTime;e>this.noFrameTimeout&&(f.log(`[RGBManager] Video end detected - no frames for ${e.toFixed(0)}ms`),this.handleVideoEnd())},1e3)}stopVideoEndDetection(){this.videoEndCheckInterval&&(clearInterval(this.videoEndCheckInterval),this.videoEndCheckInterval=null)}handleVideoEnd(){this.stopVideoEndDetection();const e=this.getFrameStatistics();e.frameCount>0?(f.log(`[RGBManager] Video end detected with ${e.frameCount} frames processed - triggering comprehensive analysis`),this.isContinuousMode&&this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),this.stopStreaming()):(f.log("[RGBManager] Video end detected but no frames processed - skipping comprehensive analysis"),this.isContinuousMode&&this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),this.stopStreaming()),this.onVideoEnd&&this.onVideoEnd(),f.log("[RGBManager] Video processing completed")}handleBatchResults(e){this.faceLandmarker&&this.faceLandmarker.handleBatchResults(e)}};_(kn,"instance");let Gr=kn;function Vg(t,e){return function(){return t.apply(e,arguments)}}const{toString:AE}=Object.prototype,{getPrototypeOf:eh}=Object,Fo=(t=>e=>{const n=AE.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),It=t=>(t=t.toLowerCase(),e=>Fo(e)===t),No=t=>e=>typeof e===t,{isArray:Ms}=Array,bi=No("undefined");function RE(t){return t!==null&&!bi(t)&&t.constructor!==null&&!bi(t.constructor)&&st(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const $g=It("ArrayBuffer");function IE(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&$g(t.buffer),e}const xE=No("string"),st=No("function"),Hg=No("number"),Do=t=>t!==null&&typeof t=="object",FE=t=>t===!0||t===!1,ar=t=>{if(Fo(t)!=="object")return!1;const e=eh(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},NE=It("Date"),DE=It("File"),PE=It("Blob"),LE=It("FileList"),OE=t=>Do(t)&&st(t.pipe),ME=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||st(t.append)&&((e=Fo(t))==="formdata"||e==="object"&&st(t.toString)&&t.toString()==="[object FormData]"))},BE=It("URLSearchParams"),[UE,VE,$E,HE]=["ReadableStream","Request","Response","Headers"].map(It),WE=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Oi(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let s,i;if(typeof t!="object"&&(t=[t]),Ms(t))for(s=0,i=t.length;s<i;s++)e.call(null,t[s],s,t);else{const r=n?Object.getOwnPropertyNames(t):Object.keys(t),o=r.length;let a;for(s=0;s<o;s++)a=r[s],e.call(null,t[a],a,t)}}function Wg(t,e){e=e.toLowerCase();const n=Object.keys(t);let s=n.length,i;for(;s-- >0;)if(i=n[s],e===i.toLowerCase())return i;return null}const Nn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Gg=t=>!bi(t)&&t!==Nn;function ic(){const{caseless:t}=Gg(this)&&this||{},e={},n=(s,i)=>{const r=t&&Wg(e,i)||i;ar(e[r])&&ar(s)?e[r]=ic(e[r],s):ar(s)?e[r]=ic({},s):Ms(s)?e[r]=s.slice():e[r]=s};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&Oi(arguments[s],n);return e}const GE=(t,e,n,{allOwnKeys:s}={})=>(Oi(e,(i,r)=>{n&&st(i)?t[r]=Vg(i,n):t[r]=i},{allOwnKeys:s}),t),jE=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),qE=(t,e,n,s)=>{t.prototype=Object.create(e.prototype,s),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},zE=(t,e,n,s)=>{let i,r,o;const a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),r=i.length;r-- >0;)o=i[r],(!s||s(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=n!==!1&&eh(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},KE=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const s=t.indexOf(e,n);return s!==-1&&s===n},YE=t=>{if(!t)return null;if(Ms(t))return t;let e=t.length;if(!Hg(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},XE=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&eh(Uint8Array)),QE=(t,e)=>{const s=(t&&t[Symbol.iterator]).call(t);let i;for(;(i=s.next())&&!i.done;){const r=i.value;e.call(t,r[0],r[1])}},JE=(t,e)=>{let n;const s=[];for(;(n=t.exec(e))!==null;)s.push(n);return s},ZE=It("HTMLFormElement"),e4=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,i){return s.toUpperCase()+i}),_d=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),t4=It("RegExp"),jg=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),s={};Oi(n,(i,r)=>{let o;(o=e(i,r,t))!==!1&&(s[r]=o||i)}),Object.defineProperties(t,s)},n4=t=>{jg(t,(e,n)=>{if(st(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const s=t[n];if(st(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},s4=(t,e)=>{const n={},s=i=>{i.forEach(r=>{n[r]=!0})};return Ms(t)?s(t):s(String(t).split(e)),n},i4=()=>{},r4=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function o4(t){return!!(t&&st(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}const a4=t=>{const e=new Array(10),n=(s,i)=>{if(Do(s)){if(e.indexOf(s)>=0)return;if(!("toJSON"in s)){e[i]=s;const r=Ms(s)?[]:{};return Oi(s,(o,a)=>{const c=n(o,i+1);!bi(c)&&(r[a]=c)}),e[i]=void 0,r}}return s};return n(t,0)},c4=It("AsyncFunction"),l4=t=>t&&(Do(t)||st(t))&&st(t.then)&&st(t.catch),qg=((t,e)=>t?setImmediate:e?((n,s)=>(Nn.addEventListener("message",({source:i,data:r})=>{i===Nn&&r===n&&s.length&&s.shift()()},!1),i=>{s.push(i),Nn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",st(Nn.postMessage)),h4=typeof queueMicrotask<"u"?queueMicrotask.bind(Nn):typeof process<"u"&&process.nextTick||qg,g={isArray:Ms,isArrayBuffer:$g,isBuffer:RE,isFormData:ME,isArrayBufferView:IE,isString:xE,isNumber:Hg,isBoolean:FE,isObject:Do,isPlainObject:ar,isReadableStream:UE,isRequest:VE,isResponse:$E,isHeaders:HE,isUndefined:bi,isDate:NE,isFile:DE,isBlob:PE,isRegExp:t4,isFunction:st,isStream:OE,isURLSearchParams:BE,isTypedArray:XE,isFileList:LE,forEach:Oi,merge:ic,extend:GE,trim:WE,stripBOM:jE,inherits:qE,toFlatObject:zE,kindOf:Fo,kindOfTest:It,endsWith:KE,toArray:YE,forEachEntry:QE,matchAll:JE,isHTMLForm:ZE,hasOwnProperty:_d,hasOwnProp:_d,reduceDescriptors:jg,freezeMethods:n4,toObjectSet:s4,toCamelCase:e4,noop:i4,toFiniteNumber:r4,findKey:Wg,global:Nn,isContextDefined:Gg,isSpecCompliantForm:o4,toJSONObject:a4,isAsyncFn:c4,isThenable:l4,setImmediate:qg,asap:h4};function M(t,e,n,s,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),s&&(this.request=s),i&&(this.response=i,this.status=i.status?i.status:null)}g.inherits(M,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:g.toJSONObject(this.config),code:this.code,status:this.status}}});const zg=M.prototype,Kg={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Kg[t]={value:t}});Object.defineProperties(M,Kg);Object.defineProperty(zg,"isAxiosError",{value:!0});M.from=(t,e,n,s,i,r)=>{const o=Object.create(zg);return g.toFlatObject(t,o,function(c){return c!==Error.prototype},a=>a!=="isAxiosError"),M.call(o,t.message,e,n,s,i),o.cause=t,o.name=t.name,r&&Object.assign(o,r),o};const u4=null;function rc(t){return g.isPlainObject(t)||g.isArray(t)}function Yg(t){return g.endsWith(t,"[]")?t.slice(0,-2):t}function yd(t,e,n){return t?t.concat(e).map(function(i,r){return i=Yg(i),!n&&r?"["+i+"]":i}).join(n?".":""):e}function d4(t){return g.isArray(t)&&!t.some(rc)}const f4=g.toFlatObject(g,{},null,function(e){return/^is[A-Z]/.test(e)});function Po(t,e,n){if(!g.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=g.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,w){return!g.isUndefined(w[y])});const s=n.metaTokens,i=n.visitor||h,r=n.dots,o=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&g.isSpecCompliantForm(e);if(!g.isFunction(i))throw new TypeError("visitor must be a function");function l(m){if(m===null)return"";if(g.isDate(m))return m.toISOString();if(!c&&g.isBlob(m))throw new M("Blob is not supported. Use a Buffer instead.");return g.isArrayBuffer(m)||g.isTypedArray(m)?c&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function h(m,y,w){let k=m;if(m&&!w&&typeof m=="object"){if(g.endsWith(y,"{}"))y=s?y:y.slice(0,-2),m=JSON.stringify(m);else if(g.isArray(m)&&d4(m)||(g.isFileList(m)||g.endsWith(y,"[]"))&&(k=g.toArray(m)))return y=Yg(y),k.forEach(function(T,P){!(g.isUndefined(T)||T===null)&&e.append(o===!0?yd([y],P,r):o===null?y:y+"[]",l(T))}),!1}return rc(m)?!0:(e.append(yd(w,y,r),l(m)),!1)}const u=[],d=Object.assign(f4,{defaultVisitor:h,convertValue:l,isVisitable:rc});function p(m,y){if(!g.isUndefined(m)){if(u.indexOf(m)!==-1)throw Error("Circular reference detected in "+y.join("."));u.push(m),g.forEach(m,function(k,E){(!(g.isUndefined(k)||k===null)&&i.call(e,k,g.isString(E)?E.trim():E,y,d))===!0&&p(k,y?y.concat(E):[E])}),u.pop()}}if(!g.isObject(t))throw new TypeError("data must be an object");return p(t),e}function vd(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(s){return e[s]})}function th(t,e){this._pairs=[],t&&Po(t,this,e)}const Xg=th.prototype;Xg.append=function(e,n){this._pairs.push([e,n])};Xg.toString=function(e){const n=e?function(s){return e.call(this,s,vd)}:vd;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function p4(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Qg(t,e,n){if(!e)return t;const s=n&&n.encode||p4;g.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let r;if(i?r=i(e,n):r=g.isURLSearchParams(e)?e.toString():new th(e,n).toString(s),r){const o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+r}return t}class Ed{constructor(){this.handlers=[]}use(e,n,s){return this.handlers.push({fulfilled:e,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){g.forEach(this.handlers,function(s){s!==null&&e(s)})}}const Jg={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},m4=typeof URLSearchParams<"u"?URLSearchParams:th,g4=typeof FormData<"u"?FormData:null,_4=typeof Blob<"u"?Blob:null,y4={isBrowser:!0,classes:{URLSearchParams:m4,FormData:g4,Blob:_4},protocols:["http","https","file","blob","url","data"]},nh=typeof window<"u"&&typeof document<"u",oc=typeof navigator=="object"&&navigator||void 0,v4=nh&&(!oc||["ReactNative","NativeScript","NS"].indexOf(oc.product)<0),E4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",w4=nh&&window.location.href||"http://localhost",b4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:nh,hasStandardBrowserEnv:v4,hasStandardBrowserWebWorkerEnv:E4,navigator:oc,origin:w4},Symbol.toStringTag,{value:"Module"})),Be={...b4,...y4};function C4(t,e){return Po(t,new Be.classes.URLSearchParams,Object.assign({visitor:function(n,s,i,r){return Be.isNode&&g.isBuffer(n)?(this.append(s,n.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))}function T4(t){return g.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function S4(t){const e={},n=Object.keys(t);let s;const i=n.length;let r;for(s=0;s<i;s++)r=n[s],e[r]=t[r];return e}function Zg(t){function e(n,s,i,r){let o=n[r++];if(o==="__proto__")return!0;const a=Number.isFinite(+o),c=r>=n.length;return o=!o&&g.isArray(i)?i.length:o,c?(g.hasOwnProp(i,o)?i[o]=[i[o],s]:i[o]=s,!a):((!i[o]||!g.isObject(i[o]))&&(i[o]=[]),e(n,s,i[o],r)&&g.isArray(i[o])&&(i[o]=S4(i[o])),!a)}if(g.isFormData(t)&&g.isFunction(t.entries)){const n={};return g.forEachEntry(t,(s,i)=>{e(T4(s),i,n,0)}),n}return null}function k4(t,e,n){if(g.isString(t))try{return(e||JSON.parse)(t),g.trim(t)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(t)}const Mi={transitional:Jg,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const s=n.getContentType()||"",i=s.indexOf("application/json")>-1,r=g.isObject(e);if(r&&g.isHTMLForm(e)&&(e=new FormData(e)),g.isFormData(e))return i?JSON.stringify(Zg(e)):e;if(g.isArrayBuffer(e)||g.isBuffer(e)||g.isStream(e)||g.isFile(e)||g.isBlob(e)||g.isReadableStream(e))return e;if(g.isArrayBufferView(e))return e.buffer;if(g.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(r){if(s.indexOf("application/x-www-form-urlencoded")>-1)return C4(e,this.formSerializer).toString();if((a=g.isFileList(e))||s.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Po(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return r||i?(n.setContentType("application/json",!1),k4(e)):e}],transformResponse:[function(e){const n=this.transitional||Mi.transitional,s=n&&n.forcedJSONParsing,i=this.responseType==="json";if(g.isResponse(e)||g.isReadableStream(e))return e;if(e&&g.isString(e)&&(s&&!this.responseType||i)){const o=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?M.from(a,M.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Be.classes.FormData,Blob:Be.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};g.forEach(["delete","get","head","post","put","patch"],t=>{Mi.headers[t]={}});const A4=g.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),R4=t=>{const e={};let n,s,i;return t&&t.split(`
1645
- `).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),s=o.substring(i+1).trim(),!(!n||e[n]&&A4[n])&&(n==="set-cookie"?e[n]?e[n].push(s):e[n]=[s]:e[n]=e[n]?e[n]+", "+s:s)}),e},wd=Symbol("internals");function zs(t){return t&&String(t).trim().toLowerCase()}function cr(t){return t===!1||t==null?t:g.isArray(t)?t.map(cr):String(t)}function I4(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(t);)e[s[1]]=s[2];return e}const x4=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ga(t,e,n,s,i){if(g.isFunction(s))return s.call(this,e,n);if(i&&(e=n),!!g.isString(e)){if(g.isString(s))return e.indexOf(s)!==-1;if(g.isRegExp(s))return s.test(e)}}function F4(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,s)=>n.toUpperCase()+s)}function N4(t,e){const n=g.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+n,{value:function(i,r,o){return this[s].call(this,e,i,r,o)},configurable:!0})})}let Ke=class{constructor(e){e&&this.set(e)}set(e,n,s){const i=this;function r(a,c,l){const h=zs(c);if(!h)throw new Error("header name must be a non-empty string");const u=g.findKey(i,h);(!u||i[u]===void 0||l===!0||l===void 0&&i[u]!==!1)&&(i[u||c]=cr(a))}const o=(a,c)=>g.forEach(a,(l,h)=>r(l,h,c));if(g.isPlainObject(e)||e instanceof this.constructor)o(e,n);else if(g.isString(e)&&(e=e.trim())&&!x4(e))o(R4(e),n);else if(g.isHeaders(e))for(const[a,c]of e.entries())r(c,a,s);else e!=null&&r(n,e,s);return this}get(e,n){if(e=zs(e),e){const s=g.findKey(this,e);if(s){const i=this[s];if(!n)return i;if(n===!0)return I4(i);if(g.isFunction(n))return n.call(this,i,s);if(g.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=zs(e),e){const s=g.findKey(this,e);return!!(s&&this[s]!==void 0&&(!n||ga(this,this[s],s,n)))}return!1}delete(e,n){const s=this;let i=!1;function r(o){if(o=zs(o),o){const a=g.findKey(s,o);a&&(!n||ga(s,s[a],a,n))&&(delete s[a],i=!0)}}return g.isArray(e)?e.forEach(r):r(e),i}clear(e){const n=Object.keys(this);let s=n.length,i=!1;for(;s--;){const r=n[s];(!e||ga(this,this[r],r,e,!0))&&(delete this[r],i=!0)}return i}normalize(e){const n=this,s={};return g.forEach(this,(i,r)=>{const o=g.findKey(s,r);if(o){n[o]=cr(i),delete n[r];return}const a=e?F4(r):String(r).trim();a!==r&&delete n[r],n[a]=cr(i),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return g.forEach(this,(s,i)=>{s!=null&&s!==!1&&(n[i]=e&&g.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(`
1646
- `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const s=new this(e);return n.forEach(i=>s.set(i)),s}static accessor(e){const s=(this[wd]=this[wd]={accessors:{}}).accessors,i=this.prototype;function r(o){const a=zs(o);s[a]||(N4(i,o),s[a]=!0)}return g.isArray(e)?e.forEach(r):r(e),this}};Ke.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);g.reduceDescriptors(Ke.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(s){this[n]=s}}});g.freezeMethods(Ke);function _a(t,e){const n=this||Mi,s=e||n,i=Ke.from(s.headers);let r=s.data;return g.forEach(t,function(a){r=a.call(n,r,i.normalize(),e?e.status:void 0)}),i.normalize(),r}function e1(t){return!!(t&&t.__CANCEL__)}function Bs(t,e,n){M.call(this,t??"canceled",M.ERR_CANCELED,e,n),this.name="CanceledError"}g.inherits(Bs,M,{__CANCEL__:!0});function t1(t,e,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?t(n):e(new M("Request failed with status code "+n.status,[M.ERR_BAD_REQUEST,M.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function D4(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function P4(t,e){t=t||10;const n=new Array(t),s=new Array(t);let i=0,r=0,o;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),h=s[r];o||(o=l),n[i]=c,s[i]=l;let u=r,d=0;for(;u!==i;)d+=n[u++],u=u%t;if(i=(i+1)%t,i===r&&(r=(r+1)%t),l-o<e)return;const p=h&&l-h;return p?Math.round(d*1e3/p):void 0}}function L4(t,e){let n=0,s=1e3/e,i,r;const o=(l,h=Date.now())=>{n=h,i=null,r&&(clearTimeout(r),r=null),t.apply(null,l)};return[(...l)=>{const h=Date.now(),u=h-n;u>=s?o(l,h):(i=l,r||(r=setTimeout(()=>{r=null,o(i)},s-u)))},()=>i&&o(i)]}const jr=(t,e,n=3)=>{let s=0;const i=P4(50,250);return L4(r=>{const o=r.loaded,a=r.lengthComputable?r.total:void 0,c=o-s,l=i(c),h=o<=a;s=o;const u={loaded:o,total:a,progress:a?o/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&h?(a-o)/l:void 0,event:r,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(u)},n)},bd=(t,e)=>{const n=t!=null;return[s=>e[0]({lengthComputable:n,total:t,loaded:s}),e[1]]},Cd=t=>(...e)=>g.asap(()=>t(...e)),O4=Be.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,Be.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(Be.origin),Be.navigator&&/(msie|trident)/i.test(Be.navigator.userAgent)):()=>!0,M4=Be.hasStandardBrowserEnv?{write(t,e,n,s,i,r){const o=[t+"="+encodeURIComponent(e)];g.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),g.isString(s)&&o.push("path="+s),g.isString(i)&&o.push("domain="+i),r===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function B4(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function U4(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function n1(t,e,n){let s=!B4(e);return t&&(s||n==!1)?U4(t,e):e}const Td=t=>t instanceof Ke?{...t}:t;function $n(t,e){e=e||{};const n={};function s(l,h,u,d){return g.isPlainObject(l)&&g.isPlainObject(h)?g.merge.call({caseless:d},l,h):g.isPlainObject(h)?g.merge({},h):g.isArray(h)?h.slice():h}function i(l,h,u,d){if(g.isUndefined(h)){if(!g.isUndefined(l))return s(void 0,l,u,d)}else return s(l,h,u,d)}function r(l,h){if(!g.isUndefined(h))return s(void 0,h)}function o(l,h){if(g.isUndefined(h)){if(!g.isUndefined(l))return s(void 0,l)}else return s(void 0,h)}function a(l,h,u){if(u in e)return s(l,h);if(u in t)return s(void 0,l)}const c={url:r,method:r,data:r,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(l,h,u)=>i(Td(l),Td(h),u,!0)};return g.forEach(Object.keys(Object.assign({},t,e)),function(h){const u=c[h]||i,d=u(t[h],e[h],h);g.isUndefined(d)&&u!==a||(n[h]=d)}),n}const s1=t=>{const e=$n({},t);let{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:r,headers:o,auth:a}=e;e.headers=o=Ke.from(o),e.url=Qg(n1(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let c;if(g.isFormData(n)){if(Be.hasStandardBrowserEnv||Be.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((c=o.getContentType())!==!1){const[l,...h]=c?c.split(";").map(u=>u.trim()).filter(Boolean):[];o.setContentType([l||"multipart/form-data",...h].join("; "))}}if(Be.hasStandardBrowserEnv&&(s&&g.isFunction(s)&&(s=s(e)),s||s!==!1&&O4(e.url))){const l=i&&r&&M4.read(r);l&&o.set(i,l)}return e},V4=typeof XMLHttpRequest<"u",$4=V4&&function(t){return new Promise(function(n,s){const i=s1(t);let r=i.data;const o=Ke.from(i.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=i,h,u,d,p,m;function y(){p&&p(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(h),i.signal&&i.signal.removeEventListener("abort",h)}let w=new XMLHttpRequest;w.open(i.method.toUpperCase(),i.url,!0),w.timeout=i.timeout;function k(){if(!w)return;const T=Ke.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:T,config:t,request:w};t1(function(R){n(R),y()},function(R){s(R),y()},C),w=null}"onloadend"in w?w.onloadend=k:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(k)},w.onabort=function(){w&&(s(new M("Request aborted",M.ECONNABORTED,t,w)),w=null)},w.onerror=function(){s(new M("Network Error",M.ERR_NETWORK,t,w)),w=null},w.ontimeout=function(){let P=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const C=i.transitional||Jg;i.timeoutErrorMessage&&(P=i.timeoutErrorMessage),s(new M(P,C.clarifyTimeoutError?M.ETIMEDOUT:M.ECONNABORTED,t,w)),w=null},r===void 0&&o.setContentType(null),"setRequestHeader"in w&&g.forEach(o.toJSON(),function(P,C){w.setRequestHeader(C,P)}),g.isUndefined(i.withCredentials)||(w.withCredentials=!!i.withCredentials),a&&a!=="json"&&(w.responseType=i.responseType),l&&([d,m]=jr(l,!0),w.addEventListener("progress",d)),c&&w.upload&&([u,p]=jr(c),w.upload.addEventListener("progress",u),w.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(h=T=>{w&&(s(!T||T.type?new Bs(null,t,w):T),w.abort(),w=null)},i.cancelToken&&i.cancelToken.subscribe(h),i.signal&&(i.signal.aborted?h():i.signal.addEventListener("abort",h)));const E=D4(i.url);if(E&&Be.protocols.indexOf(E)===-1){s(new M("Unsupported protocol "+E+":",M.ERR_BAD_REQUEST,t));return}w.send(r||null)})},H4=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let s=new AbortController,i;const r=function(l){if(!i){i=!0,a();const h=l instanceof Error?l:this.reason;s.abort(h instanceof M?h:new Bs(h instanceof Error?h.message:h))}};let o=e&&setTimeout(()=>{o=null,r(new M(`timeout ${e} of ms exceeded`,M.ETIMEDOUT))},e);const a=()=>{t&&(o&&clearTimeout(o),o=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(r):l.removeEventListener("abort",r)}),t=null)};t.forEach(l=>l.addEventListener("abort",r));const{signal:c}=s;return c.unsubscribe=()=>g.asap(a),c}},W4=function*(t,e){let n=t.byteLength;if(n<e){yield t;return}let s=0,i;for(;s<n;)i=s+e,yield t.slice(s,i),s=i},G4=async function*(t,e){for await(const n of j4(t))yield*W4(n,e)},j4=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:n,value:s}=await e.read();if(n)break;yield s}}finally{await e.cancel()}},Sd=(t,e,n,s)=>{const i=G4(t,e);let r=0,o,a=c=>{o||(o=!0,s&&s(c))};return new ReadableStream({async pull(c){try{const{done:l,value:h}=await i.next();if(l){a(),c.close();return}let u=h.byteLength;if(n){let d=r+=u;n(d)}c.enqueue(new Uint8Array(h))}catch(l){throw a(l),l}},cancel(c){return a(c),i.return()}},{highWaterMark:2})},Lo=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",i1=Lo&&typeof ReadableStream=="function",q4=Lo&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),r1=(t,...e)=>{try{return!!t(...e)}catch{return!1}},z4=i1&&r1(()=>{let t=!1;const e=new Request(Be.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),kd=64*1024,ac=i1&&r1(()=>g.isReadableStream(new Response("").body)),qr={stream:ac&&(t=>t.body)};Lo&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!qr[e]&&(qr[e]=g.isFunction(t[e])?n=>n[e]():(n,s)=>{throw new M(`Response type '${e}' is not supported`,M.ERR_NOT_SUPPORT,s)})})})(new Response);const K4=async t=>{if(t==null)return 0;if(g.isBlob(t))return t.size;if(g.isSpecCompliantForm(t))return(await new Request(Be.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(g.isArrayBufferView(t)||g.isArrayBuffer(t))return t.byteLength;if(g.isURLSearchParams(t)&&(t=t+""),g.isString(t))return(await q4(t)).byteLength},Y4=async(t,e)=>{const n=g.toFiniteNumber(t.getContentLength());return n??K4(e)},X4=Lo&&(async t=>{let{url:e,method:n,data:s,signal:i,cancelToken:r,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:h,withCredentials:u="same-origin",fetchOptions:d}=s1(t);l=l?(l+"").toLowerCase():"text";let p=H4([i,r&&r.toAbortSignal()],o),m;const y=p&&p.unsubscribe&&(()=>{p.unsubscribe()});let w;try{if(c&&z4&&n!=="get"&&n!=="head"&&(w=await Y4(h,s))!==0){let C=new Request(e,{method:"POST",body:s,duplex:"half"}),v;if(g.isFormData(s)&&(v=C.headers.get("content-type"))&&h.setContentType(v),C.body){const[R,D]=bd(w,jr(Cd(c)));s=Sd(C.body,kd,R,D)}}g.isString(u)||(u=u?"include":"omit");const k="credentials"in Request.prototype;m=new Request(e,{...d,signal:p,method:n.toUpperCase(),headers:h.normalize().toJSON(),body:s,duplex:"half",credentials:k?u:void 0});let E=await fetch(m);const T=ac&&(l==="stream"||l==="response");if(ac&&(a||T&&y)){const C={};["status","statusText","headers"].forEach(U=>{C[U]=E[U]});const v=g.toFiniteNumber(E.headers.get("content-length")),[R,D]=a&&bd(v,jr(Cd(a),!0))||[];E=new Response(Sd(E.body,kd,R,()=>{D&&D(),y&&y()}),C)}l=l||"text";let P=await qr[g.findKey(qr,l)||"text"](E,t);return!T&&y&&y(),await new Promise((C,v)=>{t1(C,v,{data:P,headers:Ke.from(E.headers),status:E.status,statusText:E.statusText,config:t,request:m})})}catch(k){throw y&&y(),k&&k.name==="TypeError"&&/fetch/i.test(k.message)?Object.assign(new M("Network Error",M.ERR_NETWORK,t,m),{cause:k.cause||k}):M.from(k,k&&k.code,t,m)}}),cc={http:u4,xhr:$4,fetch:X4};g.forEach(cc,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Ad=t=>`- ${t}`,Q4=t=>g.isFunction(t)||t===null||t===!1,o1={getAdapter:t=>{t=g.isArray(t)?t:[t];const{length:e}=t;let n,s;const i={};for(let r=0;r<e;r++){n=t[r];let o;if(s=n,!Q4(n)&&(s=cc[(o=String(n)).toLowerCase()],s===void 0))throw new M(`Unknown adapter '${o}'`);if(s)break;i[o||"#"+r]=s}if(!s){const r=Object.entries(i).map(([a,c])=>`adapter ${a} `+(c===!1?"is not supported by the environment":"is not available in the build"));let o=e?r.length>1?`since :
1644
+ `)}getFrameStatistics(){const e=performance.now()-this.startTime,n=this.isContinuousMode?this.totalFrameCount:this.frameCount,s=e>0?n*1e3/e:0,i=this.qualityBuffer.length>0?this.qualityBuffer.reduce((o,a)=>o+a,0)/this.qualityBuffer.length:null;let r=100;if(this.frameTimes.length>10){const o=[];for(let h=1;h<this.frameTimes.length;h++)o.push(this.frameTimes[h]-this.frameTimes[h-1]);const a=o.reduce((h,u)=>h+u,0)/o.length,c=o.reduce((h,u)=>h+Math.pow(u-a,2),0)/o.length,l=Math.sqrt(c);r=Math.max(0,(1-l/a)*100)}return{frameCount:n,droppedFrames:this.droppedFrames,qualityDrops:this.qualityDrops,duplicateFrames:this.duplicateFrames,targetFPS:this.config.targetFPS,actualFPS:s,averageQuality:i,captureMethod:this.captureMethod,elapsedTime:e,temporalStability:r}}setTargetFPS(e){this.config.targetFPS=Math.max(1,Math.min(120,e)),this.frameCapture&&this.frameCapture.setTargetFPS(this.config.targetFPS)}setMinFrameQuality(e){this.config.minFrameQuality=Math.max(0,Math.min(1,e))}setQualityControlEnabled(e){this.config.enableQualityControl=e,f.log(`[RGBManager] Quality control ${e?"enabled":"disabled"}`)}setFrameValidationEnabled(e){this.config.enableFrameValidation=e,f.log(`[RGBManager] Frame validation ${e?"enabled":"disabled"}`)}getConfiguration(){return{...this.config}}getCaptureMethod(){return this.captureMethod}getTotalFrameCount(){return this.totalFrameCount}resetTotalFrameCount(){this.totalFrameCount=0,f.log("[RGBManager] Total frame count reset to 0")}async switchCaptureMethod(e){if(this.isCollectingData)throw new Error("Cannot switch capture method during streaming");this.frameCapture&&this.frameCapture.cleanup(),this.config.captureMethod=e,await this.initializeFrameCapture(),f.log(`[RGBManager] Switched to capture method: ${this.captureMethod}`)}cleanup(){this.stopStreaming(),this.frameCapture&&(this.frameCapture.cleanup(),this.frameCapture=null)}setFrameValidationEnabled_Legacy(e){this.setFrameValidationEnabled(e)}isFrameValidationEnabled(){return this.config.enableFrameValidation}forceResetMediaPipeTimestamps(){this.faceLandmarker&&this.faceLandmarker.resetMediaPipeTimestamps()}enableContinuousMode(e){this.isContinuousMode=!0,this.continuousModeCallback=e,this.apiKey&&this.faceLandmarker&&this.faceLandmarker.startContinuousDataCollection(this.apiKey,e),f.log("[RGBManager] Continuous mode enabled")}disableContinuousMode(){this.isContinuousMode=!1,this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),f.log("[RGBManager] Continuous mode disabled")}isContinuousModeEnabled(){return this.isContinuousMode}getDataCollectionStatus(){return this.faceLandmarker?{isCollectingData:this.isCollectingData,bufferSize:this.faceLandmarker.getRGBDataBufferSize?this.faceLandmarker.getRGBDataBufferSize():"Unknown",threshold:this.faceLandmarker.getDataCollectionThreshold?this.faceLandmarker.getDataCollectionThreshold():300,frameCount:this.frameCount,totalFrameCount:this.totalFrameCount,captureMethod:this.captureMethod,isContinuousMode:this.isContinuousMode,isDetectionActive:this.faceLandmarker.isDetectionCurrentlyActive?this.faceLandmarker.isDetectionCurrentlyActive():"Unknown"}:{error:"Face landmarker not initialized"}}getRGBTimestamps(){return this.faceLandmarker?this.faceLandmarker.getRGBTimestamps?this.faceLandmarker.getRGBTimestamps():[]:[]}isFaceDetectionActive(){var e,n;return((n=(e=this.faceLandmarker)==null?void 0:e.isDetectionCurrentlyActive)==null?void 0:n.call(e))||!1}enableVideoEndDetection(e=5e3,n){this.videoEndDetectionEnabled=!0,this.noFrameTimeout=e,this.onVideoEnd=n,this.lastFrameReceivedTime=performance.now(),this.startVideoEndDetection(),f.log(`[RGBManager] Video end detection enabled with ${e}ms timeout`)}disableVideoEndDetection(){this.videoEndDetectionEnabled=!1,this.stopVideoEndDetection(),f.log("[RGBManager] Video end detection disabled")}startVideoEndDetection(){this.videoEndCheckInterval&&clearInterval(this.videoEndCheckInterval),this.videoEndCheckInterval=setInterval(()=>{const e=performance.now()-this.lastFrameReceivedTime;e>this.noFrameTimeout&&(f.log(`[RGBManager] Video end detected - no frames for ${e.toFixed(0)}ms`),this.handleVideoEnd())},1e3)}stopVideoEndDetection(){this.videoEndCheckInterval&&(clearInterval(this.videoEndCheckInterval),this.videoEndCheckInterval=null)}handleVideoEnd(){this.stopVideoEndDetection();const e=this.getFrameStatistics();e.frameCount>0?(f.log(`[RGBManager] Video end detected with ${e.frameCount} frames processed - triggering comprehensive analysis`),this.isContinuousMode&&this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),this.stopStreaming()):(f.log("[RGBManager] Video end detected but no frames processed - skipping comprehensive analysis"),this.isContinuousMode&&this.faceLandmarker&&this.faceLandmarker.stopContinuousDataCollection(),this.stopStreaming()),this.onVideoEnd&&this.onVideoEnd(),f.log("[RGBManager] Video processing completed")}handleBatchResults(e){this.faceLandmarker&&this.faceLandmarker.handleBatchResults(e)}};_(kn,"instance");let Wr=kn;function $g(t,e){return function(){return t.apply(e,arguments)}}const{toString:RE}=Object.prototype,{getPrototypeOf:eh}=Object,xo=(t=>e=>{const n=RE.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),It=t=>(t=t.toLowerCase(),e=>xo(e)===t),No=t=>e=>typeof e===t,{isArray:Ms}=Array,bi=No("undefined");function IE(t){return t!==null&&!bi(t)&&t.constructor!==null&&!bi(t.constructor)&&st(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Hg=It("ArrayBuffer");function xE(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Hg(t.buffer),e}const NE=No("string"),st=No("function"),Wg=No("number"),Fo=t=>t!==null&&typeof t=="object",FE=t=>t===!0||t===!1,ar=t=>{if(xo(t)!=="object")return!1;const e=eh(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},DE=It("Date"),PE=It("File"),LE=It("Blob"),OE=It("FileList"),ME=t=>Fo(t)&&st(t.pipe),BE=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||st(t.append)&&((e=xo(t))==="formdata"||e==="object"&&st(t.toString)&&t.toString()==="[object FormData]"))},UE=It("URLSearchParams"),[VE,$E,HE,WE]=["ReadableStream","Request","Response","Headers"].map(It),GE=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Oi(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let s,i;if(typeof t!="object"&&(t=[t]),Ms(t))for(s=0,i=t.length;s<i;s++)e.call(null,t[s],s,t);else{const r=n?Object.getOwnPropertyNames(t):Object.keys(t),o=r.length;let a;for(s=0;s<o;s++)a=r[s],e.call(null,t[a],a,t)}}function Gg(t,e){e=e.toLowerCase();const n=Object.keys(t);let s=n.length,i;for(;s-- >0;)if(i=n[s],e===i.toLowerCase())return i;return null}const Fn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,jg=t=>!bi(t)&&t!==Fn;function ic(){const{caseless:t}=jg(this)&&this||{},e={},n=(s,i)=>{const r=t&&Gg(e,i)||i;ar(e[r])&&ar(s)?e[r]=ic(e[r],s):ar(s)?e[r]=ic({},s):Ms(s)?e[r]=s.slice():e[r]=s};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&Oi(arguments[s],n);return e}const jE=(t,e,n,{allOwnKeys:s}={})=>(Oi(e,(i,r)=>{n&&st(i)?t[r]=$g(i,n):t[r]=i},{allOwnKeys:s}),t),qE=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),zE=(t,e,n,s)=>{t.prototype=Object.create(e.prototype,s),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},KE=(t,e,n,s)=>{let i,r,o;const a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),r=i.length;r-- >0;)o=i[r],(!s||s(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=n!==!1&&eh(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},YE=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const s=t.indexOf(e,n);return s!==-1&&s===n},XE=t=>{if(!t)return null;if(Ms(t))return t;let e=t.length;if(!Wg(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},QE=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&eh(Uint8Array)),JE=(t,e)=>{const s=(t&&t[Symbol.iterator]).call(t);let i;for(;(i=s.next())&&!i.done;){const r=i.value;e.call(t,r[0],r[1])}},ZE=(t,e)=>{let n;const s=[];for(;(n=t.exec(e))!==null;)s.push(n);return s},e4=It("HTMLFormElement"),t4=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,i){return s.toUpperCase()+i}),_d=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),n4=It("RegExp"),qg=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),s={};Oi(n,(i,r)=>{let o;(o=e(i,r,t))!==!1&&(s[r]=o||i)}),Object.defineProperties(t,s)},s4=t=>{qg(t,(e,n)=>{if(st(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const s=t[n];if(st(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},i4=(t,e)=>{const n={},s=i=>{i.forEach(r=>{n[r]=!0})};return Ms(t)?s(t):s(String(t).split(e)),n},r4=()=>{},o4=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function a4(t){return!!(t&&st(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}const c4=t=>{const e=new Array(10),n=(s,i)=>{if(Fo(s)){if(e.indexOf(s)>=0)return;if(!("toJSON"in s)){e[i]=s;const r=Ms(s)?[]:{};return Oi(s,(o,a)=>{const c=n(o,i+1);!bi(c)&&(r[a]=c)}),e[i]=void 0,r}}return s};return n(t,0)},l4=It("AsyncFunction"),h4=t=>t&&(Fo(t)||st(t))&&st(t.then)&&st(t.catch),zg=((t,e)=>t?setImmediate:e?((n,s)=>(Fn.addEventListener("message",({source:i,data:r})=>{i===Fn&&r===n&&s.length&&s.shift()()},!1),i=>{s.push(i),Fn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",st(Fn.postMessage)),u4=typeof queueMicrotask<"u"?queueMicrotask.bind(Fn):typeof process<"u"&&process.nextTick||zg,g={isArray:Ms,isArrayBuffer:Hg,isBuffer:IE,isFormData:BE,isArrayBufferView:xE,isString:NE,isNumber:Wg,isBoolean:FE,isObject:Fo,isPlainObject:ar,isReadableStream:VE,isRequest:$E,isResponse:HE,isHeaders:WE,isUndefined:bi,isDate:DE,isFile:PE,isBlob:LE,isRegExp:n4,isFunction:st,isStream:ME,isURLSearchParams:UE,isTypedArray:QE,isFileList:OE,forEach:Oi,merge:ic,extend:jE,trim:GE,stripBOM:qE,inherits:zE,toFlatObject:KE,kindOf:xo,kindOfTest:It,endsWith:YE,toArray:XE,forEachEntry:JE,matchAll:ZE,isHTMLForm:e4,hasOwnProperty:_d,hasOwnProp:_d,reduceDescriptors:qg,freezeMethods:s4,toObjectSet:i4,toCamelCase:t4,noop:r4,toFiniteNumber:o4,findKey:Gg,global:Fn,isContextDefined:jg,isSpecCompliantForm:a4,toJSONObject:c4,isAsyncFn:l4,isThenable:h4,setImmediate:zg,asap:u4};function M(t,e,n,s,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),s&&(this.request=s),i&&(this.response=i,this.status=i.status?i.status:null)}g.inherits(M,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:g.toJSONObject(this.config),code:this.code,status:this.status}}});const Kg=M.prototype,Yg={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Yg[t]={value:t}});Object.defineProperties(M,Yg);Object.defineProperty(Kg,"isAxiosError",{value:!0});M.from=(t,e,n,s,i,r)=>{const o=Object.create(Kg);return g.toFlatObject(t,o,function(c){return c!==Error.prototype},a=>a!=="isAxiosError"),M.call(o,t.message,e,n,s,i),o.cause=t,o.name=t.name,r&&Object.assign(o,r),o};const d4=null;function rc(t){return g.isPlainObject(t)||g.isArray(t)}function Xg(t){return g.endsWith(t,"[]")?t.slice(0,-2):t}function yd(t,e,n){return t?t.concat(e).map(function(i,r){return i=Xg(i),!n&&r?"["+i+"]":i}).join(n?".":""):e}function f4(t){return g.isArray(t)&&!t.some(rc)}const p4=g.toFlatObject(g,{},null,function(e){return/^is[A-Z]/.test(e)});function Do(t,e,n){if(!g.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=g.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,w){return!g.isUndefined(w[y])});const s=n.metaTokens,i=n.visitor||h,r=n.dots,o=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&g.isSpecCompliantForm(e);if(!g.isFunction(i))throw new TypeError("visitor must be a function");function l(m){if(m===null)return"";if(g.isDate(m))return m.toISOString();if(!c&&g.isBlob(m))throw new M("Blob is not supported. Use a Buffer instead.");return g.isArrayBuffer(m)||g.isTypedArray(m)?c&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function h(m,y,w){let k=m;if(m&&!w&&typeof m=="object"){if(g.endsWith(y,"{}"))y=s?y:y.slice(0,-2),m=JSON.stringify(m);else if(g.isArray(m)&&f4(m)||(g.isFileList(m)||g.endsWith(y,"[]"))&&(k=g.toArray(m)))return y=Xg(y),k.forEach(function(T,P){!(g.isUndefined(T)||T===null)&&e.append(o===!0?yd([y],P,r):o===null?y:y+"[]",l(T))}),!1}return rc(m)?!0:(e.append(yd(w,y,r),l(m)),!1)}const u=[],d=Object.assign(p4,{defaultVisitor:h,convertValue:l,isVisitable:rc});function p(m,y){if(!g.isUndefined(m)){if(u.indexOf(m)!==-1)throw Error("Circular reference detected in "+y.join("."));u.push(m),g.forEach(m,function(k,E){(!(g.isUndefined(k)||k===null)&&i.call(e,k,g.isString(E)?E.trim():E,y,d))===!0&&p(k,y?y.concat(E):[E])}),u.pop()}}if(!g.isObject(t))throw new TypeError("data must be an object");return p(t),e}function vd(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(s){return e[s]})}function th(t,e){this._pairs=[],t&&Do(t,this,e)}const Qg=th.prototype;Qg.append=function(e,n){this._pairs.push([e,n])};Qg.toString=function(e){const n=e?function(s){return e.call(this,s,vd)}:vd;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function m4(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Jg(t,e,n){if(!e)return t;const s=n&&n.encode||m4;g.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let r;if(i?r=i(e,n):r=g.isURLSearchParams(e)?e.toString():new th(e,n).toString(s),r){const o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+r}return t}class Ed{constructor(){this.handlers=[]}use(e,n,s){return this.handlers.push({fulfilled:e,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){g.forEach(this.handlers,function(s){s!==null&&e(s)})}}const Zg={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},g4=typeof URLSearchParams<"u"?URLSearchParams:th,_4=typeof FormData<"u"?FormData:null,y4=typeof Blob<"u"?Blob:null,v4={isBrowser:!0,classes:{URLSearchParams:g4,FormData:_4,Blob:y4},protocols:["http","https","file","blob","url","data"]},nh=typeof window<"u"&&typeof document<"u",oc=typeof navigator=="object"&&navigator||void 0,E4=nh&&(!oc||["ReactNative","NativeScript","NS"].indexOf(oc.product)<0),w4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",b4=nh&&window.location.href||"http://localhost",C4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:nh,hasStandardBrowserEnv:E4,hasStandardBrowserWebWorkerEnv:w4,navigator:oc,origin:b4},Symbol.toStringTag,{value:"Module"})),Be={...C4,...v4};function T4(t,e){return Do(t,new Be.classes.URLSearchParams,Object.assign({visitor:function(n,s,i,r){return Be.isNode&&g.isBuffer(n)?(this.append(s,n.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))}function S4(t){return g.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function k4(t){const e={},n=Object.keys(t);let s;const i=n.length;let r;for(s=0;s<i;s++)r=n[s],e[r]=t[r];return e}function e1(t){function e(n,s,i,r){let o=n[r++];if(o==="__proto__")return!0;const a=Number.isFinite(+o),c=r>=n.length;return o=!o&&g.isArray(i)?i.length:o,c?(g.hasOwnProp(i,o)?i[o]=[i[o],s]:i[o]=s,!a):((!i[o]||!g.isObject(i[o]))&&(i[o]=[]),e(n,s,i[o],r)&&g.isArray(i[o])&&(i[o]=k4(i[o])),!a)}if(g.isFormData(t)&&g.isFunction(t.entries)){const n={};return g.forEachEntry(t,(s,i)=>{e(S4(s),i,n,0)}),n}return null}function A4(t,e,n){if(g.isString(t))try{return(e||JSON.parse)(t),g.trim(t)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(t)}const Mi={transitional:Zg,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const s=n.getContentType()||"",i=s.indexOf("application/json")>-1,r=g.isObject(e);if(r&&g.isHTMLForm(e)&&(e=new FormData(e)),g.isFormData(e))return i?JSON.stringify(e1(e)):e;if(g.isArrayBuffer(e)||g.isBuffer(e)||g.isStream(e)||g.isFile(e)||g.isBlob(e)||g.isReadableStream(e))return e;if(g.isArrayBufferView(e))return e.buffer;if(g.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(r){if(s.indexOf("application/x-www-form-urlencoded")>-1)return T4(e,this.formSerializer).toString();if((a=g.isFileList(e))||s.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Do(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return r||i?(n.setContentType("application/json",!1),A4(e)):e}],transformResponse:[function(e){const n=this.transitional||Mi.transitional,s=n&&n.forcedJSONParsing,i=this.responseType==="json";if(g.isResponse(e)||g.isReadableStream(e))return e;if(e&&g.isString(e)&&(s&&!this.responseType||i)){const o=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?M.from(a,M.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Be.classes.FormData,Blob:Be.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};g.forEach(["delete","get","head","post","put","patch"],t=>{Mi.headers[t]={}});const R4=g.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),I4=t=>{const e={};let n,s,i;return t&&t.split(`
1645
+ `).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),s=o.substring(i+1).trim(),!(!n||e[n]&&R4[n])&&(n==="set-cookie"?e[n]?e[n].push(s):e[n]=[s]:e[n]=e[n]?e[n]+", "+s:s)}),e},wd=Symbol("internals");function zs(t){return t&&String(t).trim().toLowerCase()}function cr(t){return t===!1||t==null?t:g.isArray(t)?t.map(cr):String(t)}function x4(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(t);)e[s[1]]=s[2];return e}const N4=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ma(t,e,n,s,i){if(g.isFunction(s))return s.call(this,e,n);if(i&&(e=n),!!g.isString(e)){if(g.isString(s))return e.indexOf(s)!==-1;if(g.isRegExp(s))return s.test(e)}}function F4(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,s)=>n.toUpperCase()+s)}function D4(t,e){const n=g.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+n,{value:function(i,r,o){return this[s].call(this,e,i,r,o)},configurable:!0})})}let Ke=class{constructor(e){e&&this.set(e)}set(e,n,s){const i=this;function r(a,c,l){const h=zs(c);if(!h)throw new Error("header name must be a non-empty string");const u=g.findKey(i,h);(!u||i[u]===void 0||l===!0||l===void 0&&i[u]!==!1)&&(i[u||c]=cr(a))}const o=(a,c)=>g.forEach(a,(l,h)=>r(l,h,c));if(g.isPlainObject(e)||e instanceof this.constructor)o(e,n);else if(g.isString(e)&&(e=e.trim())&&!N4(e))o(I4(e),n);else if(g.isHeaders(e))for(const[a,c]of e.entries())r(c,a,s);else e!=null&&r(n,e,s);return this}get(e,n){if(e=zs(e),e){const s=g.findKey(this,e);if(s){const i=this[s];if(!n)return i;if(n===!0)return x4(i);if(g.isFunction(n))return n.call(this,i,s);if(g.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=zs(e),e){const s=g.findKey(this,e);return!!(s&&this[s]!==void 0&&(!n||ma(this,this[s],s,n)))}return!1}delete(e,n){const s=this;let i=!1;function r(o){if(o=zs(o),o){const a=g.findKey(s,o);a&&(!n||ma(s,s[a],a,n))&&(delete s[a],i=!0)}}return g.isArray(e)?e.forEach(r):r(e),i}clear(e){const n=Object.keys(this);let s=n.length,i=!1;for(;s--;){const r=n[s];(!e||ma(this,this[r],r,e,!0))&&(delete this[r],i=!0)}return i}normalize(e){const n=this,s={};return g.forEach(this,(i,r)=>{const o=g.findKey(s,r);if(o){n[o]=cr(i),delete n[r];return}const a=e?F4(r):String(r).trim();a!==r&&delete n[r],n[a]=cr(i),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return g.forEach(this,(s,i)=>{s!=null&&s!==!1&&(n[i]=e&&g.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(`
1646
+ `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const s=new this(e);return n.forEach(i=>s.set(i)),s}static accessor(e){const s=(this[wd]=this[wd]={accessors:{}}).accessors,i=this.prototype;function r(o){const a=zs(o);s[a]||(D4(i,o),s[a]=!0)}return g.isArray(e)?e.forEach(r):r(e),this}};Ke.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);g.reduceDescriptors(Ke.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(s){this[n]=s}}});g.freezeMethods(Ke);function ga(t,e){const n=this||Mi,s=e||n,i=Ke.from(s.headers);let r=s.data;return g.forEach(t,function(a){r=a.call(n,r,i.normalize(),e?e.status:void 0)}),i.normalize(),r}function t1(t){return!!(t&&t.__CANCEL__)}function Bs(t,e,n){M.call(this,t??"canceled",M.ERR_CANCELED,e,n),this.name="CanceledError"}g.inherits(Bs,M,{__CANCEL__:!0});function n1(t,e,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?t(n):e(new M("Request failed with status code "+n.status,[M.ERR_BAD_REQUEST,M.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function P4(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function L4(t,e){t=t||10;const n=new Array(t),s=new Array(t);let i=0,r=0,o;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),h=s[r];o||(o=l),n[i]=c,s[i]=l;let u=r,d=0;for(;u!==i;)d+=n[u++],u=u%t;if(i=(i+1)%t,i===r&&(r=(r+1)%t),l-o<e)return;const p=h&&l-h;return p?Math.round(d*1e3/p):void 0}}function O4(t,e){let n=0,s=1e3/e,i,r;const o=(l,h=Date.now())=>{n=h,i=null,r&&(clearTimeout(r),r=null),t.apply(null,l)};return[(...l)=>{const h=Date.now(),u=h-n;u>=s?o(l,h):(i=l,r||(r=setTimeout(()=>{r=null,o(i)},s-u)))},()=>i&&o(i)]}const Gr=(t,e,n=3)=>{let s=0;const i=L4(50,250);return O4(r=>{const o=r.loaded,a=r.lengthComputable?r.total:void 0,c=o-s,l=i(c),h=o<=a;s=o;const u={loaded:o,total:a,progress:a?o/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&h?(a-o)/l:void 0,event:r,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(u)},n)},bd=(t,e)=>{const n=t!=null;return[s=>e[0]({lengthComputable:n,total:t,loaded:s}),e[1]]},Cd=t=>(...e)=>g.asap(()=>t(...e)),M4=Be.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,Be.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(Be.origin),Be.navigator&&/(msie|trident)/i.test(Be.navigator.userAgent)):()=>!0,B4=Be.hasStandardBrowserEnv?{write(t,e,n,s,i,r){const o=[t+"="+encodeURIComponent(e)];g.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),g.isString(s)&&o.push("path="+s),g.isString(i)&&o.push("domain="+i),r===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function U4(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function V4(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function s1(t,e,n){let s=!U4(e);return t&&(s||n==!1)?V4(t,e):e}const Td=t=>t instanceof Ke?{...t}:t;function $n(t,e){e=e||{};const n={};function s(l,h,u,d){return g.isPlainObject(l)&&g.isPlainObject(h)?g.merge.call({caseless:d},l,h):g.isPlainObject(h)?g.merge({},h):g.isArray(h)?h.slice():h}function i(l,h,u,d){if(g.isUndefined(h)){if(!g.isUndefined(l))return s(void 0,l,u,d)}else return s(l,h,u,d)}function r(l,h){if(!g.isUndefined(h))return s(void 0,h)}function o(l,h){if(g.isUndefined(h)){if(!g.isUndefined(l))return s(void 0,l)}else return s(void 0,h)}function a(l,h,u){if(u in e)return s(l,h);if(u in t)return s(void 0,l)}const c={url:r,method:r,data:r,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(l,h,u)=>i(Td(l),Td(h),u,!0)};return g.forEach(Object.keys(Object.assign({},t,e)),function(h){const u=c[h]||i,d=u(t[h],e[h],h);g.isUndefined(d)&&u!==a||(n[h]=d)}),n}const i1=t=>{const e=$n({},t);let{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:r,headers:o,auth:a}=e;e.headers=o=Ke.from(o),e.url=Jg(s1(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let c;if(g.isFormData(n)){if(Be.hasStandardBrowserEnv||Be.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((c=o.getContentType())!==!1){const[l,...h]=c?c.split(";").map(u=>u.trim()).filter(Boolean):[];o.setContentType([l||"multipart/form-data",...h].join("; "))}}if(Be.hasStandardBrowserEnv&&(s&&g.isFunction(s)&&(s=s(e)),s||s!==!1&&M4(e.url))){const l=i&&r&&B4.read(r);l&&o.set(i,l)}return e},$4=typeof XMLHttpRequest<"u",H4=$4&&function(t){return new Promise(function(n,s){const i=i1(t);let r=i.data;const o=Ke.from(i.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=i,h,u,d,p,m;function y(){p&&p(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(h),i.signal&&i.signal.removeEventListener("abort",h)}let w=new XMLHttpRequest;w.open(i.method.toUpperCase(),i.url,!0),w.timeout=i.timeout;function k(){if(!w)return;const T=Ke.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:T,config:t,request:w};n1(function(R){n(R),y()},function(R){s(R),y()},C),w=null}"onloadend"in w?w.onloadend=k:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(k)},w.onabort=function(){w&&(s(new M("Request aborted",M.ECONNABORTED,t,w)),w=null)},w.onerror=function(){s(new M("Network Error",M.ERR_NETWORK,t,w)),w=null},w.ontimeout=function(){let P=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const C=i.transitional||Zg;i.timeoutErrorMessage&&(P=i.timeoutErrorMessage),s(new M(P,C.clarifyTimeoutError?M.ETIMEDOUT:M.ECONNABORTED,t,w)),w=null},r===void 0&&o.setContentType(null),"setRequestHeader"in w&&g.forEach(o.toJSON(),function(P,C){w.setRequestHeader(C,P)}),g.isUndefined(i.withCredentials)||(w.withCredentials=!!i.withCredentials),a&&a!=="json"&&(w.responseType=i.responseType),l&&([d,m]=Gr(l,!0),w.addEventListener("progress",d)),c&&w.upload&&([u,p]=Gr(c),w.upload.addEventListener("progress",u),w.upload.addEventListener("loadend",p)),(i.cancelToken||i.signal)&&(h=T=>{w&&(s(!T||T.type?new Bs(null,t,w):T),w.abort(),w=null)},i.cancelToken&&i.cancelToken.subscribe(h),i.signal&&(i.signal.aborted?h():i.signal.addEventListener("abort",h)));const E=P4(i.url);if(E&&Be.protocols.indexOf(E)===-1){s(new M("Unsupported protocol "+E+":",M.ERR_BAD_REQUEST,t));return}w.send(r||null)})},W4=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let s=new AbortController,i;const r=function(l){if(!i){i=!0,a();const h=l instanceof Error?l:this.reason;s.abort(h instanceof M?h:new Bs(h instanceof Error?h.message:h))}};let o=e&&setTimeout(()=>{o=null,r(new M(`timeout ${e} of ms exceeded`,M.ETIMEDOUT))},e);const a=()=>{t&&(o&&clearTimeout(o),o=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(r):l.removeEventListener("abort",r)}),t=null)};t.forEach(l=>l.addEventListener("abort",r));const{signal:c}=s;return c.unsubscribe=()=>g.asap(a),c}},G4=function*(t,e){let n=t.byteLength;if(n<e){yield t;return}let s=0,i;for(;s<n;)i=s+e,yield t.slice(s,i),s=i},j4=async function*(t,e){for await(const n of q4(t))yield*G4(n,e)},q4=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:n,value:s}=await e.read();if(n)break;yield s}}finally{await e.cancel()}},Sd=(t,e,n,s)=>{const i=j4(t,e);let r=0,o,a=c=>{o||(o=!0,s&&s(c))};return new ReadableStream({async pull(c){try{const{done:l,value:h}=await i.next();if(l){a(),c.close();return}let u=h.byteLength;if(n){let d=r+=u;n(d)}c.enqueue(new Uint8Array(h))}catch(l){throw a(l),l}},cancel(c){return a(c),i.return()}},{highWaterMark:2})},Po=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",r1=Po&&typeof ReadableStream=="function",z4=Po&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),o1=(t,...e)=>{try{return!!t(...e)}catch{return!1}},K4=r1&&o1(()=>{let t=!1;const e=new Request(Be.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),kd=64*1024,ac=r1&&o1(()=>g.isReadableStream(new Response("").body)),jr={stream:ac&&(t=>t.body)};Po&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!jr[e]&&(jr[e]=g.isFunction(t[e])?n=>n[e]():(n,s)=>{throw new M(`Response type '${e}' is not supported`,M.ERR_NOT_SUPPORT,s)})})})(new Response);const Y4=async t=>{if(t==null)return 0;if(g.isBlob(t))return t.size;if(g.isSpecCompliantForm(t))return(await new Request(Be.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(g.isArrayBufferView(t)||g.isArrayBuffer(t))return t.byteLength;if(g.isURLSearchParams(t)&&(t=t+""),g.isString(t))return(await z4(t)).byteLength},X4=async(t,e)=>{const n=g.toFiniteNumber(t.getContentLength());return n??Y4(e)},Q4=Po&&(async t=>{let{url:e,method:n,data:s,signal:i,cancelToken:r,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:h,withCredentials:u="same-origin",fetchOptions:d}=i1(t);l=l?(l+"").toLowerCase():"text";let p=W4([i,r&&r.toAbortSignal()],o),m;const y=p&&p.unsubscribe&&(()=>{p.unsubscribe()});let w;try{if(c&&K4&&n!=="get"&&n!=="head"&&(w=await X4(h,s))!==0){let C=new Request(e,{method:"POST",body:s,duplex:"half"}),v;if(g.isFormData(s)&&(v=C.headers.get("content-type"))&&h.setContentType(v),C.body){const[R,D]=bd(w,Gr(Cd(c)));s=Sd(C.body,kd,R,D)}}g.isString(u)||(u=u?"include":"omit");const k="credentials"in Request.prototype;m=new Request(e,{...d,signal:p,method:n.toUpperCase(),headers:h.normalize().toJSON(),body:s,duplex:"half",credentials:k?u:void 0});let E=await fetch(m);const T=ac&&(l==="stream"||l==="response");if(ac&&(a||T&&y)){const C={};["status","statusText","headers"].forEach(U=>{C[U]=E[U]});const v=g.toFiniteNumber(E.headers.get("content-length")),[R,D]=a&&bd(v,Gr(Cd(a),!0))||[];E=new Response(Sd(E.body,kd,R,()=>{D&&D(),y&&y()}),C)}l=l||"text";let P=await jr[g.findKey(jr,l)||"text"](E,t);return!T&&y&&y(),await new Promise((C,v)=>{n1(C,v,{data:P,headers:Ke.from(E.headers),status:E.status,statusText:E.statusText,config:t,request:m})})}catch(k){throw y&&y(),k&&k.name==="TypeError"&&/fetch/i.test(k.message)?Object.assign(new M("Network Error",M.ERR_NETWORK,t,m),{cause:k.cause||k}):M.from(k,k&&k.code,t,m)}}),cc={http:d4,xhr:H4,fetch:Q4};g.forEach(cc,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Ad=t=>`- ${t}`,J4=t=>g.isFunction(t)||t===null||t===!1,a1={getAdapter:t=>{t=g.isArray(t)?t:[t];const{length:e}=t;let n,s;const i={};for(let r=0;r<e;r++){n=t[r];let o;if(s=n,!J4(n)&&(s=cc[(o=String(n)).toLowerCase()],s===void 0))throw new M(`Unknown adapter '${o}'`);if(s)break;i[o||"#"+r]=s}if(!s){const r=Object.entries(i).map(([a,c])=>`adapter ${a} `+(c===!1?"is not supported by the environment":"is not available in the build"));let o=e?r.length>1?`since :
1647
1647
  `+r.map(Ad).join(`
1648
- `):" "+Ad(r[0]):"as no adapter specified";throw new M("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return s},adapters:cc};function ya(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Bs(null,t)}function Rd(t){return ya(t),t.headers=Ke.from(t.headers),t.data=_a.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),o1.getAdapter(t.adapter||Mi.adapter)(t).then(function(s){return ya(t),s.data=_a.call(t,t.transformResponse,s),s.headers=Ke.from(s.headers),s},function(s){return e1(s)||(ya(t),s&&s.response&&(s.response.data=_a.call(t,t.transformResponse,s.response),s.response.headers=Ke.from(s.response.headers))),Promise.reject(s)})}const a1="1.8.4",Oo={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Oo[t]=function(s){return typeof s===t||"a"+(e<1?"n ":" ")+t}});const Id={};Oo.transitional=function(e,n,s){function i(r,o){return"[Axios v"+a1+"] Transitional option '"+r+"'"+o+(s?". "+s:"")}return(r,o,a)=>{if(e===!1)throw new M(i(o," has been removed"+(n?" in "+n:"")),M.ERR_DEPRECATED);return n&&!Id[o]&&(Id[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(r,o,a):!0}};Oo.spelling=function(e){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};function J4(t,e,n){if(typeof t!="object")throw new M("options must be an object",M.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let i=s.length;for(;i-- >0;){const r=s[i],o=e[r];if(o){const a=t[r],c=a===void 0||o(a,r,t);if(c!==!0)throw new M("option "+r+" must be "+c,M.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new M("Unknown option "+r,M.ERR_BAD_OPTION)}}const lr={assertOptions:J4,validators:Oo},Lt=lr.validators;let Pn=class{constructor(e){this.defaults=e,this.interceptors={request:new Ed,response:new Ed}}async request(e,n){try{return await this._request(e,n)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?r&&!String(s.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(s.stack+=`
1649
- `+r):s.stack=r}catch{}}throw s}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=$n(this.defaults,n);const{transitional:s,paramsSerializer:i,headers:r}=n;s!==void 0&&lr.assertOptions(s,{silentJSONParsing:Lt.transitional(Lt.boolean),forcedJSONParsing:Lt.transitional(Lt.boolean),clarifyTimeoutError:Lt.transitional(Lt.boolean)},!1),i!=null&&(g.isFunction(i)?n.paramsSerializer={serialize:i}:lr.assertOptions(i,{encode:Lt.function,serialize:Lt.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),lr.assertOptions(n,{baseUrl:Lt.spelling("baseURL"),withXsrfToken:Lt.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=r&&g.merge(r.common,r[n.method]);r&&g.forEach(["delete","get","head","post","put","patch","common"],m=>{delete r[m]}),n.headers=Ke.concat(o,r);const a=[];let c=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(c=c&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let h,u=0,d;if(!c){const m=[Rd.bind(this),void 0];for(m.unshift.apply(m,a),m.push.apply(m,l),d=m.length,h=Promise.resolve(n);u<d;)h=h.then(m[u++],m[u++]);return h}d=a.length;let p=n;for(u=0;u<d;){const m=a[u++],y=a[u++];try{p=m(p)}catch(w){y.call(this,w);break}}try{h=Rd.call(this,p)}catch(m){return Promise.reject(m)}for(u=0,d=l.length;u<d;)h=h.then(l[u++],l[u++]);return h}getUri(e){e=$n(this.defaults,e);const n=n1(e.baseURL,e.url,e.allowAbsoluteUrls);return Qg(n,e.params,e.paramsSerializer)}};g.forEach(["delete","get","head","options"],function(e){Pn.prototype[e]=function(n,s){return this.request($n(s||{},{method:e,url:n,data:(s||{}).data}))}});g.forEach(["post","put","patch"],function(e){function n(s){return function(r,o,a){return this.request($n(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}Pn.prototype[e]=n(),Pn.prototype[e+"Form"]=n(!0)});let Z4=class c1{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(r){n=r});const s=this;this.promise.then(i=>{if(!s._listeners)return;let r=s._listeners.length;for(;r-- >0;)s._listeners[r](i);s._listeners=null}),this.promise.then=i=>{let r;const o=new Promise(a=>{s.subscribe(a),r=a}).then(i);return o.cancel=function(){s.unsubscribe(r)},o},e(function(r,o,a){s.reason||(s.reason=new Bs(r,o,a),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=s=>{e.abort(s)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new c1(function(i){e=i}),cancel:e}}};function ew(t){return function(n){return t.apply(null,n)}}function tw(t){return g.isObject(t)&&t.isAxiosError===!0}const lc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(lc).forEach(([t,e])=>{lc[e]=t});function l1(t){const e=new Pn(t),n=Vg(Pn.prototype.request,e);return g.extend(n,Pn.prototype,e,{allOwnKeys:!0}),g.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return l1($n(t,i))},n}const te=l1(Mi);te.Axios=Pn;te.CanceledError=Bs;te.CancelToken=Z4;te.isCancel=e1;te.VERSION=a1;te.toFormData=Po;te.AxiosError=M;te.Cancel=te.CanceledError;te.all=function(e){return Promise.all(e)};te.spread=ew;te.isAxiosError=tw;te.mergeConfig=$n;te.AxiosHeaders=Ke;te.formToJSON=t=>Zg(g.isHTMLForm(t)?new FormData(t):t);te.getAdapter=o1.getAdapter;te.HttpStatusCode=lc;te.default=te;const{Axios:tb,AxiosError:nb,CanceledError:sb,isCancel:ib,CancelToken:rb,VERSION:ob,all:ab,Cancel:cb,isAxiosError:lb,spread:hb,toFormData:ub,AxiosHeaders:db,HttpStatusCode:fb,formToJSON:pb,getAdapter:mb,mergeConfig:gb}=te,Bt=Object.create(null);Bt.open="0";Bt.close="1";Bt.ping="2";Bt.pong="3";Bt.message="4";Bt.upgrade="5";Bt.noop="6";const hr=Object.create(null);Object.keys(Bt).forEach(t=>{hr[Bt[t]]=t});const hc={type:"error",data:"parser error"},h1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",u1=typeof ArrayBuffer=="function",d1=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,sh=({type:t,data:e},n,s)=>h1&&e instanceof Blob?n?s(e):xd(e,s):u1&&(e instanceof ArrayBuffer||d1(e))?n?s(e):xd(new Blob([e]),s):s(Bt[t]+(e||"")),xd=(t,e)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];e("b"+(s||""))},n.readAsDataURL(t)};function Fd(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let va;function nw(t,e){if(h1&&t.data instanceof Blob)return t.data.arrayBuffer().then(Fd).then(e);if(u1&&(t.data instanceof ArrayBuffer||d1(t.data)))return e(Fd(t.data));sh(t,!1,n=>{va||(va=new TextEncoder),e(va.encode(n))})}const Nd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Js=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let t=0;t<Nd.length;t++)Js[Nd.charCodeAt(t)]=t;const sw=t=>{let e=t.length*.75,n=t.length,s,i=0,r,o,a,c;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const l=new ArrayBuffer(e),h=new Uint8Array(l);for(s=0;s<n;s+=4)r=Js[t.charCodeAt(s)],o=Js[t.charCodeAt(s+1)],a=Js[t.charCodeAt(s+2)],c=Js[t.charCodeAt(s+3)],h[i++]=r<<2|o>>4,h[i++]=(o&15)<<4|a>>2,h[i++]=(a&3)<<6|c&63;return l},iw=typeof ArrayBuffer=="function",ih=(t,e)=>{if(typeof t!="string")return{type:"message",data:f1(t,e)};const n=t.charAt(0);return n==="b"?{type:"message",data:rw(t.substring(1),e)}:hr[n]?t.length>1?{type:hr[n],data:t.substring(1)}:{type:hr[n]}:hc},rw=(t,e)=>{if(iw){const n=sw(t);return f1(n,e)}else return{base64:!0,data:t}},f1=(t,e)=>{switch(e){case"blob":return t instanceof Blob?t:new Blob([t]);case"arraybuffer":default:return t instanceof ArrayBuffer?t:t.buffer}},p1="",ow=(t,e)=>{const n=t.length,s=new Array(n);let i=0;t.forEach((r,o)=>{sh(r,!1,a=>{s[o]=a,++i===n&&e(s.join(p1))})})},aw=(t,e)=>{const n=t.split(p1),s=[];for(let i=0;i<n.length;i++){const r=ih(n[i],e);if(s.push(r),r.type==="error")break}return s};function cw(){return new TransformStream({transform(t,e){nw(t,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}t.data&&typeof t.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let Ea;function Xi(t){return t.reduce((e,n)=>e+n.length,0)}function Qi(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)n[i]=t[0][s++],s===t[0].length&&(t.shift(),s=0);return t.length&&s<t[0].length&&(t[0]=t[0].slice(s)),n}function lw(t,e){Ea||(Ea=new TextDecoder);const n=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(s===0){if(Xi(n)<1)break;const c=Qi(n,1);r=(c[0]&128)===128,i=c[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(Xi(n)<2)break;const c=Qi(n,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(Xi(n)<8)break;const c=Qi(n,8),l=new DataView(c.buffer,c.byteOffset,c.length),h=l.getUint32(0);if(h>Math.pow(2,21)-1){a.enqueue(hc);break}i=h*Math.pow(2,32)+l.getUint32(4),s=3}else{if(Xi(n)<i)break;const c=Qi(n,i);a.enqueue(ih(r?c:Ea.decode(c),e)),s=0}if(i===0||i>t){a.enqueue(hc);break}}}})}const m1=4;function Te(t){if(t)return hw(t)}function hw(t){for(var e in Te.prototype)t[e]=Te.prototype[e];return t}Te.prototype.on=Te.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this};Te.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this};Te.prototype.off=Te.prototype.removeListener=Te.prototype.removeAllListeners=Te.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+t],this;for(var s,i=0;i<n.length;i++)if(s=n[i],s===e||s.fn===e){n.splice(i,1);break}return n.length===0&&delete this._callbacks["$"+t],this};Te.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,i=n.length;s<i;++s)n[s].apply(this,e)}return this};Te.prototype.emitReserved=Te.prototype.emit;Te.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]};Te.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Mo=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,n)=>n(e,0),ft=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),uw="arraybuffer";function g1(t,...e){return e.reduce((n,s)=>(t.hasOwnProperty(s)&&(n[s]=t[s]),n),{})}const dw=ft.setTimeout,fw=ft.clearTimeout;function Bo(t,e){e.useNativeTimers?(t.setTimeoutFn=dw.bind(ft),t.clearTimeoutFn=fw.bind(ft)):(t.setTimeoutFn=ft.setTimeout.bind(ft),t.clearTimeoutFn=ft.clearTimeout.bind(ft))}const pw=1.33;function mw(t){return typeof t=="string"?gw(t):Math.ceil((t.byteLength||t.size)*pw)}function gw(t){let e=0,n=0;for(let s=0,i=t.length;s<i;s++)e=t.charCodeAt(s),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(s++,n+=4);return n}function _1(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function _w(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function yw(t){let e={},n=t.split("&");for(let s=0,i=n.length;s<i;s++){let r=n[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class vw extends Error{constructor(e,n,s){super(e),this.description=n,this.context=s,this.type="TransportError"}}class rh extends Te{constructor(e){super(),this.writable=!1,Bo(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,n,s){return super.emitReserved("error",new vw(e,n,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const n=ih(e,this.socket.binaryType);this.onPacket(n)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,n={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const n=_w(e);return n.length?"?"+n:""}}class Ew extends rh{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const n=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||n()})),this.writable||(s++,this.once("drain",function(){--s||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const n=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};aw(e,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,ow(e,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=_1()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(e,n)}}let y1=!1;try{y1=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ww=y1;function bw(){}class Cw extends Ew{constructor(e){if(super(e),typeof location<"u"){const n=location.protocol==="https:";let s=location.port;s||(s=n?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,n){const s=this.request({method:"POST",data:e});s.on("success",n),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(n,s)=>{this.onError("xhr poll error",n,s)}),this.pollXhr=e}}let ls=class ur extends Te{constructor(e,n,s){super(),this.createRequest=e,Bo(this,s),this._opts=s,this._method=s.method||"GET",this._uri=n,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const n=g1(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(n);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ur.requestsCount++,ur.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=bw,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ur.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ls.requestsCount=0;ls.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Dd);else if(typeof addEventListener=="function"){const t="onpagehide"in ft?"pagehide":"unload";addEventListener(t,Dd,!1)}}function Dd(){for(let t in ls.requests)ls.requests.hasOwnProperty(t)&&ls.requests[t].abort()}const Tw=function(){const t=v1({xdomain:!1});return t&&t.responseType!==null}();class Sw extends Cw{constructor(e){super(e);const n=e&&e.forceBase64;this.supportsBinary=Tw&&!n}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ls(v1,this.uri(),e)}}function v1(t){const e=t.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||ww))return new XMLHttpRequest}catch{}if(!e)try{return new ft[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const E1=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class kw extends rh{get name(){return"websocket"}doOpen(){const e=this.uri(),n=this.opts.protocols,s=E1?{}:g1(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,n,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const s=e[n],i=n===e.length-1;sh(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&Mo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=_1()),this.supportsBinary||(n.b64=1),this.createUri(e,n)}}const wa=ft.WebSocket||ft.MozWebSocket;class Aw extends kw{createSocket(e,n,s){return E1?new wa(e,n,s):n?new wa(e,n):new wa(e)}doWrite(e,n){this.ws.send(n)}}class Rw extends rh{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const n=lw(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(n).getReader(),i=cw();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:a,value:c})=>{a||(this.onPacket(c),r())}).catch(a=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const s=e[n],i=n===e.length-1;this._writer.write(s).then(()=>{i&&Mo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Iw={websocket:Aw,webtransport:Rw,polling:Sw},xw=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fw=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function uc(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),s=t.indexOf("]");n!=-1&&s!=-1&&(t=t.substring(0,n)+t.substring(n,s).replace(/:/g,";")+t.substring(s,t.length));let i=xw.exec(t||""),r={},o=14;for(;o--;)r[Fw[o]]=i[o]||"";return n!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Nw(r,r.path),r.queryKey=Dw(r,r.query),r}function Nw(t,e){const n=/\/{2,9}/g,s=e.replace(n,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Dw(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(n[i]=r)}),n}const dc=typeof addEventListener=="function"&&typeof removeEventListener=="function",dr=[];dc&&addEventListener("offline",()=>{dr.forEach(t=>t())},!1);class un extends Te{constructor(e,n){if(super(),this.binaryType=uw,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(n=e,e=null),e){const s=uc(e);n.hostname=s.host,n.secure=s.protocol==="https"||s.protocol==="wss",n.port=s.port,s.query&&(n.query=s.query)}else n.host&&(n.hostname=uc(n.host).host);Bo(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=yw(this.opts.query)),dc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},dr.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const n=Object.assign({},this.opts.query);n.EIO=m1,n.transport=e,this.id&&(n.sid=this.id);const s=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&un.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(e);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",un.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=e.data,this._onError(n);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(n+=mw(i)),s>0&&n>this._maxPayload)return this.writeBuffer.slice(0,s);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Mo(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,n,s){return this._sendPacket("message",e,n,s),this}send(e,n,s){return this._sendPacket("message",e,n,s),this}_sendPacket(e,n,s,i){if(typeof n=="function"&&(i=n,n=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:n,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),e()},s=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(un.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),dc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=dr.indexOf(this._offlineEventListener);s!==-1&&dr.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,n),this.writeBuffer=[],this._prevBufferLen=0}}}un.protocol=m1;class Pw extends un{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let n=this.createTransport(e),s=!1;un.priorWebsocketSuccess=!1;const i=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",u=>{if(!s)if(u.type==="pong"&&u.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;un.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const d=new Error("probe error");d.transport=n.name,this.emitReserved("upgradeError",d)}}))};function r(){s||(s=!0,h(),n.close(),n=null)}const o=u=>{const d=new Error("probe error: "+u);d.transport=n.name,r(),this.emitReserved("upgradeError",d)};function a(){o("transport closed")}function c(){o("socket closed")}function l(u){n&&u.name!==n.name&&r()}const h=()=>{n.removeListener("open",i),n.removeListener("error",o),n.removeListener("close",a),this.off("close",c),this.off("upgrading",l)};n.once("open",i),n.once("error",o),n.once("close",a),this.once("close",c),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const n=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&n.push(e[s]);return n}}let Lw=class extends Pw{constructor(e,n={}){const s=typeof e=="object"?e:n;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>Iw[i]).filter(i=>!!i)),super(e,s)}};function Ow(t,e="",n){let s=t;n=n||typeof location<"u"&&location,t==null&&(t=n.protocol+"//"+n.host),typeof t=="string"&&(t.charAt(0)==="/"&&(t.charAt(1)==="/"?t=n.protocol+t:t=n.host+t),/^(https?|wss?):\/\//.test(t)||(typeof n<"u"?t=n.protocol+"//"+t:t="https://"+t),s=uc(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}const Mw=typeof ArrayBuffer=="function",Bw=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,w1=Object.prototype.toString,Uw=typeof Blob=="function"||typeof Blob<"u"&&w1.call(Blob)==="[object BlobConstructor]",Vw=typeof File=="function"||typeof File<"u"&&w1.call(File)==="[object FileConstructor]";function oh(t){return Mw&&(t instanceof ArrayBuffer||Bw(t))||Uw&&t instanceof Blob||Vw&&t instanceof File}function fr(t,e){if(!t||typeof t!="object")return!1;if(Array.isArray(t)){for(let n=0,s=t.length;n<s;n++)if(fr(t[n]))return!0;return!1}if(oh(t))return!0;if(t.toJSON&&typeof t.toJSON=="function"&&arguments.length===1)return fr(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&fr(t[n]))return!0;return!1}function $w(t){const e=[],n=t.data,s=t;return s.data=fc(n,e),s.attachments=e.length,{packet:s,buffers:e}}function fc(t,e){if(!t)return t;if(oh(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}else if(Array.isArray(t)){const n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=fc(t[s],e);return n}else if(typeof t=="object"&&!(t instanceof Date)){const n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=fc(t[s],e));return n}return t}function Hw(t,e){return t.data=pc(t.data,e),delete t.attachments,t}function pc(t,e){if(!t)return t;if(t&&t._placeholder===!0){if(typeof t.num=="number"&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}else if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=pc(t[n],e);else if(typeof t=="object")for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=pc(t[n],e));return t}const Ww=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Gw=5;var G;(function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"})(G||(G={}));class jw{constructor(e){this.replacer=e}encode(e){return(e.type===G.EVENT||e.type===G.ACK)&&fr(e)?this.encodeAsBinary({type:e.type===G.EVENT?G.BINARY_EVENT:G.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let n=""+e.type;return(e.type===G.BINARY_EVENT||e.type===G.BINARY_ACK)&&(n+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(n+=e.nsp+","),e.id!=null&&(n+=e.id),e.data!=null&&(n+=JSON.stringify(e.data,this.replacer)),n}encodeAsBinary(e){const n=$w(e),s=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(s),i}}function Pd(t){return Object.prototype.toString.call(t)==="[object Object]"}class ah extends Te{constructor(e){super(),this.reviver=e}add(e){let n;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(e);const s=n.type===G.BINARY_EVENT;s||n.type===G.BINARY_ACK?(n.type=s?G.EVENT:G.ACK,this.reconstructor=new qw(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(oh(e)||e.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(e),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let n=0;const s={type:Number(e.charAt(0))};if(G[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===G.BINARY_EVENT||s.type===G.BINARY_ACK){const r=n+1;for(;e.charAt(++n)!=="-"&&n!=e.length;);const o=e.substring(r,n);if(o!=Number(o)||e.charAt(n)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(n+1)==="/"){const r=n+1;for(;++n&&!(e.charAt(n)===","||n===e.length););s.nsp=e.substring(r,n)}else s.nsp="/";const i=e.charAt(n+1);if(i!==""&&Number(i)==i){const r=n+1;for(;++n;){const o=e.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===e.length)break}s.id=Number(e.substring(r,n+1))}if(e.charAt(++n)){const r=this.tryParse(e.substr(n));if(ah.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,n){switch(e){case G.CONNECT:return Pd(n);case G.DISCONNECT:return n===void 0;case G.CONNECT_ERROR:return typeof n=="string"||Pd(n);case G.EVENT:case G.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Ww.indexOf(n[0])===-1);case G.ACK:case G.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class qw{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const n=Hw(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const zw=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ah,Encoder:jw,get PacketType(){return G},protocol:Gw},Symbol.toStringTag,{value:"Module"}));function Et(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Kw=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class b1 extends Te{constructor(e,n,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=n,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Et(e,"open",this.onopen.bind(this)),Et(e,"packet",this.onpacket.bind(this)),Et(e,"error",this.onerror.bind(this)),Et(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...n){var s,i,r;if(Kw.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(n.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:G.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const h=this.ids++,u=n.pop();this._registerAckCallback(h,u),o.id=h}const a=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!a||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,n){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=n;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);n.call(this,new Error("operation has timed out"))},i),o=(...a)=>{this.io.clearTimeoutFn(r),n.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...n){return new Promise((s,i)=>{const r=(o,a)=>o?i(o):s(a);r.withError=!0,n.push(r),this.emit(e,...n)})}_addToQueue(e){let n;typeof e[e.length-1]=="function"&&(n=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>s!==this._queue[0]?void 0:(i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!e||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:G.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case G.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case G.EVENT:case G.BINARY_EVENT:this.onevent(e);break;case G.ACK:case G.BINARY_ACK:this.onack(e);break;case G.DISCONNECT:this.ondisconnect();break;case G.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const n=e.data||[];e.id!=null&&n.push(this.ack(e.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const s of n)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const n=this;let s=!1;return function(...i){s||(s=!0,n.packet({type:G.ACK,id:e,data:i}))}}onack(e){const n=this.acks[e.id];typeof n=="function"&&(delete this.acks[e.id],n.withError&&e.data.unshift(null),n.apply(this,e.data))}onconnect(e,n){this.id=e,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:G.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const n=this._anyListeners;for(let s=0;s<n.length;s++)if(e===n[s])return n.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const n=this._anyOutgoingListeners;for(let s=0;s<n.length;s++)if(e===n[s])return n.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const s of n)s.apply(this,e.data)}}}function Us(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Us.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=(Math.floor(e*10)&1)==0?t-n:t+n}return Math.min(t,this.max)|0};Us.prototype.reset=function(){this.attempts=0};Us.prototype.setMin=function(t){this.ms=t};Us.prototype.setMax=function(t){this.max=t};Us.prototype.setJitter=function(t){this.jitter=t};class mc extends Te{constructor(e,n){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(n=e,e=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Bo(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((s=n.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Us({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=e;const i=n.parser||zw;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var n;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(n=this.backoff)===null||n===void 0||n.setMin(e),this)}randomizationFactor(e){var n;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(n=this.backoff)===null||n===void 0||n.setJitter(e),this)}reconnectionDelayMax(e){var n;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(n=this.backoff)===null||n===void 0||n.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Lw(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=Et(n,"open",function(){s.onopen(),e&&e()}),r=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Et(n,"error",r);if(this._timeout!==!1){const a=this._timeout,c=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),n.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Et(e,"ping",this.onping.bind(this)),Et(e,"data",this.ondata.bind(this)),Et(e,"error",this.onerror.bind(this)),Et(e,"close",this.onclose.bind(this)),Et(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(n){this.onclose("parse error",n)}}ondecoded(e){Mo(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,n){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new b1(this,e,n),this.nsps[e]=s),s}_destroy(e){const n=Object.keys(this.nsps);for(const s of n)if(this.nsps[s].active)return;this._close()}_packet(e){const n=this.encoder.encode(e);for(let s=0;s<n.length;s++)this.engine.write(n[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,n){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},n);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ks={};function pr(t,e){typeof t=="object"&&(e=t,t=void 0),e=e||{};const n=Ow(t,e.path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=Ks[i]&&r in Ks[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let c;return a?c=new mc(s,e):(Ks[i]||(Ks[i]=new mc(s,e)),c=Ks[i]),n.query&&!e.query&&(e.query=n.queryKey),c.socket(n.path,e)}Object.assign(pr,{Manager:mc,Socket:b1,io:pr,connect:pr});const An=class An{constructor(){_(this,"socket");_(this,"backendUrl",xo("server"));_(this,"videoStream");_(this,"videoElement");_(this,"isConnected",!1);_(this,"isStreaming",!1);_(this,"jobId");_(this,"onDisconnection");_(this,"canvas");_(this,"encoderBusy",!1);_(this,"playHandler",()=>{if(!this.videoElement||!this.canvas)return;const e=this.videoElement,n=this.canvas,s=()=>{const o=e.videoWidth||640,a=e.videoHeight||480;(n.width!==o||n.height!==a)&&(n.width=o,n.height=a)},i=n.getContext("2d");if(!i)return;const r=()=>{if(this.isStreaming){if((e.videoWidth||0)===0||(e.videoHeight||0)===0){requestAnimationFrame(r);return}s(),!e.paused&&!e.ended&&(i.drawImage(e,0,0,n.width,n.height),this.encoderBusy||(this.encoderBusy=!0,this.sendFrameToBackend(n,()=>{this.encoderBusy=!1}))),requestAnimationFrame(r)}};r()});_(this,"stopStreaming",()=>{this.isStreaming=!1,this.removePlayEventListener()})}static getInstance(){return An.instance||(An.instance=new An),An.instance}async setupWebSocketConnection(){return new Promise((e,n)=>{if(this.socket)return e(!0);this.socket=pr(this.backendUrl,{transports:["websocket","polling"]}),this.socket.once("connect",()=>{this.isConnected=!0,e(!0)}),this.socket.once("connect_error",s=>{n(O.ConnectionLostError)}),this.socket.once("disconnect",s=>{this.handleSocketDisconnection(s)})})}handleSocketDisconnection(e){this.isConnected=!1}async initializeStreaming(e,n){this.videoStream=e,this.videoElement=n,this.videoElement.srcObject=e,this.canvas=document.createElement("canvas"),this.canvas.width=n.videoWidth||640,this.canvas.height=n.videoHeight||480,await this.setupWebSocketConnection()}startStreaming(e){var n;this.jobId=e,(n=this.socket)==null||n.emit("register",e),this.sendInitialRequest(e),this.isStreaming=!0,this.startVideoStream(),this.addDisconnectionListener()}async sendInitialRequest(e){await te.post(`${this.backendUrl}/react`,{username:e,uuid:e,device_id:"1234567",face_detector:"BlazefaceFacemesh",motion_tracking:!0,skin_segmentor:"HSVandYCrCbSkinSegmentation",extreme_pixel_removal:!1,gamma_value:1,eularian_color_magnification:!1},{headers:{"Content-Type":"application/json"}})}startVideoStream(){if(!this.videoElement){f.error("Video stream not found when trying to start streaming");return}const e=this.videoElement,n=()=>{e.videoWidth>0&&e.videoHeight>0&&(this.playHandler(),e.removeEventListener("loadedmetadata",n),e.removeEventListener("playing",n))};e.addEventListener("playing",n),e.addEventListener("loadedmetadata",n),e.readyState>=2&&e.videoWidth>0&&e.videoHeight>0&&n(),e.addEventListener("play",this.playHandler),e.play().catch(s=>f.error("Error starting video stream:",s))}sendFrameToBackend(e,n){e.toBlob(s=>{if(n&&n(),!s){f.warn("[WARN] canvas.toBlob returned null (likely 0×0 canvas or tainted).");return}const i=new FileReader;i.onloadend=()=>{var r;if(this.isConnected&&this.isStreaming){const o=i.result;(r=this.socket)==null||r.emit("frame",o)}},i.readAsArrayBuffer(s)},"image/jpeg",.7)}removePlayEventListener(){this.videoElement&&this.videoElement.removeEventListener("play",this.playHandler)}setOnDisconnection(e){this.onDisconnection=e}addDisconnectionListener(){const e=er(),n=Ys(e,`${this.jobId}/disconnect`),s=Zi(n,i=>{i.val()!=null&&(this.stopStreaming(),this.onDisconnection&&this.onDisconnection(),s())})}};_(An,"instance");let zr=An;class C1{constructor(){_(this,"backendUrl",xo("server"));_(this,"streamingManager",zr.getInstance());_(this,"accessTokenProvider")}setAccessTokenProvider(e){this.accessTokenProvider=e}}class Yw extends C1{constructor(){super();_(this,"streamingManager",zr.getInstance());_(this,"rgbManager",Gr.getInstance());this.backendUrl=xo("server"),f.log("ServerRepository",this.backendUrl)}async getTokenWithUsernameAndPassword(n,s){try{return(await te.post(this.backendUrl.concat("/clientlogin"),{username:n,password:s})).data.access_token}catch(i){q.handleErrorResponse(i)}}async getTokenWithLicenseKey(n){try{return(await te.post(this.backendUrl.concat("/clientloginwithlicensekey"),{license_key:n})).data.access_token}catch(s){q.handleErrorResponse(s)}}async getAPIKey(n){n||q.throwKnownError(O.InvalidAccessTokenError);try{return(await te.post(this.backendUrl.concat("/clientgeturl"),{host_name:"www.nervoscan.com"},{headers:{Authorization:`Bearer ${n}`}})).data.url.split("?api_key=")[1]}catch(s){q.handleErrorResponse(s)}}async uploadVideoToServer(n,s,i){(!s||!i)&&q.throwKnownError(O.InvalidAccessTokenError);const r=new FormData;r.append("file",n,"recording.webm"),r.append("data",JSON.stringify({uuid:i,meta_data:{}}));const a=await(await fetch(this.backendUrl.concat("/submitscan"),{method:"POST",headers:{Authorization:`Bearer ${s}`},body:r})).json();return a.success===!1&&q.handleErrorResponse(a),a}async sendRgbDataToBackend(n,s,i,r){try{const o=this.accessTokenProvider?await this.accessTokenProvider():void 0;o||q.throwKnownError(O.InvalidAccessTokenError);const a={job_id:r,timestamp:Date.now(),rgbData:n,resolution:{width:s,height:i}};return f.log(`[Backend] Sending RGB data to backend with resolution: ${s}x${i}`),f.debug("Sending RGB data to backend:",a),(await te.post(`${this.backendUrl}/rgb-data`,a,{headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})).data}catch(o){q.handleErrorResponse(o)}}}class Xw extends C1{constructor(){super(),this.backendUrl=xo("serverless")}async getTokenWithUsernameAndPassword(e,n){try{const s=await te.post(this.backendUrl.concat("/user/login"),{username:e,password:n});if(s.data.success===!1)q.throwKnownError(O.InvalidUsernameError);else return JSON.parse(s.data.body).idToken}catch(s){f.error("error printed in serverless repository",s),q.handleErrorResponse(s)}}async getTokenWithLicenseKey(e){q.throwKnownError(O.NotImplementedError)}async getAPIKey(e){e||q.throwKnownError(O.InvalidAccessTokenError);try{return(await te.post(this.backendUrl.concat("/get-redirection-url"),{host_name:"www.nervoscan.com"},{headers:{Authorization:`Bearer ${e}`}})).data.url.split("?api_key=")[1]}catch(n){q.handleErrorResponse(n)}}async uploadVideoToServer(e,n,s){(!n||!s)&&q.throwKnownError(O.InvalidAccessTokenError);try{const i=await this.generatePreSignedUrl(s);return i||q.throwKnownError(O.InvalidAccessTokenError),await this.uploadVideoToS3(e,i)}catch(i){throw f.error("Error uploading video:",i),i.response?(f.error("Error response:",i.response.data),f.error("Error status:",i.response.status),f.error("Error headers:",i.response.headers)):i.request?f.error("Error request:",i.request):f.error("Error message:",i.message),i}}async generatePreSignedUrl(e){try{return(await te.get(this.backendUrl.concat("/generate-presigned-url?job_id="+e))).data.upload_url}catch(n){q.handleErrorResponse(n)}}async uploadVideoToS3(e,n){try{return(await te.put(n,e,{headers:{"Content-Type":"video/mp4"}})).data}catch(s){q.handleErrorResponse(s)}}async sendRgbDataToBackend(e,n,s,i){q.throwKnownError(O.NotImplementedError)}}class T1{static createBackendRepository(e,n){if(e==="server")return new Yw;if(e==="serverless")return new Xw;q.throwKnownError(O.InvalidServerTypeError)}}class Qw{constructor(e,n,s,i="server"){_(this,"backendRepository");_(this,"username");_(this,"password");_(this,"licenseKey");this.backendRepository=T1.createBackendRepository(i,!1),this.username=e,this.password=n,this.licenseKey=s,e&&n&&f.warn("Using username and password for authentication is deprecated. Please use license key instead.")}async validate(){if(this.licenseKey)return this.validateWithKey(this.licenseKey);if(this.username&&this.password)return this.validatewithUsernameAndPassword(this.username,this.password);q.throwKnownError(O.InvalidCredentialsError)}async validateWithKey(e){return this.backendRepository.getTokenWithLicenseKey(e)}async validatewithUsernameAndPassword(e,n){return this.backendRepository.getTokenWithUsernameAndPassword(e,n)}}const Rn=class Rn{constructor(){_(this,"initialized",!1);_(this,"accessToken");_(this,"backendRepository");_(this,"onWindowResults");_(this,"onFinalResults");_(this,"onError");_(this,"firebaseHandlers",[]);_(this,"useRgb",!1);_(this,"rgbManager",Gr.getInstance());_(this,"onDisconnection",()=>{});_(this,"licenceManager");Rf({apiKey:"AIzaSyAoOpQqLrc6wQLJI5KRE2Vt7QV1cplsZv8",authDomain:"nervowebreact.firebaseapp.com",databaseURL:"https://nervowebreact-default-rtdb.asia-southeast1.firebasedatabase.app",projectId:"nervowebreact",storageBucket:"nervowebreact.firebasestorage.app",messagingSenderId:"1025695568936",appId:"1:1025695568936:web:36f269a1eb74e1fdda511d",measurementId:"G-L3105FG92S"})}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}initialize({username:e,password:n,licenseKey:s,serverType:i="server",useRgb:r=!1}){this.initialized=!0,this.useRgb=r,this.licenceManager=new Qw(e,n,s,i),this.backendRepository=T1.createBackendRepository(i,r),this.backendRepository.setAccessTokenProvider(async()=>this.licenceManager.validate())}async uploadVideo(e){var i,r;this.initialized||q.throwKnownError(O.NotInitializedError),e instanceof Blob||q.throwKnownError(O.VideoTypeError),(e===null||e.size===0)&&q.throwKnownError(O.EmptyVideoError);const n=await this.licenceManager.validate(),s=await((i=this.backendRepository)==null?void 0:i.getAPIKey(n));return(r=this.backendRepository)==null||r.uploadVideoToServer(e,n,s),s&&this.addfirebaseListeners(s),s}setOnWindowResults(e){this.onWindowResults=e}setOnFinalResults(e){this.onFinalResults=e}setOnError(e){this.onError=e}setOnDisconnection(e){var n;(n=this.backendRepository)==null||n.streamingManager.setOnDisconnection(e),this.onDisconnection=e}setOnAlignmentStatus(e){this.rgbManager.setAlignmentStatusCallback(e)}startFaceDetection(){this.useRgb&&this.rgbManager.startFaceDetection()}stopFaceDetection(){this.useRgb&&this.rgbManager.stopFaceDetection()}resetMediaPipeTimestamps(){this.useRgb&&this.rgbManager.forceResetMediaPipeTimestamps()}setFrameValidationEnabled(e){this.useRgb&&this.rgbManager.setFrameValidationEnabled(e)}isFrameValidationEnabled(){return this.useRgb?this.rgbManager.isFrameValidationEnabled():!1}async initializeStreaming(e,n,s={}){var i;this.useRgb?await this.rgbManager.initialize(e,n,this.backendRepository,this.onDisconnection,s):await((i=this.backendRepository)==null?void 0:i.streamingManager.initializeStreaming(e,n))}async startStreaming(){var s,i;this.initialized||q.throwKnownError(O.NotInitializedError);const e=await this.licenceManager.validate(),n=await((s=this.backendRepository)==null?void 0:s.getAPIKey(e));if(n)return this.useRgb?(f.log("Starting RGB streaming"),await this.rgbManager.startStreaming(n)):(i=this.backendRepository)==null||i.streamingManager.startStreaming(n),this.addfirebaseListeners(n),n;q.throwKnownError(O.InvalidAccessTokenError)}stopStreaming(){var e;(e=this.backendRepository)==null||e.streamingManager.stopStreaming(),this.rgbManager.stopStreaming()}enableImprovedCapture(e={}){f.log("[Client] Using legacy capture method for maximum compatibility. Configuration ignored:",e)}disableImprovedCapture(){f.log("[Client] Already using legacy capture method")}isImprovedCaptureEnabled(){return!1}setCaptureMethod(e){if(e!==Wr.LEGACY){f.warn(`[Client] Only legacy capture method is supported. Ignoring request for: ${e}`);return}try{this.rgbManager.switchCaptureMethod(e),f.log("[Client] Using legacy capture method")}catch(n){f.error("[Client] Failed to switch capture method:",n)}}getCaptureMethod(){return this.rgbManager.getCaptureMethod()}setTargetFPS(e){this.rgbManager.setTargetFPS(e)}setMinFrameQuality(e){this.rgbManager.setMinFrameQuality(e)}setQualityControlEnabled(e){this.rgbManager.setQualityControlEnabled(e)}getFrameStatistics(){return this.rgbManager.getFrameStatistics()}getTotalFrameCount(){return this.useRgb?this.rgbManager.getTotalFrameCount():0}getConfiguration(){return this.rgbManager.getConfiguration()}enableContinuousMode(e){this.useRgb&&this.rgbManager.enableContinuousMode(e)}disableContinuousMode(){this.useRgb&&this.rgbManager.disableContinuousMode()}enableVideoEndDetection(e=5e3,n){this.useRgb&&this.rgbManager.enableVideoEndDetection(e,n)}disableVideoEndDetection(){this.useRgb&&this.rgbManager.disableVideoEndDetection()}async addfirebaseListeners(e){this.addWindowListener(e),this.addFinalListener(e),this.addErrorListener(e)}addWindowListener(e){const n=er(),s=Ys(n,`${e}`),i=_3(s,r=>{r.val()!==null&&r.key&&/^\d+$/.test(r.key)&&this.onWindowResults&&this.onWindowResults(r.val())});this.firebaseHandlers.push(i)}removefirebaseListeners(){this.firebaseHandlers.forEach(e=>{e()}),this.firebaseHandlers=[]}addFinalListener(e){f.log(`Adding final listener for job ${e}`);const n=er(),s=Ys(n,`/${e}/averaged_results/`),i=Zi(s,r=>{if(r.val()===null)return;const o=r.val();f.log(`[Client] Received results for job ${e}:`,o),this.useRgb&&this.rgbManager.isContinuousModeEnabled()?this.rgbManager.handleBatchResults(o):(this.onFinalResults&&this.onFinalResults(o),this.removefirebaseListeners())});this.firebaseHandlers.push(i)}addErrorListener(e){const n=er(),s=Ys(n,`/${e}/error/`),i=Zi(s,a=>{if(a.val()===null)return;const c=q.handleScanError(a.val());this.onError?this.onError(c):q.throwKnownError(O.ErrorCallbackNotSetError),this.removefirebaseListeners()}),r=Ys(n,`/${e}/job_completed/`),o=Zi(r,a=>{a.val()!==null&&(a.val()==="failed"&&this.onError?(this.onError(O.ScanFailedError),this.removefirebaseListeners()):a.val()==="success"&&this.removefirebaseListeners())});this.firebaseHandlers.push(i),this.firebaseHandlers.push(o)}getRGBDataCollectionStatus(){return this.useRgb&&this.rgbManager?this.rgbManager.getDataCollectionStatus():{error:"RGB mode not enabled"}}getRGBTimestamps(){return this.useRgb&&this.rgbManager?this.rgbManager.getRGBTimestamps():[]}isFaceDetectionActive(){return this.useRgb&&this.rgbManager?this.rgbManager.isFaceDetectionActive():!1}isContinuousModeEnabled(){return this.useRgb&&this.rgbManager?this.rgbManager.isContinuousModeEnabled():!1}};_(Rn,"instance");let gc=Rn;exports.Client=gc;exports.ConnectionLostError=af;exports.EmptyVideoError=Md;exports.EnvIncompatibleError=pf;exports.ErrorCallbackNotSetError=Zd;exports.Errors=Y;exports.FPSCalculationError=zd;exports.FaceLandmarkerNotInitializedError=ff;exports.FaceLookingLeftError=Qd;exports.FaceLookingRightError=Jd;exports.FaceNotCenteredError=Kd;exports.FaceTooCloseError=Xd;exports.FaceTooFarError=Yd;exports.InvalidAccessTokenError=Hd;exports.InvalidContentTypeError=nf;exports.InvalidCredentialsError=hf;exports.InvalidPasswordError=Vd;exports.InvalidServerTypeError=Gd;exports.InvalidUsernameError=Ud;exports.JobNotRegisteredError=sf;exports.LicenseInactiveError=uf;exports.LowFPSError=qd;exports.LowFrameCountError=of;exports.NervoscanError=K;exports.NoScanDataError=Wd;exports.NoScansAvailableError=$d;exports.NotImplementedError=jd;exports.NotInitializedError=Od;exports.RGBError=df;exports.ScanFailedError=cf;exports.SkinExtractionError=tf;exports.UnhandledError=rf;exports.UnhandledScanError=ef;exports.VideoError=lf;exports.VideoTypeError=Bd;
1648
+ `):" "+Ad(r[0]):"as no adapter specified";throw new M("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return s},adapters:cc};function _a(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Bs(null,t)}function Rd(t){return _a(t),t.headers=Ke.from(t.headers),t.data=ga.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),a1.getAdapter(t.adapter||Mi.adapter)(t).then(function(s){return _a(t),s.data=ga.call(t,t.transformResponse,s),s.headers=Ke.from(s.headers),s},function(s){return t1(s)||(_a(t),s&&s.response&&(s.response.data=ga.call(t,t.transformResponse,s.response),s.response.headers=Ke.from(s.response.headers))),Promise.reject(s)})}const c1="1.8.4",Lo={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Lo[t]=function(s){return typeof s===t||"a"+(e<1?"n ":" ")+t}});const Id={};Lo.transitional=function(e,n,s){function i(r,o){return"[Axios v"+c1+"] Transitional option '"+r+"'"+o+(s?". "+s:"")}return(r,o,a)=>{if(e===!1)throw new M(i(o," has been removed"+(n?" in "+n:"")),M.ERR_DEPRECATED);return n&&!Id[o]&&(Id[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(r,o,a):!0}};Lo.spelling=function(e){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};function Z4(t,e,n){if(typeof t!="object")throw new M("options must be an object",M.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let i=s.length;for(;i-- >0;){const r=s[i],o=e[r];if(o){const a=t[r],c=a===void 0||o(a,r,t);if(c!==!0)throw new M("option "+r+" must be "+c,M.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new M("Unknown option "+r,M.ERR_BAD_OPTION)}}const lr={assertOptions:Z4,validators:Lo},Lt=lr.validators;let Pn=class{constructor(e){this.defaults=e,this.interceptors={request:new Ed,response:new Ed}}async request(e,n){try{return await this._request(e,n)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?r&&!String(s.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(s.stack+=`
1649
+ `+r):s.stack=r}catch{}}throw s}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=$n(this.defaults,n);const{transitional:s,paramsSerializer:i,headers:r}=n;s!==void 0&&lr.assertOptions(s,{silentJSONParsing:Lt.transitional(Lt.boolean),forcedJSONParsing:Lt.transitional(Lt.boolean),clarifyTimeoutError:Lt.transitional(Lt.boolean)},!1),i!=null&&(g.isFunction(i)?n.paramsSerializer={serialize:i}:lr.assertOptions(i,{encode:Lt.function,serialize:Lt.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),lr.assertOptions(n,{baseUrl:Lt.spelling("baseURL"),withXsrfToken:Lt.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=r&&g.merge(r.common,r[n.method]);r&&g.forEach(["delete","get","head","post","put","patch","common"],m=>{delete r[m]}),n.headers=Ke.concat(o,r);const a=[];let c=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(c=c&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let h,u=0,d;if(!c){const m=[Rd.bind(this),void 0];for(m.unshift.apply(m,a),m.push.apply(m,l),d=m.length,h=Promise.resolve(n);u<d;)h=h.then(m[u++],m[u++]);return h}d=a.length;let p=n;for(u=0;u<d;){const m=a[u++],y=a[u++];try{p=m(p)}catch(w){y.call(this,w);break}}try{h=Rd.call(this,p)}catch(m){return Promise.reject(m)}for(u=0,d=l.length;u<d;)h=h.then(l[u++],l[u++]);return h}getUri(e){e=$n(this.defaults,e);const n=s1(e.baseURL,e.url,e.allowAbsoluteUrls);return Jg(n,e.params,e.paramsSerializer)}};g.forEach(["delete","get","head","options"],function(e){Pn.prototype[e]=function(n,s){return this.request($n(s||{},{method:e,url:n,data:(s||{}).data}))}});g.forEach(["post","put","patch"],function(e){function n(s){return function(r,o,a){return this.request($n(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}Pn.prototype[e]=n(),Pn.prototype[e+"Form"]=n(!0)});let ew=class l1{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(r){n=r});const s=this;this.promise.then(i=>{if(!s._listeners)return;let r=s._listeners.length;for(;r-- >0;)s._listeners[r](i);s._listeners=null}),this.promise.then=i=>{let r;const o=new Promise(a=>{s.subscribe(a),r=a}).then(i);return o.cancel=function(){s.unsubscribe(r)},o},e(function(r,o,a){s.reason||(s.reason=new Bs(r,o,a),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=s=>{e.abort(s)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new l1(function(i){e=i}),cancel:e}}};function tw(t){return function(n){return t.apply(null,n)}}function nw(t){return g.isObject(t)&&t.isAxiosError===!0}const lc={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(lc).forEach(([t,e])=>{lc[e]=t});function h1(t){const e=new Pn(t),n=$g(Pn.prototype.request,e);return g.extend(n,Pn.prototype,e,{allOwnKeys:!0}),g.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return h1($n(t,i))},n}const te=h1(Mi);te.Axios=Pn;te.CanceledError=Bs;te.CancelToken=ew;te.isCancel=t1;te.VERSION=c1;te.toFormData=Do;te.AxiosError=M;te.Cancel=te.CanceledError;te.all=function(e){return Promise.all(e)};te.spread=tw;te.isAxiosError=nw;te.mergeConfig=$n;te.AxiosHeaders=Ke;te.formToJSON=t=>e1(g.isHTMLForm(t)?new FormData(t):t);te.getAdapter=a1.getAdapter;te.HttpStatusCode=lc;te.default=te;const{Axios:nb,AxiosError:sb,CanceledError:ib,isCancel:rb,CancelToken:ob,VERSION:ab,all:cb,Cancel:lb,isAxiosError:hb,spread:ub,toFormData:db,AxiosHeaders:fb,HttpStatusCode:pb,formToJSON:mb,getAdapter:gb,mergeConfig:_b}=te,Bt=Object.create(null);Bt.open="0";Bt.close="1";Bt.ping="2";Bt.pong="3";Bt.message="4";Bt.upgrade="5";Bt.noop="6";const hr=Object.create(null);Object.keys(Bt).forEach(t=>{hr[Bt[t]]=t});const hc={type:"error",data:"parser error"},u1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",d1=typeof ArrayBuffer=="function",f1=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,sh=({type:t,data:e},n,s)=>u1&&e instanceof Blob?n?s(e):xd(e,s):d1&&(e instanceof ArrayBuffer||f1(e))?n?s(e):xd(new Blob([e]),s):s(Bt[t]+(e||"")),xd=(t,e)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];e("b"+(s||""))},n.readAsDataURL(t)};function Nd(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let ya;function sw(t,e){if(u1&&t.data instanceof Blob)return t.data.arrayBuffer().then(Nd).then(e);if(d1&&(t.data instanceof ArrayBuffer||f1(t.data)))return e(Nd(t.data));sh(t,!1,n=>{ya||(ya=new TextEncoder),e(ya.encode(n))})}const Fd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Js=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let t=0;t<Fd.length;t++)Js[Fd.charCodeAt(t)]=t;const iw=t=>{let e=t.length*.75,n=t.length,s,i=0,r,o,a,c;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const l=new ArrayBuffer(e),h=new Uint8Array(l);for(s=0;s<n;s+=4)r=Js[t.charCodeAt(s)],o=Js[t.charCodeAt(s+1)],a=Js[t.charCodeAt(s+2)],c=Js[t.charCodeAt(s+3)],h[i++]=r<<2|o>>4,h[i++]=(o&15)<<4|a>>2,h[i++]=(a&3)<<6|c&63;return l},rw=typeof ArrayBuffer=="function",ih=(t,e)=>{if(typeof t!="string")return{type:"message",data:p1(t,e)};const n=t.charAt(0);return n==="b"?{type:"message",data:ow(t.substring(1),e)}:hr[n]?t.length>1?{type:hr[n],data:t.substring(1)}:{type:hr[n]}:hc},ow=(t,e)=>{if(rw){const n=iw(t);return p1(n,e)}else return{base64:!0,data:t}},p1=(t,e)=>{switch(e){case"blob":return t instanceof Blob?t:new Blob([t]);case"arraybuffer":default:return t instanceof ArrayBuffer?t:t.buffer}},m1="",aw=(t,e)=>{const n=t.length,s=new Array(n);let i=0;t.forEach((r,o)=>{sh(r,!1,a=>{s[o]=a,++i===n&&e(s.join(m1))})})},cw=(t,e)=>{const n=t.split(m1),s=[];for(let i=0;i<n.length;i++){const r=ih(n[i],e);if(s.push(r),r.type==="error")break}return s};function lw(){return new TransformStream({transform(t,e){sw(t,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}t.data&&typeof t.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let va;function Xi(t){return t.reduce((e,n)=>e+n.length,0)}function Qi(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)n[i]=t[0][s++],s===t[0].length&&(t.shift(),s=0);return t.length&&s<t[0].length&&(t[0]=t[0].slice(s)),n}function hw(t,e){va||(va=new TextDecoder);const n=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(s===0){if(Xi(n)<1)break;const c=Qi(n,1);r=(c[0]&128)===128,i=c[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(Xi(n)<2)break;const c=Qi(n,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(Xi(n)<8)break;const c=Qi(n,8),l=new DataView(c.buffer,c.byteOffset,c.length),h=l.getUint32(0);if(h>Math.pow(2,21)-1){a.enqueue(hc);break}i=h*Math.pow(2,32)+l.getUint32(4),s=3}else{if(Xi(n)<i)break;const c=Qi(n,i);a.enqueue(ih(r?c:va.decode(c),e)),s=0}if(i===0||i>t){a.enqueue(hc);break}}}})}const g1=4;function Te(t){if(t)return uw(t)}function uw(t){for(var e in Te.prototype)t[e]=Te.prototype[e];return t}Te.prototype.on=Te.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this};Te.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this};Te.prototype.off=Te.prototype.removeListener=Te.prototype.removeAllListeners=Te.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+t],this;for(var s,i=0;i<n.length;i++)if(s=n[i],s===e||s.fn===e){n.splice(i,1);break}return n.length===0&&delete this._callbacks["$"+t],this};Te.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,i=n.length;s<i;++s)n[s].apply(this,e)}return this};Te.prototype.emitReserved=Te.prototype.emit;Te.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]};Te.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Oo=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,n)=>n(e,0),ft=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),dw="arraybuffer";function _1(t,...e){return e.reduce((n,s)=>(t.hasOwnProperty(s)&&(n[s]=t[s]),n),{})}const fw=ft.setTimeout,pw=ft.clearTimeout;function Mo(t,e){e.useNativeTimers?(t.setTimeoutFn=fw.bind(ft),t.clearTimeoutFn=pw.bind(ft)):(t.setTimeoutFn=ft.setTimeout.bind(ft),t.clearTimeoutFn=ft.clearTimeout.bind(ft))}const mw=1.33;function gw(t){return typeof t=="string"?_w(t):Math.ceil((t.byteLength||t.size)*mw)}function _w(t){let e=0,n=0;for(let s=0,i=t.length;s<i;s++)e=t.charCodeAt(s),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(s++,n+=4);return n}function y1(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function yw(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function vw(t){let e={},n=t.split("&");for(let s=0,i=n.length;s<i;s++){let r=n[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class Ew extends Error{constructor(e,n,s){super(e),this.description=n,this.context=s,this.type="TransportError"}}class rh extends Te{constructor(e){super(),this.writable=!1,Mo(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,n,s){return super.emitReserved("error",new Ew(e,n,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const n=ih(e,this.socket.binaryType);this.onPacket(n)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,n={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const n=yw(e);return n.length?"?"+n:""}}class ww extends rh{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const n=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||n()})),this.writable||(s++,this.once("drain",function(){--s||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const n=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};cw(e,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,aw(e,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=y1()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(e,n)}}let v1=!1;try{v1=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const bw=v1;function Cw(){}class Tw extends ww{constructor(e){if(super(e),typeof location<"u"){const n=location.protocol==="https:";let s=location.port;s||(s=n?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,n){const s=this.request({method:"POST",data:e});s.on("success",n),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(n,s)=>{this.onError("xhr poll error",n,s)}),this.pollXhr=e}}let ls=class ur extends Te{constructor(e,n,s){super(),this.createRequest=e,Mo(this,s),this._opts=s,this._method=s.method||"GET",this._uri=n,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const n=_1(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(n);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ur.requestsCount++,ur.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Cw,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ur.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ls.requestsCount=0;ls.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Dd);else if(typeof addEventListener=="function"){const t="onpagehide"in ft?"pagehide":"unload";addEventListener(t,Dd,!1)}}function Dd(){for(let t in ls.requests)ls.requests.hasOwnProperty(t)&&ls.requests[t].abort()}const Sw=function(){const t=E1({xdomain:!1});return t&&t.responseType!==null}();class kw extends Tw{constructor(e){super(e);const n=e&&e.forceBase64;this.supportsBinary=Sw&&!n}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ls(E1,this.uri(),e)}}function E1(t){const e=t.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||bw))return new XMLHttpRequest}catch{}if(!e)try{return new ft[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const w1=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Aw extends rh{get name(){return"websocket"}doOpen(){const e=this.uri(),n=this.opts.protocols,s=w1?{}:_1(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,n,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const s=e[n],i=n===e.length-1;sh(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&Oo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=y1()),this.supportsBinary||(n.b64=1),this.createUri(e,n)}}const Ea=ft.WebSocket||ft.MozWebSocket;class Rw extends Aw{createSocket(e,n,s){return w1?new Ea(e,n,s):n?new Ea(e,n):new Ea(e)}doWrite(e,n){this.ws.send(n)}}class Iw extends rh{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const n=hw(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(n).getReader(),i=lw();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:a,value:c})=>{a||(this.onPacket(c),r())}).catch(a=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const s=e[n],i=n===e.length-1;this._writer.write(s).then(()=>{i&&Oo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const xw={websocket:Rw,webtransport:Iw,polling:kw},Nw=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fw=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function uc(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),s=t.indexOf("]");n!=-1&&s!=-1&&(t=t.substring(0,n)+t.substring(n,s).replace(/:/g,";")+t.substring(s,t.length));let i=Nw.exec(t||""),r={},o=14;for(;o--;)r[Fw[o]]=i[o]||"";return n!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Dw(r,r.path),r.queryKey=Pw(r,r.query),r}function Dw(t,e){const n=/\/{2,9}/g,s=e.replace(n,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Pw(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(n[i]=r)}),n}const dc=typeof addEventListener=="function"&&typeof removeEventListener=="function",dr=[];dc&&addEventListener("offline",()=>{dr.forEach(t=>t())},!1);class un extends Te{constructor(e,n){if(super(),this.binaryType=dw,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(n=e,e=null),e){const s=uc(e);n.hostname=s.host,n.secure=s.protocol==="https"||s.protocol==="wss",n.port=s.port,s.query&&(n.query=s.query)}else n.host&&(n.hostname=uc(n.host).host);Mo(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=vw(this.opts.query)),dc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},dr.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const n=Object.assign({},this.opts.query);n.EIO=g1,n.transport=e,this.id&&(n.sid=this.id);const s=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&un.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(e);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",un.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=e.data,this._onError(n);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(n+=gw(i)),s>0&&n>this._maxPayload)return this.writeBuffer.slice(0,s);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Oo(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,n,s){return this._sendPacket("message",e,n,s),this}send(e,n,s){return this._sendPacket("message",e,n,s),this}_sendPacket(e,n,s,i){if(typeof n=="function"&&(i=n,n=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:n,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),e()},s=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(un.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),dc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=dr.indexOf(this._offlineEventListener);s!==-1&&dr.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,n),this.writeBuffer=[],this._prevBufferLen=0}}}un.protocol=g1;class Lw extends un{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let n=this.createTransport(e),s=!1;un.priorWebsocketSuccess=!1;const i=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",u=>{if(!s)if(u.type==="pong"&&u.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;un.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const d=new Error("probe error");d.transport=n.name,this.emitReserved("upgradeError",d)}}))};function r(){s||(s=!0,h(),n.close(),n=null)}const o=u=>{const d=new Error("probe error: "+u);d.transport=n.name,r(),this.emitReserved("upgradeError",d)};function a(){o("transport closed")}function c(){o("socket closed")}function l(u){n&&u.name!==n.name&&r()}const h=()=>{n.removeListener("open",i),n.removeListener("error",o),n.removeListener("close",a),this.off("close",c),this.off("upgrading",l)};n.once("open",i),n.once("error",o),n.once("close",a),this.once("close",c),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const n=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&n.push(e[s]);return n}}let Ow=class extends Lw{constructor(e,n={}){const s=typeof e=="object"?e:n;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>xw[i]).filter(i=>!!i)),super(e,s)}};function Mw(t,e="",n){let s=t;n=n||typeof location<"u"&&location,t==null&&(t=n.protocol+"//"+n.host),typeof t=="string"&&(t.charAt(0)==="/"&&(t.charAt(1)==="/"?t=n.protocol+t:t=n.host+t),/^(https?|wss?):\/\//.test(t)||(typeof n<"u"?t=n.protocol+"//"+t:t="https://"+t),s=uc(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}const Bw=typeof ArrayBuffer=="function",Uw=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,b1=Object.prototype.toString,Vw=typeof Blob=="function"||typeof Blob<"u"&&b1.call(Blob)==="[object BlobConstructor]",$w=typeof File=="function"||typeof File<"u"&&b1.call(File)==="[object FileConstructor]";function oh(t){return Bw&&(t instanceof ArrayBuffer||Uw(t))||Vw&&t instanceof Blob||$w&&t instanceof File}function fr(t,e){if(!t||typeof t!="object")return!1;if(Array.isArray(t)){for(let n=0,s=t.length;n<s;n++)if(fr(t[n]))return!0;return!1}if(oh(t))return!0;if(t.toJSON&&typeof t.toJSON=="function"&&arguments.length===1)return fr(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&fr(t[n]))return!0;return!1}function Hw(t){const e=[],n=t.data,s=t;return s.data=fc(n,e),s.attachments=e.length,{packet:s,buffers:e}}function fc(t,e){if(!t)return t;if(oh(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}else if(Array.isArray(t)){const n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=fc(t[s],e);return n}else if(typeof t=="object"&&!(t instanceof Date)){const n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=fc(t[s],e));return n}return t}function Ww(t,e){return t.data=pc(t.data,e),delete t.attachments,t}function pc(t,e){if(!t)return t;if(t&&t._placeholder===!0){if(typeof t.num=="number"&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}else if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=pc(t[n],e);else if(typeof t=="object")for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=pc(t[n],e));return t}const Gw=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],jw=5;var j;(function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"})(j||(j={}));class qw{constructor(e){this.replacer=e}encode(e){return(e.type===j.EVENT||e.type===j.ACK)&&fr(e)?this.encodeAsBinary({type:e.type===j.EVENT?j.BINARY_EVENT:j.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let n=""+e.type;return(e.type===j.BINARY_EVENT||e.type===j.BINARY_ACK)&&(n+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(n+=e.nsp+","),e.id!=null&&(n+=e.id),e.data!=null&&(n+=JSON.stringify(e.data,this.replacer)),n}encodeAsBinary(e){const n=Hw(e),s=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(s),i}}function Pd(t){return Object.prototype.toString.call(t)==="[object Object]"}class ah extends Te{constructor(e){super(),this.reviver=e}add(e){let n;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(e);const s=n.type===j.BINARY_EVENT;s||n.type===j.BINARY_ACK?(n.type=s?j.EVENT:j.ACK,this.reconstructor=new zw(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(oh(e)||e.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(e),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let n=0;const s={type:Number(e.charAt(0))};if(j[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===j.BINARY_EVENT||s.type===j.BINARY_ACK){const r=n+1;for(;e.charAt(++n)!=="-"&&n!=e.length;);const o=e.substring(r,n);if(o!=Number(o)||e.charAt(n)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(n+1)==="/"){const r=n+1;for(;++n&&!(e.charAt(n)===","||n===e.length););s.nsp=e.substring(r,n)}else s.nsp="/";const i=e.charAt(n+1);if(i!==""&&Number(i)==i){const r=n+1;for(;++n;){const o=e.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===e.length)break}s.id=Number(e.substring(r,n+1))}if(e.charAt(++n)){const r=this.tryParse(e.substr(n));if(ah.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,n){switch(e){case j.CONNECT:return Pd(n);case j.DISCONNECT:return n===void 0;case j.CONNECT_ERROR:return typeof n=="string"||Pd(n);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&Gw.indexOf(n[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class zw{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const n=Ww(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Kw=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ah,Encoder:qw,get PacketType(){return j},protocol:jw},Symbol.toStringTag,{value:"Module"}));function Et(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Yw=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class C1 extends Te{constructor(e,n,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=n,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Et(e,"open",this.onopen.bind(this)),Et(e,"packet",this.onpacket.bind(this)),Et(e,"error",this.onerror.bind(this)),Et(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...n){var s,i,r;if(Yw.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(n.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:j.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const h=this.ids++,u=n.pop();this._registerAckCallback(h,u),o.id=h}const a=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!a||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,n){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=n;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);n.call(this,new Error("operation has timed out"))},i),o=(...a)=>{this.io.clearTimeoutFn(r),n.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...n){return new Promise((s,i)=>{const r=(o,a)=>o?i(o):s(a);r.withError=!0,n.push(r),this.emit(e,...n)})}_addToQueue(e){let n;typeof e[e.length-1]=="function"&&(n=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>s!==this._queue[0]?void 0:(i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!e||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:j.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case j.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case j.EVENT:case j.BINARY_EVENT:this.onevent(e);break;case j.ACK:case j.BINARY_ACK:this.onack(e);break;case j.DISCONNECT:this.ondisconnect();break;case j.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const n=e.data||[];e.id!=null&&n.push(this.ack(e.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const s of n)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const n=this;let s=!1;return function(...i){s||(s=!0,n.packet({type:j.ACK,id:e,data:i}))}}onack(e){const n=this.acks[e.id];typeof n=="function"&&(delete this.acks[e.id],n.withError&&e.data.unshift(null),n.apply(this,e.data))}onconnect(e,n){this.id=e,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:j.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const n=this._anyListeners;for(let s=0;s<n.length;s++)if(e===n[s])return n.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const n=this._anyOutgoingListeners;for(let s=0;s<n.length;s++)if(e===n[s])return n.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const s of n)s.apply(this,e.data)}}}function Us(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Us.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=(Math.floor(e*10)&1)==0?t-n:t+n}return Math.min(t,this.max)|0};Us.prototype.reset=function(){this.attempts=0};Us.prototype.setMin=function(t){this.ms=t};Us.prototype.setMax=function(t){this.max=t};Us.prototype.setJitter=function(t){this.jitter=t};class mc extends Te{constructor(e,n){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(n=e,e=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Mo(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((s=n.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Us({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=e;const i=n.parser||Kw;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var n;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(n=this.backoff)===null||n===void 0||n.setMin(e),this)}randomizationFactor(e){var n;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(n=this.backoff)===null||n===void 0||n.setJitter(e),this)}reconnectionDelayMax(e){var n;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(n=this.backoff)===null||n===void 0||n.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Ow(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=Et(n,"open",function(){s.onopen(),e&&e()}),r=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Et(n,"error",r);if(this._timeout!==!1){const a=this._timeout,c=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),n.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Et(e,"ping",this.onping.bind(this)),Et(e,"data",this.ondata.bind(this)),Et(e,"error",this.onerror.bind(this)),Et(e,"close",this.onclose.bind(this)),Et(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(n){this.onclose("parse error",n)}}ondecoded(e){Oo(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,n){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new C1(this,e,n),this.nsps[e]=s),s}_destroy(e){const n=Object.keys(this.nsps);for(const s of n)if(this.nsps[s].active)return;this._close()}_packet(e){const n=this.encoder.encode(e);for(let s=0;s<n.length;s++)this.engine.write(n[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,n){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},n);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ks={};function pr(t,e){typeof t=="object"&&(e=t,t=void 0),e=e||{};const n=Mw(t,e.path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=Ks[i]&&r in Ks[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let c;return a?c=new mc(s,e):(Ks[i]||(Ks[i]=new mc(s,e)),c=Ks[i]),n.query&&!e.query&&(e.query=n.queryKey),c.socket(n.path,e)}Object.assign(pr,{Manager:mc,Socket:C1,io:pr,connect:pr});const An=class An{constructor(){_(this,"socket");_(this,"backendUrl",Io("server"));_(this,"videoStream");_(this,"videoElement");_(this,"isConnected",!1);_(this,"isStreaming",!1);_(this,"jobId");_(this,"onDisconnection");_(this,"canvas");_(this,"encoderBusy",!1);_(this,"playHandler",()=>{if(!this.videoElement||!this.canvas)return;const e=this.videoElement,n=this.canvas,s=()=>{const o=e.videoWidth||640,a=e.videoHeight||480;(n.width!==o||n.height!==a)&&(n.width=o,n.height=a)},i=n.getContext("2d");if(!i)return;const r=()=>{if(this.isStreaming){if((e.videoWidth||0)===0||(e.videoHeight||0)===0){requestAnimationFrame(r);return}s(),!e.paused&&!e.ended&&(i.drawImage(e,0,0,n.width,n.height),this.encoderBusy||(this.encoderBusy=!0,this.sendFrameToBackend(n,()=>{this.encoderBusy=!1}))),requestAnimationFrame(r)}};r()});_(this,"stopStreaming",()=>{this.isStreaming=!1,this.removePlayEventListener()})}static getInstance(){return An.instance||(An.instance=new An),An.instance}async setupWebSocketConnection(){return new Promise((e,n)=>{if(this.socket)return e(!0);this.socket=pr(this.backendUrl,{transports:["websocket","polling"]}),this.socket.once("connect",()=>{this.isConnected=!0,e(!0)}),this.socket.once("connect_error",s=>{n(L.ConnectionLostError)}),this.socket.once("disconnect",s=>{this.handleSocketDisconnection(s)})})}handleSocketDisconnection(e){this.isConnected=!1}async initializeStreaming(e,n){this.videoStream=e,this.videoElement=n,this.videoElement.srcObject=e,this.canvas=document.createElement("canvas"),this.canvas.width=n.videoWidth||640,this.canvas.height=n.videoHeight||480,await this.setupWebSocketConnection()}startStreaming(e){var n;this.jobId=e,(n=this.socket)==null||n.emit("register",e),this.sendInitialRequest(e),this.isStreaming=!0,this.startVideoStream(),this.addDisconnectionListener()}async sendInitialRequest(e){await te.post(`${this.backendUrl}/react`,{username:e,uuid:e,device_id:"1234567",face_detector:"BlazefaceFacemesh",motion_tracking:!0,skin_segmentor:"HSVandYCrCbSkinSegmentation",extreme_pixel_removal:!1,gamma_value:1,eularian_color_magnification:!1},{headers:{"Content-Type":"application/json"}})}startVideoStream(){if(!this.videoElement){f.error("Video stream not found when trying to start streaming");return}const e=this.videoElement,n=()=>{e.videoWidth>0&&e.videoHeight>0&&(this.playHandler(),e.removeEventListener("loadedmetadata",n),e.removeEventListener("playing",n))};e.addEventListener("playing",n),e.addEventListener("loadedmetadata",n),e.readyState>=2&&e.videoWidth>0&&e.videoHeight>0&&n(),e.addEventListener("play",this.playHandler),e.play().catch(s=>f.error("Error starting video stream:",s))}sendFrameToBackend(e,n){e.toBlob(s=>{if(n&&n(),!s){f.warn("[WARN] canvas.toBlob returned null (likely 0×0 canvas or tainted).");return}const i=new FileReader;i.onloadend=()=>{var r;if(this.isConnected&&this.isStreaming){const o=i.result;(r=this.socket)==null||r.emit("frame",o)}},i.readAsArrayBuffer(s)},"image/jpeg",.7)}removePlayEventListener(){this.videoElement&&this.videoElement.removeEventListener("play",this.playHandler)}setOnDisconnection(e){this.onDisconnection=e}addDisconnectionListener(){const e=er(),n=Ys(e,`${this.jobId}/disconnect`),s=Zi(n,i=>{i.val()!=null&&(this.stopStreaming(),this.onDisconnection&&this.onDisconnection(),s())})}};_(An,"instance");let qr=An;class T1{constructor(){_(this,"backendUrl",Io("server"));_(this,"streamingManager",qr.getInstance());_(this,"accessTokenProvider")}setAccessTokenProvider(e){this.accessTokenProvider=e}}class Xw extends T1{constructor(){super();_(this,"streamingManager",qr.getInstance());_(this,"rgbManager",Wr.getInstance());this.backendUrl=Io("server"),f.log("ServerRepository",this.backendUrl)}async getTokenWithUsernameAndPassword(n,s){try{return(await te.post(this.backendUrl.concat("/clientlogin"),{username:n,password:s})).data.access_token}catch(i){W.handleErrorResponse(i)}}async getTokenWithLicenseKey(n){try{return(await te.post(this.backendUrl.concat("/clientloginwithlicensekey"),{license_key:n})).data.access_token}catch(s){W.handleErrorResponse(s)}}async getAPIKey(n){n||W.throwKnownError(L.InvalidAccessTokenError);try{return(await te.post(this.backendUrl.concat("/clientgeturl"),{host_name:"www.nervoscan.com"},{headers:{Authorization:`Bearer ${n}`}})).data.url.split("?api_key=")[1]}catch(s){W.handleErrorResponse(s)}}async uploadVideoToServer(n,s,i){(!s||!i)&&W.throwKnownError(L.InvalidAccessTokenError);const r=new FormData;r.append("file",n,"recording.webm"),r.append("data",JSON.stringify({uuid:i,meta_data:{}}));const a=await(await fetch(this.backendUrl.concat("/submitscan"),{method:"POST",headers:{Authorization:`Bearer ${s}`},body:r})).json();return a.success===!1&&W.handleErrorResponse(a),a}async sendRgbDataToBackend(n,s,i,r){try{const o=this.accessTokenProvider?await this.accessTokenProvider():void 0;o||W.throwKnownError(L.InvalidAccessTokenError);const a={job_id:r,timestamp:Date.now(),rgbData:n,resolution:{width:s,height:i}};return f.log(`[Backend] Sending RGB data to backend with resolution: ${s}x${i}`),f.debug("Sending RGB data to backend:",a),(await te.post(`${this.backendUrl}/rgb-data`,a,{headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})).data}catch(o){W.handleErrorResponse(o)}}}class Qw extends T1{constructor(){super(),this.backendUrl=Io("serverless")}async getTokenWithUsernameAndPassword(e,n){try{const s=await te.post(this.backendUrl.concat("/user/login"),{username:e,password:n});if(s.data.success===!1)W.throwKnownError(L.InvalidUsernameError);else return JSON.parse(s.data.body).idToken}catch(s){f.error("error printed in serverless repository",s),W.handleErrorResponse(s)}}async getTokenWithLicenseKey(e){W.throwKnownError(L.NotImplementedError)}async getAPIKey(e){e||W.throwKnownError(L.InvalidAccessTokenError);try{return(await te.post(this.backendUrl.concat("/get-redirection-url"),{host_name:"www.nervoscan.com"},{headers:{Authorization:`Bearer ${e}`}})).data.url.split("?api_key=")[1]}catch(n){W.handleErrorResponse(n)}}async uploadVideoToServer(e,n,s){(!n||!s)&&W.throwKnownError(L.InvalidAccessTokenError);try{const i=await this.generatePreSignedUrl(s);return i||W.throwKnownError(L.InvalidAccessTokenError),await this.uploadVideoToS3(e,i)}catch(i){throw f.error("Error uploading video:",i),i.response?(f.error("Error response:",i.response.data),f.error("Error status:",i.response.status),f.error("Error headers:",i.response.headers)):i.request?f.error("Error request:",i.request):f.error("Error message:",i.message),i}}async generatePreSignedUrl(e){try{return(await te.get(this.backendUrl.concat("/generate-presigned-url?job_id="+e))).data.upload_url}catch(n){W.handleErrorResponse(n)}}async uploadVideoToS3(e,n){try{return(await te.put(n,e,{headers:{"Content-Type":"video/mp4"}})).data}catch(s){W.handleErrorResponse(s)}}async sendRgbDataToBackend(e,n,s,i){W.throwKnownError(L.NotImplementedError)}}class S1{static createBackendRepository(e,n){if(e==="server")return new Xw;if(e==="serverless")return new Qw;W.throwKnownError(L.InvalidServerTypeError)}}class Jw{constructor(e,n,s,i="server"){_(this,"backendRepository");_(this,"username");_(this,"password");_(this,"licenseKey");this.backendRepository=S1.createBackendRepository(i,!1),this.username=e,this.password=n,this.licenseKey=s,e&&n&&f.warn("Using username and password for authentication is deprecated. Please use license key instead.")}async validate(){if(this.licenseKey)return this.validateWithKey(this.licenseKey);if(this.username&&this.password)return this.validatewithUsernameAndPassword(this.username,this.password);W.throwKnownError(L.InvalidCredentialsError)}async validateWithKey(e){return this.backendRepository.getTokenWithLicenseKey(e)}async validatewithUsernameAndPassword(e,n){return this.backendRepository.getTokenWithUsernameAndPassword(e,n)}}const Rn=class Rn{constructor(){_(this,"initialized",!1);_(this,"accessToken");_(this,"backendRepository");_(this,"onWindowResults");_(this,"onFinalResults");_(this,"onError");_(this,"firebaseHandlers",[]);_(this,"useRgb",!1);_(this,"rgbManager",Wr.getInstance());_(this,"onDisconnection",()=>{});_(this,"licenceManager");If({apiKey:"AIzaSyAoOpQqLrc6wQLJI5KRE2Vt7QV1cplsZv8",authDomain:"nervowebreact.firebaseapp.com",databaseURL:"https://nervowebreact-default-rtdb.asia-southeast1.firebasedatabase.app",projectId:"nervowebreact",storageBucket:"nervowebreact.firebasestorage.app",messagingSenderId:"1025695568936",appId:"1:1025695568936:web:36f269a1eb74e1fdda511d",measurementId:"G-L3105FG92S"})}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}initialize({username:e,password:n,licenseKey:s,serverType:i="server",useRgb:r=!1}){this.initialized=!0,this.useRgb=r,this.licenceManager=new Jw(e,n,s,i),this.backendRepository=S1.createBackendRepository(i,r),this.backendRepository.setAccessTokenProvider(async()=>this.licenceManager.validate())}async uploadVideo(e){var i,r;this.initialized||W.throwKnownError(L.NotInitializedError),e instanceof Blob||W.throwKnownError(L.VideoTypeError),(e===null||e.size===0)&&W.throwKnownError(L.EmptyVideoError);const n=await this.licenceManager.validate(),s=await((i=this.backendRepository)==null?void 0:i.getAPIKey(n));return(r=this.backendRepository)==null||r.uploadVideoToServer(e,n,s),s&&this.addfirebaseListeners(s),s}setOnFinalResults(e){this.onFinalResults=e}setOnError(e){this.onError=e}setOnDisconnection(e){var n;(n=this.backendRepository)==null||n.streamingManager.setOnDisconnection(e),this.onDisconnection=e}setOnAlignmentStatus(e){this.rgbManager.setAlignmentStatusCallback(e)}startFaceDetection(){this.useRgb&&this.rgbManager.startFaceDetection()}stopFaceDetection(){this.useRgb&&this.rgbManager.stopFaceDetection()}async initializeStreaming(e,n,s={}){var i;this.useRgb?await this.rgbManager.initialize(e,n,this.backendRepository,this.onDisconnection,s):await((i=this.backendRepository)==null?void 0:i.streamingManager.initializeStreaming(e,n))}async startStreaming(){var s,i;this.initialized||W.throwKnownError(L.NotInitializedError);const e=await this.licenceManager.validate(),n=await((s=this.backendRepository)==null?void 0:s.getAPIKey(e));if(n)return this.useRgb?(f.log("Starting RGB streaming"),await this.rgbManager.startStreaming(n)):(i=this.backendRepository)==null||i.streamingManager.startStreaming(n),this.addfirebaseListeners(n),n;W.throwKnownError(L.InvalidAccessTokenError)}async stopStreaming(e=!1){var n;if((n=this.backendRepository)==null||n.streamingManager.stopStreaming(),this.rgbManager.stopStreaming(),!e)try{await this.validateScanCompletion()}catch(s){throw s}}async validateScanCompletion(){if(this.initialized||W.throwKnownError(L.NotInitializedError),!this.useRgb)return;const e=this.getRGBDataCollectionStatus();if(e.error&&e.error==="RGB mode not enabled")return;const n=300,s=13.5;((e==null?void 0:e.bufferSize)||0)<n&&W.throwKnownError(L.InsufficientDataError);const r=this.getRGBTimestamps();if(r.length>=2){const o=r[0],c=r[r.length-1]-o,l=(r.length-1)/c;if(l<s){const h=`Camera frame rate is too low (${l.toFixed(1)} FPS). Please try again with better lighting and ensure your device is not under heavy load.`;throw new z.LowFPSError(h)}}else W.throwKnownError(L.FPSCalculationError)}async addfirebaseListeners(e){this.addWindowListener(e),this.addFinalListener(e),this.addErrorListener(e)}addWindowListener(e){const n=er(),s=Ys(n,`${e}`),i=y3(s,r=>{r.val()!==null&&r.key&&/^\d+$/.test(r.key)&&this.onWindowResults&&this.onWindowResults(r.val())});this.firebaseHandlers.push(i)}removefirebaseListeners(){this.firebaseHandlers.forEach(e=>{e()}),this.firebaseHandlers=[]}addFinalListener(e){f.log(`Adding final listener for job ${e}`);const n=er(),s=Ys(n,`/${e}/averaged_results/`),i=Zi(s,r=>{if(r.val()===null)return;const o=r.val();f.log(`[Client] Received results for job ${e}:`,o),this.useRgb&&this.rgbManager.isContinuousModeEnabled()?this.rgbManager.handleBatchResults(o):(this.onFinalResults&&this.onFinalResults(o),this.removefirebaseListeners())});this.firebaseHandlers.push(i)}addErrorListener(e){const n=er(),s=Ys(n,`/${e}/error/`),i=Zi(s,a=>{if(a.val()===null)return;const c=W.handleScanError(a.val());this.onError?this.onError(c):W.throwKnownError(L.ErrorCallbackNotSetError),this.removefirebaseListeners()}),r=Ys(n,`/${e}/job_completed/`),o=Zi(r,a=>{a.val()!==null&&(a.val()==="failed"&&this.onError?(this.onError(L.ScanFailedError),this.removefirebaseListeners()):a.val()==="success"&&this.removefirebaseListeners())});this.firebaseHandlers.push(i),this.firebaseHandlers.push(o)}getRGBDataCollectionStatus(){return this.useRgb&&this.rgbManager?this.rgbManager.getDataCollectionStatus():{error:"RGB mode not enabled"}}getRGBTimestamps(){return this.useRgb&&this.rgbManager?this.rgbManager.getRGBTimestamps():[]}};_(Rn,"instance");let gc=Rn;exports.Client=gc;exports.ConnectionLostError=af;exports.EmptyVideoError=Md;exports.EnvIncompatibleError=pf;exports.ErrorCallbackNotSetError=Zd;exports.Errors=z;exports.FPSCalculationError=zd;exports.FaceLandmarkerNotInitializedError=ff;exports.FaceLookingLeftError=Qd;exports.FaceLookingRightError=Jd;exports.FaceNotCenteredError=Kd;exports.FaceTooCloseError=Xd;exports.FaceTooFarError=Yd;exports.InsufficientDataError=mf;exports.InvalidAccessTokenError=Hd;exports.InvalidContentTypeError=nf;exports.InvalidCredentialsError=hf;exports.InvalidPasswordError=Vd;exports.InvalidServerTypeError=Gd;exports.InvalidUsernameError=Ud;exports.JobNotRegisteredError=sf;exports.LicenseInactiveError=uf;exports.LowFPSError=qd;exports.LowFrameCountError=of;exports.NervoscanError=K;exports.NoScanDataError=Wd;exports.NoScansAvailableError=$d;exports.NotImplementedError=jd;exports.NotInitializedError=Od;exports.RGBError=df;exports.ScanFailedError=cf;exports.SkinExtractionError=tf;exports.UnhandledError=rf;exports.UnhandledScanError=ef;exports.VideoError=lf;exports.VideoTypeError=Bd;