@nuralogix.ai/web-measurement-embedded-app 0.1.0-beta.3 → 0.1.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stylex.css CHANGED
@@ -31,8 +31,8 @@
31
31
  margin: auto;
32
32
  }
33
33
 
34
- .padding-x1dvq9d0 {
35
- padding: .75rem 0 1.25rem;
34
+ .padding-x1vy5iyh {
35
+ padding: .75rem 0 3rem;
36
36
  }
37
37
 
38
38
  .padding-xc7ga6q {
@@ -57,12 +57,12 @@
57
57
  border-radius: 4px;
58
58
  }
59
59
 
60
- .gap-x13z6uf9 {
61
- gap: .5rem;
60
+ .gap-xvh977a {
61
+ gap: .25rem;
62
62
  }
63
63
 
64
- .gap-x1uma3xh {
65
- gap: .6rem;
64
+ .gap-x13z6uf9 {
65
+ gap: .5rem;
66
66
  }
67
67
 
68
68
  .overflow-xysyzu8 {
@@ -189,12 +189,12 @@
189
189
  margin-bottom: 8px;
190
190
  }
191
191
 
192
- .marginTop-x1mjqqkp {
193
- margin-top: .5rem;
192
+ .marginTop-x1tbvfm1 {
193
+ margin-top: .25rem;
194
194
  }
195
195
 
196
- .marginTop-xv0uc0e {
197
- margin-top: .6rem;
196
+ .marginTop-x1mjqqkp {
197
+ margin-top: .5rem;
198
198
  }
199
199
 
200
200
  .marginTop-xqui205 {
package/lib/index.d.ts CHANGED
@@ -955,8 +955,6 @@ interface MeasurementEmbeddedAppOptions {
955
955
  config?: Config;
956
956
  /** API URL for region-specific data processing */
957
957
  apiUrl?: string;
958
- /** Callback function to handle load errors */
959
- loadError?: (error: string) => void;
960
958
  }
961
959
  declare enum logCategory {
962
960
  measurement = "Measurement",
@@ -971,7 +969,7 @@ interface Log {
971
969
  meta?: any;
972
970
  }
973
971
  interface MeasurementEmbedded {
974
- init(options: MeasurementEmbeddedAppOptions): void;
972
+ init(options: MeasurementEmbeddedAppOptions): Promise<void>;
975
973
  destroy(): Promise<void>;
976
974
  /**
977
975
  * Cancel the measurement
@@ -1142,7 +1140,7 @@ declare class MeasurementEmbeddedApp implements MeasurementEmbedded {
1142
1140
  };
1143
1141
  /** @hideconstructor */
1144
1142
  constructor();
1145
- init(options: MeasurementEmbeddedAppOptions): void;
1143
+ init(options: MeasurementEmbeddedAppOptions): Promise<void>;
1146
1144
  destroy(): Promise<void>;
1147
1145
  setTheme(theme: 'light' | 'dark'): void;
1148
1146
  setLanguage(language: SupportedLanguage): void;
package/lib/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Nt="0.1.0-beta.3";const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelled",DESTROYED:"destroyed",LOGS:"logs"};var je=(t=>(t.measurement="Measurement",t.collector="Collector",t.camera="Camera",t.app="App",t))(je||{});const O={INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},N={CAMERA_STARTED:"CAMERA_STARTED",APP_LOADED:"APP_LOADED",MEASUREMENT_PREPARED:"MEASUREMENT_PREPARED",ASSETS_DOWNLOADED:"ASSETS_DOWNLOADED",MEASUREMENT_STARTED:"MEASUREMENT_STARTED",MEASUREMENT_COMPLETED:"MEASUREMENT_COMPLETED",CAMERA_PERMISSION_GRANTED:"CAMERA_PERMISSION_GRANTED",INTERMEDIATE_RESULTS:"INTERMEDIATE_RESULTS",RESULTS_RECEIVED:"RESULTS_RECEIVED",MEASUREMENT_CANCELED:"MEASUREMENT_CANCELED",CONSTRAINT_VIOLATION:"CONSTRAINT_VIOLATION",PAGE_UNLOADED:"PAGE_UNLOADED",PAGE_VISIBILITY_CHANGE:"PAGE_VISIBILITY_CHANGE"},Lt={CAMERA_STARTED:{event:N.CAMERA_STARTED,level:O.INFO},APP_LOADED:{event:N.APP_LOADED,level:O.INFO},MEASUREMENT_PREPARED:{event:N.MEASUREMENT_PREPARED,level:O.INFO},ASSETS_DOWNLOADED:{event:N.ASSETS_DOWNLOADED,level:O.INFO},MEASUREMENT_STARTED:{event:N.MEASUREMENT_STARTED,level:O.INFO},MEASUREMENT_COMPLETED:{event:N.MEASUREMENT_COMPLETED,level:O.INFO},CAMERA_PERMISSION_GRANTED:{event:N.CAMERA_PERMISSION_GRANTED,level:O.INFO},INTERMEDIATE_RESULTS:{event:N.INTERMEDIATE_RESULTS,level:O.INFO},RESULTS_RECEIVED:{event:N.RESULTS_RECEIVED,level:O.INFO},MEASUREMENT_CANCELED:{event:N.MEASUREMENT_CANCELED,level:O.WARN},CONSTRAINT_VIOLATION:{event:N.CONSTRAINT_VIOLATION,level:O.ERROR},PAGE_UNLOADED:{event:N.PAGE_UNLOADED,level:O.INFO},PAGE_VISIBILITY_CHANGE:{event:N.PAGE_VISIBILITY_CHANGE,level:O.INFO}},re={DESTROY:"destroy",CANCEL:"cancel",SET_THEME:"setTheme",SET_LANGUAGE:"setLanguage",GET_LOGS:"getLogs"};var Ye=(t=>(t.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",t.WORKER_ERROR="WORKER_ERROR",t.PROFILE_INFO_NOT_SET="PROFILE_INFO_NOT_SET",t.NO_DEVICES_FOUND="NO_DEVICES_FOUND",t.PAGE_NOT_VISIBLE="PAGE_NOT_VISIBLE",t.CAMERA_START_FAILED="CAMERA_START_FAILED",t.MEASUREMENT_LOW_SNR="MEASUREMENT_LOW_SNR",t.COLLECTOR="COLLECTOR",t.WEBSOCKET_DISCONNECTED="WEBSOCKET_DISCONNECTED",t.MEASUREMENT_PREPARE_FAILED="MEASUREMENT_PREPARE_FAILED",t))(Ye||{}),Je="0.1.0-beta.2",J=(t=>(t.DELETE="DELETE",t.GET="GET",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.CONNECT="CONNECT",t))(J||{}),V=(t=>(t.ON_BEFORE_REST_CALL_ERROR="ON_BEFORE_REST_CALL_ERROR",t))(V||{});const Xe=typeof DedicatedWorkerGlobalScope<"u",be=async({baseUrl:t,urlFragment:e,method:i,headers:r,data:c},d)=>{const n=`${t}/${e}`;let a={Code:"",Message:""};try{const u=await fetch(n,{method:i,cache:"no-store",credentials:"include",headers:r,...c!=null&&{body:JSON.stringify(c)}}),h=u.headers.get("content-type"),E=u.status.toString();a={Code:"UNSUPPORTED_RESPONSE_CONTENT_TYPE",Message:"UNSUPPORTED_RESPONSE_CONTENT_TYPE"},E==="503"&&(a={Code:"SERVICE_UNAVAILABLE",Message:"Service unavailable"}),E==="429"&&(a={Code:"TOO_MANY_REQUESTS",Message:"Too many requests"}),h!=null&&(h.startsWith("application/json;")&&(a=await u.json()),h.startsWith("text/plain;")&&(a={data:await u.text()}));let _=u.headers;if(Xe){const C={};u.headers.forEach((k,I)=>{C[I]=k}),_=C}try{d(E,E==="200"?void 0:a)}catch(C){console.error("Error running onAfterRESTCall callback",C)}return{status:E,headers:_,body:a}}catch(u){return u instanceof SyntaxError?a={Code:"SYNTAX_ERROR",Message:"SYNTAX_ERROR"}:a={Code:"UNEXPECTED_ERROR",Message:"UNEXPECTED_ERROR"},{status:"UNKNOWN",headers:Xe?{}:new Headers,body:a}}},_e=()=>new Headers({"Content-Type":"application/json"});var Dt=Object.defineProperty,It=(t,e,i)=>e in t?Dt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xt=(t,e,i)=>It(t,e+"",i);class Fe{constructor(e){xt(this,"parent"),this.parent=e}async onBeforeRESTCall(){try{return this.parent.onBeforeRESTCall(),{Code:"SUCCESS",Message:"SUCCESS"}}catch{return{Code:V.ON_BEFORE_REST_CALL_ERROR,Message:V.ON_BEFORE_REST_CALL_ERROR}}}getDefaults(e){return{baseUrl:JSON.parse(this.parent.getUrl()).http.slice(0,-1),method:J[e],headers:_e()}}getHeaderWithDeviceToken(){const e=_e();return e.set("Authorization",`Bearer ${this.parent.getSession().deviceToken}`),e}getHeaderWithUserToken(){const e=_e();return e.set("Authorization",`Bearer ${this.parent.getSession().userToken}`),e}getHeaderWithSessionEnabled(){const e=_e();return e.set("x-nura-session","true"),e}}class Ft extends Fe{async create(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===V.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await be({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"measurements",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({lastMeasurementId:n.ID}),{status:d,body:n,headers:a}}}class Mt extends Fe{async retrieveSdkConfigData(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===V.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await be({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"studies/sdkconfig",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({studyCfgData:n.ConfigFile,studyCfgHash:n.MD5Hash}),{status:d,body:n,headers:a}}}class Pt extends Fe{async renew(e,i){const{Code:r,Message:c}=await this.onBeforeRESTCall();if(r===V.ON_BEFORE_REST_CALL_ERROR)return{status:r,body:{Code:r,Message:c},headers:new Headers};const{status:d,body:n,headers:a}=await be({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auths/renew",data:e},this.parent.onAfterRESTCall);if(d==="200"){const u=n.Token,h=n.RefreshToken,E={...i==="user"&&{userToken:u,userRefreshToken:h},...i==="device"&&{deviceToken:u,deviceRefreshToken:h}};this.parent.setSession(E)}return{status:d,body:n,headers:a}}async validate(e){const{Code:i,Message:r}=await this.onBeforeRESTCall();return i===V.ON_BEFORE_REST_CALL_ERROR?{status:i,body:{Code:i,Message:r},headers:new Headers}:await be({...this.getDefaults(J.GET),headers:e==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auth/v1/validate"},this.parent.onAfterRESTCall)}}var Wt=Object.defineProperty,ze=t=>{throw TypeError(t)},Ut=(t,e,i)=>e in t?Wt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Me=(t,e,i)=>Ut(t,typeof e!="symbol"?e+"":e,i),qe=(t,e,i)=>e.has(t)||ze("Cannot "+i),Pe=(t,e,i)=>(qe(t,e,"read from private field"),i?i.call(t):e.get(t)),Ze=(t,e,i)=>e.has(t)?ze("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ge=(t,e,i,r)=>(qe(t,e,"write to private field"),e.set(t,i),i),ne,X;class $t{constructor(e){Ze(this,ne,{http:new URL("https://api.deepaffex.ai")}),Ze(this,X),Me(this,"onBeforeRESTCall"),Me(this,"onAfterRESTCall"),Me(this,"http"),ge(this,X,{deviceToken:"",deviceRefreshToken:"",userToken:"",userRefreshToken:"",deviceId:"",roleId:"",userId:"",selectedStudy:"",lastMeasurementId:"",studyCfgHash:"",studyCfgData:""}),this.http={measurements:new Ft(this),studies:new Mt(this),auths:new Pt(this)},this.onBeforeRESTCall=e?.onBeforeRESTCall?e.onBeforeRESTCall:()=>{},this.onAfterRESTCall=e?.onAfterRESTCall?e.onAfterRESTCall:()=>{},e?.url!=null&&ge(this,ne,e.url)}static new(e){return new this(e??void 0)}getUrl(){return JSON.stringify(Pe(this,ne))}setUrl(e){ge(this,ne,{http:new URL(e)})}getSession(){return Pe(this,X)}setSession(e){const i=["deviceToken","deviceRefreshToken","userToken","userRefreshToken","deviceId","userId","roleId","selectedStudy","lastMeasurementId","studyCfgHash","studyCfgData"];Object.keys(e).every(d=>i.includes(d)&&typeof e[d]=="string")&&ge(this,X,{...Pe(this,X),...e})}}ne=new WeakMap,X=new WeakMap;const Bt=t=>$t.new(t);var Gt=Object.defineProperty,Qe=t=>{throw TypeError(t)},Ht=(t,e,i)=>e in t?Gt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Vt=(t,e,i)=>Ht(t,e+"",i),Kt=(t,e,i)=>e.has(t)||Qe("Cannot "+i),jt=(t,e,i)=>e.has(t)?Qe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),We=(t,e,i)=>(Kt(t,e,"access private method"),i),oe,Ue,et;let tt=t=>new Int8Array(t);class Yt extends EventTarget{constructor(){super(...arguments),jt(this,oe),Vt(this,"canDecompress",!1)}static init(){return new this}dispatch(e,i){this.dispatchEvent(new CustomEvent(e,{detail:i}))}getBytesDownloadedEvent(e,i,r,c){return new CustomEvent("bytesDownloaded",{detail:{bytes:e,uncompressedSize:i,url:r,done:c}})}getBytesDownloadErrorEvent(e,i){return new CustomEvent("downloadedError",{detail:{url:e,error:i}})}decompressBrotli(e){const i=atob(e),r=new Uint8Array(i.length);for(let n=0;n<i.length;n++)r[n]=i.charCodeAt(n);const c=new Int8Array(r.length);for(let n=0;n<r.length;n++)c[n]=r[n]>=128?r[n]-256:r[n];return tt(c).buffer}async fetchAsset(e,i,r,c,d){const n=i+r,a=e.find(h=>h.file===r).uncompressedSize,u=(h,E,_,C)=>We(this,oe,Ue).call(this,this.getBytesDownloadedEvent(h,E,_,C));try{const E=(await fetch(n)).body?.getReader();if(!E)throw new Error("Failed to get reader from response body.");let _=0;const C=new ReadableStream({async start(I){await W();async function W(){const{done:G,value:M}=await E.read();if(G){I.close(),u(_,a,n,!0);return}M&&(I.enqueue(M),_+=M.length,u(_,a,n,!1)),await W()}}}),k=new Response(C);if(c){const I=await k.json(),{base64EncodedValue:W}=I;if(d==="gzip"){await We(this,oe,et).call(this,W);return}return this.decompressBrotli(W)}else return await k.arrayBuffer()}catch(h){We(this,oe,Ue).call(this,this.getBytesDownloadErrorEvent(n,h))}}}oe=new WeakSet,Ue=function(t){this.dispatchEvent(t)},et=async function(t){const e=Uint8Array.from(atob(t),h=>h.charCodeAt(0)),r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),c=await new Response(r).arrayBuffer(),d=new TextDecoder().decode(new Uint8Array(c)),n=new Blob([d],{type:"application/javascript"}),a=URL.createObjectURL(n);tt=(await import(a)).BrotliDecode,this.canDecompress=!0,URL.revokeObjectURL(a)};var Jt=Object.defineProperty,Xt=(t,e,i)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,it=(t,e,i)=>Xt(t,typeof e!="symbol"?e+"":e,i);class zt{constructor(){it(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""}),it(this,"debugLogs",[])}appendLog(e){this.debugLogs.push(e)}transferLogs(){}generateHTMLTable(){return`
1
+ var Lt="0.1.0-beta.5";const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEvent",CANCELLED:"cancelled",DESTROYED:"destroyed",LOGS:"logs"};var Ye=(t=>(t.measurement="Measurement",t.collector="Collector",t.camera="Camera",t.app="App",t))(Ye||{});const N={INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},L={CAMERA_STARTED:"CAMERA_STARTED",APP_LOADED:"APP_LOADED",MEASUREMENT_PREPARED:"MEASUREMENT_PREPARED",ASSETS_DOWNLOADED:"ASSETS_DOWNLOADED",MEASUREMENT_STARTED:"MEASUREMENT_STARTED",MEASUREMENT_COMPLETED:"MEASUREMENT_COMPLETED",CAMERA_PERMISSION_GRANTED:"CAMERA_PERMISSION_GRANTED",INTERMEDIATE_RESULTS:"INTERMEDIATE_RESULTS",RESULTS_RECEIVED:"RESULTS_RECEIVED",MEASUREMENT_CANCELED:"MEASUREMENT_CANCELED",CONSTRAINT_VIOLATION:"CONSTRAINT_VIOLATION",PAGE_UNLOADED:"PAGE_UNLOADED",PAGE_VISIBILITY_CHANGE:"PAGE_VISIBILITY_CHANGE"},Dt={CAMERA_STARTED:{event:L.CAMERA_STARTED,level:N.INFO},APP_LOADED:{event:L.APP_LOADED,level:N.INFO},MEASUREMENT_PREPARED:{event:L.MEASUREMENT_PREPARED,level:N.INFO},ASSETS_DOWNLOADED:{event:L.ASSETS_DOWNLOADED,level:N.INFO},MEASUREMENT_STARTED:{event:L.MEASUREMENT_STARTED,level:N.INFO},MEASUREMENT_COMPLETED:{event:L.MEASUREMENT_COMPLETED,level:N.INFO},CAMERA_PERMISSION_GRANTED:{event:L.CAMERA_PERMISSION_GRANTED,level:N.INFO},INTERMEDIATE_RESULTS:{event:L.INTERMEDIATE_RESULTS,level:N.INFO},RESULTS_RECEIVED:{event:L.RESULTS_RECEIVED,level:N.INFO},MEASUREMENT_CANCELED:{event:L.MEASUREMENT_CANCELED,level:N.WARN},CONSTRAINT_VIOLATION:{event:L.CONSTRAINT_VIOLATION,level:N.ERROR},PAGE_UNLOADED:{event:L.PAGE_UNLOADED,level:N.INFO},PAGE_VISIBILITY_CHANGE:{event:L.PAGE_VISIBILITY_CHANGE,level:N.INFO}},ne={DESTROY:"destroy",CANCEL:"cancel",SET_THEME:"setTheme",SET_LANGUAGE:"setLanguage",GET_LOGS:"getLogs"};var Je=(t=>(t.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",t.WORKER_ERROR="WORKER_ERROR",t.PROFILE_INFO_NOT_SET="PROFILE_INFO_NOT_SET",t.NO_DEVICES_FOUND="NO_DEVICES_FOUND",t.PAGE_NOT_VISIBLE="PAGE_NOT_VISIBLE",t.CAMERA_START_FAILED="CAMERA_START_FAILED",t.MEASUREMENT_LOW_SNR="MEASUREMENT_LOW_SNR",t.COLLECTOR="COLLECTOR",t.WEBSOCKET_DISCONNECTED="WEBSOCKET_DISCONNECTED",t.MEASUREMENT_PREPARE_FAILED="MEASUREMENT_PREPARE_FAILED",t))(Je||{}),Xe="0.1.0-beta.2",J=(t=>(t.DELETE="DELETE",t.GET="GET",t.PATCH="PATCH",t.POST="POST",t.PUT="PUT",t.CONNECT="CONNECT",t))(J||{}),H=(t=>(t.ON_BEFORE_REST_CALL_ERROR="ON_BEFORE_REST_CALL_ERROR",t))(H||{});const ze=typeof DedicatedWorkerGlobalScope<"u",_e=async({baseUrl:t,urlFragment:e,method:i,headers:a,data:c},d)=>{const n=`${t}/${e}`;let r={Code:"",Message:""};try{const u=await fetch(n,{method:i,cache:"no-store",credentials:"include",headers:a,...c!=null&&{body:JSON.stringify(c)}}),h=u.headers.get("content-type"),p=u.status.toString();r={Code:"UNSUPPORTED_RESPONSE_CONTENT_TYPE",Message:"UNSUPPORTED_RESPONSE_CONTENT_TYPE"},p==="503"&&(r={Code:"SERVICE_UNAVAILABLE",Message:"Service unavailable"}),p==="429"&&(r={Code:"TOO_MANY_REQUESTS",Message:"Too many requests"}),h!=null&&(h.startsWith("application/json;")&&(r=await u.json()),h.startsWith("text/plain;")&&(r={data:await u.text()}));let S=u.headers;if(ze){const C={};u.headers.forEach((k,O)=>{C[O]=k}),S=C}try{d(p,p==="200"?void 0:r)}catch(C){console.error("Error running onAfterRESTCall callback",C)}return{status:p,headers:S,body:r}}catch(u){return u instanceof SyntaxError?r={Code:"SYNTAX_ERROR",Message:"SYNTAX_ERROR"}:r={Code:"UNEXPECTED_ERROR",Message:"UNEXPECTED_ERROR"},{status:"UNKNOWN",headers:ze?{}:new Headers,body:r}}},ge=()=>new Headers({"Content-Type":"application/json"});var It=Object.defineProperty,xt=(t,e,i)=>e in t?It(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ft=(t,e,i)=>xt(t,e+"",i);class Me{constructor(e){Ft(this,"parent"),this.parent=e}async onBeforeRESTCall(){try{return this.parent.onBeforeRESTCall(),{Code:"SUCCESS",Message:"SUCCESS"}}catch{return{Code:H.ON_BEFORE_REST_CALL_ERROR,Message:H.ON_BEFORE_REST_CALL_ERROR}}}getDefaults(e){return{baseUrl:JSON.parse(this.parent.getUrl()).http.slice(0,-1),method:J[e],headers:ge()}}getHeaderWithDeviceToken(){const e=ge();return e.set("Authorization",`Bearer ${this.parent.getSession().deviceToken}`),e}getHeaderWithUserToken(){const e=ge();return e.set("Authorization",`Bearer ${this.parent.getSession().userToken}`),e}getHeaderWithSessionEnabled(){const e=ge();return e.set("x-nura-session","true"),e}}class Mt extends Me{async create(e,i){const{Code:a,Message:c}=await this.onBeforeRESTCall();if(a===H.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:c},headers:new Headers};const{status:d,body:n,headers:r}=await _e({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"measurements",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({lastMeasurementId:n.ID}),{status:d,body:n,headers:r}}}class Pt extends Me{async retrieveSdkConfigData(e,i){const{Code:a,Message:c}=await this.onBeforeRESTCall();if(a===H.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:c},headers:new Headers};const{status:d,body:n,headers:r}=await _e({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"studies/sdkconfig",data:e},this.parent.onAfterRESTCall);return d==="200"&&this.parent.setSession({studyCfgData:n.ConfigFile,studyCfgHash:n.MD5Hash}),{status:d,body:n,headers:r}}}class Wt extends Me{async renew(e,i){const{Code:a,Message:c}=await this.onBeforeRESTCall();if(a===H.ON_BEFORE_REST_CALL_ERROR)return{status:a,body:{Code:a,Message:c},headers:new Headers};const{status:d,body:n,headers:r}=await _e({...this.getDefaults(J.POST),headers:i==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auths/renew",data:e},this.parent.onAfterRESTCall);if(d==="200"){const u=n.Token,h=n.RefreshToken,p={...i==="user"&&{userToken:u,userRefreshToken:h},...i==="device"&&{deviceToken:u,deviceRefreshToken:h}};this.parent.setSession(p)}return{status:d,body:n,headers:r}}async validate(e){const{Code:i,Message:a}=await this.onBeforeRESTCall();return i===H.ON_BEFORE_REST_CALL_ERROR?{status:i,body:{Code:i,Message:a},headers:new Headers}:await _e({...this.getDefaults(J.GET),headers:e==="device"?this.getHeaderWithDeviceToken():this.getHeaderWithUserToken(),urlFragment:"auth/v1/validate"},this.parent.onAfterRESTCall)}}var Ut=Object.defineProperty,qe=t=>{throw TypeError(t)},$t=(t,e,i)=>e in t?Ut(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Pe=(t,e,i)=>$t(t,typeof e!="symbol"?e+"":e,i),Ze=(t,e,i)=>e.has(t)||qe("Cannot "+i),We=(t,e,i)=>(Ze(t,e,"read from private field"),i?i.call(t):e.get(t)),Qe=(t,e,i)=>e.has(t)?qe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),we=(t,e,i,a)=>(Ze(t,e,"write to private field"),e.set(t,i),i),oe,X;class Bt{constructor(e){Qe(this,oe,{http:new URL("https://api.deepaffex.ai")}),Qe(this,X),Pe(this,"onBeforeRESTCall"),Pe(this,"onAfterRESTCall"),Pe(this,"http"),we(this,X,{deviceToken:"",deviceRefreshToken:"",userToken:"",userRefreshToken:"",deviceId:"",roleId:"",userId:"",selectedStudy:"",lastMeasurementId:"",studyCfgHash:"",studyCfgData:""}),this.http={measurements:new Mt(this),studies:new Pt(this),auths:new Wt(this)},this.onBeforeRESTCall=e?.onBeforeRESTCall?e.onBeforeRESTCall:()=>{},this.onAfterRESTCall=e?.onAfterRESTCall?e.onAfterRESTCall:()=>{},e?.url!=null&&we(this,oe,e.url)}static new(e){return new this(e??void 0)}getUrl(){return JSON.stringify(We(this,oe))}setUrl(e){we(this,oe,{http:new URL(e)})}getSession(){return We(this,X)}setSession(e){const i=["deviceToken","deviceRefreshToken","userToken","userRefreshToken","deviceId","userId","roleId","selectedStudy","lastMeasurementId","studyCfgHash","studyCfgData"];Object.keys(e).every(d=>i.includes(d)&&typeof e[d]=="string")&&we(this,X,{...We(this,X),...e})}}oe=new WeakMap,X=new WeakMap;const Gt=t=>Bt.new(t);var Ht=Object.defineProperty,et=t=>{throw TypeError(t)},Vt=(t,e,i)=>e in t?Ht(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Kt=(t,e,i)=>Vt(t,e+"",i),jt=(t,e,i)=>e.has(t)||et("Cannot "+i),Yt=(t,e,i)=>e.has(t)?et("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),Ue=(t,e,i)=>(jt(t,e,"access private method"),i),le,$e,tt;let it=t=>new Int8Array(t);class Jt extends EventTarget{constructor(){super(...arguments),Yt(this,le),Kt(this,"canDecompress",!1)}static init(){return new this}dispatch(e,i){this.dispatchEvent(new CustomEvent(e,{detail:i}))}getBytesDownloadedEvent(e,i,a,c){return new CustomEvent("bytesDownloaded",{detail:{bytes:e,uncompressedSize:i,url:a,done:c}})}getBytesDownloadErrorEvent(e,i){return new CustomEvent("downloadedError",{detail:{url:e,error:i}})}decompressBrotli(e){const i=atob(e),a=new Uint8Array(i.length);for(let n=0;n<i.length;n++)a[n]=i.charCodeAt(n);const c=new Int8Array(a.length);for(let n=0;n<a.length;n++)c[n]=a[n]>=128?a[n]-256:a[n];return it(c).buffer}async fetchAsset(e,i,a,c,d){const n=i+a,r=e.find(h=>h.file===a).uncompressedSize,u=(h,p,S,C)=>Ue(this,le,$e).call(this,this.getBytesDownloadedEvent(h,p,S,C));try{const p=(await fetch(n)).body?.getReader();if(!p)throw new Error("Failed to get reader from response body.");let S=0;const C=new ReadableStream({async start(O){await P();async function P(){const{done:G,value:re}=await p.read();if(G){O.close(),u(S,r,n,!0);return}re&&(O.enqueue(re),S+=re.length,u(S,r,n,!1)),await P()}}}),k=new Response(C);if(c){const O=await k.json(),{base64EncodedValue:P}=O;if(d==="gzip"){await Ue(this,le,tt).call(this,P);return}return this.decompressBrotli(P)}else return await k.arrayBuffer()}catch(h){Ue(this,le,$e).call(this,this.getBytesDownloadErrorEvent(n,h))}}}le=new WeakSet,$e=function(t){this.dispatchEvent(t)},tt=async function(t){const e=Uint8Array.from(atob(t),h=>h.charCodeAt(0)),a=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),c=await new Response(a).arrayBuffer(),d=new TextDecoder().decode(new Uint8Array(c)),n=new Blob([d],{type:"application/javascript"}),r=URL.createObjectURL(n);it=(await import(r)).BrotliDecode,this.canDecompress=!0,URL.revokeObjectURL(r)};var Xt=Object.defineProperty,zt=(t,e,i)=>e in t?Xt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,st=(t,e,i)=>zt(t,typeof e!="symbol"?e+"":e,i);class qt{constructor(){st(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""}),st(this,"debugLogs",[])}appendLog(e){this.debugLogs.push(e)}transferLogs(){}generateHTMLTable(){return`
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8">
@@ -128,7 +128,7 @@ var Nt="0.1.0-beta.3";const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEven
128
128
  <label for="thread-filter">Filter by Thread:</label>
129
129
  <select id="thread-filter">
130
130
  <option value="none">None</option>
131
- ${[...new Set(this.debugLogs.map(r=>r.thread))].map(r=>`<option value="${r}">${r}</option>`).join("")}
131
+ ${[...new Set(this.debugLogs.map(a=>a.thread))].map(a=>`<option value="${a}">${a}</option>`).join("")}
132
132
  </select>
133
133
  <br>
134
134
  <br>
@@ -736,4 +736,4 @@ var Nt="0.1.0-beta.3";const U={RESULTS:"results",ERROR:"error",APPEVENT:"appEven
736
736
  <\/script>
737
737
  </body>
738
738
  </html>
739
- `}openLogInNewWindow(){const e=this.generateHTMLTable(),i=new Blob([e],{type:"text/html"}),r=URL.createObjectURL(i);window.open(r,"_blank")}}var qt=Object.defineProperty,Zt=(t,e,i)=>e in t?qt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,we=(t,e,i)=>Zt(t,typeof e!="symbol"?e+"":e,i);class xe{constructor(e,i){we(this,"workerUrl"),we(this,"worker"),this.worker=e,this.workerUrl=i}static init(e,i,r){const c=new Blob([e],{type:"application/javascript"}),d=URL.createObjectURL(c),n=r||`WORKER${String(new Date().getTime())}`,a=new Worker(new URL(d,import.meta.url),{name:n,type:i});return new xe(a,d)}destroy(){this.worker&&(this.worker.terminate(),URL.revokeObjectURL(this.worker))}}const Qt=(t,e,i,r)=>{const c=t/e,d=i/r;let n=0,a=0;c>d?(n=t,a=t/d):(a=e,n=e*d);const u=(t-n)/2,h=(e-a)/2;return{width:n||0,height:a||0,offsetX:u||0,offsetY:h||0}},ei=(t,e,i,r)=>{const c=(t-i)/2,d=(e-r)/2;return{width:i||0,height:r||0,offsetX:c||0,offsetY:d||0}},ti=(t,e,i,r)=>{const c=t/e,d=i/r;let n=0,a=0;c>d?(a=e,n=e*d):(n=t,a=t/d);const u=(t-n)/2,h=(e-a)/2;return{width:n||0,height:a||0,offsetX:u||0,offsetY:h||0}},ii=(t,e)=>{switch(t){case"none":return ei(...e);case"cover":return Qt(...e);case"contain":default:return ti(...e)}},st=t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(t),si=t=>t===void 0?!0:!(typeof t.mediaPipe<"u"&&typeof t.mediaPipe!="boolean"||typeof t.beforeRESTCall<"u"&&typeof t.beforeRESTCall!="boolean"||typeof t.afterRESTCall<"u"&&typeof t.afterRESTCall!="boolean"||typeof t.extractionLibWasm<"u"&&typeof t.extractionLibWasm!="boolean"||typeof t.apiClient<"u"&&typeof t.apiClient!="boolean"||typeof t.extractionWorker<"u"&&typeof t.extractionWorker!="boolean"||typeof t.faceTrackerWorkers<"u"&&typeof t.faceTrackerWorkers!="boolean"||typeof t.sdk<"u"&&typeof t.sdk!="boolean"),ai=(t,e)=>{const i={...t};if(e.logger)if(si(e.logger))i.logger={...i.logger,...e.logger};else return{results:"invalid"};if(e.apiUrl!==void 0)if(typeof e.apiUrl=="string")i.apiUrl=e.apiUrl;else return{results:"invalid"};if(e.metrics!==void 0)if(typeof e.metrics=="boolean")i.metrics=e.metrics;else return{results:"invalid"};if(e.mirrorVideo!==void 0)if(typeof e.mirrorVideo=="boolean")i.mirrorVideo=e.mirrorVideo;else return{results:"invalid"};if(e.displayMediaStream!==void 0)if(typeof e.displayMediaStream=="boolean")i.displayMediaStream=e.displayMediaStream;else return{results:"invalid"};if(e.assetFolder!==void 0)if(typeof e.assetFolder=="string")i.assetFolder=e.assetFolder;else return{results:"invalid"};if(e.mediaElement!==void 0)if(e.mediaElement instanceof HTMLDivElement)i.mediaElement=e.mediaElement;else return{results:"invalid"};if(e.constraintOverrides!==void 0){let r=function(n,a){if(!(n in d))return!1;const u=d[n];return typeof a===u};const d=Object.fromEntries(Object.entries({backLightMaxPixels_pct:30,backLightSearchMult:1.5,backLightThresh:240,boxCenterX_pct:50,boxCenterY_pct:50,boxHeight_pct:99,boxWidth_pct:50,cameraRot_chunkThresh:.7853981633974483,cameraRot_windowThresh:.2617993877991494,checkBackLight:!1,checkCameraMovement:!1,checkCentered:!1,checkDistance:!1,checkEyebrowMovement:!1,checkFaceDirection:!1,checkLighting:!1,checkMaxDistance:!1,checkMinFps:!1,checkMovement:!1,chunkMovementThresh_pct:60,enableDebugLog:!1,enableFigures:!1,faceRotLR_thresh:.33,faceRotUD_lowerthresh:.25,faceRotUD_upperThresh:5,hy_faceRotLR_thresh:.05,hy_maxFaceRotLR_deg:2,hy_maxFaceRotUD_deg:2,hy_minInterPupilDist_px:5,hy_minimumFps:1,maxEyebrowMovement_mm:3,maxFaceRotLR_deg:12.5,maxFaceRotUD_deg:25,maxMovement_mm:10,minInterPupilDist_px:100,minimumFps:26,movementWindow_ms:2e3,threshBright:225,threshDark:48}).map(([n,a])=>[n,typeof a]));for(const n in e.constraintOverrides){const a=e.constraintOverrides[n];if(!r(n,a))return{results:"invalid"}}i.constraintOverrides=e.constraintOverrides}return{results:"valid",settings:i}},ri=t=>typeof t.age!="number"||t.age<13||t.age>120?(console.error("Invalid age. It should be a number between 13 and 120."),!1):typeof t.height!="number"||t.height<120||t.height>220?(console.error("Invalid height. It should be a number between 120 and 220."),!1):typeof t.weight!="number"||t.weight<30||t.weight>300?(console.error("Invalid weight. It should be a number between 30 and 300."),!1):typeof t.sex!="number"||t.sex<1||t.sex>3?(console.error("Invalid sex. It should be a number between 1 and 3."),!1):typeof t.diabetes!="number"||t.diabetes<4||t.diabetes>6?(console.error("Invalid diabetes. It should be a number between 4 and 6."),!1):typeof t.bloodPressureMedication!="number"||t.bloodPressureMedication!==0&&t.bloodPressureMedication!==1?(console.error("Invalid bloodPressureMedication. It should be either 0 or 1."),!1):typeof t.smoking!="number"||t.smoking!==0&&t.smoking!==1?(console.error("Invalid smoking. It should be either 0 or 1."),!1):!0;var m=(t=>(t.beforeRESTCall="Before REST call event",t.afterRESTCall="After REST call event",t.mediaPipe="MediaPipe",t.extractionLibWasm="DFX Extraction lib WASM",t.apiClient="DFX API client",t.webSocket="WebSocket",t.sdk="SDK",t.dfxWorker="DFX Worker",t))(m||{});const ni=t=>{switch(t){case"Before REST call event":return"red";case"After REST call event":return"orange";case"MediaPipe":return"green";case"DFX Extraction lib WASM":return"violet";case"DFX API client":return"#d34110";case"WebSocket":return"#d34110";case"SDK":return"#d34110";case"DFX Worker":return"#ad4393";default:return"black"}};class at{constructor(e=1e3){we(this,"timestamps",[]),we(this,"windowMs"),this.windowMs=e}tick(e=performance.now()){for(this.timestamps.push(e);this.timestamps.length>0&&e-this.timestamps[0]>this.windowMs;)this.timestamps.shift()}get fps(){const e=this.timestamps.length,i=this.timestamps.at(-1)-this.timestamps[0]||1;return e/i*1e3}get frameCount(){return this.timestamps.length}reset(){this.timestamps=[]}}var oi=Object.defineProperty,li=(t,e,i)=>e in t?oi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rt=(t,e,i)=>li(t,typeof e!="symbol"?e+"":e,i);const ci=()=>{const t=new Date,e=(t.getMonth()+1).toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),r=t.getFullYear();let c=t.getHours();const d=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0"),a=t.getMilliseconds().toString().padStart(3,"0"),u=c>=12?"PM":"AM";return c=c%12||12,`[${e}/${i}/${r}, ${c}:${d}:${n}.${a} ${u}]`};class nt{constructor(){rt(this,"mertics",new zt),rt(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""})}retrieveLogs(){this.mertics.transferLogs(),this.mertics.openLogInNewWindow(),this.mertics.debugLogs=[]}setVersion(e){this.version=e,this.mertics.version=e}log(e,i,r,c=!1,d={}){const n=ci();if(c)this.mertics.appendLog({thread:"Main",timestamp:n,category:i,message:e,meta:d});else{const a=`[${i}]`,u=" ",h=e,E=`color:${r}; font-weight:800;`,_=`color:${ni(i)}; font-weight:700;`;console.log("%c%s%c%s%c%s%c%s",E,n,_,a,"background:inherit;",u,"font-style: italic;",h)}}info(e,i){this.log(e,i,"blue")}warn(e,i){this.log(e,i,"orange")}error(e,i){this.log(e,i,"red")}debug(e,i){this.log(e,i,"green")}start(){console.log("%c%s","color: #5e5e5e; background-color: #2d2d2d; letter-spacing: 0.1em; text-shadow: -1px -1px 1px #111, 2px 2px 1px #363636; font-size: 36px; padding: 20px 40px; text-align: center; text-transform: uppercase; text-rendering: optimizeLegibility;","Anura Web Core SDK"),console.log(`Version: ${this.version.webSDK}`),console.log("https://www.deepaffex.ai")}}const di={SEX_NOT_PROVIDED:1,SEX_ASSIGNED_MALE_AT_BIRTH:2,SEX_ASSIGNED_FEMALE_AT_BIRTH:3,DIABETES_NONE:4,DIABETES_TYPE1:5,DIABETES_TYPE2:6,SMOKER_TRUE:0,SMOKER_FALSE:1,BLOOD_PRESSURE_MEDICATION_TRUE:1,BLOOD_PRESSURE_MEDICATION_FALSE:0},K={SEX_ASSIGNED_AT_BIRTH:1,AGE_YEARS:2,HEIGHT_CM:3,WEIGHT_KG:4,SMOKER:5,BLOOD_PRESSURE_MEDICATION:7,DIABETES:8};var ot=(t=>(t[t.BGR=1]="BGR",t[t.RGB=2]="RGB",t[t.BGRA=3]="BGRA",t[t.RGBA=4]="RGBA",t[t.Infrared=5]="Infrared",t[t.Infrared888=6]="Infrared888",t[t.BGR_Infrared=7]="BGR_Infrared",t[t.RGB_Infrared=8]="RGB_Infrared",t[t.Gray=9]="Gray",t))(ot||{});const j={ASSETS_NOT_DOWNLOADED:"ASSETS_NOT_DOWNLOADED",NOT_LOADED:"NOT_LOADED",LOADING:"LOADING",LOADED:"LOADED",READY:"READY"},Re={COLLECTOR:"COLLECTOR",ASSET_DOWNLOAD:"ASSET_DOWNLOAD",WEB_SOCKET:"WEB_SOCKET"},Ce={CONTAIN:"contain",COVER:"cover",NONE:"none"};var $=(t=>(t.INIT="INIT",t.READY="READY",t.INIT_TFJS="INIT_TFJS",t.SET_PORT="SET_PORT",t.TRACK="TRACK",t.RESULTS_READY="RESULTS_READY",t.WARM_UP="WARM_UP",t.DESTROY="DESTROY",t.LANDMARKS="LANDMARKS",t.VIDEO_FRAME="VIDEO_FRAME",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))($||{}),hi=Object.defineProperty,lt=t=>{throw TypeError(t)},mi=(t,e,i)=>e in t?hi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e,i)=>mi(t,typeof e!="symbol"?e+"":e,i),$e=(t,e,i)=>e.has(t)||lt("Cannot "+i),ct=(t,e,i)=>($e(t,e,"read from private field"),i?i.call(t):e.get(t)),dt=(t,e,i)=>e.has(t)?lt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ui=(t,e,i,r)=>($e(t,e,"write to private field"),e.set(t,i),i),fi=(t,e,i)=>($e(t,e,"access private method"),i),le,Be,ht;const Ei=class yt{constructor(e,i,r){dt(this,Be),dt(this,le),w(this,"mediaElement"),w(this,"numOfFramesPresented",0),w(this,"workers",[]),w(this,"numOftrackedVideoFrames",0),w(this,"warmupFrameNumber",0),w(this,"videoCallbackId",0),w(this,"numOfWorkers",4),w(this,"isLoggingFaceTrackerWorkers",!1),w(this,"isLoggingSdk",!1),w(this,"workerIndex",0),w(this,"metrics",!1),w(this,"videoFpsTracker",new at(1e3)),w(this,"faceTrackerFpsTracker",new at(1e3)),w(this,"videoElementSize",{width:0,height:0,offsetX:0,offsetY:0}),w(this,"videoElement",document.createElement("video")),w(this,"frameWidth",0),w(this,"frameHeight",0),w(this,"mirrorVideo",!0),w(this,"settings",{faceTrackerWidth:0,faceTrackerHeight:0,displayMediaStream:!0,objectFit:Ce.COVER}),w(this,"isExtracting",!1),w(this,"starRating",0),w(this,"scaleFactor",1),w(this,"warmupIndex",0),w(this,"warmingUp",!0),w(this,"ftWorkerIndex",0),w(this,"lastFrameNumber",-1),w(this,"on",{faceTrackersReady:null,frameAvailable:null,landmarksAvailable:null,scaleFactorChanged:null});const{mediaElement:c,mirrorVideo:d,numOfWorkers:n,isLoggingFaceTrackerWorkers:a,isLoggingSdk:u,metrics:h,displayMediaStream:E}=i;this.numOfWorkers=n,this.isLoggingFaceTrackerWorkers=a,this.isLoggingSdk=u,this.metrics=h,ui(this,le,r),this.settings.displayMediaStream=E,this.mirrorVideo=d,this.mediaElement=c,this.videoFrameCallback=this.videoFrameCallback.bind(this),this.workers=e,this.scaleFactor=i.scaleFactor,this.initWorkerOnMessage(i.models),this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.preload="auto"}static async init(e,i){const{numOfWorkers:r,faceTrackerCode:c}=e,d=[],n=new TextDecoder().decode(new Uint8Array(c));if(r>0)for(let a=1;a<=r;a+=1){const u=xe.init(n,"module",`FACE_TRACKER_WORKER_${a-1}`);d.push({ft:u,channel:new MessageChannel,isBusy:!1})}return new yt(d,e,i)}initWorkerOnMessage(e){const i=window.matchMedia("(orientation: portrait)").matches,r=i?360:640,c=i?640:360;this.workers.forEach(d=>{d.ft.worker.postMessage({action:$.INIT_TFJS,payload:{width:r,height:c,models:e,scaleFactor:this.scaleFactor}}),d.ft.worker.postMessage({action:$.SET_PORT,payload:{port:d.channel.port2}},[d.channel.port2]),d.ft.worker.onmessage=n=>{const{action:a,payload:u}=n.data;switch(a){case $.INIT_TFJS:break;case $.READY:{const{workerName:h,version:E,workerId:_,backend:C}=u;this.on.faceTrackersReady&&this.on.faceTrackersReady(h,E,_,C);break}case $.LANDMARKS:{this.faceTrackerFpsTracker.tick(),d.isBusy=!1,this.warmingUp&&this.warmupIndex++;const{face:h,annotations:E,frameTimestamp:_}=u;this.on.landmarksAvailable&&this.on.landmarksAvailable(h,E,_);break}case $.DESTROY:{const{workerId:h}=u;this.workers[h].ft.destroy();break}}}})}getMediaElement(){return this.mediaElement}setIsExtracting(e){this.isExtracting=e}destroyWorkers(){setTimeout(async()=>{this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.workers.forEach(e=>e.ft.worker.postMessage({action:$.DESTROY}))},200)}createMediaElements(){this.videoElement.addEventListener("ended",async()=>{this.destroyWorkers()});const e=document.createElement("div"),i=this.settings.displayMediaStream?this.videoElement:e,r="white";this.mediaElement.appendChild(i),i.style.width="100%",i.style.height="100%",i.style.boxSizing="border-box",this.settings.displayMediaStream&&(i.style.border=`1px solid ${r}`),i.style.objectFit=this.settings.objectFit,i.style.transform=`scale(${this.mirrorVideo?"-1":"1"},1)`,this.settings.displayMediaStream||(i.style.height=`${this.frameHeight}px`,i.style.width=`${this.frameWidth}px`),new ResizeObserver(d=>{const{contentRect:n,target:a}=d[0],{width:u,height:h}=n,{x:E,y:_}=a.getBoundingClientRect(),{faceTrackerWidth:C,faceTrackerHeight:k}=this.settings;this.videoElementSize=ii(this.settings.objectFit,[u,h,this.frameWidth,this.frameHeight]);const{width:I,height:W}=this.videoElementSize;if(!this.settings.displayMediaStream){const G=this.settings.objectFit===Ce.NONE;i.style.height=`${Math.trunc(G?W:h)}px`,i.style.width=`${Math.trunc(G?I:u)}px`}this.mediaElement.dispatchEvent(new CustomEvent("mediaElementSizeChanged",{detail:{mediaElementSize:{width:u,height:h,x:E,y:_},videoElementSize:this.videoElementSize,frameInfo:{mediaStreamWidth:this.frameWidth,mediaStreamHeight:this.frameHeight,faceTrackerWidth:C,faceTrackerHeight:k},isPortrait:h>u,aspectRatio:u/h}}))}).observe(this.mediaElement)}log(e,i,r){this.isLoggingSdk&&ct(this,le).info(e,i),this.metrics&&ct(this,le).log(e,i,"",!0,r)}videoFrameCallback(e,i){const{presentedFrames:r,captureTime:c,expectedDisplayTime:d,mediaTime:n}=i;this.videoFpsTracker.tick();const a=c===void 0?d:c;this.numOfFramesPresented=r;const u=`Number of frames presented: ${this.numOfFramesPresented} - time: ${a}`;let h=0;if(n&&n>0?h=n*1e3:c&&c>0?h=c>1e6?c-performance.timeOrigin:c:h=e,this.log(u,m.sdk,{captureTime:a,presentedFrames:r}),this.warmingUp)if(this.warmupIndex>=this.numOfWorkers)this.warmingUp=!1;else{const E=this.workers[this.warmupIndex];if(!E.isBusy){E.isBusy=!0;const _=new VideoFrame(this.videoElement,{timestamp:h});E.ft.worker.postMessage({action:"TRACK",payload:{frame:_,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[_])}}if(!this.warmingUp){const E=new VideoFrame(this.videoElement,{timestamp:h});let _=!1;for(let C=0;C<this.numOfWorkers;C++){this.ftWorkerIndex=(this.ftWorkerIndex+1)%this.numOfWorkers;const k=this.workers[this.ftWorkerIndex];if(k&&!k.isBusy){k.isBusy=!0,this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!0),k.ft.worker.postMessage({action:"TRACK",payload:{frame:E,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[E]),_=!0;break}}_||this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!1,E)}this.lastFrameNumber=this.numOfFramesPresented,this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback)}setFaceTrackerMediaStreamResolution(e,i){(e<=360||i<=360)&&(this.scaleFactor=1),this.settings.faceTrackerWidth=e*this.scaleFactor,this.settings.faceTrackerHeight=i*this.scaleFactor,this.workers.forEach(r=>r.ft.worker.postMessage({action:$.SCALE_FACTOR_CHANGED,payload:{scaleFactor:this.scaleFactor}})),this.on.scaleFactorChanged&&this.on.scaleFactorChanged(this.scaleFactor)}async setMediaStream(e){if(e instanceof MediaStream)try{const{settings:i,constraints:r}=await fi(this,Be,ht).call(this,e,this.videoElement);await this.videoElement.play(),this.settings.displayMediaStream||(this.videoElement.style.visibility="none");const{width:c,height:d}=i;return this.setFaceTrackerMediaStreamResolution(c??0,d??0),this.frameWidth=c||1,this.frameHeight=d||1,this.log(`Face tracker resolution: ${c} x ${d} pixels. Video resolution: ${this.frameWidth} x ${this.frameHeight} pixels`,m.sdk,{ftWidth:c,ftHeight:d,frameWidth:this.frameWidth,frameHeight:this.frameHeight}),this.createMediaElements(),this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback),!0}catch(i){return console.log("Error applying face tracker video track constraints",i),!1}return!1}stopTracking(){this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.videoElement.pause(),this.videoElement.srcObject=null}};le=new WeakMap,Be=new WeakSet,ht=async function(t,e){e.srcObject=t,await new Promise(r=>e.onloadedmetadata=r);const[i]=t.getVideoTracks();return{constraints:i.getConstraints(),settings:i.getSettings()}};let pi=Ei;var T=(t=>(t.INIT="INIT",t.READY="READY",t.SET_MODE="SET_MODE",t.SET_NUMBER_OF_CHUNKS="SET_NUMBER_OF_CHUNKS",t.SET_TARGET_FPS="SET_TARGET_FPS",t.SET_CHUNK_DURATION_SECONDS="SET_CHUNK_DURATION_SECONDS",t.SET_FRAME_ORDER="SET_FRAME_ORDER",t.GET_CONSTRAINTS_CONFIG="GET_CONSTRAINTS_CONFIG",t.SET_CONSTRAINTS_CONFIG="SET_CONSTRAINTS_CONFIG",t.SET_FACE_ATTRIBUTE="SET_FACE_ATTRIBUTE",t.RESET_COLLECTION="RESET_COLLECTION",t.CANCEL_COLLECTION="CANCEL_COLLECTION",t.START_COLLECTION="START_COLLECTION",t.SET_PORTS="SET_PORTS",t.COLLECTOR_ERROR="COLLECTOR_ERROR",t.STAR_RATING="STAR_RATING",t.ALL_FACE_TRACKERS_WARMED_UP="ALL_FACE_TRACKERS_WARMED_UP",t.CONSTRAINTS_UPDATED="CONSTRAINTS_UPDATED",t.SHOULD_END_MEASUREMENT_EARLY="SHOULD_END_MEASUREMENT_EARLY",t.GET_LOGS="GET_LOGS",t.NEW_FRAME="NEW_FRAME",t.TRACKING_STATUS="TRACKING_STATUS",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))(T||{}),y=(t=>(t.CONNECT="CONNECT",t.DISCONNECT="DISCONNECT",t.DISCONNECTED="DISCONNECTED",t.LOGIN_WITH_TOKEN_SUCCESS="LOGIN_WITH_TOKEN_SUCCESS",t.SUBSCRIBED_TO_RESULTS="SUBSCRIBED_TO_RESULTS",t.CHUNK_SENT="CHUNK_SENT",t.RESULTS_RECEIVED="RESULTS_RECEIVED",t.CHUNK_ACKNOWLEDGED="CHUNK_ACKNOWLEDGED",t.ERROR="ERROR",t.NETWORK_DELAY="NETWORK_DELAY",t))(y||{}),Ti=Object.defineProperty,mt=t=>{throw TypeError(t)},Si=(t,e,i)=>e in t?Ti(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ut=(t,e,i)=>Si(t,typeof e!="symbol"?e+"":e,i),Ge=(t,e,i)=>e.has(t)||mt("Cannot "+i),s=(t,e,i)=>(Ge(t,e,"read from private field"),i?i.call(t):e.get(t)),S=(t,e,i)=>e.has(t)?mt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,r)=>(Ge(t,e,"write to private field"),e.set(t,i),i),l=(t,e,i)=>(Ge(t,e,"access private method"),i),bi=(t,e,i,r)=>({set _(c){f(t,e,c)},get _(){return s(t,e,r)}}),x,g,P,v,L,ke,ve,Ae,ye,ce,z,Oe,de,he,b,q,D,me,F,Ne,Z,Q,ee,te,ue,fe,Y,Ee,Le,ie,De,se,pe,A,Te,B,Se,o,ft,Et,pt,He,Ve,Tt,St,bt,_t,gt,wt,Ie,Ke,p,Rt,Ct,kt,vt,ae,R;const At=Symbol("instance_creation_key"),_i=class Ot{constructor(e){if(S(this,o),S(this,x),S(this,g,{mediaElement:document.createElement("div"),assetFolder:"",apiUrl:"",metrics:!1,logger:{sdk:!1,mediaPipe:!1,beforeRESTCall:!1,afterRESTCall:!1,extractionLibWasm:!1,apiClient:!1,extractionWorker:!1,faceTrackerWorkers:!1},mirrorVideo:!0,displayMediaStream:!0,constraintOverrides:{}}),S(this,P,[{file:"decompress.json",uncompressedSize:89469},{file:"extraction_worker_0.1.0-beta.2_js.json",uncompressedSize:59696},{file:"facetracker_worker_0.1.0-beta.2_js.json",uncompressedSize:306553},{file:"extraction_wasm_0.1.0-beta.2.json",uncompressedSize:1926126},{file:"detectorModel_json.json",uncompressedSize:4640},{file:"detectorModel_bin.json",uncompressedSize:242046},{file:"landmarkModel_json.json",uncompressedSize:5036},{file:"landmarkModel_bin.json",uncompressedSize:1704814}]),S(this,v,new nt),S(this,L,Yt.init()),S(this,ke),S(this,ve),S(this,Ae),S(this,ye),S(this,ce),S(this,z),S(this,Oe),S(this,de,{version:"",sdkId:""}),S(this,he,""),S(this,b),S(this,q,0),S(this,D),S(this,me,j.ASSETS_NOT_DOWNLOADED),S(this,F,""),S(this,Ne,""),S(this,Z,!1),S(this,Q,5),S(this,ee,30),S(this,te,5),S(this,ue,!1),S(this,fe,4),S(this,Y),S(this,Ee),S(this,Le),S(this,ie,1e7),S(this,De,0),S(this,se,new Map),S(this,pe,Promise.resolve()),S(this,A,0),S(this,Te,-1),S(this,B,-1),S(this,Se,.5),ut(this,"on",{beforeRESTCall:null,afterRESTCall:null,bytesDownloaded:null,faceTrackerStateChanged:null,resultsReceived:null,constraintsUpdated:null,mediaElementResize:null,facialLandmarksUpdated:null,chunkSent:null,error:null}),e!==At)throw new Error("Use await Measurement.init() to create an instance of Measurement class.")}static async init(e){if(!e)throw new Error("Missing `settings` object");const i=new Ot(At);if(!i.setSettings(e))throw new Error("Invalid settings object");f(i,x,Bt({url:{http:new URL("https://api.deepaffex.ai")},onBeforeRESTCall:()=>{var n,a;l(n=i,o,St).call(n),l(a=i,o,bt).call(a)},onAfterRESTCall:(n,a)=>{var u,h;l(u=i,o,_t).call(u,n,a),l(h=i,o,gt).call(h,n,a)}}));const c=n=>{var a;const{bytes:u,url:h,uncompressedSize:E,done:_}=n.detail;l(a=i,o,p).call(a,`bytesDownloaded event, ${u}, ${E}, ${h}, ${_}`,m.mediaPipe),i.on.bytesDownloaded&&i.on.bytesDownloaded(u,E,h,_)},d=n=>{var a;const{error:u,url:h}=n.detail;l(a=i,o,p).call(a,`downloadError event, ${h}, ${u}`,m.mediaPipe),i.on.error&&i.on.error(Re.ASSET_DOWNLOAD,{url:h,error:u})};return s(i,L).addEventListener("downloadedError",d),s(i,L).addEventListener("bytesDownloaded",c),s(i,v).setVersion(i.getVersion()),s(i,g).logger&&Object.values(s(i,g).logger).some(n=>n===!0)&&s(i,v).start(),setTimeout(()=>{var n;l(n=i,o,ae).call(n,j.ASSETS_NOT_DOWNLOADED)},500),new Proxy(i,{get(n,a,u){const h=a;return typeof n[h]=="function"?n[h].bind(n):Reflect.get(n,h,u)},set(n,a,u){return console.log(`Setting property "${String(a)}" to "${u}" is not allowed`),!0}})}loadMask(e){if(s(this,b)){let i=!1;const r=s(this,b).mediaElement.querySelector("svg");r&&(i=!0,s(this,b).mediaElement.removeChild(r)),s(this,b).mediaElement.appendChild(e),i&&(s(this,b).mediaElement.style.setProperty("border","1px solid transparent"),setTimeout(()=>{s(this,b).mediaElement.removeAttribute("style")},100))}}setSettings(e){const i=ai(s(this,g),e);return i.results==="valid"?(f(this,g,i.settings),!0):!1}getVersion(){return{webSDK:Je,extractionLib:s(this,de),faceTracker:s(this,he)}}async downloadAssets(){const{assetFolder:e}=s(this,g);try{if(l(this,o,p).call(this,`Asset base URL ${e}`,m.sdk),l(this,o,p).call(this,"Start downloading decompressor...",m.sdk),await s(this,L).fetchAsset(s(this,P),`${e}/`,"decompress.json",!0,"gzip"),s(this,L).canDecompress){await l(this,o,Et).call(this,e),s(this,z)&&await l(this,o,Ve).call(this),l(this,o,p).call(this,"Start downloading TFJS worker...",m.mediaPipe);const i=await s(this,L).fetchAsset(s(this,P),`${e}/`,`facetracker_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli");return i&&(f(this,Oe,i),await l(this,o,ft).call(this,e),await l(this,o,He).call(this)),l(this,o,pt).call(this),!0}}catch{return l(this,o,p).call(this,"Failed to download TFJS face tracker or DFX extraction worker WASM assets",m.mediaPipe),!1}}setExtractionLibSettings(e=6,i=30,r=5){f(this,Q,e-1),f(this,ee,i),f(this,te,r)}async setNextChunkAsFinal(){f(this,ue,!0),await l(this,o,R).call(this,T.SHOULD_END_MEASUREMENT_EARLY,{},!0),l(this,o,p).call(this,"Set the action for the next chunk to LAST::PROCESS",m.extractionLibWasm)}async startTracking(){s(this,b)&&(s(this,b).isExtracting||(s(this,b).setIsExtracting(!0),l(this,o,p).call(this,"Start tracking frames",m.mediaPipe),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,Ie).call(this)))}async stopTracking(){if(s(this,b)){s(this,b).stopTracking(),await l(this,o,wt).call(this),s(this,b).setIsExtracting(!1),l(this,o,p).call(this,"Stop extracting frames",m.mediaPipe);const{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:r}=s(this,b);l(this,o,p).call(this,"Tracking metrics",m.sdk,{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:r}),f(this,F,"")}}async disconnect(){s(this,Z)&&await l(this,o,R).call(this,y.DISCONNECT,{},!0),s(this,g).metrics&&(await l(this,o,R).call(this,T.GET_LOGS,{},!0),s(this,v).retrieveLogs())}async destroy(){s(this,D)&&(s(this,D).destroy(),l(this,o,p).call(this,"Destroyed",m.extractionLibWasm)),s(this,b)&&(s(this,b).destroyWorkers(),l(this,o,p).call(this,"Destroyed",m.mediaPipe))}async reset(){return s(this,me)===j.READY?(await this.stopTracking(),await this.destroy(),f(this,v,new nt),f(this,de,{version:"",sdkId:""}),f(this,he,""),f(this,q,0),f(this,F,""),f(this,Z,!1),f(this,Q,5),f(this,ee,30),f(this,te,5),f(this,ue,!1),f(this,Y,void 0),f(this,ie,1e7),f(this,De,0),f(this,se,new Map),f(this,pe,Promise.resolve()),f(this,A,0),f(this,Te,-1),f(this,B,-1),s(this,g).mediaElement.innerHTML="",await l(this,o,Ve).call(this),await l(this,o,He).call(this),!0):!1}async setMediaStream(e){if(s(this,b)&&!s(this,b).isExtracting&&s(this,D)){await s(this,b).setMediaStream(e);const i=Object.fromEntries(s(this,b).workers.map((r,c)=>[`port${c+1}`,r.channel.port1]));s(this,D).worker.postMessage({action:T.SET_PORTS,payload:{numOfWorkers:s(this,fe),workerPorts:i}},[...s(this,b).workers.map(r=>r.channel.port1)])}}async prepare(e,i,r,c){s(this,x).setSession({userToken:e,userRefreshToken:i});const{region:d,status:n}=await l(this,o,Rt).call(this,"user");let a=`api.${d}.deepaffex.ai`;s(this,g).apiUrl?a=s(this,g).apiUrl:s(this,g).apiUrl=a,s(this,x).setUrl(`https://${a}`);const u=await l(this,o,Ct).call(this,e,i,"user"),h=await l(this,o,kt).call(this,r,c);return u&&h&&n==="200"}async setConstraintsConfig(e){await l(this,o,R).call(this,T.SET_CONSTRAINTS_CONFIG,{...s(this,Le),...e&&{...s(this,g).constraintOverrides}},!0)}async startMeasurement(e=!1,i={}){if(f(this,ue,!1),f(this,F,""),await l(this,o,vt).call(this,i),s(this,D)&&s(this,F)!==""){await l(this,o,Ke).call(this),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,Q)+1},!0),await this.setConstraintsConfig(e),await l(this,o,Tt).call(this),await l(this,o,Ie).call(this);const{userToken:r}=s(this,x).getSession();r?await l(this,o,R).call(this,y.CONNECT,{token:r,measurementId:s(this,F)},!0):l(this,o,p).call(this,"User token is missing. Unable to connect.",m.webSocket)}}setDemographics(e){ri(e)?(f(this,Y,e),l(this,o,p).call(this,`Demographics updated ${JSON.stringify(e)}`,m.extractionLibWasm)):l(this,o,p).call(this,`Error updating Demographics ${JSON.stringify(e)}`,m.extractionLibWasm)}setObjectFit(e){return s(this,b)&&Ce!==void 0&&Object.values(Ce).includes(e)?(s(this,b).settings.objectFit=e,!0):!1}};x=new WeakMap,g=new WeakMap,P=new WeakMap,v=new WeakMap,L=new WeakMap,ke=new WeakMap,ve=new WeakMap,Ae=new WeakMap,ye=new WeakMap,ce=new WeakMap,z=new WeakMap,Oe=new WeakMap,de=new WeakMap,he=new WeakMap,b=new WeakMap,q=new WeakMap,D=new WeakMap,me=new WeakMap,F=new WeakMap,Ne=new WeakMap,Z=new WeakMap,Q=new WeakMap,ee=new WeakMap,te=new WeakMap,ue=new WeakMap,fe=new WeakMap,Y=new WeakMap,Ee=new WeakMap,Le=new WeakMap,ie=new WeakMap,De=new WeakMap,se=new WeakMap,pe=new WeakMap,A=new WeakMap,Te=new WeakMap,B=new WeakMap,Se=new WeakMap,o=new WeakSet,ft=async function(t){l(this,o,p).call(this,"Start downloading TFJS face tracker assets...",m.mediaPipe);const e=`${t}/models/`,[i,r,c,d]=await Promise.all([s(this,L).fetchAsset(s(this,P),e,"detectorModel_json.json",!0,"brotli"),s(this,L).fetchAsset(s(this,P),e,"detectorModel_bin.json",!0,"brotli"),s(this,L).fetchAsset(s(this,P),e,"landmarkModel_json.json",!0,"brotli"),s(this,L).fetchAsset(s(this,P),e,"landmarkModel_bin.json",!0,"brotli")]);l(this,o,p).call(this,"TFJS face tracker assets successfully downloaded",m.mediaPipe),f(this,ke,i),f(this,ve,r),f(this,Ae,c),f(this,ye,d)},Et=async function(t){l(this,o,p).call(this,"Start downloading DFX extraction worker assets...",m.extractionLibWasm);const[e,i]=await Promise.all([s(this,L).fetchAsset(s(this,P),`${t}/extraction/`,`extraction_wasm_${this.getVersion().webSDK}.json`,!0,"brotli"),s(this,L).fetchAsset(s(this,P),`${t}/`,`extraction_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);l(this,o,p).call(this,"DFX extraction worker assets successfully downloaded",m.extractionLibWasm),f(this,ce,e),f(this,z,i)},pt=function(){if(s(this,b)){const t=e=>{this.on.mediaElementResize&&this.on.mediaElementResize(e)};s(this,g).mediaElement.addEventListener("mediaElementSizeChanged",t)}},He=async function(){s(this,g),l(this,o,ae).call(this,j.NOT_LOADED);const t={faceTrackerCode:s(this,Oe),numOfWorkers:s(this,fe),mediaElement:s(this,g).mediaElement,mirrorVideo:s(this,g).mirrorVideo,metrics:s(this,g).metrics,displayMediaStream:s(this,g).displayMediaStream,isLoggingFaceTrackerWorkers:s(this,g).logger?.faceTrackerWorkers??!1,isLoggingSdk:s(this,g).logger?.sdk??!1,scaleFactor:s(this,Se),models:{detectorJson:s(this,ke),detectorBin:s(this,ve),landmarkJson:s(this,Ae),landmarkBin:s(this,ye)}};l(this,o,ae).call(this,j.LOADING),f(this,b,await pi.init(t,s(this,v))),s(this,b).on.faceTrackersReady=(e,i,r,c)=>{l(this,o,p).call(this,`TFJS face tracker version ${i} loaded. Worker name: ${e} - workerId: ${r} - backend: ${c}`,m.mediaPipe),f(this,he,`${i}-${c}`),f(this,q,s(this,q)+1),s(this,v).setVersion(this.getVersion()),s(this,q)===s(this,fe)&&l(this,o,ae).call(this,j.LOADED)},s(this,b).on.frameAvailable=(e,i,r,c,d)=>{!c&&d?s(this,D).worker.postMessage({action:T.NEW_FRAME,payload:{frameNumber:i,frameTimestamp:e,frame:d,lastFrameNumber:r,tracked:c}},[d]):s(this,D).worker.postMessage({action:T.TRACKING_STATUS,payload:{frameNumber:i,frameTimestamp:e,lastFrameNumber:r,tracked:c}})},s(this,b).on.landmarksAvailable=(e,i,r)=>{const c=r/1e3;s(this,B)===0&&f(this,B,c),f(this,Te,c),s(this,b).numOftrackedVideoFrames+=1;const{starRating:d}=s(this,b),n=30,a=Math.min(s(this,Te)-s(this,B),n),u=s(this,B)>0?a/n*100:0,h={video:s(this,b).videoFpsTracker.fps.toFixed(1),faceTracker:s(this,b).faceTrackerFpsTracker.fps.toFixed(1)},E={face:e,annotations:i,starRating:d,percentCompleted:u,fps:h};this.on.facialLandmarksUpdated&&this.on.facialLandmarksUpdated(E)},s(this,b).on.scaleFactorChanged=e=>{f(this,Se,e),s(this,b).scaleFactor=e,s(this,D).worker.postMessage({action:T.SCALE_FACTOR_CHANGED,payload:{scaleFactor:e}})}},Ve=async function(){const t=new TextDecoder().decode(new Uint8Array(s(this,z)));f(this,D,xe.init(t,"module","EXTRACTION_WORKER"));const{studyCfgData:e}=s(this,x).getSession();e&&s(this,ce)&&s(this,z)&&(s(this,D).worker.onmessage=async i=>{const{data:r}=i,{id:c,result:d}=r,{action:n,payload:a}=d,u=s(this,se).get(c);if(u||c===-1){switch(n){case T.READY:{const{sdkId:h,version:E,workerName:_}=a;f(this,de,{version:E,sdkId:h}),l(this,o,p).call(this,`DFX extraction worker WASM loaded. SDK ID: ${h} - Version: ${E} - Worker Name: ${_}`,m.extractionLibWasm),await l(this,o,R).call(this,T.SET_MODE,{value:"discrete"},!0),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,R).call(this,T.SET_TARGET_FPS,{value:s(this,ee)},!0),await l(this,o,R).call(this,T.SET_CHUNK_DURATION_SECONDS,{value:s(this,te)},!0),await l(this,o,R).call(this,T.SET_FRAME_ORDER,{value:ot.RGBA},!0),await l(this,o,R).call(this,T.GET_CONSTRAINTS_CONFIG,{},!0),f(this,Le,s(this,Ee));break}case T.SET_MODE:{a&&l(this,o,p).call(this,`Set mode to ${a.mode}`,m.extractionLibWasm);break}case T.SET_NUMBER_OF_CHUNKS:{a&&l(this,o,p).call(this,`Set number of chunks to ${d.number}`,m.extractionLibWasm);break}case T.SET_TARGET_FPS:{a&&l(this,o,p).call(this,`Set target FPS to ${s(this,ee)}`,m.extractionLibWasm);break}case T.SET_CHUNK_DURATION_SECONDS:{a&&l(this,o,p).call(this,`Set chunk duration to ${s(this,te)} Seconds`,m.extractionLibWasm);break}case T.SET_FRAME_ORDER:{a&&l(this,o,p).call(this,"Set channel order RGBA",m.extractionLibWasm);break}case T.GET_CONSTRAINTS_CONFIG:{a&&(f(this,Ee,a),l(this,o,p).call(this,`Get constraints ${JSON.stringify(a)}`,m.extractionLibWasm));break}case T.SET_CONSTRAINTS_CONFIG:{a&&(f(this,Ee,a),l(this,o,p).call(this,`Set constraints ${JSON.stringify(a)}`,m.extractionLibWasm));break}case T.SET_FACE_ATTRIBUTE:{const{success:h,faceId:E,attribute:_,value:C}=a;h&&l(this,o,p).call(this,`Set face attribute: faceId: ${E}, attribute: ${_}, value: ${C}`,m.extractionLibWasm);break}case T.RESET_COLLECTION:{a&&l(this,o,p).call(this,"Reset collection",m.extractionLibWasm);break}case T.CANCEL_COLLECTION:{a&&l(this,o,p).call(this,"Collecttion cancelled",m.extractionLibWasm);break}case T.START_COLLECTION:{a&&l(this,o,p).call(this,`Collector started - state: ${a}`,m.extractionLibWasm);break}case T.SET_PORTS:{a&&l(this,o,p).call(this,"Ports set",m.extractionLibWasm);break}case T.COLLECTOR_ERROR:{if(a){const{error:h,frameNumber:E}=a;l(this,o,p).call(this,`Collector error on frame ${E}: ${h}`,m.extractionLibWasm),this.on.error&&this.on.error(Re.COLLECTOR,a),await this.stopTracking()}break}case T.STAR_RATING:{s(this,b).starRating=a.rating;break}case T.ALL_FACE_TRACKERS_WARMED_UP:{const{frameNumber:h}=d;s(this,b).warmupFrameNumber=h,l(this,o,p).call(this,"All face tracker workers are warmed up.",m.mediaPipe),l(this,o,ae).call(this,j.READY);break}case T.CONSTRAINTS_UPDATED:{const{feedback:h,status:E}=a;this.on.constraintsUpdated&&this.on.constraintsUpdated(h,E);break}case T.SHOULD_END_MEASUREMENT_EARLY:{const{currentFinalChunkNumber:h,currentResultsOrder:E,newFinalChunkNumber:_}=d;l(this,o,p).call(this,`Request the end measurement early. Current final chunk number: ${h}, Current results order: ${E}, New final chunk number: ${_}`,m.extractionLibWasm);break}case T.GET_LOGS:{console.log(`DFX Log: ${a}`);break}case y.CONNECT:{f(this,Z,!0),f(this,B,0),l(this,o,p).call(this,a?"Connected":"Connection error",m.webSocket);break}case y.LOGIN_WITH_TOKEN_SUCCESS:{l(this,o,p).call(this,"Successfully logged in with token",m.webSocket);break}case y.SUBSCRIBED_TO_RESULTS:{l(this,o,p).call(this,"Subscribed to the results",m.webSocket);break}case y.CHUNK_SENT:{l(this,o,p).call(this,`Chunk sent ${JSON.stringify(a)}`,m.webSocket),this.on.chunkSent&&this.on.chunkSent(a);break}case y.DISCONNECT:{f(this,Z,!1),l(this,o,p).call(this,"Disconnect",m.webSocket);break}case y.DISCONNECTED:{l(this,o,p).call(this,`Disconnected! - code: ${a.code}, reason: ${a.reason}, wasClean: ${a.wasClean}`,m.webSocket),this.on.error&&this.on.error(Re.WEB_SOCKET,a);break}case y.CHUNK_ACKNOWLEDGED:{l(this,o,p).call(this,`Chunk number ${a.chunkOrder} received by the server!`,m.webSocket),s(this,Q)===a.chunkOrder&&await this.stopTracking();break}case y.RESULTS_RECEIVED:{const{resultsOrder:h,finalChunkNumber:E}=a;this.on.resultsReceived&&this.on.resultsReceived(a),l(this,o,p).call(this,`Results received: ${JSON.stringify(a)}`,m.webSocket),h===E&&(await l(this,o,R).call(this,y.DISCONNECT,{},!0),await l(this,o,Ke).call(this),await l(this,o,Ie).call(this));break}case y.NETWORK_DELAY:{const{delay:h,description:E,actionId:_}=a;l(this,o,p).call(this,`Round-trip delay for ${E} call with Action ID ${_} was ${h.toFixed(2)} ms`,m.webSocket,{delay:h,actionId:_,description:E});break}case y.ERROR:{l(this,o,p).call(this,"Error",m.webSocket),this.on.error&&this.on.error(Re.WEB_SOCKET,a);break}}u&&(u.resolve(d),s(this,se).delete(c))}},await l(this,o,R).call(this,T.INIT,{wasm:s(this,ce),studyConfigData:e,isLogging:s(this,g).logger?.extractionWorker||!1,metrics:s(this,g).metrics||!1,apiUrl:s(this,g).apiUrl,scaleFactor:s(this,Se)},!0))},Tt=async function(){if(s(this,b)&&s(this,Y)){const{age:e,height:i,weight:r,sex:c,smoking:d,bloodPressureMedication:n,diabetes:a}=s(this,Y);await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.SEX_ASSIGNED_AT_BIRTH,value:c},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.AGE_YEARS,value:e},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.HEIGHT_CM,value:i},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.WEIGHT_KG,value:r},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.SMOKER,value:d},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.BLOOD_PRESSURE_MEDICATION,value:n},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:K.DIABETES,value:a},!0),l(this,o,p).call(this,`Set demographics for Face ID 1, ${JSON.stringify(s(this,Y))}`,m.extractionLibWasm)}},St=function(){},bt=function(){const t=new Date().toISOString();st(t)&&(l(this,o,p).call(this,`Action ID: ${s(this,A)}`,m.beforeRESTCall),this.on.beforeRESTCall&&this.on.beforeRESTCall(t,s(this,A)))},_t=function(t,e){},gt=function(t,e){const i=new Date().toISOString();st(i)&&(l(this,o,p).call(this,`Action ID: ${s(this,A)}, HTTP status code: ${t}, error: ${JSON.stringify(e)}`,m.afterRESTCall),this.on.afterRESTCall&&this.on.afterRESTCall(i,s(this,A),t,e))},wt=async function(){await l(this,o,R).call(this,T.CANCEL_COLLECTION,{},!0)},Ie=async function(){await l(this,o,R).call(this,T.START_COLLECTION,{},!0)},Ke=async function(){await l(this,o,R).call(this,T.RESET_COLLECTION,{},!0),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0)},p=function(t,e,i){s(this,g).metrics&&s(this,v).log(t,e,"",!0,i),s(this,g).logger?.mediaPipe&&e===m.mediaPipe&&s(this,v).info(t,e),s(this,g).logger?.beforeRESTCall&&e===m.beforeRESTCall&&s(this,v).info(t,e),s(this,g).logger?.afterRESTCall&&e===m.afterRESTCall&&s(this,v).info(t,e),s(this,g).logger?.extractionLibWasm&&e===m.extractionLibWasm&&s(this,v).info(t,e),s(this,g).logger?.apiClient&&e===m.apiClient&&s(this,v).info(t,e),s(this,g).logger?.webSocket&&e===m.webSocket&&s(this,v).info(t,e),s(this,g).logger?.sdk&&e===m.sdk&&s(this,v).info(t,e)},Rt=async function(t){f(this,A,0);const e=performance.now(),i=await s(this,x).http.auths.validate(t),r=performance.now()-e,{status:c,body:d}=i;if(l(this,o,p).call(this,c==="200"?"Successfully validated the Token":`Failed to validate token. Status: ${c}`,m.apiClient,{delay:r,actionId:s(this,A),description:"Validate Token"}),c==="200"){const{Region:n}=d;return{region:n,status:c}}else return{status:c,region:""}},Ct=async function(t,e,i){f(this,A,2304);const r=performance.now(),c=await s(this,x).http.auths.renew({Token:t,RefreshToken:e},i),d=performance.now()-r,{status:n}=c;return l(this,o,p).call(this,n==="200"?"Successfully refreshed the Token":`Failed to refresh token. Status: ${n}`,m.apiClient,{delay:d,actionId:s(this,A),description:"Refresh Token"}),n==="200"},kt=async function(t,e){f(this,A,806);const i=performance.now();f(this,Ne,t);const r=await s(this,x).http.studies.retrieveSdkConfigData({StudyID:t,...e&&{sdkId:e}},"user"),c=performance.now()-i,{status:d}=r;return l(this,o,p).call(this,d==="200"?"Retrieve SDK Config Data - success":"Retrieve SDK Config Data - failure",m.apiClient,{delay:c,actionId:s(this,A),description:"Retrieve SDK Config Data"}),d==="200"},vt=async function(t){l(this,o,p).call(this,"Get Measurement ID",m.apiClient),f(this,A,504);const e=performance.now(),i={StudyID:s(this,Ne),Resolution:100};t.partnerId&&(i.PartnerID=t.partnerId),t.userProfileId&&(i.UserProfileID=t.userProfileId);const r=await s(this,x).http.measurements.create(i,"user"),c=performance.now()-e,{status:d,body:n}=r;let a="";d==="200"?(f(this,F,n.ID),a=`Successfully obtained measurement ID: ${s(this,F)}`):(f(this,F,""),a=`Failed to obtain measurement ID. Status: ${d}`),l(this,o,p).call(this,a,m.apiClient,{delay:c,actionId:s(this,A),measurementId:s(this,F),description:"Get Measurement ID"})},ae=function(t){f(this,me,t),l(this,o,p).call(this,`Face tracker state changed: ${t}`,m.mediaPipe),this.on.faceTrackerStateChanged&&this.on.faceTrackerStateChanged(s(this,me))},R=function(t,e,i=!1){return new Promise(r=>{const c=bi(this,De)._++;s(this,se).set(c,{resolve:r,action:t});const d=()=>s(this,D).worker.postMessage({id:c,action:t,payload:e});i?f(this,pe,s(this,pe).then(d).catch(n=>console.error(n))):d()})},ut(_i,"VERSION",Je);class gi{static VERSION=Nt;#e=document.createElement("div");#i=document.createElement("div");#s=!1;on={results:null,error:null,event:null};constructor(){this.#e.style.height="100%"}init(e){const{container:i,appPath:r,settings:c,profile:d,config:n,loadError:a,language:u,apiUrl:h}=e;this.#i=i;const E=i.attachShadow({mode:"open"}),_="app",C=document.createElement("link");C.rel="stylesheet",C.href=`${r}/stylex.css`,E.appendChild(C);const k=document.createElement("link");k.rel="stylesheet",k.href=`${r}/${_}.css`,E.appendChild(k);const I=H=>{this.on.results&&this.on.results({...H.detail})},W=H=>{this.on.error&&this.on.error({...H.detail})},G=H=>{this.on.event&&this.on.event({...H.detail})};this.#e.addEventListener(U.RESULTS,I),this.#e.addEventListener(U.ERROR,W),this.#e.addEventListener(U.APPEVENT,G),E.appendChild(this.#e);const M=document.createElement("script");M.type="module",M.src=`${r}/${_}.mjs`,M.onload=()=>{import(M.src).then(H=>{H.app.init(this.#e,r,c,d,h,n,u),this.#s=!0}).catch(()=>{a&&a("Failed to initialize Measurement Embedded React app")})},M.onerror=()=>{a&&a("Failed to load the measurement embedded app script")},E.appendChild(M)}#t(){if(!this.#s)throw new Error("MeasurementEmbeddedApp is not initialized. Call init() before using this method.")}async destroy(){return this.#t(),new Promise(e=>{const i=c=>{if(this.#e.removeEventListener(U.DESTROYED,i),this.#i){const d=this.#i.cloneNode(!1);this.#i.replaceWith(d)}e()};this.#e.addEventListener(U.DESTROYED,i);const r=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.DESTROY,data:{}}});this.#e.dispatchEvent(r)})}setTheme(e){this.#t();const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.SET_THEME,data:{theme:e}}});this.#e.dispatchEvent(i)}setLanguage(e){this.#t();const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.SET_LANGUAGE,data:{language:e}}});this.#e.dispatchEvent(i)}async cancel(e){return this.#t(),new Promise(i=>{const r=d=>{this.#e.removeEventListener(U.CANCELLED,r),i(d.detail.reset)};this.#e.addEventListener(U.CANCELLED,r);const c=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.CANCEL,data:{reset:e}}});this.#e.dispatchEvent(c)})}getLogs(){return this.#t(),new Promise(e=>{const i=c=>{this.#e.removeEventListener(U.LOGS,i),e(c.detail.logs)};this.#e.addEventListener(U.LOGS,i);const r=new CustomEvent("measurement-embedded-app-action",{detail:{action:re.GET_LOGS,data:{}}});this.#e.dispatchEvent(r)})}}export{Ye as ErrorCodes,Lt as appEvents,gi as default,di as faceAttributeValue,je as logCategory};
739
+ `}openLogInNewWindow(){const e=this.generateHTMLTable(),i=new Blob([e],{type:"text/html"}),a=URL.createObjectURL(i);window.open(a,"_blank")}}var Zt=Object.defineProperty,Qt=(t,e,i)=>e in t?Zt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Re=(t,e,i)=>Qt(t,typeof e!="symbol"?e+"":e,i);class Fe{constructor(e,i){Re(this,"workerUrl"),Re(this,"worker"),this.worker=e,this.workerUrl=i}static init(e,i,a){const c=new Blob([e],{type:"application/javascript"}),d=URL.createObjectURL(c),n=a||`WORKER${String(new Date().getTime())}`,r=new Worker(new URL(d,import.meta.url),{name:n,type:i});return new Fe(r,d)}destroy(){this.worker&&(this.worker.terminate(),URL.revokeObjectURL(this.worker))}}const ei=(t,e,i,a)=>{const c=t/e,d=i/a;let n=0,r=0;c>d?(n=t,r=t/d):(r=e,n=e*d);const u=(t-n)/2,h=(e-r)/2;return{width:n||0,height:r||0,offsetX:u||0,offsetY:h||0}},ti=(t,e,i,a)=>{const c=(t-i)/2,d=(e-a)/2;return{width:i||0,height:a||0,offsetX:c||0,offsetY:d||0}},ii=(t,e,i,a)=>{const c=t/e,d=i/a;let n=0,r=0;c>d?(r=e,n=e*d):(n=t,r=t/d);const u=(t-n)/2,h=(e-r)/2;return{width:n||0,height:r||0,offsetX:u||0,offsetY:h||0}},si=(t,e)=>{switch(t){case"none":return ti(...e);case"cover":return ei(...e);case"contain":default:return ii(...e)}},at=t=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(t),ai=t=>t===void 0?!0:!(typeof t.mediaPipe<"u"&&typeof t.mediaPipe!="boolean"||typeof t.beforeRESTCall<"u"&&typeof t.beforeRESTCall!="boolean"||typeof t.afterRESTCall<"u"&&typeof t.afterRESTCall!="boolean"||typeof t.extractionLibWasm<"u"&&typeof t.extractionLibWasm!="boolean"||typeof t.apiClient<"u"&&typeof t.apiClient!="boolean"||typeof t.extractionWorker<"u"&&typeof t.extractionWorker!="boolean"||typeof t.faceTrackerWorkers<"u"&&typeof t.faceTrackerWorkers!="boolean"||typeof t.sdk<"u"&&typeof t.sdk!="boolean"),ri=(t,e)=>{const i={...t};if(e.logger)if(ai(e.logger))i.logger={...i.logger,...e.logger};else return{results:"invalid"};if(e.apiUrl!==void 0)if(typeof e.apiUrl=="string")i.apiUrl=e.apiUrl;else return{results:"invalid"};if(e.metrics!==void 0)if(typeof e.metrics=="boolean")i.metrics=e.metrics;else return{results:"invalid"};if(e.mirrorVideo!==void 0)if(typeof e.mirrorVideo=="boolean")i.mirrorVideo=e.mirrorVideo;else return{results:"invalid"};if(e.displayMediaStream!==void 0)if(typeof e.displayMediaStream=="boolean")i.displayMediaStream=e.displayMediaStream;else return{results:"invalid"};if(e.assetFolder!==void 0)if(typeof e.assetFolder=="string")i.assetFolder=e.assetFolder;else return{results:"invalid"};if(e.mediaElement!==void 0)if(e.mediaElement instanceof HTMLDivElement)i.mediaElement=e.mediaElement;else return{results:"invalid"};if(e.constraintOverrides!==void 0){let a=function(n,r){if(!(n in d))return!1;const u=d[n];return typeof r===u};const d=Object.fromEntries(Object.entries({backLightMaxPixels_pct:30,backLightSearchMult:1.5,backLightThresh:240,boxCenterX_pct:50,boxCenterY_pct:50,boxHeight_pct:99,boxWidth_pct:50,cameraRot_chunkThresh:.7853981633974483,cameraRot_windowThresh:.2617993877991494,checkBackLight:!1,checkCameraMovement:!1,checkCentered:!1,checkDistance:!1,checkEyebrowMovement:!1,checkFaceDirection:!1,checkLighting:!1,checkMaxDistance:!1,checkMinFps:!1,checkMovement:!1,chunkMovementThresh_pct:60,enableDebugLog:!1,enableFigures:!1,faceRotLR_thresh:.33,faceRotUD_lowerthresh:.25,faceRotUD_upperThresh:5,hy_faceRotLR_thresh:.05,hy_maxFaceRotLR_deg:2,hy_maxFaceRotUD_deg:2,hy_minInterPupilDist_px:5,hy_minimumFps:1,maxEyebrowMovement_mm:3,maxFaceRotLR_deg:12.5,maxFaceRotUD_deg:25,maxMovement_mm:10,minInterPupilDist_px:100,minimumFps:26,movementWindow_ms:2e3,threshBright:225,threshDark:48}).map(([n,r])=>[n,typeof r]));for(const n in e.constraintOverrides){const r=e.constraintOverrides[n];if(!a(n,r))return{results:"invalid"}}i.constraintOverrides=e.constraintOverrides}return{results:"valid",settings:i}},ni=t=>typeof t.age!="number"||t.age<13||t.age>120?(console.error("Invalid age. It should be a number between 13 and 120."),!1):typeof t.height!="number"||t.height<120||t.height>220?(console.error("Invalid height. It should be a number between 120 and 220."),!1):typeof t.weight!="number"||t.weight<30||t.weight>300?(console.error("Invalid weight. It should be a number between 30 and 300."),!1):typeof t.sex!="number"||t.sex<1||t.sex>3?(console.error("Invalid sex. It should be a number between 1 and 3."),!1):typeof t.diabetes!="number"||t.diabetes<4||t.diabetes>6?(console.error("Invalid diabetes. It should be a number between 4 and 6."),!1):typeof t.bloodPressureMedication!="number"||t.bloodPressureMedication!==0&&t.bloodPressureMedication!==1?(console.error("Invalid bloodPressureMedication. It should be either 0 or 1."),!1):typeof t.smoking!="number"||t.smoking!==0&&t.smoking!==1?(console.error("Invalid smoking. It should be either 0 or 1."),!1):!0;var m=(t=>(t.beforeRESTCall="Before REST call event",t.afterRESTCall="After REST call event",t.mediaPipe="MediaPipe",t.extractionLibWasm="DFX Extraction lib WASM",t.apiClient="DFX API client",t.webSocket="WebSocket",t.sdk="SDK",t.dfxWorker="DFX Worker",t))(m||{});const oi=t=>{switch(t){case"Before REST call event":return"red";case"After REST call event":return"orange";case"MediaPipe":return"green";case"DFX Extraction lib WASM":return"violet";case"DFX API client":return"#d34110";case"WebSocket":return"#d34110";case"SDK":return"#d34110";case"DFX Worker":return"#ad4393";default:return"black"}};class rt{constructor(e=1e3){Re(this,"timestamps",[]),Re(this,"windowMs"),this.windowMs=e}tick(e=performance.now()){for(this.timestamps.push(e);this.timestamps.length>0&&e-this.timestamps[0]>this.windowMs;)this.timestamps.shift()}get fps(){const e=this.timestamps.length,i=this.timestamps.at(-1)-this.timestamps[0]||1;return e/i*1e3}get frameCount(){return this.timestamps.length}reset(){this.timestamps=[]}}var li=Object.defineProperty,ci=(t,e,i)=>e in t?li(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nt=(t,e,i)=>ci(t,typeof e!="symbol"?e+"":e,i);const di=()=>{const t=new Date,e=(t.getMonth()+1).toString().padStart(2,"0"),i=t.getDate().toString().padStart(2,"0"),a=t.getFullYear();let c=t.getHours();const d=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0"),r=t.getMilliseconds().toString().padStart(3,"0"),u=c>=12?"PM":"AM";return c=c%12||12,`[${e}/${i}/${a}, ${c}:${d}:${n}.${r} ${u}]`};class ot{constructor(){nt(this,"mertics",new qt),nt(this,"version",{webSDK:"",extractionLib:{version:"",sdkId:""},faceTracker:""})}retrieveLogs(){this.mertics.transferLogs(),this.mertics.openLogInNewWindow(),this.mertics.debugLogs=[]}setVersion(e){this.version=e,this.mertics.version=e}log(e,i,a,c=!1,d={}){const n=di();if(c)this.mertics.appendLog({thread:"Main",timestamp:n,category:i,message:e,meta:d});else{const r=`[${i}]`,u=" ",h=e,p=`color:${a}; font-weight:800;`,S=`color:${oi(i)}; font-weight:700;`;console.log("%c%s%c%s%c%s%c%s",p,n,S,r,"background:inherit;",u,"font-style: italic;",h)}}info(e,i){this.log(e,i,"blue")}warn(e,i){this.log(e,i,"orange")}error(e,i){this.log(e,i,"red")}debug(e,i){this.log(e,i,"green")}start(){console.log("%c%s","color: #5e5e5e; background-color: #2d2d2d; letter-spacing: 0.1em; text-shadow: -1px -1px 1px #111, 2px 2px 1px #363636; font-size: 36px; padding: 20px 40px; text-align: center; text-transform: uppercase; text-rendering: optimizeLegibility;","Anura Web Core SDK"),console.log(`Version: ${this.version.webSDK}`),console.log("https://www.deepaffex.ai")}}const hi={SEX_NOT_PROVIDED:1,SEX_ASSIGNED_MALE_AT_BIRTH:2,SEX_ASSIGNED_FEMALE_AT_BIRTH:3,DIABETES_NONE:4,DIABETES_TYPE1:5,DIABETES_TYPE2:6,SMOKER_TRUE:0,SMOKER_FALSE:1,BLOOD_PRESSURE_MEDICATION_TRUE:1,BLOOD_PRESSURE_MEDICATION_FALSE:0},V={SEX_ASSIGNED_AT_BIRTH:1,AGE_YEARS:2,HEIGHT_CM:3,WEIGHT_KG:4,SMOKER:5,BLOOD_PRESSURE_MEDICATION:7,DIABETES:8};var lt=(t=>(t[t.BGR=1]="BGR",t[t.RGB=2]="RGB",t[t.BGRA=3]="BGRA",t[t.RGBA=4]="RGBA",t[t.Infrared=5]="Infrared",t[t.Infrared888=6]="Infrared888",t[t.BGR_Infrared=7]="BGR_Infrared",t[t.RGB_Infrared=8]="RGB_Infrared",t[t.Gray=9]="Gray",t))(lt||{});const K={ASSETS_NOT_DOWNLOADED:"ASSETS_NOT_DOWNLOADED",NOT_LOADED:"NOT_LOADED",LOADING:"LOADING",LOADED:"LOADED",READY:"READY"},Ce={COLLECTOR:"COLLECTOR",ASSET_DOWNLOAD:"ASSET_DOWNLOAD",WEB_SOCKET:"WEB_SOCKET"},ke={CONTAIN:"contain",COVER:"cover",NONE:"none"};var $=(t=>(t.INIT="INIT",t.READY="READY",t.INIT_TFJS="INIT_TFJS",t.SET_PORT="SET_PORT",t.TRACK="TRACK",t.RESULTS_READY="RESULTS_READY",t.WARM_UP="WARM_UP",t.DESTROY="DESTROY",t.LANDMARKS="LANDMARKS",t.VIDEO_FRAME="VIDEO_FRAME",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))($||{}),mi=Object.defineProperty,ct=t=>{throw TypeError(t)},ui=(t,e,i)=>e in t?mi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e,i)=>ui(t,typeof e!="symbol"?e+"":e,i),Be=(t,e,i)=>e.has(t)||ct("Cannot "+i),dt=(t,e,i)=>(Be(t,e,"read from private field"),i?i.call(t):e.get(t)),ht=(t,e,i)=>e.has(t)?ct("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),fi=(t,e,i,a)=>(Be(t,e,"write to private field"),e.set(t,i),i),Ei=(t,e,i)=>(Be(t,e,"access private method"),i),ce,Ge,mt;const pi=class Ot{constructor(e,i,a){ht(this,Ge),ht(this,ce),w(this,"mediaElement"),w(this,"numOfFramesPresented",0),w(this,"workers",[]),w(this,"numOftrackedVideoFrames",0),w(this,"warmupFrameNumber",0),w(this,"videoCallbackId",0),w(this,"numOfWorkers",4),w(this,"isLoggingFaceTrackerWorkers",!1),w(this,"isLoggingSdk",!1),w(this,"workerIndex",0),w(this,"metrics",!1),w(this,"videoFpsTracker",new rt(1e3)),w(this,"faceTrackerFpsTracker",new rt(1e3)),w(this,"videoElementSize",{width:0,height:0,offsetX:0,offsetY:0}),w(this,"videoElement",document.createElement("video")),w(this,"frameWidth",0),w(this,"frameHeight",0),w(this,"mirrorVideo",!0),w(this,"settings",{faceTrackerWidth:0,faceTrackerHeight:0,displayMediaStream:!0,objectFit:ke.COVER}),w(this,"isExtracting",!1),w(this,"starRating",0),w(this,"scaleFactor",1),w(this,"warmupIndex",0),w(this,"warmingUp",!0),w(this,"ftWorkerIndex",0),w(this,"lastFrameNumber",-1),w(this,"on",{faceTrackersReady:null,frameAvailable:null,landmarksAvailable:null,scaleFactorChanged:null});const{mediaElement:c,mirrorVideo:d,numOfWorkers:n,isLoggingFaceTrackerWorkers:r,isLoggingSdk:u,metrics:h,displayMediaStream:p}=i;this.numOfWorkers=n,this.isLoggingFaceTrackerWorkers=r,this.isLoggingSdk=u,this.metrics=h,fi(this,ce,a),this.settings.displayMediaStream=p,this.mirrorVideo=d,this.mediaElement=c,this.videoFrameCallback=this.videoFrameCallback.bind(this),this.workers=e,this.scaleFactor=i.scaleFactor,this.initWorkerOnMessage(i.models),this.videoElement.muted=!0,this.videoElement.playsInline=!0,this.videoElement.preload="auto"}static async init(e,i){const{numOfWorkers:a,faceTrackerCode:c}=e,d=[],n=new TextDecoder().decode(new Uint8Array(c));if(a>0)for(let r=1;r<=a;r+=1){const u=Fe.init(n,"module",`FACE_TRACKER_WORKER_${r-1}`);d.push({ft:u,channel:new MessageChannel,isBusy:!1})}return new Ot(d,e,i)}initWorkerOnMessage(e){const i=window.matchMedia("(orientation: portrait)").matches,a=i?360:640,c=i?640:360;this.workers.forEach(d=>{d.ft.worker.postMessage({action:$.INIT_TFJS,payload:{width:a,height:c,models:e,scaleFactor:this.scaleFactor}}),d.ft.worker.postMessage({action:$.SET_PORT,payload:{port:d.channel.port2}},[d.channel.port2]),d.ft.worker.onmessage=n=>{const{action:r,payload:u}=n.data;switch(r){case $.INIT_TFJS:break;case $.READY:{const{workerName:h,version:p,workerId:S,backend:C}=u;this.on.faceTrackersReady&&this.on.faceTrackersReady(h,p,S,C);break}case $.LANDMARKS:{this.faceTrackerFpsTracker.tick(),d.isBusy=!1,this.warmingUp&&this.warmupIndex++;const{face:h,annotations:p,frameTimestamp:S}=u;this.on.landmarksAvailable&&this.on.landmarksAvailable(h,p,S);break}case $.DESTROY:{const{workerId:h}=u;this.workers[h].ft.destroy();break}}}})}getMediaElement(){return this.mediaElement}setIsExtracting(e){this.isExtracting=e}destroyWorkers(){setTimeout(async()=>{this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.workers.forEach(e=>e.ft.worker.postMessage({action:$.DESTROY}))},200)}createMediaElements(){this.videoElement.addEventListener("ended",async()=>{this.destroyWorkers()});const e=document.createElement("div"),i=this.settings.displayMediaStream?this.videoElement:e,a="white";this.mediaElement.appendChild(i),i.style.width="100%",i.style.height="100%",i.style.boxSizing="border-box",this.settings.displayMediaStream&&(i.style.border=`1px solid ${a}`),i.style.objectFit=this.settings.objectFit,i.style.transform=`scale(${this.mirrorVideo?"-1":"1"},1)`,this.settings.displayMediaStream||(i.style.height=`${this.frameHeight}px`,i.style.width=`${this.frameWidth}px`),new ResizeObserver(d=>{const{contentRect:n,target:r}=d[0],{width:u,height:h}=n,{x:p,y:S}=r.getBoundingClientRect(),{faceTrackerWidth:C,faceTrackerHeight:k}=this.settings;this.videoElementSize=si(this.settings.objectFit,[u,h,this.frameWidth,this.frameHeight]);const{width:O,height:P}=this.videoElementSize;if(!this.settings.displayMediaStream){const G=this.settings.objectFit===ke.NONE;i.style.height=`${Math.trunc(G?P:h)}px`,i.style.width=`${Math.trunc(G?O:u)}px`}this.mediaElement.dispatchEvent(new CustomEvent("mediaElementSizeChanged",{detail:{mediaElementSize:{width:u,height:h,x:p,y:S},videoElementSize:this.videoElementSize,frameInfo:{mediaStreamWidth:this.frameWidth,mediaStreamHeight:this.frameHeight,faceTrackerWidth:C,faceTrackerHeight:k},isPortrait:h>u,aspectRatio:u/h}}))}).observe(this.mediaElement)}log(e,i,a){this.isLoggingSdk&&dt(this,ce).info(e,i),this.metrics&&dt(this,ce).log(e,i,"",!0,a)}videoFrameCallback(e,i){const{presentedFrames:a,captureTime:c,expectedDisplayTime:d,mediaTime:n}=i;this.videoFpsTracker.tick();const r=c===void 0?d:c;this.numOfFramesPresented=a;const u=`Number of frames presented: ${this.numOfFramesPresented} - time: ${r}`;let h=0;if(n&&n>0?h=n*1e3:c&&c>0?h=c>1e6?c-performance.timeOrigin:c:h=e,this.log(u,m.sdk,{captureTime:r,presentedFrames:a}),this.warmingUp)if(this.warmupIndex>=this.numOfWorkers)this.warmingUp=!1;else{const p=this.workers[this.warmupIndex];if(!p.isBusy){p.isBusy=!0;const S=new VideoFrame(this.videoElement,{timestamp:h});p.ft.worker.postMessage({action:"TRACK",payload:{frame:S,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[S])}}if(!this.warmingUp){const p=new VideoFrame(this.videoElement,{timestamp:h});let S=!1;for(let C=0;C<this.numOfWorkers;C++){this.ftWorkerIndex=(this.ftWorkerIndex+1)%this.numOfWorkers;const k=this.workers[this.ftWorkerIndex];if(k&&!k.isBusy){k.isBusy=!0,this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!0),k.ft.worker.postMessage({action:"TRACK",payload:{frame:p,frameTimestamp:h,frameNumber:this.numOfFramesPresented}},[p]),S=!0;break}}S||this.on.frameAvailable(h,this.numOfFramesPresented,this.lastFrameNumber,!1,p)}this.lastFrameNumber=this.numOfFramesPresented,this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback)}setFaceTrackerMediaStreamResolution(e,i){(e<=360||i<=360)&&(this.scaleFactor=1),this.settings.faceTrackerWidth=e*this.scaleFactor,this.settings.faceTrackerHeight=i*this.scaleFactor,this.workers.forEach(a=>a.ft.worker.postMessage({action:$.SCALE_FACTOR_CHANGED,payload:{scaleFactor:this.scaleFactor}})),this.on.scaleFactorChanged&&this.on.scaleFactorChanged(this.scaleFactor)}async setMediaStream(e){if(e instanceof MediaStream)try{const{settings:i,constraints:a}=await Ei(this,Ge,mt).call(this,e,this.videoElement);await this.videoElement.play(),this.settings.displayMediaStream||(this.videoElement.style.visibility="none");const{width:c,height:d}=i;return this.setFaceTrackerMediaStreamResolution(c??0,d??0),this.frameWidth=c||1,this.frameHeight=d||1,this.log(`Face tracker resolution: ${c} x ${d} pixels. Video resolution: ${this.frameWidth} x ${this.frameHeight} pixels`,m.sdk,{ftWidth:c,ftHeight:d,frameWidth:this.frameWidth,frameHeight:this.frameHeight}),this.createMediaElements(),this.videoCallbackId=this.videoElement.requestVideoFrameCallback(this.videoFrameCallback),!0}catch(i){return console.log("Error applying face tracker video track constraints",i),!1}return!1}stopTracking(){this.videoCallbackId&&this.videoElement.cancelVideoFrameCallback(this.videoCallbackId),this.videoElement.pause(),this.videoElement.srcObject=null}};ce=new WeakMap,Ge=new WeakSet,mt=async function(t,e){e.srcObject=t,await new Promise(a=>e.onloadedmetadata=a);const[i]=t.getVideoTracks();return{constraints:i.getConstraints(),settings:i.getSettings()}};let Ti=pi;var T=(t=>(t.INIT="INIT",t.READY="READY",t.SET_MODE="SET_MODE",t.SET_NUMBER_OF_CHUNKS="SET_NUMBER_OF_CHUNKS",t.SET_TARGET_FPS="SET_TARGET_FPS",t.SET_CHUNK_DURATION_SECONDS="SET_CHUNK_DURATION_SECONDS",t.SET_FRAME_ORDER="SET_FRAME_ORDER",t.GET_CONSTRAINTS_CONFIG="GET_CONSTRAINTS_CONFIG",t.SET_CONSTRAINTS_CONFIG="SET_CONSTRAINTS_CONFIG",t.SET_FACE_ATTRIBUTE="SET_FACE_ATTRIBUTE",t.RESET_COLLECTION="RESET_COLLECTION",t.CANCEL_COLLECTION="CANCEL_COLLECTION",t.START_COLLECTION="START_COLLECTION",t.SET_PORTS="SET_PORTS",t.COLLECTOR_ERROR="COLLECTOR_ERROR",t.STAR_RATING="STAR_RATING",t.ALL_FACE_TRACKERS_WARMED_UP="ALL_FACE_TRACKERS_WARMED_UP",t.CONSTRAINTS_UPDATED="CONSTRAINTS_UPDATED",t.SHOULD_END_MEASUREMENT_EARLY="SHOULD_END_MEASUREMENT_EARLY",t.GET_LOGS="GET_LOGS",t.NEW_FRAME="NEW_FRAME",t.TRACKING_STATUS="TRACKING_STATUS",t.SCALE_FACTOR_CHANGED="SCALE_FACTOR_CHANGED",t))(T||{}),y=(t=>(t.CONNECT="CONNECT",t.DISCONNECT="DISCONNECT",t.DISCONNECTED="DISCONNECTED",t.LOGIN_WITH_TOKEN_SUCCESS="LOGIN_WITH_TOKEN_SUCCESS",t.SUBSCRIBED_TO_RESULTS="SUBSCRIBED_TO_RESULTS",t.CHUNK_SENT="CHUNK_SENT",t.RESULTS_RECEIVED="RESULTS_RECEIVED",t.CHUNK_ACKNOWLEDGED="CHUNK_ACKNOWLEDGED",t.ERROR="ERROR",t.NETWORK_DELAY="NETWORK_DELAY",t))(y||{}),Si=Object.defineProperty,ut=t=>{throw TypeError(t)},bi=(t,e,i)=>e in t?Si(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ft=(t,e,i)=>bi(t,typeof e!="symbol"?e+"":e,i),He=(t,e,i)=>e.has(t)||ut("Cannot "+i),s=(t,e,i)=>(He(t,e,"read from private field"),i?i.call(t):e.get(t)),b=(t,e,i)=>e.has(t)?ut("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,a)=>(He(t,e,"write to private field"),e.set(t,i),i),l=(t,e,i)=>(He(t,e,"access private method"),i),_i=(t,e,i,a)=>({set _(c){f(t,e,c)},get _(){return s(t,e,a)}}),x,g,M,v,D,ve,Ae,ye,Oe,de,z,Ne,he,me,_,q,I,ue,F,Le,Z,Q,ee,te,fe,Ee,j,pe,De,ie,Ie,se,Te,A,Se,B,be,o,Et,pt,Tt,Ve,Ke,St,bt,_t,gt,wt,Rt,xe,je,E,Ct,kt,vt,At,ae,R;const yt=Symbol("instance_creation_key"),gi=class Nt{constructor(e){if(b(this,o),b(this,x),b(this,g,{mediaElement:document.createElement("div"),assetFolder:"",apiUrl:"",metrics:!1,logger:{sdk:!1,mediaPipe:!1,beforeRESTCall:!1,afterRESTCall:!1,extractionLibWasm:!1,apiClient:!1,extractionWorker:!1,faceTrackerWorkers:!1},mirrorVideo:!0,displayMediaStream:!0,constraintOverrides:{}}),b(this,M,[{file:"decompress.json",uncompressedSize:89469},{file:"extraction_worker_0.1.0-beta.2_js.json",uncompressedSize:59696},{file:"facetracker_worker_0.1.0-beta.2_js.json",uncompressedSize:306553},{file:"extraction_wasm_0.1.0-beta.2.json",uncompressedSize:1926126},{file:"detectorModel_json.json",uncompressedSize:4640},{file:"detectorModel_bin.json",uncompressedSize:242046},{file:"landmarkModel_json.json",uncompressedSize:5036},{file:"landmarkModel_bin.json",uncompressedSize:1704814}]),b(this,v,new ot),b(this,D,Jt.init()),b(this,ve),b(this,Ae),b(this,ye),b(this,Oe),b(this,de),b(this,z),b(this,Ne),b(this,he,{version:"",sdkId:""}),b(this,me,""),b(this,_),b(this,q,0),b(this,I),b(this,ue,K.ASSETS_NOT_DOWNLOADED),b(this,F,""),b(this,Le,""),b(this,Z,!1),b(this,Q,5),b(this,ee,30),b(this,te,5),b(this,fe,!1),b(this,Ee,4),b(this,j),b(this,pe),b(this,De),b(this,ie,1e7),b(this,Ie,0),b(this,se,new Map),b(this,Te,Promise.resolve()),b(this,A,0),b(this,Se,-1),b(this,B,-1),b(this,be,.5),ft(this,"on",{beforeRESTCall:null,afterRESTCall:null,bytesDownloaded:null,faceTrackerStateChanged:null,resultsReceived:null,constraintsUpdated:null,mediaElementResize:null,facialLandmarksUpdated:null,chunkSent:null,error:null}),e!==yt)throw new Error("Use await Measurement.init() to create an instance of Measurement class.")}static async init(e){if(!e)throw new Error("Missing `settings` object");const i=new Nt(yt);if(!i.setSettings(e))throw new Error("Invalid settings object");f(i,x,Gt({url:{http:new URL("https://api.deepaffex.ai")},onBeforeRESTCall:()=>{var n,r;l(n=i,o,bt).call(n),l(r=i,o,_t).call(r)},onAfterRESTCall:(n,r)=>{var u,h;l(u=i,o,gt).call(u,n,r),l(h=i,o,wt).call(h,n,r)}}));const c=n=>{var r;const{bytes:u,url:h,uncompressedSize:p,done:S}=n.detail;l(r=i,o,E).call(r,`bytesDownloaded event, ${u}, ${p}, ${h}, ${S}`,m.mediaPipe),i.on.bytesDownloaded&&i.on.bytesDownloaded(u,p,h,S)},d=n=>{var r;const{error:u,url:h}=n.detail;l(r=i,o,E).call(r,`downloadError event, ${h}, ${u}`,m.mediaPipe),i.on.error&&i.on.error(Ce.ASSET_DOWNLOAD,{url:h,error:u})};return s(i,D).addEventListener("downloadedError",d),s(i,D).addEventListener("bytesDownloaded",c),s(i,v).setVersion(i.getVersion()),s(i,g).logger&&Object.values(s(i,g).logger).some(n=>n===!0)&&s(i,v).start(),setTimeout(()=>{var n;l(n=i,o,ae).call(n,K.ASSETS_NOT_DOWNLOADED)},500),new Proxy(i,{get(n,r,u){const h=r;return typeof n[h]=="function"?n[h].bind(n):Reflect.get(n,h,u)},set(n,r,u){return console.log(`Setting property "${String(r)}" to "${u}" is not allowed`),!0}})}loadMask(e){if(s(this,_)){let i=!1;const a=s(this,_).mediaElement.querySelector("svg");a&&(i=!0,s(this,_).mediaElement.removeChild(a)),s(this,_).mediaElement.appendChild(e),i&&(s(this,_).mediaElement.style.setProperty("border","1px solid transparent"),setTimeout(()=>{s(this,_).mediaElement.removeAttribute("style")},100))}}setSettings(e){const i=ri(s(this,g),e);return i.results==="valid"?(f(this,g,i.settings),!0):!1}getVersion(){return{webSDK:Xe,extractionLib:s(this,he),faceTracker:s(this,me)}}async downloadAssets(){const{assetFolder:e}=s(this,g);try{if(l(this,o,E).call(this,`Asset base URL ${e}`,m.sdk),l(this,o,E).call(this,"Start downloading decompressor...",m.sdk),await s(this,D).fetchAsset(s(this,M),`${e}/`,"decompress.json",!0,"gzip"),s(this,D).canDecompress){await l(this,o,pt).call(this,e),s(this,z)&&await l(this,o,Ke).call(this),l(this,o,E).call(this,"Start downloading TFJS worker...",m.mediaPipe);const i=await s(this,D).fetchAsset(s(this,M),`${e}/`,`facetracker_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli");return i&&(f(this,Ne,i),await l(this,o,Et).call(this,e),await l(this,o,Ve).call(this)),l(this,o,Tt).call(this),!0}}catch{return l(this,o,E).call(this,"Failed to download TFJS face tracker or DFX extraction worker WASM assets",m.mediaPipe),!1}}setExtractionLibSettings(e=6,i=30,a=5){f(this,Q,e-1),f(this,ee,i),f(this,te,a)}async setNextChunkAsFinal(){f(this,fe,!0),await l(this,o,R).call(this,T.SHOULD_END_MEASUREMENT_EARLY,{},!0),l(this,o,E).call(this,"Set the action for the next chunk to LAST::PROCESS",m.extractionLibWasm)}async startTracking(){s(this,_)&&(s(this,_).isExtracting||(s(this,_).setIsExtracting(!0),l(this,o,E).call(this,"Start tracking frames",m.mediaPipe),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,xe).call(this)))}async stopTracking(){if(s(this,_)){s(this,_).stopTracking(),await l(this,o,Rt).call(this),s(this,_).setIsExtracting(!1),l(this,o,E).call(this,"Stop extracting frames",m.mediaPipe);const{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:a}=s(this,_);l(this,o,E).call(this,"Tracking metrics",m.sdk,{numOfFramesPresented:e,warmupFrameNumber:i,numOftrackedVideoFrames:a}),f(this,F,"")}}async disconnect(){s(this,Z)&&await l(this,o,R).call(this,y.DISCONNECT,{},!0),s(this,g).metrics&&(await l(this,o,R).call(this,T.GET_LOGS,{},!0),s(this,v).retrieveLogs())}async destroy(){s(this,I)&&(s(this,I).destroy(),l(this,o,E).call(this,"Destroyed",m.extractionLibWasm)),s(this,_)&&(s(this,_).destroyWorkers(),l(this,o,E).call(this,"Destroyed",m.mediaPipe))}async reset(){return s(this,ue)===K.READY?(await this.stopTracking(),await this.destroy(),f(this,v,new ot),f(this,he,{version:"",sdkId:""}),f(this,me,""),f(this,q,0),f(this,F,""),f(this,Z,!1),f(this,Q,5),f(this,ee,30),f(this,te,5),f(this,fe,!1),f(this,j,void 0),f(this,ie,1e7),f(this,Ie,0),f(this,se,new Map),f(this,Te,Promise.resolve()),f(this,A,0),f(this,Se,-1),f(this,B,-1),s(this,g).mediaElement.innerHTML="",await l(this,o,Ke).call(this),await l(this,o,Ve).call(this),!0):!1}async setMediaStream(e){if(s(this,_)&&!s(this,_).isExtracting&&s(this,I)){await s(this,_).setMediaStream(e);const i=Object.fromEntries(s(this,_).workers.map((a,c)=>[`port${c+1}`,a.channel.port1]));s(this,I).worker.postMessage({action:T.SET_PORTS,payload:{numOfWorkers:s(this,Ee),workerPorts:i}},[...s(this,_).workers.map(a=>a.channel.port1)])}}async prepare(e,i,a,c){s(this,x).setSession({userToken:e,userRefreshToken:i});const{region:d,status:n}=await l(this,o,Ct).call(this,"user");let r=`api.${d}.deepaffex.ai`;s(this,g).apiUrl?r=s(this,g).apiUrl:s(this,g).apiUrl=r,s(this,x).setUrl(`https://${r}`);const u=await l(this,o,kt).call(this,e,i,"user"),h=await l(this,o,vt).call(this,a,c);return u&&h&&n==="200"}async setConstraintsConfig(e){await l(this,o,R).call(this,T.SET_CONSTRAINTS_CONFIG,{...s(this,De),...e&&{...s(this,g).constraintOverrides}},!0)}async startMeasurement(e=!1,i={}){if(f(this,fe,!1),f(this,F,""),await l(this,o,At).call(this,i),s(this,I)&&s(this,F)!==""){await l(this,o,je).call(this),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,Q)+1},!0),await this.setConstraintsConfig(e),await l(this,o,St).call(this),await l(this,o,xe).call(this);const{userToken:a}=s(this,x).getSession();a?await l(this,o,R).call(this,y.CONNECT,{token:a,measurementId:s(this,F)},!0):l(this,o,E).call(this,"User token is missing. Unable to connect.",m.webSocket)}}setDemographics(e){ni(e)?(f(this,j,e),l(this,o,E).call(this,`Demographics updated ${JSON.stringify(e)}`,m.extractionLibWasm)):l(this,o,E).call(this,`Error updating Demographics ${JSON.stringify(e)}`,m.extractionLibWasm)}setObjectFit(e){return s(this,_)&&ke!==void 0&&Object.values(ke).includes(e)?(s(this,_).settings.objectFit=e,!0):!1}};x=new WeakMap,g=new WeakMap,M=new WeakMap,v=new WeakMap,D=new WeakMap,ve=new WeakMap,Ae=new WeakMap,ye=new WeakMap,Oe=new WeakMap,de=new WeakMap,z=new WeakMap,Ne=new WeakMap,he=new WeakMap,me=new WeakMap,_=new WeakMap,q=new WeakMap,I=new WeakMap,ue=new WeakMap,F=new WeakMap,Le=new WeakMap,Z=new WeakMap,Q=new WeakMap,ee=new WeakMap,te=new WeakMap,fe=new WeakMap,Ee=new WeakMap,j=new WeakMap,pe=new WeakMap,De=new WeakMap,ie=new WeakMap,Ie=new WeakMap,se=new WeakMap,Te=new WeakMap,A=new WeakMap,Se=new WeakMap,B=new WeakMap,be=new WeakMap,o=new WeakSet,Et=async function(t){l(this,o,E).call(this,"Start downloading TFJS face tracker assets...",m.mediaPipe);const e=`${t}/models/`,[i,a,c,d]=await Promise.all([s(this,D).fetchAsset(s(this,M),e,"detectorModel_json.json",!0,"brotli"),s(this,D).fetchAsset(s(this,M),e,"detectorModel_bin.json",!0,"brotli"),s(this,D).fetchAsset(s(this,M),e,"landmarkModel_json.json",!0,"brotli"),s(this,D).fetchAsset(s(this,M),e,"landmarkModel_bin.json",!0,"brotli")]);l(this,o,E).call(this,"TFJS face tracker assets successfully downloaded",m.mediaPipe),f(this,ve,i),f(this,Ae,a),f(this,ye,c),f(this,Oe,d)},pt=async function(t){l(this,o,E).call(this,"Start downloading DFX extraction worker assets...",m.extractionLibWasm);const[e,i]=await Promise.all([s(this,D).fetchAsset(s(this,M),`${t}/extraction/`,`extraction_wasm_${this.getVersion().webSDK}.json`,!0,"brotli"),s(this,D).fetchAsset(s(this,M),`${t}/`,`extraction_worker_${this.getVersion().webSDK}_js.json`,!0,"brotli")]);l(this,o,E).call(this,"DFX extraction worker assets successfully downloaded",m.extractionLibWasm),f(this,de,e),f(this,z,i)},Tt=function(){if(s(this,_)){const t=e=>{this.on.mediaElementResize&&this.on.mediaElementResize(e)};s(this,g).mediaElement.addEventListener("mediaElementSizeChanged",t)}},Ve=async function(){s(this,g),l(this,o,ae).call(this,K.NOT_LOADED);const t={faceTrackerCode:s(this,Ne),numOfWorkers:s(this,Ee),mediaElement:s(this,g).mediaElement,mirrorVideo:s(this,g).mirrorVideo,metrics:s(this,g).metrics,displayMediaStream:s(this,g).displayMediaStream,isLoggingFaceTrackerWorkers:s(this,g).logger?.faceTrackerWorkers??!1,isLoggingSdk:s(this,g).logger?.sdk??!1,scaleFactor:s(this,be),models:{detectorJson:s(this,ve),detectorBin:s(this,Ae),landmarkJson:s(this,ye),landmarkBin:s(this,Oe)}};l(this,o,ae).call(this,K.LOADING),f(this,_,await Ti.init(t,s(this,v))),s(this,_).on.faceTrackersReady=(e,i,a,c)=>{l(this,o,E).call(this,`TFJS face tracker version ${i} loaded. Worker name: ${e} - workerId: ${a} - backend: ${c}`,m.mediaPipe),f(this,me,`${i}-${c}`),f(this,q,s(this,q)+1),s(this,v).setVersion(this.getVersion()),s(this,q)===s(this,Ee)&&l(this,o,ae).call(this,K.LOADED)},s(this,_).on.frameAvailable=(e,i,a,c,d)=>{!c&&d?s(this,I).worker.postMessage({action:T.NEW_FRAME,payload:{frameNumber:i,frameTimestamp:e,frame:d,lastFrameNumber:a,tracked:c}},[d]):s(this,I).worker.postMessage({action:T.TRACKING_STATUS,payload:{frameNumber:i,frameTimestamp:e,lastFrameNumber:a,tracked:c}})},s(this,_).on.landmarksAvailable=(e,i,a)=>{const c=a/1e3;s(this,B)===0&&f(this,B,c),f(this,Se,c),s(this,_).numOftrackedVideoFrames+=1;const{starRating:d}=s(this,_),n=30,r=Math.min(s(this,Se)-s(this,B),n),u=s(this,B)>0?r/n*100:0,h={video:s(this,_).videoFpsTracker.fps.toFixed(1),faceTracker:s(this,_).faceTrackerFpsTracker.fps.toFixed(1)},p={face:e,annotations:i,starRating:d,percentCompleted:u,fps:h};this.on.facialLandmarksUpdated&&this.on.facialLandmarksUpdated(p)},s(this,_).on.scaleFactorChanged=e=>{f(this,be,e),s(this,_).scaleFactor=e,s(this,I).worker.postMessage({action:T.SCALE_FACTOR_CHANGED,payload:{scaleFactor:e}})}},Ke=async function(){const t=new TextDecoder().decode(new Uint8Array(s(this,z)));f(this,I,Fe.init(t,"module","EXTRACTION_WORKER"));const{studyCfgData:e}=s(this,x).getSession();e&&s(this,de)&&s(this,z)&&(s(this,I).worker.onmessage=async i=>{const{data:a}=i,{id:c,result:d}=a,{action:n,payload:r}=d,u=s(this,se).get(c);if(u||c===-1){switch(n){case T.READY:{const{sdkId:h,version:p,workerName:S}=r;f(this,he,{version:p,sdkId:h}),l(this,o,E).call(this,`DFX extraction worker WASM loaded. SDK ID: ${h} - Version: ${p} - Worker Name: ${S}`,m.extractionLibWasm),await l(this,o,R).call(this,T.SET_MODE,{value:"discrete"},!0),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0),await l(this,o,R).call(this,T.SET_TARGET_FPS,{value:s(this,ee)},!0),await l(this,o,R).call(this,T.SET_CHUNK_DURATION_SECONDS,{value:s(this,te)},!0),await l(this,o,R).call(this,T.SET_FRAME_ORDER,{value:lt.RGBA},!0),await l(this,o,R).call(this,T.GET_CONSTRAINTS_CONFIG,{},!0),f(this,De,s(this,pe));break}case T.SET_MODE:{r&&l(this,o,E).call(this,`Set mode to ${r.mode}`,m.extractionLibWasm);break}case T.SET_NUMBER_OF_CHUNKS:{r&&l(this,o,E).call(this,`Set number of chunks to ${d.number}`,m.extractionLibWasm);break}case T.SET_TARGET_FPS:{r&&l(this,o,E).call(this,`Set target FPS to ${s(this,ee)}`,m.extractionLibWasm);break}case T.SET_CHUNK_DURATION_SECONDS:{r&&l(this,o,E).call(this,`Set chunk duration to ${s(this,te)} Seconds`,m.extractionLibWasm);break}case T.SET_FRAME_ORDER:{r&&l(this,o,E).call(this,"Set channel order RGBA",m.extractionLibWasm);break}case T.GET_CONSTRAINTS_CONFIG:{r&&(f(this,pe,r),l(this,o,E).call(this,`Get constraints ${JSON.stringify(r)}`,m.extractionLibWasm));break}case T.SET_CONSTRAINTS_CONFIG:{r&&(f(this,pe,r),l(this,o,E).call(this,`Set constraints ${JSON.stringify(r)}`,m.extractionLibWasm));break}case T.SET_FACE_ATTRIBUTE:{const{success:h,faceId:p,attribute:S,value:C}=r;h&&l(this,o,E).call(this,`Set face attribute: faceId: ${p}, attribute: ${S}, value: ${C}`,m.extractionLibWasm);break}case T.RESET_COLLECTION:{r&&l(this,o,E).call(this,"Reset collection",m.extractionLibWasm);break}case T.CANCEL_COLLECTION:{r&&l(this,o,E).call(this,"Collecttion cancelled",m.extractionLibWasm);break}case T.START_COLLECTION:{r&&l(this,o,E).call(this,`Collector started - state: ${r}`,m.extractionLibWasm);break}case T.SET_PORTS:{r&&l(this,o,E).call(this,"Ports set",m.extractionLibWasm);break}case T.COLLECTOR_ERROR:{if(r){const{error:h,frameNumber:p}=r;l(this,o,E).call(this,`Collector error on frame ${p}: ${h}`,m.extractionLibWasm),this.on.error&&this.on.error(Ce.COLLECTOR,r),await this.stopTracking()}break}case T.STAR_RATING:{s(this,_).starRating=r.rating;break}case T.ALL_FACE_TRACKERS_WARMED_UP:{const{frameNumber:h}=d;s(this,_).warmupFrameNumber=h,l(this,o,E).call(this,"All face tracker workers are warmed up.",m.mediaPipe),l(this,o,ae).call(this,K.READY);break}case T.CONSTRAINTS_UPDATED:{const{feedback:h,status:p}=r;this.on.constraintsUpdated&&this.on.constraintsUpdated(h,p);break}case T.SHOULD_END_MEASUREMENT_EARLY:{const{currentFinalChunkNumber:h,currentResultsOrder:p,newFinalChunkNumber:S}=d;l(this,o,E).call(this,`Request the end measurement early. Current final chunk number: ${h}, Current results order: ${p}, New final chunk number: ${S}`,m.extractionLibWasm);break}case T.GET_LOGS:{console.log(`DFX Log: ${r}`);break}case y.CONNECT:{f(this,Z,!0),f(this,B,0),l(this,o,E).call(this,r?"Connected":"Connection error",m.webSocket);break}case y.LOGIN_WITH_TOKEN_SUCCESS:{l(this,o,E).call(this,"Successfully logged in with token",m.webSocket);break}case y.SUBSCRIBED_TO_RESULTS:{l(this,o,E).call(this,"Subscribed to the results",m.webSocket);break}case y.CHUNK_SENT:{l(this,o,E).call(this,`Chunk sent ${JSON.stringify(r)}`,m.webSocket),this.on.chunkSent&&this.on.chunkSent(r);break}case y.DISCONNECT:{f(this,Z,!1),l(this,o,E).call(this,"Disconnect",m.webSocket);break}case y.DISCONNECTED:{l(this,o,E).call(this,`Disconnected! - code: ${r.code}, reason: ${r.reason}, wasClean: ${r.wasClean}`,m.webSocket),this.on.error&&this.on.error(Ce.WEB_SOCKET,r);break}case y.CHUNK_ACKNOWLEDGED:{l(this,o,E).call(this,`Chunk number ${r.chunkOrder} received by the server!`,m.webSocket),s(this,Q)===r.chunkOrder&&await this.stopTracking();break}case y.RESULTS_RECEIVED:{const{resultsOrder:h,finalChunkNumber:p}=r;this.on.resultsReceived&&this.on.resultsReceived(r),l(this,o,E).call(this,`Results received: ${JSON.stringify(r)}`,m.webSocket),h===p&&(await l(this,o,R).call(this,y.DISCONNECT,{},!0),await l(this,o,je).call(this),await l(this,o,xe).call(this));break}case y.NETWORK_DELAY:{const{delay:h,description:p,actionId:S}=r;l(this,o,E).call(this,`Round-trip delay for ${p} call with Action ID ${S} was ${h.toFixed(2)} ms`,m.webSocket,{delay:h,actionId:S,description:p});break}case y.ERROR:{l(this,o,E).call(this,"Error",m.webSocket),this.on.error&&this.on.error(Ce.WEB_SOCKET,r);break}}u&&(u.resolve(d),s(this,se).delete(c))}},await l(this,o,R).call(this,T.INIT,{wasm:s(this,de),studyConfigData:e,isLogging:s(this,g).logger?.extractionWorker||!1,metrics:s(this,g).metrics||!1,apiUrl:s(this,g).apiUrl,scaleFactor:s(this,be)},!0))},St=async function(){if(s(this,_)&&s(this,j)){const{age:e,height:i,weight:a,sex:c,smoking:d,bloodPressureMedication:n,diabetes:r}=s(this,j);await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.SEX_ASSIGNED_AT_BIRTH,value:c},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.AGE_YEARS,value:e},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.HEIGHT_CM,value:i},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.WEIGHT_KG,value:a},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.SMOKER,value:d},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.BLOOD_PRESSURE_MEDICATION,value:n},!0),await l(this,o,R).call(this,T.SET_FACE_ATTRIBUTE,{faceId:"1",attribute:V.DIABETES,value:r},!0),l(this,o,E).call(this,`Set demographics for Face ID 1, ${JSON.stringify(s(this,j))}`,m.extractionLibWasm)}},bt=function(){},_t=function(){const t=new Date().toISOString();at(t)&&(l(this,o,E).call(this,`Action ID: ${s(this,A)}`,m.beforeRESTCall),this.on.beforeRESTCall&&this.on.beforeRESTCall(t,s(this,A)))},gt=function(t,e){},wt=function(t,e){const i=new Date().toISOString();at(i)&&(l(this,o,E).call(this,`Action ID: ${s(this,A)}, HTTP status code: ${t}, error: ${JSON.stringify(e)}`,m.afterRESTCall),this.on.afterRESTCall&&this.on.afterRESTCall(i,s(this,A),t,e))},Rt=async function(){await l(this,o,R).call(this,T.CANCEL_COLLECTION,{},!0)},xe=async function(){await l(this,o,R).call(this,T.START_COLLECTION,{},!0)},je=async function(){await l(this,o,R).call(this,T.RESET_COLLECTION,{},!0),await l(this,o,R).call(this,T.SET_NUMBER_OF_CHUNKS,{value:s(this,ie)},!0)},E=function(t,e,i){s(this,g).metrics&&s(this,v).log(t,e,"",!0,i),s(this,g).logger?.mediaPipe&&e===m.mediaPipe&&s(this,v).info(t,e),s(this,g).logger?.beforeRESTCall&&e===m.beforeRESTCall&&s(this,v).info(t,e),s(this,g).logger?.afterRESTCall&&e===m.afterRESTCall&&s(this,v).info(t,e),s(this,g).logger?.extractionLibWasm&&e===m.extractionLibWasm&&s(this,v).info(t,e),s(this,g).logger?.apiClient&&e===m.apiClient&&s(this,v).info(t,e),s(this,g).logger?.webSocket&&e===m.webSocket&&s(this,v).info(t,e),s(this,g).logger?.sdk&&e===m.sdk&&s(this,v).info(t,e)},Ct=async function(t){f(this,A,0);const e=performance.now(),i=await s(this,x).http.auths.validate(t),a=performance.now()-e,{status:c,body:d}=i;if(l(this,o,E).call(this,c==="200"?"Successfully validated the Token":`Failed to validate token. Status: ${c}`,m.apiClient,{delay:a,actionId:s(this,A),description:"Validate Token"}),c==="200"){const{Region:n}=d;return{region:n,status:c}}else return{status:c,region:""}},kt=async function(t,e,i){f(this,A,2304);const a=performance.now(),c=await s(this,x).http.auths.renew({Token:t,RefreshToken:e},i),d=performance.now()-a,{status:n}=c;return l(this,o,E).call(this,n==="200"?"Successfully refreshed the Token":`Failed to refresh token. Status: ${n}`,m.apiClient,{delay:d,actionId:s(this,A),description:"Refresh Token"}),n==="200"},vt=async function(t,e){f(this,A,806);const i=performance.now();f(this,Le,t);const a=await s(this,x).http.studies.retrieveSdkConfigData({StudyID:t,...e&&{sdkId:e}},"user"),c=performance.now()-i,{status:d}=a;return l(this,o,E).call(this,d==="200"?"Retrieve SDK Config Data - success":"Retrieve SDK Config Data - failure",m.apiClient,{delay:c,actionId:s(this,A),description:"Retrieve SDK Config Data"}),d==="200"},At=async function(t){l(this,o,E).call(this,"Get Measurement ID",m.apiClient),f(this,A,504);const e=performance.now(),i={StudyID:s(this,Le),Resolution:100};t.partnerId&&(i.PartnerID=t.partnerId),t.userProfileId&&(i.UserProfileID=t.userProfileId);const a=await s(this,x).http.measurements.create(i,"user"),c=performance.now()-e,{status:d,body:n}=a;let r="";d==="200"?(f(this,F,n.ID),r=`Successfully obtained measurement ID: ${s(this,F)}`):(f(this,F,""),r=`Failed to obtain measurement ID. Status: ${d}`),l(this,o,E).call(this,r,m.apiClient,{delay:c,actionId:s(this,A),measurementId:s(this,F),description:"Get Measurement ID"})},ae=function(t){f(this,ue,t),l(this,o,E).call(this,`Face tracker state changed: ${t}`,m.mediaPipe),this.on.faceTrackerStateChanged&&this.on.faceTrackerStateChanged(s(this,ue))},R=function(t,e,i=!1){return new Promise(a=>{const c=_i(this,Ie)._++;s(this,se).set(c,{resolve:a,action:t});const d=()=>s(this,I).worker.postMessage({id:c,action:t,payload:e});i?f(this,Te,s(this,Te).then(d).catch(n=>console.error(n))):d()})},ft(gi,"VERSION",Xe);class wi{static VERSION=Lt;#e=document.createElement("div");#i=document.createElement("div");#s=!1;on={results:null,error:null,event:null};constructor(){this.#e.style.height="100%"}async init(e){const{container:i,appPath:a,settings:c,profile:d,config:n,language:r,apiUrl:u}=e;return this.#i=i,new Promise((h,p)=>{const S=i.attachShadow({mode:"open"}),C="app",k=document.createElement("link");k.rel="stylesheet",k.href=`${a}/stylex.css`,S.appendChild(k);const O=document.createElement("link");O.rel="stylesheet",O.href=`${a}/${C}.css`,S.appendChild(O);const P=W=>{this.on.results&&this.on.results({...W.detail})},G=W=>{this.on.error&&this.on.error({...W.detail})},re=W=>{this.on.event&&this.on.event({...W.detail})};this.#e.addEventListener(U.RESULTS,P),this.#e.addEventListener(U.ERROR,G),this.#e.addEventListener(U.APPEVENT,re),S.appendChild(this.#e);const Y=document.createElement("script");Y.type="module",Y.src=`${a}/${C}.mjs`,Y.onload=()=>{import(Y.src).then(W=>{W.app.init(this.#e,a,c,d,u,n,r),this.#s=!0,h()}).catch(W=>{p(new Error("Failed to initialize Measurement Embedded React app: "+W.message))})},Y.onerror=()=>{p(new Error("Failed to load the measurement embedded app script"))},S.appendChild(Y)})}#t(){if(!this.#s)throw new Error("MeasurementEmbeddedApp is not initialized. Call init() before using this method.")}async destroy(){return this.#t(),new Promise(e=>{const i=c=>{if(this.#e.removeEventListener(U.DESTROYED,i),this.#i){const d=this.#i.cloneNode(!1);this.#i.replaceWith(d)}e()};this.#e.addEventListener(U.DESTROYED,i);const a=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.DESTROY,data:{}}});this.#e.dispatchEvent(a)})}setTheme(e){this.#t();const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.SET_THEME,data:{theme:e}}});this.#e.dispatchEvent(i)}setLanguage(e){this.#t();const i=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.SET_LANGUAGE,data:{language:e}}});this.#e.dispatchEvent(i)}async cancel(e){return this.#t(),new Promise(i=>{const a=d=>{this.#e.removeEventListener(U.CANCELLED,a),i(d.detail.reset)};this.#e.addEventListener(U.CANCELLED,a);const c=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.CANCEL,data:{reset:e}}});this.#e.dispatchEvent(c)})}getLogs(){return this.#t(),new Promise(e=>{const i=c=>{this.#e.removeEventListener(U.LOGS,i),e(c.detail.logs)};this.#e.addEventListener(U.LOGS,i);const a=new CustomEvent("measurement-embedded-app-action",{detail:{action:ne.GET_LOGS,data:{}}});this.#e.dispatchEvent(a)})}}export{Je as ErrorCodes,Dt as appEvents,wi as default,hi as faceAttributeValue,Ye as logCategory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuralogix.ai/web-measurement-embedded-app",
3
- "version": "0.1.0-beta.3",
3
+ "version": "0.1.0-beta.5",
4
4
  "description": "Web Measurement Embedded App",
5
5
  "homepage": "https://docs.deepaffex.ai/wmea/",
6
6
  "contributors": [